# Policies

> Say who may take which action on which API address, MCP tool or other resource, and when, with one deny refusing whatever else allows.

A policy is one rule: *agents may `GET` anything under `/invoices/`*, or *nobody may `DELETE` an order*. You write
policies in the realm, and every enforcement point in front of your APIs reads the same ones, so changing who may do
what is a change in the realm, never in your API's code.

Policies decide calls: an HTTP method on an address, or an MCP tool, resource or prompt by name. What a user or agent
*holds*, and so which scopes their tokens carry, is decided by [entitlements](../entitlements/). The two work together:
a policy can require a scope that only an entitlement grants.

## Before you begin

- **Who can do it:** a realm administrator, in a group that holds `RealmOwner`
  ([Delegated administration](/platform/realms/delegated-administration/)). `RealmViewer` can read policies.
- **Where:** today this is done through the API ([Call the API](/develop/api/) shows how to get `$CVYUH_SESSION`).
- **First:** an enforcement point in front of your API that asks the realm or holds its policies: the gateway, or
  your own code ([Ask the realm](/gateway/decisions/ask-the-realm/)). A policy no enforcement point reads decides
  nothing.

## A policy, start to finish

This policy, in the realm's `default` set and on the `url` resource type, is all it takes to let agents read invoices:

```json
{
  "active": true,
  "resources": ["*://*:*/invoices/*"],
  "actionValues": { "GET": true, "DELETE": false },
  "subject": { "type": "JwtClaim", "claimName": "principal_type",
               "claimValue": "agent" },
  "condition": { "type": "OAuth2Scope", "requiredScopes": ["invoices:read"] }
}
```

What it decides, for any address under `/invoices/` on your API:

- **An agent whose token holds `invoices:read`** may `GET` it, and is refused `DELETE` (`policy_denied`), even if
  another policy would allow it.
- **An agent without the scope** isn't allowed: the refusal names `invoices:read` as what would pass.
- **A user**, or any call this policy doesn't cover, is refused (`no_matching_policy`) unless another policy allows
  it.

## How it works

A realm keeps three kinds of object for this, managed like any other object in the realm:

- A **resource type** (`resourceType`) is a kind of thing a policy can be about: the `patterns` its resources fall
  within, and the `actions` it has.
- A **policy set** (`policySet`) is a group of policies an enforcement point asks for by name. It names the resource
  types it guards, how resources match (`comparator`), and which kinds of subject and condition its policies may use.
- A **policy** (`policy`) belongs to one set and one type, and says who may or may not take which actions on which
  resources, and when.

Every realm is born with the resource type `url` (any `http` or `https` address, with the actions `GET`, `POST`,
`PUT`, `DELETE`, `HEAD`, `OPTIONS` and `PATCH`) guarded by the policy set `default`. It's also born with the type
`delegation` and its set `delegation`, for [agents acting for users](../../agents/acting-for-users/), and the type `client` and
its set `issuance`, for the [issuance policy](../issuance-policy/). Every set is born empty, and an empty set allows
nothing.

### What a policy says

- **`resources`**: the patterns it covers, within its type's patterns.
- **`actionValues`**: each action with `true` to allow or `false` to deny.
- **`subject`**: who it applies to. Any signed-in caller (`AuthenticatedUsers`), named users, agents or groups
  (`Identity`), a token claim with a value (`JwtClaim`), or `AND`, `OR` and `NOT` of these.
- **`condition`**, optional: when it applies. By default a set allows what an enforcement point knows from the request
  and its token: the **scopes** the token holds (`OAuth2Scope`), the exact actions its **authorization details**
  carry (`OAuth2AuthorizationDetails`, in the same bounds an entitlement uses: see [Rich authorization requests](../rich-authorization-requests/)), the
  caller's **IPv4 or IPv6 address** (at the gateway, the address that connected to it: behind a TLS front end, the
  front end's; see [Run the gateway](/gateway/protect-apis/run-the-gateway/#good-to-know)), and a **time window**
  (times, days, dates, a time zone), with `AND`, `OR` and
  `NOT` of these. A set may also allow conditions on the **sign-in** behind the token (its level, its method, its
  chain, its realm, how long ago), on the **session**, and on the caller's **group membership**.
- **`resourceAttributes`**, optional: values returned with an allow.
- **`active`**: an inactive policy takes no part in any decision.

### How a decision is reached

Every active policy of the set and of the resource's type is evaluated, and they combine **deny-overrides**: one deny
refuses, whatever else allows. The answer is one of five, and every refusal says which:

| `reason` | Allowed | Meaning |
|---|---|---|
| `allow` | Yes | A policy allowed it and nothing denied it |
| `policy_denied` | No | A policy denied it. The answer names the policy |
| `no_matching_policy` | No | Nothing allowed it |
| `condition_pending` | No | An allow stood, but a condition or subject couldn't be decided, and it might have been a deny |
| `policies_excluded` | No | An allow stood, but the set has a policy left out (see [Good to know](#good-to-know)), which might have been a deny |

Where a condition names what would have passed, such as the scopes a call needs or a stronger sign-in, the answer
carries it as advice, so an enforcement point can tell the caller what to get.

### How addresses and names match

A set's `comparator` decides how a requested resource is matched against a policy's patterns:

- **`prefix`** (the default) matches segment by segment and ignores case, as web addresses want. `*` stands for
  anything, and `-*-` for exactly one path segment. Write `/invoices/*` to cover everything under `/invoices/`.
- **`regex`** matches the whole name, with `*` for anything, and **respects case**, as tool and object names want.
  Start a pattern with `(?i)` to ignore case. Use it for [MCP tool calls](/gateway/mcp-servers/mcp-tool-calls/).

A requested resource is always concrete: a request whose resource holds `*` matches no policy.

## Set it up

Each call sends your session as `$CVYUH_SESSION` ([Call the API](/develop/api/)).

1. Write the policy:

   ```sh
   curl -X POST "https://foobar.cvyuh.com/api/v0/am/objects/v1/policy?id=invoices-read" \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "active": true,
           "resources": ["*://*:*/invoices/*"],
           "actionValues": { "GET": true },
           "subject": { "type": "JwtClaim", "claimName": "principal_type", "claimValue": "agent" } }'
   ```

2. Link it to its set and its type:

   ```sh
   curl -X POST https://foobar.cvyuh.com/api/v0/am/objects/v1/policy/invoices-read/relationships/policySet \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "targetId": "default" }'

   curl -X POST https://foobar.cvyuh.com/api/v0/am/objects/v1/policy/invoices-read/relationships/resourceType \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "targetId": "url" }'
   ```

   To guard against someone else's change in between, send the policy's revision as `If-Match: "<rev>"`.

3. Point an enforcement point at the set: the gateway's `POLICY_SET` (see
   [Run the gateway](/gateway/protect-apis/run-the-gateway/#settings)), or `context.policySet` when your API asks the realm
   (see [Ask the realm](/gateway/decisions/ask-the-realm/)).

Create the policy first, then link it to its set and type, as above. For your own kinds of resource, write a
`resourceType` with its `patterns` and `actions`, and a `policySet` that names it, before the policies.

### Test a policy before it decides

There's no report-only mode and no simulation: a policy that is `active` and in a set an enforcement point reads
decides real calls at once. To try one safely, write it with `"active": false`, or in a test set no enforcement point
reads, and ask the realm's decision API what it would answer. See
[Test a policy safely](../../guides/access-policies/test-a-policy-safely/).

## What the caller sees

A call a policy refuses is refused by the enforcement point: the gateway answers `403`, with the scopes or the
stronger sign-in that would pass when a condition names them (see [Step-up and
re-authentication](../../applications/single-sign-on/step-up/)). The realm's decision API answers `"decision": false`
with the `reason` from the table above, and the deciding policy for a deny.

## Limits and defaults

| Setting or limit | Default | Range |
|---|---|---|
| Resource types and sets in a new realm | `url` with `default`, `delegation` with `delegation`, `client` with `issuance` | add your own |
| A new set's policies | none: an empty set allows nothing | |
| `comparator` | `prefix` | `prefix` or `regex` |
| `active` | as written | `true` or `false` |
| `auditDecisions` | `agents` | `agents` or `all` |
| Policies, policy sets or resource types in a realm | | up to 10,000 of each; past that, decisions are an error |
| `conditionTypes` of a new set | scopes, authorization details, IPv4, IPv6, time, `AND`, `OR`, `NOT` | add sign-in, session and group conditions |

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| Every call is refused with `no_matching_policy` | The set is empty, or the policy isn't linked to the set and type, or it's inactive | Link it to its set and type, and set `active: true` |
| Refusals say `policies_excluded` | A policy in the set breaks the set's rules, so it's left out | Find the policy that no longer fits its type's patterns or actions, or the set's subject and condition kinds, and fix it |
| Refusals say `condition_pending` | A condition couldn't be decided where it was asked, such as groups when only a token is held | Ask the realm's decision API, which reads groups itself |
| Linking a policy answers `400` | Its resources, actions, subject or condition don't fit the set or type | Read the message; change the policy or widen the set |
| A rule works for some addresses and not others | The pattern doesn't match the way you expect | With `prefix`, `*` is anything and `-*-` is one segment; with `regex`, case counts |

## Audit record

A change to a policy, set or resource type is recorded as `CREATED`, `UPDATED`, `PATCHED` or `DELETED` in
**Audit → Config** ([Change history](/audit-reports/audit-trail/change-history/)). Each decision the realm makes is
recorded as `POLICY_DECIDED`: every deny, and every decision with an agent in it; set `auditDecisions` to `all` to keep
a user's own allows too (**Audit → Authentication**).

## Good to know

- **Nothing decided is nothing allowed.** A set with no policies allows nothing, and a set or type that doesn't exist
  is an error, never an allow.
- **An undecided fact never becomes an allow.** A condition type the engine doesn't know never holds, `NOT` of one
  doesn't hold either, and a stored bound that can't be read (a time such as `99:00`) makes the condition fail, never
  widen.
- **Unknown groups are unknown, not empty.** A token carries no groups, so where only a token is held, a policy that
  needs the caller's groups is undecided, and a deny aimed at a group can't silently stop applying. The realm's decision API
  ([Ask the realm](/gateway/decisions/ask-the-realm/)) reads the groups from its own store, and the gateway
  asks it.
- **A policy that breaks its set's rules is refused on write.** Once a policy names both its set and its type, at the
  link that completes it and at every later write, one whose resources fall outside its type's patterns, whose actions
  aren't its type's, or whose subject or condition kinds its set doesn't allow is refused `400`.
- **A policy that breaks them later is left out.** A set or type narrowed after its policies were written, or a policy
  with no set or type, is left out of every decision and counted. That count is why `policies_excluded` exists: a
  missing allow only refuses more, but a missing deny would allow more.
- **The realm decides what it's told.** It doesn't look up a caller's token claims itself: whoever asks for a
  decision sends them.
- **Only conditions the realm can decide.** Conditions that need a directory search, a script or the resource's
  environment can't be used: no set can list them in `conditionTypes`, so a policy that names one is refused when
  it's linked, and never allows.

## Reference

### Fields

| Object | Field | What it sets |
|---|---|---|
| `resourceType` | `patterns`, `actions` | What the type's resources look like, and the actions it has |
| `policySet` | `comparator` | `prefix` (default) or `regex` |
| `policySet` | `subjectTypes`, `conditionTypes` | The kinds of subject and condition its policies may use |
| `policySet` | `resourceTypes` | The types it guards |
| `policy` | `active`, `resources`, `actionValues`, `subject`, `condition`, `resourceAttributes` | The rule itself |
| `policy` | `policySet`, `resourceType` | The set and the type it belongs to, as links |

## Coming next

- **Geolocation conditions:** a rule that holds only for calls from a country or region. See
  [What's next for authorization](../whats-next/#geolocation-conditions).

## Related

- [Common access policies](../../guides/access-policies/common-access-policies/): workforce rules, ready to adapt.
- [Test a policy safely](../../guides/access-policies/test-a-policy-safely/): try a rule before it decides.
- [Open an API to agents](/gateway/guides/open-an-api-to-agents/): a first policy, enforced.
- [Protect an MCP server](../../../gateway/guides/protect-an-mcp-server/): policies per tool.
- [Ask the realm](/gateway/decisions/ask-the-realm/): how an API asks for a decision.
- [Decide locally](/gateway/decisions/decide-locally/): how an enforcement point holds the policies itself.
- [Agents acting for users](../../agents/acting-for-users/): the delegation policy set.
