> ## Documentation Index
> Fetch the complete documentation index at: https://docs.formal.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Policy Evaluation

> Available input data and context at each policy evaluation stage

Policies are evaluated at three stages: **session** (connection time), **request** (before query execution), and **response** (after data retrieval). Each stage provides different input data for making policy decisions.

> [!TIP]
>
> For available enforcement actions at each stage, see [Enforcement](https://docs.formal.ai/docs/guides/policies/enforcement.md). If you have existing policies using `pre_request` / `post_request`, see [Legacy Stage Names](#legacy-stage-names).

## Policy Scope

By default, policies apply universally to all users, resources, and data locations. You can narrow the scope within each policy using conditions.

### User Context Quick Reference

Access user information via `input.user` and `input.end_user`:

| Field | Type | Description |
| - | - | - |
| `id` | **String** | Formal user ID |
| `username` | **String** | Unique username |
| `email` | **String** | Email address (human users only) |
| `groups` | **\[]String** | Group names the user belongs to |
| `group_ids` | **\[]String** | Formal group IDs the user belongs to |
| `type` | **String** | `human` or `machine` |
| `idp.attributes` | **Object** | Custom SSO attributes sent by the identity provider |
| `idp.group_ids` | **\[]String** | Raw IdP group IDs (e.g. Okta group IDs) |
| `oidc.claims` | **Object** | Federated OIDC token claims (machine users only) |
| `oauth` | **Object** | Formal OAuth client and consent (OAuth requests only) |

### Resource Context Quick Reference

Filter by resource via `input.resource`:

| Field | Type | Description |
| - | - | - |
| `id` | **String** | Resource ID |
| `name` | **String** | Resource name |
| `technology` | **String** | `postgres`, `mongodb`, `snowflake`, etc. |
| `hostname` | **String** | Resource hostname |
| `environment` | **String** | Environment tag |

## Policy stages

### Session stage

#### Available inputs

| Name | Type | Description |
| - | - | - |
| policy\_id | **STRING** | ID of the policy evaluated. |
| session | **Session Object** | Formal session identity. Use `input.session.id` for the session ID. |
| application | **Application Object** | Client application. Use `input.application.name` for the application name. |
| client\_network | **Client Network Object** | Client IP address and whether the client connection is encrypted. |
| db\_name | **STRING** | Name of the database. |
| native\_user | **STRING** | Selected Native User label. |
| native\_user\_assignment | **STRING** | How the user was selected: `cel` or `user-requested`. |
| native\_user\_selection | **OBJECT** | Requested Native User and assigned default. Each contains `id`, `label`, and `user_type`. Omitted for direct native sessions. |
| user | **User Object** | The user making a connection to the database. User object includes name, email and groups. |
| end\_user | **User Object** | If the user is a machine user, the end user is the user behind the application, otherwise the end user has the same value as the user. |
| device | **Device Object** | Device information. |
| agent | **Agent Object** | AI agent context. Populated when the connection originates from an AI coding agent via the Formal Endpoint. |
| resource | **Resource Object** | The Resource being queried. |
| connector | **Connector Object** | The current Connector, or empty when the Endpoint evaluates. |
| http | **HTTP Object** | HTTP request details when the technology exposes transport context at session policy. |
| clickhouse | **ClickHouse Object** | ClickHouse named-session context. At this stage, `session_id` is the ClickHouse-specific field available. |
| aws | **AWS Object** | AWS resources **for SSH and Kubernetes**. |
| kubernetes | **Kubernetes Object** | Kubernetes resource context **for Kubernetes**. |
| snowflake | **Snowflake Object** | Snowflake specific information. |
| space | **Space Object** | Space specific information. |

#### Available actions

For this policy stage, these actions are possible:

| Action | Supported on | Effect |
| - | - | - |
| `allow` | All technologies | Lets the connection proceed |
| `block` | All technologies | Refuses the connection |
| `mfa` | Users running the Formal Endpoint | Asks the user for device-owner verification first |
| `quarantine` | SSH, Kubernetes `exec` | Ends the user's sessions and blocks the user until an admin unblocks them |
| `suspend` | SSH, Kubernetes `exec` | Ends the current session |
| `impersonate` | Kubernetes | Forwards requests with Kubernetes impersonation headers |

See [Enforcement](https://docs.formal.ai/docs/guides/policies/enforcement.md) for each action's parameters.

### Tick stage

Tick rules let a policy end an SSH or Kubernetes `exec` session after it has started. Session rules only run once, when the session starts, so they miss anything that changes later. Tick rules keep running on a timer until the session closes.

To use this stage, add two rules to your policy:

* `tick` decides whether to end the session. It gets the same input as a session rule and can return `block`, `quarantine` or `suspend`.
* `tick_interval` is how often to run `tick`, in seconds. Formal reads it once, when the session starts. A session with no interval is never checked.

For example, this policy checks every open SSH session once a minute. It ends the session if the `host_status` [hook](https://docs.formal.ai/docs/guides/policies/hooks.md) reports that the host is now restricted.

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

tick := {
  "action": "block",
  "type": "block_with_formal_message",
  "reason": "This host is restricted"
} if {
  input.hooks.host_status.restricted
}

tick_interval := 60 if {
  input.resource.technology == "ssh"
}
```

### Request stage

Request rules are evaluated by the proxy when it intercepts a request (query) just before sending it to the resource. This evaluation stage is especially useful in blocking write requests.

#### Available inputs

| Name | Type | Description |
| - | - | - |
| policy\_id | **STRING** | ID of the policy evaluated. |
| session | **Session Object** | Formal session identity. Use `input.session.id` for the session ID. |
| request | **Request Object** | Formal request identity. Use `input.request.id` for the request ID. |
| application | **Application Object** | Client application. Use `input.application.name` for the application name. |
| client\_network | **Client Network Object** | Client IP address and whether the client connection is encrypted. |
| sql\_query | **SQL Query Object** | SQL query. |
| query | **SQL Query Object** | Deprecated alias for `sql_query`. |
| db\_name | **STRING** | Name of the database. |
| user\_type | **ENUM** | Underlying type used by the user to connect to the database, can be `formal` or `native`. |
| schema\_paths | **\[]STRING** | List of the schema paths that are accessed by a query. |
| table\_paths | **\[]STRING** | List of the table paths that are accessed by a query. |
| user | **User Object** | The user making a connection to the database. User object includes name, email and groups. |
| end\_user | **User Object** | If the user is a machine user, the end user is the user behind the application, otherwise the end user has the same value as the user. |
| device | **Device Object** | Device information. |
| agent | **Agent Object** | AI agent context. Populated when the connection originates from an AI coding agent via the Formal Endpoint. |
| space | **Space Object** | Space information. |
| row | **\[]Column Object** | Rows of data being queried. |
| resource | **Resource Object** | The Resource being queried. |
| connector | **Connector Object** | The current Connector, or empty when the Endpoint evaluates. |
| http | **HTTP Object** | HTTP request details. Populated for HTTP-based resources, including LLM. |
| integrations | **Integrations Object** | Data from connected integrations. Populated for HTTP requests. See [Integrations object](#integrations-object). |
| clickhouse | **ClickHouse Object** | ClickHouse-specific request context. |
| mongodb | **MongoDB Object** | MongoDB-specific request context. |
| snowflake | **Snowflake Object** | Snowflake specific information. |

#### Available actions

For this policy stage, five types of actions are possible: `allow`, `block`, `mfa`, `rewrite`, and `decrypt`.

### Response stage

Response rules are evaluated by the proxy when it intercepts data received from the resource. This evaluation stage is particularly useful in the context of masking or filtering read requests.

#### Available inputs

| Name | Type | Description |
| - | - | - |
| policy\_id | **STRING** | ID of the policy evaluated. |
| session | **Session Object** | Formal session identity. Use `input.session.id` for the session ID. |
| request | **Request Object** | Formal request identity. Use `input.request.id` for the request ID. |
| application | **Application Object** | Client application. Use `input.application.name` for the application name. |
| client\_network | **Client Network Object** | Client IP address and whether the client connection is encrypted. |
| sql\_query | **SQL Query Object** | SQL query. |
| query | **SQL Query Object** | Deprecated alias for `sql_query`. |
| db\_name | **STRING** | Name of the database. |
| schema\_paths | **\[]STRING** | List of the schema paths that are accessed by a query. |
| table\_paths | **\[]STRING** | List of the table paths that are accessed by a query. |
| row | **\[]Column Object** | Rows of data being queried. |
| user | **User Object** | The user making a connection to the database. User object includes name, email and groups. |
| end\_user | **User Object** | If the user is a machine user, the end user is the user behind the application, otherwise the end user has the same value as the user. |
| device | **Device Object** | Device information. |
| agent | **Agent Object** | AI agent context. Populated when the connection originates from an AI coding agent via the Formal Endpoint. |
| resource | **Resource Object** | The Resource being queried. |
| connector | **Connector Object** | The current Connector, or empty when the Endpoint evaluates. |
| http | **HTTP Object** | HTTP response details. Populated for HTTP-based resources, including LLM. |
| clickhouse | **ClickHouse Object** | ClickHouse response context, including the server-produced output format. |
| snowflake | **Snowflake Object** | Snowflake specific information. |
| space | **Space Object** | Space specific information. |

#### Available actions

For this policy stage, these actions are possible: `allow`, `block`, `filter`, `mask`, `encrypt`, and `rewrite`. `rewrite` at this stage changes HTTP response headers or bodies.

## Standard input data

Policies can access various data types, including user information, resource information, SQL query information, and HTTP request information. The following sections describe the available data types.

### Session object

| Value | Type | Description |
| - | - | - |
| id | **STRING** | Formal session identifier |

### Request object

| Value | Type | Description |
| - | - | - |
| id | **NUMBER** | Formal request identifier within the session. Present at request and response stages. |

### Application object

| Value | Type | Description |
| - | - | - |
| id | **STRING** | ID of the application, when the client sends one |
| name | **STRING** | Name of the client application (e.g. `psql`) |
| environment | **STRING** | Environment of the application, when the client sends one |

### Client network object

| Value | Type | Description |
| - | - | - |
| ip\_address | **STRING** | IP address of the client |
| encrypted\_connection | **BOOLEAN** | Whether the connection between the client and the Connector is encrypted with TLS or SSH |

### User object

| Value | Type | Description |
| - | - | - |
| id | **STRING** | Formal user ID |
| username | **STRING** | Username of the user |
| email | **STRING** | If it's a human user, their email address |
| groups | **\[]STRING** | Groups in which the user is included |
| group\_ids | **\[]STRING** | Formal group IDs of those groups |
| type | **STRING** | Type of the user, can be either `human` or `machine` |
| external\_ids | **\[]STRING** | External IDs linked to the user |
| idp | **Object** | `attributes` (custom SSO attributes) and `group_ids` (raw IdP group IDs) from the identity provider |
| oidc | **Object** | Set on a machine user when the request authenticated with a federated OIDC token. Contains `integration_id` and the token's `claims`, e.g. `input.user.oidc.claims.sub`. See [OIDC integrations](https://docs.formal.ai/docs/guides/integrations/oidc.md). |
| oauth | **Object** | Set when the request authenticated with a Formal OAuth access token. See [OAuth clients](#oauth-clients). |
| spend | **Spend Object** | LLM spend of the user, available in the `request` rule of LLM resources. See [Spend object](#spend-object). |

> [!NOTE]
>
> Logs show OIDC claims under `user.formal.oidc.claims`. Policies and suspension input conditions read them at `input.user.oidc.claims`, without `formal`.

### Spend object

`today`, `this_week` and `this_month` each hold the user's LLM usage in that UTC calendar window. Weeks start on Monday.

| Value | Type | Description |
| - | - | - |
| cost | **map\[STRING]FLOAT** | Estimated cost of priced requests by ISO 4217 currency code, e.g. `{"USD": 12.5}`. Empty when nothing was spent |
| token\_count | **INT** | Input plus output tokens of all requests, cache and reasoning included |

Use `object.get(input.user.spend.today.cost, "USD", 0)` to read one currency, since a currency is absent until it has spend.

### Connector object

| Value | Type | Description |
| - | - | - |
| id | **STRING** | ID of the Connector |
| name | **STRING** | Name of the Connector |

### Resource object

| Value | Type | Description |
| - | - | - |
| id | **STRING** | ID of the Resource |
| name | **STRING** | Name of the Resource |
| technology | **STRING** | Technology of the Resource |
| hostname | **STRING** | Hostname of the Resource |
| hostname\_name | **STRING** | Name of the Hostname of the Resource |
| environment | **STRING** | Environment of the Resource |
| port | **STRING** | Port of the Resource |

### Column object

| Value | Type | Description |
| - | - | - |
| name | **STRING** | Name of the column |
| data\_label | **STRING** | Label assigned to the column |
| json\_path | **STRING** | JSON path of the column |
| data\_type | **STRING** | Data type of the column |
| value | **STRING** | Value of the column |
| in\_functions | **\[]Function Object** | List of functions that the column is used in |

`input.row` lists all columns extracted from your SQL query.

A single returned column can come from multiple source columns (e.g. when using wildcards, joins, or unions), and thus result in several policy columns. When the Connector cannot resolve a source, the returned column itself stands in as its own policy column.

This column lineage mapping is then used by the Connector's policy engine: a `response` rule that masks a policy column will be able to mask every returned column whose lineage includes it.

For example, in `SELECT email FROM users UNION SELECT email FROM customers`, the returned `email` column has two source columns: `users.email` and `customers.email`. Either one alone is enough to mask it for the entire result.

### Function object

| Value | Type | Description |
| - | - | - |
| name | **STRING** | Name of the function (e.g. `MAX`) |
| categories | **\[]STRING** | Categories of the function (e.g. `["aggregate", "window"]`) |

Function categories are used to group functions into different categories. The following categories are available: `aggregate`, `bitwise`, `conditional`, `context`, `conversion`, `data_generation`, `date_time`, `differential_privacy`, `encryption`, `file`, `geospatial`, `hash`, `metadata`, `notification`, `numeric`, `scalar`, `semi_structured`, `string_and_binary`, `system`, `table`, `vector_similarity`, `window`.

These categories are inspired by the [Snowflake documentation](https://docs.snowflake.com/en/sql-reference-functions).

### Space object

| Value | Type | Description |
| - | - | - |
| name | **STRING** | Name of the space |
| id | **STRING** | ID of the space |

### HTTP object

| Value | Type | Description |
| - | - | - |
| hostname | **STRING** | Upstream hostname (e.g. `api.anthropic.com`) |
| method | **STRING** | HTTP method |
| path | **STRING** | Request path |
| headers | **OBJECT** | HTTP headers as a map from header name to string array. Header names are normalized to lowercase in policy input. |
| body | **STRING** | Raw HTTP body, when available |
| json | **OBJECT** | Parsed JSON body, when the body is valid JSON and the content type is JSON |
| package\_registry | **STRING** | Package registry family of the request host: `npm`, `pypi`, `maven`, `cargo`, `rubygems`, `openvsx`, `nuget`, `go`, or `conda`. Empty for any other host. See [Package registries](#package-registries) for the hosts. |

### Package registries

`package_registry` is set when the hostname exactly matches one of these hosts. Subdomains and private mirrors do not match.

| `package_registry` | Hosts |
| - | - |
| `npm` | `registry.npmjs.org`, `registry.npmjs.com`, `registry.yarnpkg.com` |
| `pypi` | `pypi.org`, `pypi.python.org`, `files.pythonhosted.org` |
| `maven` | `repo1.maven.org`, `repo.maven.apache.org` |
| `cargo` | `crates.io`, `index.crates.io`, `static.crates.io` |
| `rubygems` | `rubygems.org`, `index.rubygems.org`, `bundler.rubygems.org` |
| `openvsx` | `open-vsx.org`, `openvsx.eclipsecontent.org`, `openvsxorg.blob.core.windows.net` |
| `nuget` | `api.nuget.org`, `www.nuget.org`, `packages.nuget.org`, `globalcdn.nuget.org` |
| `go` | `proxy.golang.org` |
| `conda` | `repo.anaconda.com` |

### Integrations object

| Value | Type | Description |
| - | - | - |
| socket | **Socket Object** | Socket's verdict on a package download. Fetched only when a policy reads a verdict field. See [Socket policy input](https://docs.formal.ai/docs/guides/integrations/socket.md#policy-input). |

## Native users

You can enforce policies on the Native User selected for an upstream
connection. `input.native_user` contains the selected label.

This policy allows only the `reader` label:

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if
import future.keywords.in

default session := { "action": "block", "type": "block_with_formal_message" }

session := { "action": "allow", "reason": "reader native user" } if {
	input.native_user == "reader"
}
```

### Native user assignment

The `native_user_assignment` field explains how Formal selected the Native
User:

| Value | Description |
| - | - |
| `cel` | The Resource's default selection expression assigned the user |
| `user-requested` | The client requested a Native User in the connection username |

This policy blocks every explicit override:

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

default session := { "action": "allow" }

session := { "action": "block", "type": "block_with_formal_message", "message": "Manual native user override is not allowed" } if {
	input.native_user_assignment == "user-requested"
}
```

### Requested and assigned Native Users

Native Users add `input.native_user_selection`. It can contain:

```json theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
{
  "requested": {
    "id": "nativeuser_requested",
    "label": "break-glass",
    "user_type": "basic"
  },
  "assigned": {
    "id": "nativeuser_assigned",
    "label": "reader",
    "user_type": "basic"
  }
}
```

`requested` is present when the client
[uses an `@<label>` suffix](https://docs.formal.ai/docs/guides/client-apps/cli#specify-native-user).
`assigned` is present when the Resource has a
[default Native User selection](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md#select-a-default-native-user).

The selected Native User is `requested` when both values exist. Policies can
compare the two before allowing the connection:

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

default session := {"action": "allow"}

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  input.native_user_assignment == "user-requested"
  input.native_user_selection.requested.id != input.native_user_selection.assigned.id
}
```

The `user_type` value describes the credential shape. See
[supported credential types](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md#supported-credential-types)
for the full list.

See [Select a default Native User](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md#select-a-default-native-user)
for selection examples.

## ClickHouse resources

ClickHouse request policies receive ClickHouse-specific fields under
`input.clickhouse`. HTTP transport context is available through `input.http` at
request and response policy. SQL context is available through `input.sql_query`.
Database and write-target context use `input.db_name` and `input.table_paths`.

### ClickHouse object

| Value | Type | Description |
| - | - | - |
| `endpoint` | **STRING** | Type of ClickHouse request or custom-handler path. Available at request and response stages. |
| `format` | **STRING** | Output format reported by ClickHouse. Populated at the response stage only. |
| `url_settings` | **OBJECT** | Settings supplied as URL parameters by this request. |
| `url_filters` | **\[]STRING** | `filter` URL parameters supplied by this request, in order. |
| `request_parameters` | **OBJECT** | Request-scoped `param_*` query bindings, without the prefix. |
| `query_id` | **STRING** | Query ID used for the request. |
| `quota_key` | **STRING** | Effective quota key supplied by the request. |
| `session_id` | **STRING** | Named ClickHouse HTTP session; empty for a stateless request. This is the ClickHouse-specific field available at session policy. |
| `session_check` | **BOOLEAN** | Whether ClickHouse must reject the request unless the named session already exists. |

For database, query, and table-path inputs, see [ClickHouse policy
evaluation](https://docs.formal.ai/docs/guides/core-concepts/resources/clickhouse.md#policy-evaluation).

## Snowflake resources

You can enforce policies on Snowflake resources based on the role used to connect to the resource.

### Snowflake object

| Value | Type | Description |
| - | - | - |
| role | **STRING** | Role used to connect to the Snowflake resource |

## MongoDB resources

MongoDB request policies receive the command being run under `input.mongodb`, and its database under `input.db_name`. MongoDB has no schema layer, so the collections a command names are available in `input.table_paths` using the `database.collection` format. That includes the namespaces a `bulkWrite` or a `renameCollection` names, and the collections an aggregation pipeline reads from or writes to through `$lookup`, `$graphLookup`, `$unionWith`, `$out` or `$merge`, sub-pipelines included.

### MongoDB object

| Value | Type | Description |
| - | - | - |
| `command` | **STRING** | Name of the command, such as `find`, `insert`, or `aggregate`. |
| `projection` | **OBJECT** | Projection of a `find`, or `fields` of a `findAndModify`, as written by the client. For example, `{"name": 1, "_id": 0, "exposed": "$ssn"}`. Absent when the command has no projection. |
| `untraceable_fields` | **BOOLEAN** | Whether the command can move data somewhere masking can't follow, e.g. `$map`, `$out` or `$rename`. |

Masking follows MongoDB fields that a command returns under another name: a `response` rule on `ssn` also masks `exposed` in `find({}, {"exposed": "$ssn"})`.

For example, to block the commands that masking cannot follow:

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

request := {
	"action": "block",
	"type": "block_with_custom_message",
	"message": "This command can move data between fields in ways Formal cannot track yet.",
} if {
	input.resource.technology == "mongodb"
	input.mongodb.untraceable_fields
}
```

## SQL resources

Formal can also enforce policies specific to SQL queries.

**SQL Query Object**

| Value | Type | Description |
| - | - | - |
| query | **STRING** | SQL query |
| statement\_type | **STRING** | Type of the SQL statement |
| command\_type | **STRING** | Type of the SQL command |
| incomplete | **BOOLEAN** | Whether the query context may omit details. |
| limit | **INT** | Limit of the SQL query |
| transaction\_in\_progress | **BOOLEAN** | Whether a transaction is currently in progress. **Postgres only.** |
| transaction\_history | **\[]STRING** | List of the most recent statements executed in the current transaction (up to 15). **Postgres only.** |

### Example: Run all SQL statements in a transaction in order

You can use a [workflow](https://docs.formal.ai/docs/guides/configuration/workflows.md) to create a policy suspension that ensures a sequence of SQL statements is executed in the correct order within a transaction. The workflow below accepts a list of ordered statements via its API trigger and creates a suspension that validates each statement matches the expected sequence using `transaction_history`.

```yaml theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
trigger:
  type: api-request
  name: my_workflow_trigger
  args:
    allow: <allow expression here>
actions:
- type: formal-app-command
  name: create_policy_suspension
  args:
    app: Policies
    command:
      name: PolicySuspension
      type: Create
    machine_user_id: <machine user id>
    input:
      policy_id: <policy id>
      identity_type: user
      identity_id: ${{trigger.user.id}}
      input_condition: "input.sql_query.transaction_in_progress && size(input.sql_query.transaction_history) < size(${{trigger.payload.transaction}}) && lists.range(size(input.sql_query.transaction_history)).all(i, ${{trigger.payload.transaction}}[i] == input.sql_query.transaction_history[i]) && ${{trigger.payload.transaction}}[size(input.sql_query.transaction_history)] == input.sql_query.query"
      oneoff: false
      expiration_minutes: 60
```

## AWS resources

Formal can also enforce policies on specific AWS Resources. These policies can be actively used for the SSH or Kubernetes.

### AWS object

| Value | Type | Description |
| - | - | - |
| account | **Account Object** | The AWS account and region of the target AWS resource. |
| ecs | **ECS Object** | Configuration details for ECS resources |
| ec2 | **EC2 Object** | Configuration details for EC2 instances |
| eks | **EKS Object** | Configuration details for EKS resources |

### Account object

The account object describes the session's target AWS resource, which is an EC2 instance, an ECS task or an EKS cluster.

| Value | Type | Description |
| - | - | - |
| account\_id | **STRING** | The ID of the AWS account that contains the target AWS resource. |
| region | **STRING** | The AWS region that contains the target AWS resource, such as `us-east-1`. |

Both values are empty when the session has no target AWS resource. For example, they are empty for an SSH session to a server's address, even when that server is an EC2 instance.

### ECS object

| Value | Type | Description |
| - | - | - |
| cluster\_name | **STRING** | Name of the ECS cluster |
| service\_name | **STRING** | Name of the ECS service |
| task\_id | **STRING** | ID of the ECS task |
| container\_name | **STRING** | Name of the ECS container |

### EC2 object

| Value | Type | Description |
| - | - | - |
| tags | **\[]STRING** | Tags of the EC2 instance |
| instance\_id | **STRING** | Identifier of the EC2 instance |

### EKS object

| Value | Type | Description |
| - | - | - |
| cluster\_arn | **STRING** | Amazon Resource Name (ARN) of the EKS cluster |
| cluster\_name | **STRING** | Name of the EKS cluster |

## Kubernetes resources

Formal can enforce policies on Kubernetes API requests based on the resource being accessed. The Kubernetes context is available via `input.kubernetes`.

### Kubernetes object

| Value | Type | Description |
| - | - | - |
| group | **STRING** | API group of the resource (e.g. `apps`). Empty string for core API resources. |
| group\_version | **STRING** | API version of the resource (e.g. `v1`). |
| namespace | **STRING** | Namespace of the resource. Empty for cluster-scoped resources. |
| kind | **STRING** | Kind of the resource (e.g. `pods`). |
| name | **STRING** | Name of the specific resource. Empty for list or collection operations. |
| subresource | **STRING** | Subresource being accessed (e.g. `exec`). |
| verb | **STRING** | Kubernetes API verb: `get`, `list`, `watch`, `create` or the lower-cased HTTP method for non-resource requests (e.g. `get` for `/healthz`). |

## SSH resources

Formal can enforce policies on SSH sessions. The SSH context is available via `input.ssh`. SSH states what a session is for before any of it happens, so a `session` rule can decide on the command the client asked to run.

### SSH object

| Value | Type | Description |
| - | - | - |
| is\_sftp | **BOOLEAN** | Whether the session is an SFTP transfer rather than a shell or a command |
| is\_pty | **BOOLEAN** | Whether the client asked for a terminal |
| is\_shell | **BOOLEAN** | Whether the session opens a shell rather than running a command |
| command | **STRING** | What the far side will run, verbatim. Absent when the session gets a shell |
| forward | **OBJECT** | The port forward the session carries. Absent unless the session is a port forward |

`command` is the string as the client sent it. The far side runs it with a shell, so one session can ask for several things at once: match on what a rule cares about inside the command rather than comparing the whole of it.

Git runs over SSH this way, which is what makes a push distinguishable from a clone: `git-receive-pack` writes to a repository and `git-upload-pack` reads from one, each naming the repository.

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

repository := "acme/infrastructure.git"

session := {
	"action": "mfa",
	"message": sprintf("push to %s", [repository]),
} if {
	contains(input.ssh.command, "git-receive-pack")
	contains(input.ssh.command, repository)
}
```

### Port forwards

Each port forward (`ssh -L` or `ssh -D`) is a session of its own. A `session` rule decides on every forward, separately from the shell or command on the same connection. A forward has no `command`, and `is_shell` is false for it.

| Value | Type | Description |
| - | - | - |
| forward.is\_reverse | **BOOLEAN** | Whether the forward is a reverse forward (`ssh -R`), which listens on the resource side and connects back through the client (currently unsupported) |
| forward.destination.host | **STRING** | Host the client asked the resource side to connect to |
| forward.destination.port | **NUMBER** | Port the client asked the resource side to connect to |

This policy blocks forwards to anything except a database port on the host itself:

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if
import future.keywords.in

session := {
	"action": "block",
	"type": "block_with_formal_message",
} if {
	input.ssh.forward
	not allowed_forward(input.ssh.forward.destination)
}

allowed_forward(destination) if {
	destination.host in {"localhost", "127.0.0.1"}
	destination.port == 5432
}
```

## LLM resources

Formal can enforce policies on LLM API sessions. Use `session` rules to block a connection before it reaches the upstream provider, `request` rules to inspect and rewrite outgoing request headers or bodies, and `response` rules to evaluate model responses.

For assessed LLM tool calls, response policies can also read `input.assessment`. See [Assessments](https://docs.formal.ai/docs/guides/core-concepts/assessments.md) for its fields and an example.

> [!NOTE]
>
> Tool calls are part of the model response, so policies that inspect `input.llm.tool_calls` should use the `response` rule.

### LLM object

| Value | Type | Description |
| - | - | - |
| `provider` | **STRING** | LLM provider name (e.g. `anthropic`, `openai`) |
| `author` | **STRING** | Who made the model (e.g. `anthropic` for Claude through Cursor). Absent when unknown |
| `model` | **STRING** | LLM model name |
| `request_format` | **STRING** | Wire format (e.g. `anthropic_messages`, `openai_responses`) |
| `system_instruction` | **STRING** | System prompt when present |
| `messages` | **\[]Message Object** | Request messages and content parts |
| `response_messages` | **\[]Message Object** | Model reply, available in the `response` rule once the full response is evaluated; empty when a streamed tool call is checked before the response ends |
| `tools` | **\[]Tool Object** | Tools declared on the request |
| `available_skills` | **\[]Object** | Skills the agent can load. Each has `name` and `description`. Populated for Claude Code requests. |
| `loaded_skills` | **\[]Object** | Skills loaded into the conversation. Each has `name`, `description`, and `contents`. Populated for Claude Code requests. |
| `stop_reason` | **STRING** | Reason the model stopped generating |
| `input_tokens` | **INT** | Number of input tokens |
| `output_tokens` | **INT** | Number of output tokens |
| `cost` | **FLOAT** | Estimated cost of the request in `currency`, available in the `response` rule. Absent when unpriced |
| `currency` | **STRING** | ISO 4217 code of the matched [token price](https://docs.formal.ai/docs/guides/ai-governance/spend.md), e.g. `USD`. Absent when unpriced |
| `priced` | **BOOLEAN** | Whether a [token price](https://docs.formal.ai/docs/guides/ai-governance/spend.md) matches the model |
| `price_source` | **STRING** | `provider`, `author` (an author's default price) or `none` |
| `tool_calls` | **\[]Tool Call Object** | Tool/function calls made by the model |
| `provider_session_id` | **STRING** | Provider's session identifier |

### Message object

| Value | Type | Description |
| - | - | - |
| `role` | **STRING** | Normalized role: `system`, `user`, `assistant`, `tool` |
| `raw_role` | **STRING** | Provider role before normalization |
| `content_parts` | **\[]Content Part** | Text, media, and tool parts in the message |

### Content part object

| Value | Type | Description |
| - | - | - |
| `type` | **STRING** | `text`, `reasoning`, `image`, `audio`, `file`, `tool_call`, `tool_result`, or `unknown` |
| `text` | **STRING** | Text content when `type` is `text`, `reasoning`, or `tool_result` |
| `name` | **STRING** | Tool name or filename when applicable |
| `tool_call_id` | **STRING** | Correlates tool call and tool result parts |
| `input` | **Object** | Tool-call arguments when `type` is `tool_call` |

### Tool object

| Value | Type | Description |
| - | - | - |
| `name` | **STRING** | Request-declared tool or function name |
| `type` | **STRING** | Request-declared tool type |
| `description` | **STRING** | Tool description when present |
| `input_schema` | **Object** | Request-declared input schema when available |

### Tool call object

| Value | Type | Description |
| - | - | - |
| `name` | **STRING** | Name of the tool/function called |
| `id` | **STRING** | Unique identifier for the call |
| `input` | **Object** | Arguments passed to the tool |

### Example: Rewrite request headers

The following policy adds request headers before the LLM request is sent to the upstream provider. Header values must be arrays of strings. Set a header to an empty array to remove it.

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

rewritten_headers := object.union(input.http.headers, {
  "anthropic-allowed-org-ids": ["aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"],
})

request := {
  "action": "rewrite",
  "headers": rewritten_headers,
} if {
  input.resource.technology == "llm"
}
```

For the full walkthrough, see [Restrict Anthropic Sign-Ins to One Org](https://docs.formal.ai/docs/guides/example-use-cases/restrict-anthropic-sign-ins.md).

### Example: Redact SSNs from request messages

Use a request-stage `rewrite` with `regex.replace` on `input.http.body` to strip sensitive values from prompts without blocking the session. This keeps coding agents usable when SSNs appear in the context window.

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if
import future.keywords.in

ssn_pattern := `\b\d{3}-\d{2}-\d{4}\b`

request := {
  "action": "rewrite",
  "body": regex.replace(input.http.body, ssn_pattern, "[REDACTED-SSN]"),
  "reason": "Redact SSNs from LLM request messages",
} if {
  input.resource.technology == "llm"
  some msg in input.llm.messages
  some part in msg.content_parts
  part.type in {"text", "tool_result"}
  regex.match(ssn_pattern, part.text)
}
```

The rewrite replaces the full HTTP body string. Keep replacements JSON-safe so the upstream request stays valid. See [HTTP body rewrites](https://docs.formal.ai/docs/guides/core-concepts/resources/http.md#body-rewrites).

### Example: Block specific tool calls

The following policy blocks any LLM response that includes a `Bash` tool call with a specific command:

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if
import future.keywords.in

response := {"action": "block", "type": "block_with_formal_message"} if {
  some tool_call in input.llm.tool_calls
  tool_call.name == "Bash"
  tool_call.input.command == "echo hi"
}
```

## MCP resources

Formal can enforce policies on MCP tool calls. The MCP context is available via `input.mcp` at the request and response stages when the request is a tool call.

### MCP object

| Value | Type | Description |
| - | - | - |
| `method` | **STRING** | JSON-RPC method (e.g. `tools/call`, `tools/list`) |
| `tool_name` | **STRING** | Name of the MCP tool being called (e.g. `read_file`, `delete_file`) |
| `tool_params` | **Object** | Parameters passed to the tool |

To block unapproved MCP servers and point agents to approved ones, see [`mcp_suggest_alternatives`](https://docs.formal.ai/docs/guides/policies/enforcement#suggest-approved-mcp-alternatives).

### Example: Block a specific tool

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

default request := {"action": "allow"}

request := {"action": "block", "type": "block_with_formal_message"} if {
  input.mcp.tool_name == "list_pull_requests"
}
```

To seal OAuth Bearer tokens for MCP clients, see [Encrypt MCP OAuth Tokens](https://docs.formal.ai/docs/guides/example-use-cases/encrypt-mcp-oauth-tokens.md).

## Device

Formal can also enforce policies on specific device attributes.

> [!WARNING]
>
> This feature is only available for devices using the Formal Endpoint.

### Device info object

| Value | Type | Description |
| - | - | - |
| hardware | **Hardware Info Object** | Hardware information of the device |
| software | **Software Info Object** | Software information of the device |
| scope | **STRING** | Scope set with `formal run --as <scope>`, empty otherwise |

### Hardware info object

| Value | Type | Description |
| - | - | - |
| model\_name | **STRING** | Model name of the device |
| model\_identifier | **STRING** | Model identifier of the device |
| model\_number | **STRING** | Model number of the device |
| system\_firmware\_version | **STRING** | System firmware version of the device |
| os\_loader\_version | **STRING** | OS loader version of the device |
| serial\_number | **STRING** | Serial number of the device |
| hardware\_uuid | **STRING** | Hardware UUID of the device |
| provisioning\_udid | **STRING** | Provisioning UDID of the device |
| activation\_lock\_status | **STRING** | Activation lock status of the device |

### Software info object

| Value | Type | Description |
| - | - | - |
| system\_version | **STRING** | System version of the device |
| kernel\_version | **STRING** | Kernel version of the device |
| boot\_volume | **STRING** | Boot volume of the device |
| boot\_mode | **STRING** | Boot mode of the device |
| computer\_name | **STRING** | Computer name of the device |
| user\_name | **STRING** | User name of the device |
| secure\_virtual\_memory | **STRING** | Secure virtual memory of the device |
| system\_integrity\_protection | **STRING** | System integrity protection of the device |
| time\_since\_boot | **STRING** | Time since boot of the device |

## AI agents

Formal tracks connections that originate from AI coding agents running through the [Formal Endpoint](https://docs.formal.ai/docs/guides/client-apps/desktop-app.md). When an agent is detected, `input.agent` is populated with context about that agent.

> [!NOTE]
>
> `input.agent` is only populated for connections made via the Formal Endpoint. It is empty for direct connections.

### Agent object

| Value | Type | Description |
| - | - | - |
| type | **STRING** | The agent type (e.g. `claude-cli` for Claude Code, `cursor`, `codex_cli_rs` for Codex). |
| provider | **STRING** | The LLM provider used by the agent (e.g. `anthropic`, `openai`). |
| provider\_session\_id | **STRING** | The LLM provider's session ID for the current conversation. |
| version | **STRING** | The version of the agent. |
| yolo\_mode | **BOOLEAN** | `true` if the agent was launched with the `--dangerously-skip-permissions` flag. This flag is specific to [Claude Code](https://docs.anthropic.com/en/docs/claude-code/overview) and bypasses its interactive permission prompts, allowing it to execute tool calls without user confirmation. |

### Example: block Claude Code in YOLO mode

Use `input.agent.yolo_mode` to block autonomous agents from accessing sensitive resources without per-action approval:

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

default session := {"action": "allow"}

session := {"action": "block", "type": "block_with_formal_message"} if {
    input.agent.yolo_mode == true
}
```

## OAuth clients

When an MCP client or other application connects to a resource with a Formal OAuth access token, `input.user.oauth` describes the OAuth client acting for the user. It is absent for any other kind of authentication.

### OAuth object

| Value | Type | Description |
| - | - | - |
| client.id | **STRING** | The client's metadata document URL, or the ID of a client pre-registered in Formal. |
| client.name | **STRING** | The client's display name. |
| client.type | **STRING** | `cimd` for a client identified by its metadata document URL, `pre_registered` for a client pre-registered in Formal. |
| consent\_id | **STRING** | The ID of the user's approval of this client. |

> [!WARNING]
>
> A `cimd` client chooses its own name. Match on `client.id` or `client.type` instead of `client.name`.

### Example: allow only pre-registered OAuth clients

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

default session := {"action": "allow"}

session := {"action": "block", "type": "block_with_formal_message"} if {
    input.user.oauth
    input.user.oauth.client.type != "pre_registered"
}
```

## Policy Input Retention

Formal can [optionally retain these inputs](https://docs.formal.ai/docs/guides/observability/logs.md#policy-evaluation-input-retention) for **policy backtesting** where you can test policies on historical data.

## Extending Policies with External Data

You can extend policies with custom data returned by Hooks. Each hook's result is accessible via `input.hooks` using the hook's name.

**Example:**

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
# If your hook is named "approved_users"
input.hooks.approved_users.user_ids
```

For more information, see [Hooks](https://docs.formal.ai/docs/guides/policies/hooks.md).

## Legacy Stage Names

Prior to Connector v1.31.19, the Rego rule names for the request and response stages were `pre_request` and `post_request`. These legacy names still work and existing policies do not need to be updated. To migrate, rename `pre_request` to `request` and `post_request` to `response` in your policy code. Different policies can use different naming conventions.


## Related topics

- [Policy Hooks](https://docs.formal.ai/docs/guides/policies/hooks.md)
- [Policies](https://docs.formal.ai/docs/guides/policies/introduction.md)
- [Policy Operations](https://docs.formal.ai/docs/guides/policies/operations.md)
- [List log policy evaluation inputs](https://docs.formal.ai/api-reference/corev1logsservice/list-log-policy-evaluation-inputs.md)
- [Policy Examples](https://docs.formal.ai/docs/guides/policies/examples.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.