# Security Policy

This document describes the security practices, policies, and architecture of
the Oshun platform.

## Table of Contents

- [Reporting Vulnerabilities](#reporting-vulnerabilities)
- [Security Architecture](#security-architecture)
- [Authentication and Authorization](#authentication-and-authorization)
- [Secrets Management](#secrets-management)
- [Dependency Scanning](#dependency-scanning)
- [Static Analysis and Code Scanning](#static-analysis-and-code-scanning)
- [Secret Scanning](#secret-scanning)
- [Container Security](#container-security)
- [License Compliance](#license-compliance)
- [Secure Development Practices](#secure-development-practices)
- [Environment and Configuration Security](#environment-and-configuration-security)

---

## Reporting Vulnerabilities

If you discover a security vulnerability in the Oshun platform, please report it
responsibly.

### How to Report

1. **Do NOT open a public issue.** Security vulnerabilities should never be
   disclosed publicly before they are addressed.

2. **Email the security team** with the following details:
   - Description of the vulnerability
   - Steps to reproduce
   - Affected components (domain, library, service)
   - Potential impact assessment
   - Any suggested mitigation

3. **Expected response times:**
   - Acknowledgment: Within 48 hours
   - Initial assessment: Within 5 business days
   - Fix timeline: Depends on severity (see below)

### Severity Levels and Response

| Severity | Example                             | Target Fix Time |
| -------- | ----------------------------------- | --------------- |
| Critical | Remote code execution, auth bypass  | 24-48 hours     |
| High     | SQL injection, XSS, data exposure   | 1 week          |
| Medium   | CSRF, information disclosure        | 2 weeks         |
| Low      | Security header missing, minor leak | Next release    |

### Recognition

We appreciate responsible disclosure. Contributors who report valid security
vulnerabilities will be acknowledged (with their permission) in release notes.

---

## Security Architecture

### Domain Isolation

Oshun is an Nx monorepo with strict domain boundaries enforced at the build
level. The `@nx/enforce-module-boundaries` ESLint rule prevents cross-domain
imports that violate the dependency graph.

Each domain can only depend on:

- `scope:shared` -- Foundation libraries
- `scope:contracts` -- Cross-domain type contracts
- `scope:auth` -- Authentication libraries
- Its own scope

This isolation ensures that a vulnerability in one domain does not cascade to
others through direct code dependencies.

### Layer Architecture

The codebase enforces a layered architecture:

```
contracts (most foundational)
   |
   v
infra (infrastructure services)
   |
   v
data (data access)
   |
   v
domain (business logic)
   |
   v
ui (user-facing)
```

Each layer can only depend on layers below it. This prevents UI code from
directly accessing infrastructure, and ensures that business logic is separated
from data access concerns.

### Security-Sensitive Code Ownership

Files in security-sensitive directories are protected by CODEOWNERS:

```
**/auth/**       -> @oshun/security @oshun/core-team
**/security/**   -> @oshun/security @oshun/core-team
**/identity/**   -> @oshun/security @oshun/core-team
**/database/**   -> @oshun/core-team @oshun/platform
**/migrations/** -> @oshun/core-team @oshun/platform
```

Any pull request modifying these paths automatically requires review from the
security and core teams.

---

## Authentication and Authorization

### @oshun/auth-primitives

The `@oshun/auth-primitives` library (`libs/shared/auth-primitives/`) provides
low-level, framework-agnostic authentication building blocks:

**JWT Service:**

- Token signing and verification with configurable algorithms (HMAC, RSA)
- JWT ID generation for token tracking
- Authorization header parsing and creation
- Configurable token expiration and issuer validation

**Password Handling:**

- `PasswordHasher` -- Secure password hashing (bcrypt-based)
- `PasswordValidator` -- Configurable password policy enforcement
- `generatePassword()` -- Cryptographically secure password generation
- Default policy enforces minimum length, uppercase, lowercase, numbers, and
  special characters

**Session Management:**

- `SessionManager` -- Session creation, validation, and revocation
- `InMemorySessionStore` -- Development/testing session store
- Device information tracking (user agent parsing)
- Session ID generation with cryptographic randomness

**Token Refresh:**

- `TokenRefreshManager` -- Refresh token rotation with family tracking
- Refresh token reuse detection (revokes entire token family on reuse)
- Configurable refresh token TTL

**API Key Management:**

- `ApiKeyManager` -- API key creation, validation, and revocation
- Key hashing (keys are never stored in plaintext)
- Key masking for display (`sk_...abc`)
- Extraction from headers and query parameters

### @oshun/auth

The `@oshun/auth` library (`libs/shared/auth/`) builds on auth-primitives to
provide a complete authentication and authorization service:

**Authentication Service (`AuthService`):**

- User registration with email verification
- Login with credential validation
- Token pair management (access + refresh)
- OAuth provider integration helpers
- Event-driven audit logging (login, logout, registration, token refresh)

**Role-Based Access Control (RBAC):**

- Hierarchical roles with `ROLE_HIERARCHY`
- `hasMinimumRole()` -- Check if a user meets a minimum role level
- `getRolesAtOrBelow()` -- Get all roles at or below a given level

**Permission-Based Authorization:**

- Fine-grained permissions mapped to roles via `ROLE_PERMISSIONS`
- `hasPermission()`, `hasAllPermissions()`, `hasAnyPermission()`
- Role-to-permission resolution

**Account Lockout Protection:**

- `AccountLockoutManager` -- Local lockout tracking
- `DistributedLockoutManager` -- Redis-backed distributed lockout
- Configurable: max attempts (default 5), lockout duration, auto-reset period

**Middleware:**

- `createAuthMiddleware()` -- Framework-agnostic authentication middleware
- `requireAuth()` / `optionalAuth()` -- Authentication gates
- `requireRole()` / `requireRoles()` -- Role-based authorization
- `requirePermissions()` / `requireAnyPermission()` -- Permission-based
  authorization
- `requireOwnership()` / `requireOwnershipOrPermission()` -- Resource ownership
  checks
- `denySelf()` -- Prevents users from performing actions on their own accounts
  (e.g., self-promotion)
- Token extraction from Bearer headers and cookies

### @oshun/security

The `@oshun/security` library (`libs/shared/security/`) provides security
utilities:

**Audit Logging:**

- `AuditLogger` -- Structured audit event recording
- Event types: authentication, authorization, data access, data modification,
  system events
- Actor tracking (user, service, system, anonymous)
- Target tracking (what resource was accessed/modified)
- Request context (IP address, user agent, geo-location)
- Batched writes for performance
- Stores: `MemoryAuditStore` (development), `DatabaseAuditStore` (production)
- Query support with filtering, pagination, and aggregation

**Security Scanning:**

- `BuiltinSecurityScanner` -- Pattern-based secret and threat detection
- `ClamAVScanner` -- Antivirus integration for file scanning
- Scans for: API keys, tokens, passwords, AWS credentials, private keys, credit
  card numbers, SSNs
- File and text content scanning

**Secret Management:**

- `SecretManager` -- Secret lifecycle management
- Secret creation, retrieval, update, and deletion
- Automatic rotation with configurable intervals
- Version history tracking
- Caching with configurable TTL
- Stores: `MemorySecretStore` (development), `DatabaseSecretStore` (production)
- Secret types: API keys, database credentials, encryption keys, certificates,
  OAuth secrets

### @oshun/identity

The `@oshun/identity` library (`libs/shared/identity/`) provides user identity
management utilities for the platform.

### @oshun/rate-limit

The `@oshun/rate-limit` library (`libs/shared/rate-limit/`) provides rate
limiting capabilities to protect APIs from abuse.

---

## Secrets Management

### Environment Variables

All secrets are managed through environment variables. The repository enforces
strict separation:

- `.env` files are excluded via `.gitignore`
- `.env.example` files provide templates with placeholder values
- No secrets are ever committed to the repository

The `.gitignore` file explicitly excludes:

```
.env
.env.local
.env.development
.env.development.local
.env.test
.env.test.local
.env.production
.env.production.local
.env.staging
.env.staging.local
.env*.local
*.env
*.pem
*.key
*.crt
*.p12
*.pfx
**/certs/*.pem
**/certs/*.key
```

### Runtime Secret Management

The `@oshun/security` library provides `SecretManager` for runtime secret
management with:

- Encrypted storage
- Automatic rotation with configurable intervals (e.g., 30-day database password
  rotation)
- Version tracking for rollback
- In-memory caching with TTL to reduce store lookups
- Pluggable store backends (memory for development, database for production)

### CI/CD Secrets

Secrets used in CI/CD are stored as GitHub repository secrets and referenced via
`${{ secrets.SECRET_NAME }}`. The CI workflows use:

- `NX_CLOUD_ACCESS_TOKEN` -- Nx Cloud for distributed caching
- `GITHUB_TOKEN` -- GitHub API access (automatically provided)

---

## Dependency Scanning

### Automated Auditing

The CI pipeline includes a security audit job that runs on every push to
`main`/`develop` and on every pull request:

1. **pnpm audit** -- Scans all dependencies for known vulnerabilities at the
   `high` severity level and above.

2. **Critical vulnerability gate** -- The CI fails if any critical
   vulnerabilities are found.

3. **Hardcoded secret scan** -- Searches source code for patterns matching
   passwords, API keys, tokens, and secrets.

### Iris Domain-Specific Security

The Iris AI Assistant platform has an additional dedicated security workflow
(`.github/workflows/iris-security.yml`) that runs daily:

- Dependency vulnerability scanning with reporting
- Detection of deprecated/problematic dependencies (lodash, moment, request)
- Iris-specific package analysis

### Dependency Management Practices

- **pnpm catalog** (`pnpm-workspace.yaml`) centralizes shared dependency
  versions. This ensures consistent versions across all packages and makes it
  easier to update vulnerable packages in one place.

- **pnpm overrides** in the root `package.json` force minimum versions for
  packages with known vulnerabilities:

  ```json
  "pnpm": {
    "overrides": {
      "glob": ">=10.0.0",
      "qs": ">=6.14.0",
      "validator": ">=13.15.0",
      "zod": ">=3.23.0",
      "esbuild": ">=0.25.0",
      "tmp": ">=0.2.4"
    }
  }
  ```

- **PR dependency review** -- The CI bot automatically detects and comments on
  dependency changes in pull requests, listing added and removed packages for
  manual review.

---

## Static Analysis and Code Scanning

### CodeQL

GitHub CodeQL analysis runs on:

- Every push to `main` and `develop` (for `.ts`, `.tsx`, `.js`, `.jsx` files)
- Every pull request to `main`
- Weekly scheduled scans (Sundays at 2 AM UTC)

Configuration:

- Language: `javascript-typescript`
- Query suites: `security-extended` and `security-and-quality`
- Scans `libs/`, `apps/`, `yemaya/packages/`, `yemaya/apps/`, `lilith/services/`
- Excludes: `node_modules`, `dist`, test files

### ESLint Security Rules

The Iris security workflow runs ESLint with security-focused rules and scans for
dangerous patterns:

**Dangerous patterns detected:**

- `eval()` and `new Function()`
- `innerHTML` assignment
- `dangerouslySetInnerHTML`
- `document.write()`
- `child_process` usage
- `spawn()` and `execSync()`
- `__proto__` access
- `constructor[]` access

**SQL injection detection:**

- Raw SQL queries with string concatenation
- Template literal interpolation in SQL statements

**XSS prevention:**

- `innerHTML` / `outerHTML` assignment
- `document.write()`
- `insertAdjacentHTML()`

---

## Secret Scanning

### Gitleaks

The Iris security workflow uses [Gitleaks](https://github.com/gitleaks/gitleaks)
for secret scanning:

- Scans the full git history for leaked secrets
- Detects: passwords, API keys, tokens, Bearer tokens, AWS access keys
  (`AKIA...`), OpenAI keys (`sk-...`)
- Fails the build if potential secrets are found

### Hardcoded Value Detection

Both the main CI and Iris security workflows scan source code for hardcoded
sensitive values using pattern matching:

```
password\s*[:=]\s*['"][^'"]{8,}['"]
api[_-]?key\s*[:=]\s*['"][^'"]{16,}['"]
secret\s*[:=]\s*['"][^'"]{8,}['"]
token\s*[:=]\s*['"][^'"]{20,}['"]
Bearer\s+[A-Za-z0-9\-_]{20,}
sk-[A-Za-z0-9]{20,}
AKIA[0-9A-Z]{16}
```

Test files, examples, and mock data are excluded from these scans.

---

## Container Security

### Dockerfile Scanning

When Dockerfiles are present, the Iris security workflow uses
[Trivy](https://github.com/aquasecurity/trivy) to scan for:

- Misconfiguration in Dockerfiles
- High and critical severity issues

### Dockerfile Best Practices

The CI checks Dockerfiles for:

- **USER instruction** -- Containers should not run as root
- **HEALTHCHECK instruction** -- Containers should define health checks
- **No `:latest` tag** -- Use specific version tags for reproducibility
- **Multi-stage builds** -- Recommended for smaller, more secure images

---

## License Compliance

The Iris security workflow includes license compliance checking. Allowed
licenses:

```
MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC, 0BSD,
CC0-1.0, Unlicense, WTFPL, CC-BY-3.0, CC-BY-4.0
```

Packages with `GPL`, `LGPL`, `AGPL`, or `UNKNOWN` licenses are flagged for
review.

---

## Secure Development Practices

### Input Validation

- Use **Zod** (`^3.23.0`) for runtime type validation and schema enforcement
- Validate all external input at API boundaries
- Use parameterized queries for database access (the `@oshun/database` library
  uses positional parameter replacement via tagged template literals)

### Error Handling

- Never expose internal error details to clients in production
- Use the `@oshun/errors` library for structured, typed error handling
- Log detailed errors server-side via `@oshun/logger` (Pino-based structured
  logging)

### Authentication Best Practices

- Passwords are hashed using bcrypt (via `@oshun/auth-primitives`)
- JWT tokens have configurable short-lived access tokens (default 15 minutes)
  and longer-lived refresh tokens (default 7 days)
- Refresh token rotation with family tracking detects token reuse attacks
- Account lockout after configurable failed attempts (default 5)
- Rate limiting on authentication endpoints

### Data Protection

- Audit logging for all authentication and authorization events
- Structured audit trails with actor, target, and request context
- Secret scanning in CI prevents accidental credential commits
- Domain-isolated databases prevent cross-domain data access at the
  infrastructure level

---

## Environment and Configuration Security

### Development Environment

The local development environment uses Docker Compose with default credentials
for convenience:

- PostgreSQL: `oshun:oshun_dev@localhost:5432`
- MinIO: `minioadmin:minioadmin@localhost:9000`
- Redis: No password (localhost only)

These credentials are for local development only and must never be used in
staging or production environments.

### Production Considerations

- All secrets must be provided via environment variables or a secrets manager
- Database connections must use SSL/TLS
- Redis connections must be authenticated
- S3/MinIO connections must use proper IAM credentials
- All inter-service communication should be encrypted in transit
- Use the `@oshun/security` `SecretManager` for runtime secret access with
  automatic rotation

### Infrastructure as Code

Terraform configurations are stored in `infra/terraform/`. Terraform state files
and variable files are excluded from the repository via `.gitignore`:

```
.terraform/
*.tfstate
*.tfstate.*
*.tfvars
.terraform.lock.hcl
```
