# Media & File Uploads

> Magic-byte sniffing, SSRF-hardened URL sideloading, presigned upload quarantine, SHA-256 deduplication, local and pure-Go S3/R2 storage, and sandboxed Delivery streaming.

OvertCMS Core treats every uploaded or sideloaded file as **untrusted binary input**. Files are verified by magic bytes (never by filename or declared `Content-Type`), deduplicated per site by SHA-256, quarantined during presigned uploads to eliminate TOCTOU tampering, and served with strict browser sandboxing headers.

## Allowed Media Types & Magic-Byte Sniffing

OvertCMS Core verifies the first **64 KiB** of every payload (`mediaSniffReadHeadBytes`) in pure Go:

| Kind | Allowed MIME Types | Canonical Extensions | Extracted Metadata |
| :--- | :--- | :--- | :--- |
| `image` | `image/jpeg`, `image/png`, `image/gif`, `image/webp`, `image/avif` | `.jpg`, `.png`, `.gif`, `.webp`, `.avif` | Pure-Go `width` & `height` (JPEG, PNG, GIF, WebP VP8/VP8L/VP8X) |
| `audio` | `audio/mpeg`, `audio/ogg`, `audio/wav`, `audio/mp4`, `audio/webm` | `.mp3`, `.ogg`, `.wav`, `.m4a`, `.webm` | Verified via ID3/MPEG frame sync, `OggS`, `RIFF/WAVE`, `ftyp M4A`, EBML |
| `video` | `video/mp4`, `video/webm` | `.mp4`, `.webm` | Verified via ISO-BMFF `ftyp` brands and EBML headers |
| `document` | `application/pdf`, `text/csv`, `text/plain` | `.pdf`, `.csv`, `.txt` | `%PDF-` magic bytes; `text/plain` & `text/csv` accepted **only** when explicitly declared and verified safe UTF-8 |

### Unconditionally Rejected Payloads

- **Executables & scripts**: PE/DOS (`MZ`), ELF (`\x7fELF`), Mach-O / Fat Mach-O binaries, and Unix shebang (`#!`) scripts.
- **SVG & HTML**: `<svg>`, `<?xml ... <svg`, `<!doctype html`, `<html>`, `<script>`, `<iframe>`—including NUL-byte/UTF-16LE obfuscation attempts—are always rejected.
- **MIME mismatch**: If a caller declares a non-generic `Content-Type` (anything other than empty or `application/octet-stream`) that disagrees with the sniffed magic bytes, OvertCMS Core rejects the upload with `422 media_content_mismatch`.

---

## Three Ingestion Flows

### 1. Direct Multipart Upload

Best for assets up to `OVERTCMS_MEDIA_MAX_DIRECT_BYTES` (default **25 MiB**):

- Agent Plane: `POST /agent/v1/media/upload`
- Admin Plane: `POST /admin-api/v1/sites/{siteSlug}/media/upload`

The server reads the payload, runs `media.Sniff`, computes SHA-256, checks per-site deduplication, writes to storage (`{siteId}/{assetId}{ext}`), persists the `ready` `MediaAsset`, and emits `media.created`.

### 2. SSRF-Hardened URL Sideloading

Best for AI agents and migrations pulling assets from remote URLs (up to `OVERTCMS_MEDIA_MAX_DIRECT_BYTES`, default **25 MiB**):

- Agent Plane: `POST /agent/v1/media/sideload`
- Admin Plane: `POST /admin-api/v1/sites/{siteSlug}/media/sideload`

```json
{
  "url": "https://images.example.org/hero.png",
  "filename": "hero.png",
  "alt": "Architecture diagram",
  "focalPoint": { "x": 0.5, "y": 0.4 }
}
```

**`SafeFetcher` SSRF defenses:**
- Only `http://` and `https://` schemes are allowed; no unvalidated system HTTP proxies (`Proxy: nil`).
- `localhost`, `*.localhost`, and IPv6 zone identifiers are blocked.
- **Every** DNS-resolved IP address is validated via `IsPublicIP` before dialing **any** socket (defeating DNS rebinding and dual-stack split attacks). IPv4-mapped IPv6 addresses (`::ffff:127.0.0.1`) are unmapped first.
- Blocked ranges include loopback, RFC 1918 private, link-local & cloud metadata (`169.254.0.0/16`), CGNAT (`100.64.0.0/10`), ULA (`fc00::/7`), NAT64, multicast, TEST-NET, and reserved blocks.
- Maximum **3 redirect hops** (each hop re-validated), **30-second** fetch timeout, and strict streaming memory cap (`io.LimitReader(resp.Body, maxBytes+1)`).

### 3. Presigned Upload Intents (Up to 500 MiB)

For large video, audio, or document files up to `OVERTCMS_MEDIA_MAX_PRESIGNED_BYTES` (default **500 MiB**), OvertCMS Core uses a **3-step quarantine workflow** that prevents client-side TOCTOU file swapping:

```mermaid
sequenceDiagram
    participant Client
    participant API as OvertCMS API
    participant Store as Object Storage (S3 / Local)

    Client->>API: 1. POST /media/upload-intent {filename, contentType, byteSize}
    API-->>Client: asset (status: pending_upload) + 15m presigned PUT URL to _staging/...

    Client->>Store: 2. PUT <presigned URL> (raw bytes)
    Store-->>Client: 200 OK

    Client->>API: 3. POST /media/{id}/complete
    API->>API: Atomically claim pending_upload -> processing
    API->>Store: Copy _staging/... -> server-private quarantine/{siteId}/{uuid}
    API->>Store: Stat + ReadHead(64 KiB) + Stream SHA-256 on quarantine key
    API->>Store: Promote quarantine -> final immutable {siteId}/{assetId}{ext}
    API->>Store: Delete quarantine & _staging objects
    API-->>Client: 200 OK { asset (status: ready), deduplicated }
```

- **Local driver**: Issues a 15-minute HMAC-signed `PUT` URL targeting `/agent/v1/media/{id}/upload?token=...` (or `/admin-api/v1/sites/{siteSlug}/media/{id}/upload?token=...`).
- **S3 / R2 driver**: Issues a pure-Go **AWS SigV4** presigned `PUT` URL directly to the bucket's `_staging/` prefix, with `Content-Type` and `Content-Length` signed.
- **TOCTOU immunity**: On `complete`, the server copies staged bytes to an unguessable server-private `quarantine/` key *before* sniffing magic bytes and streaming SHA-256—so a malicious client holding the presigned URL cannot swap bytes after verification.
- **Abandoned intents**: The Worker Plane automatically cleans up stale `pending_upload` assets older than **1 hour** (`stalePendingUploadTTL`).

---

## Per-Site SHA-256 Deduplication

Every `ready` asset is indexed by `(site_id, sha256)`. Uploading, sideloading, or completing an upload whose SHA-256 matches an existing `ready` asset in the same site returns the existing `MediaAsset` with `"deduplicated": true` and deletes any newly staged bytes—eliminating duplicate storage costs and concurrent race duplicates.

---

## Storage Backends & CDN URL Templates

- **Local Filesystem (`OVERTCMS_MEDIA_DRIVER=local`)**: Stores immutable files under `OVERTCMS_MEDIA_LOCAL_DIR` (default `./.data/media`) with strict storage-key path traversal validation.
- **Pure-Go S3 / Cloudflare R2 (`OVERTCMS_MEDIA_DRIVER=s3`)**: Implements `AWS4-HMAC-SHA256` request signing, streaming `PUT`, `Range` `ReadHead`, `HEAD`, server-side `CopyObject` (checking for 200-OK XML `<Error>` bodies), and SigV4 presigned `PUT` with zero external AWS SDK dependencies.
- **Public URL Resolution**:
  - By default, assets resolve to `/delivery/v1/media/{id}`.
  - Set `OVERTCMS_MEDIA_CDN_URL_TEMPLATE` (e.g., `https://cdn.example.com/{key}`) using `{key}`, `{id}`, `{siteId}`, or `{ext}` to point `asset.url` directly at your CDN or R2 public bucket.

---

## Sandboxed Delivery Streaming

When serving media through `GET /delivery/v1/media/{id}`:
- Only assets with `status == "ready"` are served (non-ready assets return `404`).
- Responses include strong immutable caching (`Cache-Control: public, max-age=31536000, immutable` and `ETag: "sha256:<hash>"`).
- **XSS sandboxing**: Every response sets:
  - `X-Content-Type-Options: nosniff`
  - `Content-Security-Policy: sandbox; default-src 'none'; script-src 'none'; style-src 'none'`
- **Forced downloads for documents**: Documents (`application/pdf`, `text/csv`, `text/plain`, and any non-image/audio/video asset) automatically set `Content-Disposition: attachment; filename="..."` with sanitized filenames.

---

## Ephemeral Media & In-Use Protection

- **Media-in-use protection**: Every media asset referenced by an entry field or `rich_html` `<img data-asset-id="...">` is indexed in `entry_media_refs`. Attempting to delete an in-use asset is rejected unless no active entry references it.
- **Ephemeral media**: Mark temporary uploads with `"isEphemeral": true` (default TTL **24 hours**, or custom `expiresAt`). The Worker Plane's `worker:scheduler` job periodically deletes expired ephemeral assets that are not referenced by any entry.
- **Editorial metadata**: Every asset supports `defaultAlt`, `defaultCaption`, `defaultTitle`, `credit`, and normalized `focalPoint` (`x` and `y` in `[0, 1]`), editable via metadata `PATCH`.
