# Writing security rules

> **Sentinel v2 (beta):** This page documents Sentinel v2, a beta rewrite that may change before the stable release. It does not apply to Sentinel v1, the current stable version: see the [Sentinel v1 documentation](/docs/sentinel.md).

A cookbook of security-group rules for common goals. Each recipe shows the goal, the rule JSON, how it works, and how to test it before it takes effect. For how rules are evaluated, see [Security groups & rules](/docs/sentinel/v2/concepts/security-groups/). For every field, operator and limit, see the [Rules reference](/docs/sentinel/v2/reference/rules/).

Several recipes are also available as ready-made templates in the admin UI. See [Presets](/docs/sentinel/v2/policies/presets/). A preset writes ordinary rules, so you can combine it with the recipes below.

## Apply rules

A security group holds up to 100 rules. Every update replaces the whole list, so send all of the group's rules, not only the one you changed.

**In the admin UI**, open **Security groups**, select the group, and edit the JSON array under **Rules** on the **JSON** tab. The **Chart** tab shows how the rules run, **Templates** applies presets, and **Activity** counts how often each rule acted. Changes take effect when you save the group.

**With the API**, send the list to `PATCH /v2/security-groups/<id>` with an admin session:

```bash
curl -X PATCH 'https://sentinel.example.com/v2/security-groups/sgr_…' \
-H 'Authorization: Bearer <jwt>' \
-H 'Content-Type: application/json' \
-d '{ "rules": [ { "name": "origins", "action": "allow", "message": "Origin not allowed.", "conditions": [ { "field": "origin", "operator": "=", "value": ["https://example.com", "https://*.example.com"] } ] } ] }'
```

```json
{
"data": {
"id": "sgr_…",
"accountId": "acc_…",
"name": "Website",
"access": "public",
"rules": [{ "name": "origins", "action": "allow", … }],
…
}
}
```

Sentinel validates the rules before saving. An invalid list is rejected with `400 INVALID_RULES`, and `error` points to the problem:

```json
{
"code": "INVALID_RULES",
"error": "rules[0].conditions[0].value[0]: unknown network 'datacenter' (use fixed, mobile, hosting, proxy or tor)",
"statusCode": 400
}
```

See the [security groups API reference](/sentinel-api-docs-v2.html#tag/security-groups) for the request and response schema. To create a group with its rules, send `rules` with `POST /v2/security-groups`.

## How to test a rule

Test a new rule in two ways: run it in monitor mode against real traffic, and check it against a single request with `GET /v2/inspect`.

### Monitor mode

Add `"monitor": true` to a rule to evaluate it without effect. A monitored rule never denies, allows or stops evaluation, and its `set` entries aren't applied. When it *fires* (it would have acted), Sentinel records the rule's name in the request log's `context.monitor`, for API keys with request logging on. In the admin UI, the rule's **Activity** shows these counts, and **Monitor only (no effect)** toggles the flag.

```json
{
"name": "blocked-countries",
"action": "deny",
"monitor": true,
"message": "Not available in your country.",
"conditions": [{ "field": "country", "operator": "=", "value": ["high_risk"] }]
}
```

When the counts look right, remove the flag. Monitored rules are validated like live ones, so the list still saves. See [Monitor mode](/docs/sentinel/v2/reference/rules/#monitor-mode) for what *fires* means per action.

### Inspect with a rule trace

`GET /v2/inspect` shows how the API key's security group sees the caller: device, IP, network, location, `risk` and `penalty`. With `[inspect] security_rules` on, it also returns `securityRules`, the result of every rule in order:

```toml
[inspect]
enabled = true
security_rules = true   # debugging only: callers see which conditions they trip
```

See [`[inspect]`](/docs/sentinel/v2/reference/configuration/#inspect). Call it with the key whose group you're testing, and simulate the request with headers: `Origin` or `Referer` for `origin` and `headers` conditions, `Accept-Language` for `language`, `User-Agent` for device signals. The only query parameter is `timeZone`, which affects `location` and `risk`. The client IP, and with it `country`, `network` and threat conditions, is the IP you call from.

```bash
curl 'https://sentinel.example.com/v2/inspect?apiKey=key_…' \
-H 'Origin: https://evil.example'
```

A request that the rules deny still returns the inspect data, next to the `403 ACCESS_DENIED` error:

```json
{
"code": "ACCESS_DENIED",
"error": "Origin not allowed.",
"statusCode": 403,
"data": {
"ip": "203.0.113.7",
"risk": 0,
"penalty": 0,
"securityRules": [
  {
    "index": 0,
    "name": "origins",
    "action": "allow",
    "monitor": false,
    "evaluated": true,
    "matched": false,
    "outcome": "deny",
    "risk": null,
    "riskRules": null,
    "penalty": null,
    "conditions": [{ "field": "origin", "matched": false, "signals": null }]
  },
  {
    "index": 1,
    "name": "base",
    "action": "set",
    "monitor": false,
    "evaluated": false,
    "matched": null,
    "outcome": null,
    …
  }
],
…
}
}
```

| Field | Type | Description |
| --- | --- | --- |
| `index`, `name`, `action`, `monitor` | | The rule's position (from 0) and its fields. |
| `evaluated` | boolean | `false` for rules after the deciding one; their other fields are `null` or empty. |
| `matched` | boolean | Whether the rule's conditions held. For `allow`, `true` means the gate passed. |
| `outcome` | string | `continue`, `deny` or `allow` (a matching `accept`). For a monitored rule, what it would have done. |
| `risk`, `riskRules` | number, array | The risk a `risk` condition saw and the classifier rules behind it; `null` without a `risk` condition. |
| `penalty` | number | The penalty a `penalty` condition saw, from before this request; `null` without one. |
| `conditions` | array | Each condition's `field` and whether it `matched`, with the triggered `signals` for `signal` conditions. |

The request's path is `/v2/inspect`, so a rule with a `path` condition such as `/v2/verify` doesn't match here. Turn `security_rules` off again when you're done: it shows any caller how your rules evaluate.

## Allow-list your origins

**Goal:** a `public` widget key works only on your own sites.

```json
[
{
"name": "origins",
"action": "allow",
"message": "Origin not allowed.",
"conditions": [
  { "field": "origin", "operator": "=", "value": ["https://example.com", "https://*.example.com"] }
]
}
]
```

`allow` is a gate: a request whose origin matches none of the values is denied with `403 ACCESS_DENIED` and this `message`, and every other request continues to the next rule. The origin comes from `Origin`, or from `Referer` when `Origin` is absent, reduced to `scheme://host[:port]`. `*` matches any subdomain. A request with neither header is denied, so native apps and server-side callers need their own group or an `accept` rule before this one. Put the gate first, so other rules only run for your sites.

`Origin` is set by the client. This rule keeps your key off other websites, but scripts can send any header.

**Test:** call `/v2/inspect` with `-H 'Origin: https://www.example.com'` and with `-H 'Origin: https://evil.example'`. The first returns `200`, the second `403` with `"outcome": "deny"` on `origins`. The **Allowed origins** template writes the same rule.

## Block countries

**Goal:** deny requests from countries you don't serve.

```json
[
{
"name": "blocked-countries",
"action": "deny",
"message": "Not available in your country.",
"conditions": [{ "field": "country", "operator": "=", "value": ["high_risk", "by ru"] }]
}
]
```

The country is the client IP's, from the [IP resolvers](/docs/sentinel/v2/configure/ip-resolvers/). Values are ISO 3166-1 alpha-2 codes or the lists `high_risk` and `eu`; one value can hold several codes separated by spaces, commas or semicolons. An IP with no known country doesn't match `=`, so it passes. A VPN changes the country.

To challenge these countries instead of blocking them, use a `set` rule with `codeChallenge.enabled`, as in the next recipes.

**Test:** add `"monitor": true` first and watch the rule's **Activity**. `/v2/inspect` shows the country Sentinel resolved for your IP under `location` and `network`; the `country` condition's `matched` shows whether it held. The **Country block** and **Country challenge** templates cover this recipe.

## Challenge harder on penalty

**Goal:** a client that keeps failing gets harder challenges, and is blocked at the top of the scale.

```json
[
{
"name": "penalty-elevated",
"action": "set",
"conditions": [{ "field": "penalty", "operator": ">=", "value": ["3"] }],
"set": [
  { "field": "pow.counter", "value": "1-30000" },
  { "field": "codeChallenge.enabled", "value": "true" }
]
},
{
"name": "penalty-high",
"action": "set",
"conditions": [{ "field": "penalty", "operator": ">=", "value": ["6"] }],
"set": [
  { "field": "pow.algorithm", "value": "ARGON2ID" },
  { "field": "pow.cost", "value": "3" },
  { "field": "pow.counter", "value": "1-200" },
  { "field": "codeChallenge.length", "value": "6-8" },
  { "field": "codeChallenge.imageDifficulty", "value": "high" }
]
},
{
"name": "penalty-block",
"action": "deny",
"message": "Too many failed attempts.",
"conditions": [{ "field": "penalty", "operator": ">=", "value": ["9"] }]
}
]
```

The penalty is a 0–10 score per account and client IP that grows with failed verifications, rate-limit hits and other signals, and expires after `[penalty] ttl`. See [Scores, risk & penalty](/docs/sentinel/v2/concepts/scoring/). Rules see the penalty from before the current request.

`set` rules accumulate, so the order matters. From 3, the client gets a higher PBKDF2 counter and a [code challenge](/docs/sentinel/v2/features/code-challenge/). From 6, the second rule also matches and overwrites the proof-of-work with memory-hard Argon2id and a longer, harder code. It sets `pow.algorithm` and `pow.cost` in the same rule, because a `pow.cost` must fit its algorithm. From 9, the request is denied. To escalate by risk as well, add a `risk` condition with `"conditionsOperator": "or"`.

**Test:** `/v2/inspect` returns the current `penalty`, and each rule's trace shows the `penalty` its condition saw. To raise your own penalty on a test key, fail a few verifications. See [Proof-of-work](/docs/sentinel/v2/features/proof-of-work/) for the cost of each algorithm before you raise it.

## Force the code challenge for hosting IPs

**Goal:** require the code challenge from data centers, proxies and Tor, where most automated traffic comes from.

```json
[
{
"name": "hosting-code",
"action": "set",
"conditions": [{ "field": "network", "operator": "=", "value": ["hosting", "proxy", "tor"] }],
"set": [
  { "field": "codeChallenge.enabled", "value": "true" },
  { "field": "codeChallenge.audio", "value": "false" }
]
}
]
```

`network` matches the flags the IP resolvers report for the client IP: `hosting`, `proxy`, `tor`, `mobile`, or `fixed` (flags known, none set). Each flag matches on its own, so a Tor exit in a data center matches both `tor` and `hosting`. Without a network flag for the IP, `=` doesn't match. Turning off the audio code leaves only the image, which is harder for speech-to-text bots; leave it on if your visitors rely on audio.

**Test:** `/v2/inspect` lists the IP's flags under `network`. Call it from a cloud VM to see the condition match. Put this rule after any `penalty` rules that also set `codeChallenge.*` if you want it to win.

## Exempt verified agents

**Goal:** let search crawlers that sign their requests with Web Bot Auth through without escalation, and deny agents whose signature doesn't verify.

```json
[
{
"name": "verified-agents",
"action": "accept",
"conditions": [
  { "field": "agent", "operator": "=", "value": ["verified"] },
  { "field": "agent", "operator": "!=", "value": ["ai_training", "user_fetch"] }
]
},
{
"name": "unverified-agents",
"action": "deny",
"message": "Signature not verified.",
"conditions": [{ "field": "agent", "operator": "=", "value": ["unverified"] }]
}
]
```

A verified agent matches `verified`, its name and its kind (`crawler`, `ai_training`, `ai_search`, `user_fetch`). The first rule accepts verified agents that aren't AI training crawlers or user-driven fetchers; `accept` allows the request and skips every later rule, rate limits included. The second denies requests whose signature fails verification. Unsigned requests match neither rule. Put both rules at the top of the list, so the exemption runs before your gates and escalation.

**Test:** an unsigned `/v2/inspect` call shows both `agent` conditions with `"matched": false`. A verified agent shows `"outcome": "allow"` on `verified-agents`. See [Bots & AI agents](/docs/sentinel/v2/features/bots-agents/) for the agents Sentinel knows. The **Verified agents** template writes the first rule.

## Classify each form differently

**Goal:** classify form fields on every form, but tune the classifier per form: accept free email providers on the sign-up page, and check that contact-form messages are on topic.

```json
[
{
"name": "forms",
"action": "set",
"set": [{ "field": "classifier.fields", "value": "true" }]
},
{
"name": "signup-form",
"action": "set",
"conditions": [{ "field": "headers", "operator": "=", "value": ["Referer: https://example.com/signup*"] }],
"set": [{ "field": "classifier.disableRules", "value": "FREE_PROVIDER PRIVACY_RELAY" }]
},
{
"name": "contact-form",
"action": "set",
"conditions": [{ "field": "headers", "operator": "=", "value": ["Referer: https://example.com/contact*"] }],
"set": [
  { "field": "classifier.ai", "value": "true" },
  { "field": "classifier.aiPurpose", "value": "Questions from customers about our products and orders." }
]
}
]
```

`classifier.fields` makes the widget send the form's fields to `POST /v2/verify`, which then signs the email, text and injection results along with the solution. The widget calls `/v2/challenge` and `/v2/verify` from the page, so the `Referer` header carries the page URL. The `origin` condition reduces it to `scheme://host`, so use a `headers` condition with a wildcard pattern to match the path. `classifier.disableRules` replaces any earlier value, so repeat names you disabled in earlier rules. `classifier.ai` needs a configured AI provider; see [AI decider](/docs/sentinel/v2/features/ai-decider/).

The `Referer` is sent by the browser and can be stripped by a `Referrer-Policy` of `no-referrer` or `origin`. If your forms are on separate sites, match on `origin` instead; if they're on one page, use one API key per form, each in its own security group. All `classifier.*` fields are listed in [Set fields](/docs/sentinel/v2/reference/rules/#set-fields).

**Test:** call `/v2/inspect` with `-H 'Referer: https://example.com/signup/'` and check that `signup-form` shows `"matched": true`. The **Form fields** template writes the `forms` rule.

## Restrict a backend key to your servers

**Goal:** a `restricted` key used by your backend (`/v2/classifier`, `/v2/ip`, `/v2/threat`, …) works only from your servers' IPs.

```json
[
{
"name": "backend-ips",
"action": "allow",
"message": "IP not allowed.",
"conditions": [{ "field": "ip", "operator": "=", "value": ["203.0.113.10", "10.0.0.0/8"] }]
},
{
"name": "base",
"action": "set",
"set": [
  { "field": "rateLimit.limits", "value": "600/1m(key=uid)" },
  { "field": "rateLimit.scope", "value": "account" }
]
}
]
```

Use this list in a group with `access` `restricted` or `full`. The gate denies every IP outside the listed addresses and CIDR ranges (IPv4 or IPv6), so a leaked key and secret are useless elsewhere. The client IP is resolved per `[server] trusted_proxies` and `client_ip_header`; behind a proxy, list your servers' real addresses and configure the proxy as trusted. See [Listeners](/docs/sentinel/v2/configure/listeners/). `key=uid` with `rateLimit.scope` `account` makes the 600 requests per minute one budget for all the account's backend keys, whatever IP they come from. The global `[rate_limit] global` limit per client IP applies before the rules; raise it above your backend's request rate.

**Test:** call `/v2/inspect` with the backend key from a server and from your laptop:

```bash
curl 'https://sentinel.example.com/v2/inspect' -u 'key_…:sec_…'
```

The server gets `200`, your laptop `403 ACCESS_DENIED` with `IP not allowed.`. The **Backend API (allowed IPs)** template writes the same rules.

## Related

- [Security groups & rules](/docs/sentinel/v2/concepts/security-groups/)
- [Rules reference](/docs/sentinel/v2/reference/rules/)
- [Presets](/docs/sentinel/v2/policies/presets/)
- [Scores, risk & penalty](/docs/sentinel/v2/concepts/scoring/)
- [API keys & access levels](/docs/sentinel/v2/concepts/api-keys/)
- [Code challenge](/docs/sentinel/v2/features/code-challenge/)
- [Bots & AI agents](/docs/sentinel/v2/features/bots-agents/)
- [Configuration reference: `[inspect]`](/docs/sentinel/v2/reference/configuration/#inspect)
