# Security

## Middleware

| Alias / class | Where | Effect |
| --- | --- | --- |
| `RequestId` (global, first) | all | accepts a valid `X-Request-Id` (8–64 `[A-Za-z0-9._-]`) or makes a ULID; in logs, audit rows, error bodies, response header |
| `TrustCloudflareProxies` (global) | all | trusts Cloudflare IPv4/IPv6 ranges + `TRUSTED_PROXIES` (`config/proxies.php`) |
| CORS (global) | `api/*`, `sanctum/csrf-cookie` | origins only from `CORS_ALLOWED_ORIGINS`; credentials allowed |
| `SecureHeaders` (global) | all | HSTS, `nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy`, `Permissions-Policy`, COOP; CSP `default-src 'none'` on `api/*` |
| `ForceJson`, `SetLocale` | api group | JSON errors always; locale from `?lang=` / `Accept-Language`, default `ne` |
| `auth:sanctum` | me, cms, logout | session cookie (stateful CMS domain) or bearer token |
| `active` | me, cms | 403 `account_{pending,suspended,deleted}` for non-active users holding a token/session |
| `ability:cms` | cms | bearer tokens need the `cms` ability (staff); sessions pass |
| `2fa.required` | cms | requires a configured second factor for 2FA roles; exempt super-admin when `SUPER_ADMIN_OTP_ENABLED=false` |
| `2fa.recent` | dangerous actions | verification within 15 min for this token/session; exempt super-admin when `SUPER_ADMIN_OTP_ENABLED=false`; otherwise 403 `two_factor_confirmation_required` |
| `permission:{name}` | cms | AccessService evaluates roles, direct allows and denies; dangerous permissions require recent 2FA |
| `module:{key}` | optional modules | 404 `module_disabled` for disabled/scheduled/surface/audience/dependency restrictions |

`tests/Feature/System/RouteSecurityTest.php` fails the build if a `/api/v1/cms/*` route
lacks a permission guard (`permission:`, `can:`) or any `/api/v1/*`
route lacks `throttle:`.

## Rate limits (`AppServiceProvider::configureRateLimiting`, Redis DB 4)

| Limiter | Limit | Key | Routes |
| --- | --- | --- | --- |
| `public` | 300/min | IP | health, token refresh, (public website later) |
| `auth` | 10/min + 5/min | IP + account (HMAC of login/email/phone) | register, login, OTP login, 2FA challenge, OTP verify, password, invitations |
| `otp` | 3 / 10 min | target (phone/e-mail HMAC) | `auth/otp/send` (OtpService enforces the same limit for every send path) |
| `cms` | 600/min | user | `me/*`, `cms/*`, logout |
| `uploads` | 60/min | user | (media prompt) |
| `events` | 1200/min | IP | (analytics prompt) |

429 responses: `too_many_requests` with `Retry-After`.

## Authentication

* **CMS (Next.js)**: Sanctum SPA cookies. Requests whose Origin/Referer matches
  `SANCTUM_STATEFUL_DOMAINS` get a session (Redis DB 2) — call `GET /sanctum/csrf-cookie`
  first and send `X-XSRF-TOKEN`. Session ids are stored on `user_devices.session_id` so
  "logout all", force logout and device revoke can destroy them.
* **Apps**: Sanctum bearer token (60 min, abilities by user type: staff `app,cms`,
  contributor `app,reporter`, reader `app`) + opaque refresh token (30 days, sha256 at rest).
  `POST /auth/refresh` rotates both; replaying a used refresh token revokes the whole
  rotation family and is audited (`refresh_token_reuse`).
* **Passwords**: argon2id; min 10 chars + HIBP k-anonymity breached check (`Password::defaults()`,
  `PASSWORD_BREACH_CHECK`). Change → other tokens/sessions revoked. Reset → all revoked.
* **Lockout**: 5 failed password/OTP/TOTP attempts → 423 `account_locked` for 15 minutes.
  Unknown accounts get the same 401 and the same hashing cost.
* **OTP**: 6 digits, HMAC-hashed with the target, 5 min expiry, 5 attempts, 3 sends / 10 min.
  `auth/otp/send` never reveals whether an account exists.
* **2FA (TOTP/e-mail)**: required for system-admin, desk-head, editor
  (seeded role metadata, enforced by AccessService). Secret + 8 recovery codes encrypted at rest; each
  TOTP code is accepted once; recovery codes are single-use. A role that requires 2FA
  cannot disable it.
* **Super-admin**: `SUPER_ADMIN_OTP_ENABLED=true` (default) requires password plus
  e-mail OTP regardless of `TWO_FACTOR_METHOD`, without authenticator enrolment.
  When false, super-admin uses password-only login and bypasses enrolment/recent-code
  checks in CMS permissions, embedded role assignment and workflow actions. Existing
  factors are preserved. Other roles, account status, permissions/scopes, rate limits
  and auditing remain enforced. Re-enabling affects future logins and sensitive-action
  verification; it does not revoke existing sessions. See [auth.md](auth.md) for rollout.
* **New device alert**: a sign-in from an unknown device (X-Device-Id, else user agent) e-mails/SMSes the user.

## Audit log

* Table `audit_events`: InnoDB, `PARTITION BY RANGE COLUMNS(occurred_at)` monthly
  (`p_before`, `pYYYYMM`…, `pmax`), PK `(id, occurred_at)`, no foreign keys.
* `BEFORE UPDATE` / `BEFORE DELETE` triggers `SIGNAL SQLSTATE '45000'` — even the schema owner cannot change rows.
* Written only through the `audit` connection as MySQL user `pt_audit` with **INSERT + SELECT** only.
* Each row stores `prev_hash` and `hash = sha256(canonical row incl. prev_hash)`; appends are
  serialised with the Redis lock `lock:audit:chain`. `php artisan audit:verify` (nightly) recomputes
  the chain and logs `critical` on the first broken link.
* `AuditService::record()` defers the write until the surrounding transaction commits
  (rolled-back changes are not audited) and captures actor, role, IP (VARBINARY(16)),
  user agent, `X-Device-Id`, `X-App-Version`, request id.
* `audit:partitions` (monthly) carves future months out of `pmax`. Migration `down()` refuses
  outside local/testing. Note: `TRUNCATE`/`DROP` bypass triggers — only the migration user has
  those privileges; never grant them to application users.

### Audit database user

Run as MySQL root after the first migration, for each database (grants survive `migrate:fresh`):

```sql
CREATE USER IF NOT EXISTS 'pt_audit'@'127.0.0.1' IDENTIFIED BY '<secret>';
GRANT SELECT, INSERT ON `ePaschim`.`audit_events` TO 'pt_audit'@'127.0.0.1';
GRANT SELECT, INSERT ON `ePaschim_test`.`audit_events` TO 'pt_audit'@'127.0.0.1';   -- tests
```

Env: `AUDIT_DB_HOST`, `AUDIT_DB_PORT`, `AUDIT_DB_DATABASE`, `AUDIT_DB_USERNAME`, `AUDIT_DB_PASSWORD`.

## Uploads

Real MIME check (`mimetypes:` rule), size limits, random 40-char file names, private disk
(`media_private`) for documents, ClamAV scan through `App\Contracts\FileScanner`
(`UPLOAD_SCANNER=clamav`, `CLAMAV_SOCKET`). Uploads fail closed (503 `scanner_unavailable`)
when clamd is unreachable. `UPLOAD_SCANNER=none` is refused in production.

## Logging

`App\Logging\MaskSensitiveData` is attached to every channel (logging `tap`): masks keys
matching password/secret/token/otp/code/recovery/phone/mobile/email/authorization/cookie and
patterns (Bearer/Sanctum tokens, e-mails, E.164 and Nepali mobile numbers, "otp: 123456").
The local-only `sms_local` channel (`storage/logs/sms.log`) is deliberately unmasked and only
used by `SMS_DRIVER=log`, which is refused in production.

## Dashboards

Horizon (`/horizon`), Telescope (`/telescope`, local/staging only, sensitive params/headers
hidden, pruned daily) and API docs (`/docs/api`, open in local) use the gates
`viewHorizon`, `viewTelescope`, `viewApiDocs`. They check `system.horizon`,
`system.telescope` and `api-docs.view` through AccessService, including direct denies.

Set `LOCAL_DASHBOARDS_PUBLIC=true` to open Horizon and Telescope without login when
`APP_ENV=local`. The switch defaults to false and is ignored in staging, testing and
production; permission checks remain required there. Telescope is still registered
only in local/staging and needs `TELESCOPE_ENABLED=true`. API docs authorization and
Telescope's sensitive-data masking are unchanged.

After changing the environment setting, run `php artisan config:clear` (or rebuild
the configuration cache with `php artisan config:cache`). Then open `/horizon` or
`/telescope` on the backend host.

## Secrets

Only from `.env` / the secret manager. `.env` is git-ignored. `SUPER_ADMIN_PASSWORD` must be
16+ chars with mixed case, numbers, symbols and not breached in production (seeder refuses otherwise).
