# API Keys, Scopes & Kill Switch

> Scoped programmatic API keys, HMAC-SHA-256 storage, presets and scopes, per-post-type access, CIDR IP allowlists, rate limits and daily quotas, aiWritable field locks, and the instant agent kill switch.

OvertCMS Core is designed so you can safely hand autonomous AI agents and CI/CD pipelines direct access to your CMS without risking privilege escalation, runaway token loops, schema corruption, or accidental site takedowns.

## Scoped API Key Format & Storage

Programmatic credentials follow a strict, self-identifying canonical format:

```text
ocms_<env>_<16-lower-hex-id>_<64-lower-hex-secret>
```

- **`<env>`**: Either `live` (default) or `test`.
- **Lookup prefix (`keyPrefix`)**: `ocms_<env>_<16-hex-id>` (non-secret, safe to display in logs and Admin UI).
- **Cryptographic hashing**: The plaintext key is returned **once** on creation (`CreateAPIKeyResult.plaintextKey`) and never stored. Only `HMAC-SHA-256(OVERTCMS_SECRET_KEY, "overtcms-api-key-v1:" + plaintext)` is persisted and compared in constant time (`subtle.ConstantTimeCompare`).
- **Site binding**: Every API key is scoped to a single `siteId`. Cross-site requests are rejected with `403 site_not_allowed`.
- **Expiration & revocation**: Keys support optional `expiresAt` (`401 api_key_expired`) and instant revocation (`DELETE /admin-api/v1/sites/{siteSlug}/api-keys/{id}`, returning `401 api_key_revoked`).

---

## Presets & Granular Scopes

Every API key starts from one of **4 built-in presets**, and optionally narrows/overrides its explicit `scopes` from the **12 canonical scopes**:

| Preset | Default Scopes Granted | Typical Use Case |
| :--- | :--- | :--- |
| `public_read` | `delivery:read`, `schema:read`, `site:read`, `entries:read`, `media:read` | Private Delivery Plane access (`OVERTCMS_DELIVERY_REQUIRE_API_KEY=true`) or read-only research agents. |
| `agent_drafter` | `delivery:read`, `schema:read`, `site:read`, `entries:read`, `entries:write`, `media:read`, `media:write` | AI writing assistants that can draft entries and upload media, but **cannot** publish, schedule, unpublish, delete, or change site/visibility settings. |
| `agent_publisher` | All `agent_drafter` scopes + `entries:publish`, `entries:delete`, `media:delete` | Autonomous content pipelines allowed to publish, schedule, and manage media, but **cannot** alter schemas or site settings. |
| `schema_admin` | All `agent_publisher` scopes + `schema:write`, `site:write` | Full editorial & setup agents: content models, reusable blocks, site settings & AI brief, SEO/AEO visibility, redirects, media, and entries. Security & control-plane routes (users, RBAC, MFA, API keys, kill switch, webhooks, org settings) remain human Admin Plane only. |

<Tip>
  Use **`agent_drafter`** as your default preset for AI content agents. It enforces a human-in-the-loop publishing workflow at the API boundary—any attempt by an `agent_drafter` key to create a `published`/`scheduled` entry, set `scheduledAt`/`unpublishAt`, or call `/publish` fails with `403 insufficient_scope` or `403 publish_permission_required`.
</Tip>

---

## Fine-Grained Guardrails on Every Key

When minting a key via `POST /admin-api/v1/sites/{siteSlug}/api-keys`, layer multiple independent controls:

```json
{
  "name": "Docs Content Agent",
  "env": "live",
  "preset": "agent_drafter",
  "allowedPostTypes": {
    "docs": "write",
    "authors": "read",
    "categories": "read"
  },
  "allowedIps": [
    "10.20.0.0/16",
    "203.0.113.42"
  ],
  "rateLimitRpm": 60,
  "dailyWriteCap": 150,
  "dailyMediaBytesCap": 52428800,
  "expiresAt": "2027-01-01T00:00:00Z"
}
```

### 1. Per-PostType Allowlists (`allowedPostTypes`)

Maps PostType slugs (or wildcard `"*"`) to `"read"` or `"write"` (where `"write"` implies `"read"`).
- An empty map permits all PostTypes.
- When configured, `/agent/v1/schema`, `/agent/v1/prompt`, reference searches, and Delivery responses (when `DeliveryRequireAPIKey=true`) automatically filter out unpermitted PostTypes so keys only see what they are allowed to access.

### 2. IP & CIDR Allowlists (`allowedIps`)

Accepts exact IPv4/IPv6 addresses (e.g., `203.0.113.42`, `::1`) and CIDR blocks (e.g., `10.20.0.0/16`, `2001:db8::/32`). Requests from non-matching IPs are rejected with `403 ip_not_allowed` before any handler runs.

### 3. Per-Key Rate Limits & Daily Blast-Radius Caps

| Quota Field | Enforcement | Error on Breach |
| :--- | :--- | :--- |
| `rateLimitRpm` | Per-minute sliding/bucketed request limit (backed by atomic Redis/Valkey Lua scripts when `OVERTCMS_REDIS_URL` is configured, or in-memory). | `429 rate_limited` + `Retry-After` header |
| `dailyWriteCap` | Maximum mutating writes per UTC day. Batch operations atomically charge `N` writes upfront via `CheckAPIKeyDailyWriteN`. | `429 rate_limited` |
| `dailyMediaBytesCap` | Maximum uploaded/sideloaded media bytes per UTC day (including automatic inline `rich_html` image sideloading). | `429 rate_limited` |

Setting any cap to `0` disables that cap.

---

## Instant Agent Kill Switch (`agentWritesPaused`)

Every site includes an instant **emergency stop** for all automated writes—across both REST (`/agent/v1/*`) and MCP (`/mcp`):

- **Pause all agent writes immediately**:
  ```bash
  curl -X POST http://localhost:8080/admin-api/v1/sites/default/agent-writes/pause \
    -H "Authorization: Bearer $ADMIN_TOKEN"
  ```
- **Resume agent writes** (requires Step-Up MFA if enrolled):
  ```bash
  curl -X POST http://localhost:8080/admin-api/v1/sites/default/agent-writes/resume \
    -H "Authorization: Bearer $ADMIN_TOKEN"
  ```

While `agentWritesPaused: true`:
- Every mutating Agent REST call, local media upload, and MCP write tool immediately returns **`503 Service Unavailable`** with code `agent_writes_paused` and `retryable: true`.
- Idempotency claims are **not** cached on `503` rejections, so agents can safely retry with the same `Idempotency-Key` once writes resume.
- Read-only Agent routes (`/agent/v1/schema`, `/agent/v1/health`, `/.well-known/agent-cms.json`) and human Admin Plane editors continue working normally.

---

## Schema-Level Agent Guardrails

Even when an API key has `write` access to a PostType, schema-level protections remain enforced for `api_key` and `mcp` actors:

| Guardrail | How It Works |
| :--- | :--- |
| **`aiWritable: false` on Fields** | Prevents API-key and MCP actors from setting or clearing sensitive fields (for example, `featuredPriority`, `canonicalUrl`, or `legalDisclaimer`), while human editors can still edit them freely. |
| **`aiWritable: false` on Components** | Prevents AI agents from inserting or mutating restricted `<cms-block>` components (such as pricing tables or legal banners) inside `rich_html`, `object`, or `list` fields. |
| **`readOnly: true` / `writable: false`** | Blocks all API writes on system-managed fields. |
| **Strong Reference Protection** | API keys can **never** pass `force: true` to trash an entry that has incoming `strong` references. |
| **Live Takedown Confirmation** | Unpublishing, archiving, or trashing a `published` entry requires explicit `"confirmUnpublish": true`. |
| **Placeholder Link Guard** | Rejects LLM hallucinated links (`#`, `TBD`, `example.com`, `[insert link]`, `{{url}}`) with `422 placeholder_link_detected`. |
| **`If-Schema-Fingerprint`** | Prevents agents with stale prompts from writing against a breaking schema change (`409 schema_drift_detected`). |
| **`dryRun: true`** | Lets agents validate payloads, reference IDs, slug availability, and canonical HTML with **zero database or media writes**. |
| **`Idempotency-Key`** | Scoped per `(site_id, actor_scope, key)` with SHA-256 request-hash binding (`60s` in-progress lease, `24h` completed receipt TTL) so retries never create duplicate posts. |
