# Write a traffic policy

Decide what each agent and bot may do on your site with a versioned traffic policy, test it with simulate, and roll it out in shadow mode before it enforces.

Write a traffic policy to decide what each agent and bot may do: allow it, block it, rate-limit it, hand it to your own challenge, or require the person behind it to approve. Traffic policies use the same versioned [policy](https://provenanceauth.com/docs/concepts/policies.md) format as every product, with simulate, shadow mode and lists.

**Before you begin:** export the sandbox account key.

```bash
export PROVENANCE_API=https://sandbox-api.provenanceauth.com
export PROVENANCE_KEY=prv_test_acct_P9xN2vQ7bT4mW8sYd3cFjLh6gAe1kR5
```

A rule has conditions (`when`, all must hold) and an outcome (`then`). The first matching rule wins; with no match, `default` applies (`allow` unless you set it).

| `then.action` | What happens |
| --- | --- |
| `allow` | The request passes. |
| `block` | `403` with a generic "blocked" body. What the client gets is yours to choose: see [Decide what to return](#decide-what-to-return). |
| `log_only` | The request passes and the decision is recorded. |
| `rate_limit` | At most `max` requests per `window_seconds`, counted `per` ip, agent, human (pseudonym) or operator. Over it: `429` with `Retry-After`. |
| `challenge` | Your `onChallenge` hook runs, so you can hand off to the challenge you already use. |
| `require_intent` | `401` with a `ProvenanceIntent` challenge until the request carries the person's approval. See [Require a human](https://provenanceauth.com/docs/identify/guides/require-a-human.md). |

## 1. Start from a template

**curl**

```bash
curl -s $PROVENANCE_API/v1/identify/policy_templates \
  -H "Authorization: Bearer $PROVENANCE_KEY" | jq '.data[].id'
```

**Node**

```ts
const templates = await (await fetch(`${process.env.PROVENANCE_API}/v1/identify/policy_templates`, {
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}` },
})).json();
```

**Python**

```python
import os, httpx

templates = httpx.get(f"{os.environ['PROVENANCE_API']}/v1/identify/policy_templates",
                      headers={"Authorization": f"Bearer {os.environ['PROVENANCE_KEY']}"}).json()
```

```text
"welcome_shopping_agents"
"block_ai_training"
"rate_limit_unknown_bots"
"require_human_account_changes"
"accept_verified_protocols"
"slow_down_scrapers"
"agent_checkout_approval"
```

`slow_down_scrapers` allows published search crawlers and signed agents, challenges a client that reads more than 120 pages in five minutes, and holds one whose requests look like a crawl (`scraping_suspected`) to 30 pages a minute, on browse and search only. It never rejects. See [Slow down scrapers](https://provenanceauth.com/docs/identify/guides/slow-down-scrapers.md).

## 2. Save a policy

Conditions read the verdict's facts. The agent facts have the names checkout and agent rules use. Each fact takes the engine's operators, plus `contains` for `signals`:

| Fact | Example values |
| --- | --- |
| `agent.class` | `signed_agent`, `declared_bot`, `suspected_bot`, `likely_human`, `unknown` |
| `agent_category` | `search_crawler`, `ai_training_crawler`, `ai_assistant_fetch`, `shopping_agent`, `monitoring`, `other_agent` |
| `action` | your route map's names: `browse`, `checkout`, `login`, `account_change` |
| `agent_id`, `operator`, `agent_directory`, `pseudonym` | match exactly, or test with `in_list` against a [list](https://provenanceauth.com/docs/concepts/policies.md) |
| `agent.platform`, `agent.platform_source` | `openai`, `anthropic`, `google`, `microsoft`, `apple`, `perplexity`, `meta`, `common_crawl`; `signed` or `declared` ([which platform sent it](https://provenanceauth.com/docs/concepts/assessments.md#which-platform-sent-it)) |
| `human_backed`, `intent_valid`, `biometric_bound`, `agent.verified` | `true` or `false` |
| `agent.bot_score`, `vendor_score` | numbers, compared with `gt`, `gte`, `lt`, `lte` |
| `signals` | `contains` a signal code |
| `protocol`, `protocol_status`, `protocol_kind` | `ap2`, `acp`, `x402`; `verified`, `unverified`, `invalid`; `checkout_mandate`, `payment_mandate`, `checkout_session`, `payment` ([protocols](https://provenanceauth.com/docs/identify/guides/protocols.md)) |
| `protocol_amount`, `protocol_payee` | the verified amount in minor units, and the payee (`in_list` against your payees) |

**curl**

```bash
curl -s -X PUT "$PROVENANCE_API/v1/identify/policies" \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "document": {
      "rules": [
        { "id": "block-training", "when": [{ "fact": "agent_category", "op": "eq", "value": "ai_training_crawler" }], "then": { "action": "block" } }
      ],
      "default": "allow"
    }
  }'
```

**Node**

```ts
await fetch(`${process.env.PROVENANCE_API}/v1/identify/policies`, {
  method: "PUT",
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ document: { rules: [{ id: "block-training", when: [{ fact: "agent_category", op: "eq", value: "ai_training_crawler" }], then: { action: "block" } }], default: "allow" } }),
});
```

**Python**

```python
httpx.put(f"{os.environ['PROVENANCE_API']}/v1/mandate/policies", params={"domain": "traffic"},
          headers={"Authorization": f"Bearer {os.environ['PROVENANCE_KEY']}"},
          json={"document": {"rules": [{"id": "block-training", "when": [{"fact": "agent_category", "op": "eq", "value": "ai_training_crawler"}],
                                        "then": {"action": "block"}}], "default": "allow"}})
```

```json
{ "object": "policy_version", "domain": "traffic", "version": 1, "active": true, "note": null }
```

The middleware picks up the new version on its next bundle refresh, within five minutes.

In the console, **Rules › Traffic** edits the same document one rule at a time: each rule reads the facts above in
words ("Who it is is Signed agent"), and takes one outcome: Allow, Challenge, Challenge with the person's approval
(`require_intent`), Reject, Rate limit or Log. The **Otherwise** row is the document's `default`. A rule you turn off
keeps its place with `enabled: false` and never runs. Edit as JSON, with simulate and shadow mode, is under More.

## 3. Simulate before you rely on it

**curl**

```bash
curl -s "$PROVENANCE_API/v1/identify/policies/simulate" \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "facts": { "class": "signed_agent", "agent_category": "ai_training_crawler" } }'
```

**Node**

```ts
const sim = await (await fetch(`${process.env.PROVENANCE_API}/v1/identify/policies/simulate`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ facts: { "agent.class": "signed_agent", agent_category: "ai_training_crawler" } }),
})).json();
```

**Python**

```python
sim = httpx.post(f"{os.environ['PROVENANCE_API']}/v1/mandate/policies/simulate", params={"domain": "traffic"},
                 headers={"Authorization": f"Bearer {os.environ['PROVENANCE_KEY']}"},
                 json={"facts": {"class": "signed_agent", "agent_category": "ai_training_crawler"}}).json()
```

```json
{ "object": "policy_simulation", "domain": "traffic", "action": "reject", "then": { "action": "block" }, "policy": { "id": "pol_3F9A1C7E52B04D8E6A1F27C9B4", "version": 1, "rule": { "id": "rul_01JDMRSCXHRC0FAR7CRZ9067GS", "name": null, "phase": "assess", "action": "reject", "conditions": [{ "fact": "agent_category", "op": "eq", "value": "ai_training_crawler", "actual": "ai_training_crawler" }] } } }
```

## 4. Backtest it on your recorded traffic

`POST /v1/identify/policies/backtest` replays your last 30 days of recorded decisions through a draft and says what would have changed, including how many of the visits it would block or challenge went on to place an order. See [Backtest traffic rules](https://provenanceauth.com/docs/identify/guides/backtest-traffic-rules.md).

## 5. Roll out in shadow mode

Run a new version as the shadow with `POST /v1/identify/policies/versions/{version}/shadow`. The middleware evaluates it on live traffic and reports what it would have done in `decision.shadow`, without enforcing it. Compare with `GET /v1/identify/policies/shadow_report`, then activate the version when the divergence is what you expect.

## Decide what to return

A rejected or rate-limited client gets a generic machine-readable "blocked" body by default, with no rule id and no reason, so a well-behaved agent can tell it was blocked and a scraper can't tell by which rule:

```json
{ "type": "https://provenanceauth.com/problems/traffic-blocked", "title": "Blocked", "status": 403, "detail": "This site's traffic policy doesn't allow this request." }
```

The rule id and reason stay with you: in the verdict's `policy` block, the recorded decision, the console and webhooks. Set `respond` on a `block` or `rate_limit` rule to choose something else, or on the policy itself to change the default for every rule. Identify and Trace share these kinds, so a kind means the same in both.

| `respond.kind` | What the client gets |
| --- | --- |
| `not_possible` | The generic body above (the default). `include_rule: true` and `include_reason: true` put the rule id and reason back. |
| `message` | The same body with `detail` set to your text (at most 200 characters). |
| `status_only` | `403`, `404` or `429` with an empty body. |
| `page` | A status and one of your stored pages (`POST /v1/identify/response_templates` with `purpose: "block"`). |
| `empty` | `200` with `{}` or an empty HTML page. Read actions only (`browse`, `search`). |

`rate_limit` keeps `Retry-After` on every kind except `empty`. `empty` is refused when a rule can match anything but a read action: add a condition `{ "fact": "action", "op": "in", "value": ["browse", "search"] }`. If a request reaches it on another action anyway, the client gets `not_possible`. The verdict's `decision.respond` names the kind the client received, and `fallback` says why when the rule's own kind couldn't be served (a missing template, a request that isn't a read).

```json
{
  "rules": [
    {
      "label": "Retired pages",
      "when": [{ "fact": "path", "op": "matches", "value": "/old/*" }],
      "then": { "action": "block", "respond": { "kind": "page", "status": 404, "template_id": "irt_01JDTESTTEMPLATE00000000000" } }
    },
    {
      "label": "Suspected bots searching",
      "when": [{ "fact": "agent.class", "op": "eq", "value": "suspected_bot" }, { "fact": "action", "op": "eq", "value": "search" }],
      "then": { "action": "block", "respond": { "kind": "empty", "content_type": "application/json" } }
    }
  ],
  "respond": { "kind": "message", "message": "This request isn't available." }
}
```

The middleware serves stored pages from its policy bundle, with no fetch per request. A template is refused at delete while a rule names it.

## Errors you might see

| Symptom | Cause | Fix |
| --- | --- | --- |
| `400` [`policy_invalid`](https://provenanceauth.com/docs/platform/errors.md#policy_invalid) | A fact, operator or action isn't one of the documented values | `error.details` names the rule and field. |
| `400` `policy_invalid` with `respond_not_allowed_for_action` | `empty` on a rule that can match checkout, login or another write | Add an `action` condition on `browse` and `search` only. |
| `409` [`response_template_in_use`](https://provenanceauth.com/docs/platform/errors.md#response_template_in_use) | A rule still names the template you're deleting | Change the rule first. |
| `402` [`trial_ended`](https://provenanceauth.com/docs/platform/errors.md#trial_ended) | The Free trial ended, and custom traffic policies are on Pro and up | Choose a plan in **Settings → Plan & usage**; see [plans and usage](https://provenanceauth.com/docs/account/plans-and-usage.md#free-trial). |
| A rule never matches a signed agent | The agent isn't registered with Provenance, so it has no `agent_category` | Match on `agent_directory` or `operator` instead. |

## See also

- [Require a human](https://provenanceauth.com/docs/identify/guides/require-a-human.md)
- [Backtest traffic rules](https://provenanceauth.com/docs/identify/guides/backtest-traffic-rules.md)
- [Traffic rule suggestions](https://provenanceauth.com/docs/identify/guides/traffic-rule-suggestions.md)
- [Policies](https://provenanceauth.com/docs/concepts/policies.md): the shared engine, lists and versions
- [Traffic assessment](https://provenanceauth.com/docs/identify/concepts/traffic-assessment.md)
