# Ask the realm

> Your own API or gateway sends who, what and which action, and the realm's policies answer yes or no, one at a time or in a batch, or list who they would allow.

When your API or a proxy of your own is the enforcement point, it can ask the realm for each decision. It sends who is
calling, what they want to act on and the action, and the realm answers yes or no from its policies, with the reason.
The answer is always current, and the realm reads the caller's groups itself, so a policy about a group is decided
exactly. The cost is one call to the realm per decision, and a decision waits on the realm being reachable.

The realm also answers the reverse question, *who may do this?*, a page at a time. Asking the realm is available
today, with or without the gateway.

## Before you begin

- **A client for your enforcement point**, with the scope `access:evaluate` (and `access:search` to search):
  registering it takes a realm administrator in a group holding `RealmOwner`, with the API.
- **Policies to decide by**, in a policy set: see [Policies](/workforce-identity/authorization/policies/).
- **Token verification in your enforcement point.** The realm decides what it's told; it doesn't verify the caller's
  token for you.

## How it works

Your enforcement point asks the realm, at the realm's own host:

| Address | What it answers |
|---|---|
| `POST /access/v1/evaluation` | One decision |
| `POST /access/v1/evaluations` | Several, in order |
| `POST /access/v1/search/subject` | The users or agents a decision would allow |
| `POST /access/v1/search/action` | The actions a decision would allow |
| `GET /.well-known/authzen-configuration` | Where each is, for an enforcement point to find |

A request names the **subject**, the **resource**, the **action** and a **context**:

```json
{
  "subject":  { "type": "user", "id": "<maya>",
                "properties": {
                  "claims": { "sub": "<maya>", "scope": "payments:send", "act": { "sub": "<agent id>" } },
                  "groups": ["finance"] } },
  "resource": { "type": "url", "id": "https://pay.example.com:443/invoices/4471" },
  "action":   { "name": "POST" },
  "context":  { "policySet": "default", "scopes": ["payments:send"], "ip": "203.0.113.7" }
}
```

- **`subject.properties`** carries the caller as you know it: the verified token's `claims` and, if you choose, the
  caller's `groups`. The actor making the call is the outermost agent in `act`.
- **`resource.type`** names a resource type; only that type's policies are candidates.
- **`context.policySet`** names the set (`default` when absent). `scopes`, `ip` and `time` feed the conditions.

The answer is AuthZEN's boolean, with the reason beside it:

```json
{ "decision": false, "context": { "reason": "policy_denied", "decidingPolicy": "no-payments-at-night" } }
```

`context` may also carry `advices` (what would have passed, such as the scopes a condition needs), `attributes`
(returned with an allow) and `pendingConditions`. The reasons are on
[Policies](/workforce-identity/authorization/policies/#how-a-decision-is-reached).

A batch takes `defaults`, a list of `evaluations` that override them, and `options.evaluations_semantic`:
`execute_all` (the default), `deny_on_first_deny` or `permit_on_first_permit`. An `x-request-id` header is echoed
back.

### Search

A search names everything but the one it looks for, which it gives by `type` alone. Each result is decided as an
evaluation would decide it, so evaluating it answers `true`.

```json
{ "subject": { "type": "user" },
  "resource": { "type": "url", "id": "https://pay.example.com:443/invoices/4471" },
  "action": { "name": "POST" },
  "context": { "policySet": "default" },
  "page": { "limit": 25 } }
```

```json
{ "results": [{ "type": "user", "id": "<maya>" }], "page": { "next_token": "eyJ…", "count": 1 } }
```

- **Subjects** are the realm's users (`user`) or agents (`agent`), each by the user's or agent's id. Their groups are
  read by the realm, so a policy about a group finds its members. A search sends no claims, so a policy that needs a claim
  finds no one.
- **Actions** are the resource type's own. One page holds them all.
- **Resources aren't searched.** A resource is a pattern on a policy, not something the realm holds a list of.
  `/access/v1/search/resource` answers `404`, and the metadata doesn't name it.
- **Pages.** `page.limit` is 25 by default, at most 100. A page decides at most `searchCandidates` users or agents
  (500 by default), then answers, so a page can hold fewer results than its limit, or none, and still give a
  `next_token`. Send it back as `page.token` with the rest of the request unchanged, until `next_token` is `""`. The
  token is sealed by the realm and lasts `searchPageTokenSecs` (300 seconds by default). One sent with a changed
  request, past its time, or not made by the realm is refused. There's no snapshot: a user added or removed between
  pages may be missed or met twice.

## Set it up

1. **Register your enforcement point** as a client of its own, here `orders-pep`, that may ask (and search, if you
   want it to):

   ```sh
   curl "https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client?id=orders-pep" \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "status": "active",
           "tokenEndpointAuthMethod": "client_secret_basic",
           "clientSecret": "<a long random secret>",
           "grantTypes": ["client_credentials"],
           "scopes": ["access:evaluate", "access:search"],
           "defaultScopes": ["access:evaluate"],
           "allowedResources": ["https://foobar.cvyuh.com/access/v1"],
           "defaultAudience": "https://foobar.cvyuh.com/access/v1" }'
   ```

   [Call the API](/develop/api/) shows how to get `$CVYUH_SESSION`.

2. **Get its token**, good for five minutes:

   ```sh
   TOKEN=$(curl -s https://foobar.cvyuh.com/oauth2/token -u "orders-pep:<the secret>" \
     -d grant_type=client_credentials | jq -r .access_token)
   ```

3. **For each request, verify the caller's token yourself, then ask** with its claims:

   ```sh
   curl https://foobar.cvyuh.com/access/v1/evaluation \
     -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" \
     -d '{ "subject": { "type": "user", "id": "<maya>", "properties": { "claims": { "sub": "<maya>", "scope": "invoices:read" } } },
           "resource": { "type": "url", "id": "https://api.example.com:443/invoices/4471" },
           "action": { "name": "GET" },
           "context": { "policySet": "default" } }'
   ```

4. **Refuse unless the answer's `decision` is `true`.**

## Good to know

- **Who may ask.** A bearer access token of this realm whose audience is `https://foobar.cvyuh.com/access/v1` and whose
  scope holds `access:evaluate`; or a realm administrator's session with `READ` on the realm. A request with a bearer
  is judged by the bearer alone. **A search needs `access:search`**, which `access:evaluate` doesn't include: a list of
  who may do something discloses far more than one decision.
- **It decides what it's told.** It doesn't verify the caller's token: verify it first, then send its claims.
- **It finds the groups you leave out.** With no `groups` key, the realm reads the subject's groups itself, by `type`
  (`user` or `agent`) and the user's or agent's id in `id`. A `groups` key you send is used as sent, an empty list
  included. **An agent holds no groups**, so a policy about a group doesn't apply to an agent's own token.
- **Only a principal that stands is allowed.** A user who isn't `active`, or an agent that's quarantined, killed or
  retired, is answered `false` with `subject_not_active` before any policy is read, at evaluation and at search.
- **Fails closed.** A set with a policy left out can't allow (`policies_excluded`). A set or resource type that
  doesn't exist is an error, never an allow. A realm holding more than 10,000 policies, policy sets or resource types
  answers an error, never a decision on a partial set.
- **No resource search.** The realm answers *who* and *which actions*, never *which resources*: see
  [Search](#search).

## Limits and defaults

| What | Default | Range |
|---|---|---|
| Search page size (`page.limit`) | 25 | Up to 100 |
| Users or agents one search page decides (`searchCandidates`) | 500 | Up to 5000 |
| A search page token's life (`searchPageTokenSecs`) | 300 seconds | 10 to 3600 |
| Policies, policy sets or resource types in a realm | — | Up to 10,000 of each; past that, decisions are an error |
| A user's own allows on the trail (`auditDecisions`) | `agents`: not recorded | `all` |

## What your enforcement point sees when it fails

| Status | Why | What to do |
|---|---|---|
| `400` | The request lacks `subject`, `resource` or `action` | Send all three |
| `401` | The token is missing, expired or for another audience | Get a token for `https://foobar.cvyuh.com/access/v1` |
| `403` | The token lacks `access:evaluate`, or `access:search` for a search | Add the scope to the client |
| `404` | The policy set or resource type doesn't exist | Check `context.policySet` and `resource.type` |
| `503` | The realm holds more policies than one decision reads, or couldn't answer | Refuse the request; reduce the policies |

Whatever goes wrong, refuse unless the answer is `200` with `decision: true`.

## Audit record

Every deny is a `POLICY_DECIDED` record on the subject's audit trail, and so is every decision an agent is in, as the
asker or the actor. A user's own allows are recorded when `auditDecisions` is `all`. Every search is one
`POLICY_DECIDED` record: what was asked, how many were decided and how many came back. See
[Record every policy decision](/audit-reports/guides/record-every-policy-decision/).

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| A policy about a group never allows an agent | Agents hold no groups | Write the policy on the agent, or on a claim its token carries |
| A search finds no one for a policy on a claim | A search sends no claims | Search on policies about users, agents or groups |
| A search page is empty but has a `next_token` | The page decided its share of candidates and found none | Send the token back until `next_token` is `""` |
| An allow is `false` with `policies_excluded` | A policy in the set is incomplete, so the realm left it out | Link the policy to its set and its type, or delete it |

## Reference

### Settings

| Where | Setting | What it does |
|---|---|---|
| Your enforcement point's `oauth2Client` | `client_credentials`, scopes `access:evaluate` and `access:search`, resource `https://foobar.cvyuh.com/access/v1` | Lets it ask, and search |
| Realm, `authorizationSettings` | `auditDecisions` (`agents`) | Whether a user's own allows go on the trail too (`all`) |
| Realm, `authorizationSettings` | `searchCandidates` (`500`, up to `5000`) | How many users or agents one search page decides |
| Realm, `authorizationSettings` | `searchPageTokenSecs` (`300`, `10` to `3600`) | How long a search's page token resumes it |

## Related

- [Decide locally](/gateway/decisions/decide-locally/): hold the policies and decide in process instead.
- [Policies](/workforce-identity/authorization/policies/): what is decided.
- [Check a token at your API](/gateway/guides/check-a-token-at-your-api/): verifying the token first.
