> ## 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 Enforcement

> Policy actions and enforcement mechanisms for blocking, masking, filtering, and rewriting queries

## Overview

Formal policies can enforce different actions at three evaluation stages: **session**, **request**, and **response**. Each stage has specific actions available based on when the policy is evaluated.

## Evaluation Stages

> [card] Session
>
> **When**: Connection establishment. SSH and Kubernetes exec sessions can
> also be [evaluated](https://docs.formal.ai/docs/guides/policies/evaluation.md#tick-stage)
> while they run. **Actions**: `allow`, `block`, `mfa`, `quarantine`,
> `suspend`, `impersonate` Use for: Authentication, connection-level access
> control

> [card] Request
>
> **When**: Before query reaches resource **Actions**: `allow`, `block`, `mfa`,
> `rewrite`, `decrypt` Use for: Query validation, SQL rewriting, blocking writes, decrypting secrets for the upstream

> [card] Response
>
> **When**: After data returns from resource **Actions**: `allow`, `block`,
> `filter`, `mask`, `encrypt`, `rewrite` Use for: Data masking, PII redaction, filtering results, encrypting secrets before they leave

## Common Action Parameters

All actions support these parameters:

| Parameter | Type | Description |
| - | - | - |
| `action` | **String** | The enforcement action: `allow`, `block`, `filter`, `mask`, `encrypt`, `decrypt`, `rewrite`, `mfa`, `quarantine`, `suspend`, `impersonate` |
| `reason` | **String** | Explanation for the action (logged for compliance and auditing) |
| `contextual_data` | **String** | Additional context that influenced the decision (e.g., "Zendesk ticket #123") |

## Block Action

Deny access and terminate the connection or query.

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `type` | **Enum** | One of `block_with_formal_message`, `block_with_custom_message`, or `mcp_suggest_alternatives` |
| `message` | **String** | Custom message to show the user |

`block_with_formal_message` returns Formal's default block text. That message includes the policy ID plus the session ID and request ID when they are available, so users can share those identifiers with their security team.

### Example

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

import future.keywords.if

# Block all DELETE statements in production
request := {
  "action": "block",
  "type": "block_with_custom_message",
  "message": "DELETE operations are not allowed in production",
  "reason": "Production data protection policy"
} if {
  input.resource.environment == "production"
  input.sql_query.statement_type == "DELETE"
}
```

### Suggest approved MCP alternatives

Use `mcp_suggest_alternatives` to block an unapproved MCP server and tell the AI agent what to do next. The block message becomes an advisory written for the agent. It lists the MCP resources you have registered in Formal, excluding the blocked one.

The advisory tells the agent to ask the user to choose one of these options:

* Switch to one of the approved MCP servers.
* Request the blocked server. The agent looks for a [form](https://docs.formal.ai/docs/guides/configuration/forms.md) about MCP requests with `formal form list` and submits it with `formal form fill`.
* Do nothing for now.

Formal ignores `message` when it builds the advisory. If the advisory cannot be built, Formal returns `message`, or a short default text when `message` is empty.

This policy blocks tool calls to MCP servers that have no Formal resource, such as servers the [Formal Endpoint](https://docs.formal.ai/docs/guides/client-apps/desktop-app.md) intercepts on a laptop. It is the policy that the **Block unknown MCPs** control in the [AI Guardrails](https://docs.formal.ai/docs/guides/ai-governance/guardrails.md) recipe generates.

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

import future.keywords.if

request := {
  "action": "block",
  "type": "mcp_suggest_alternatives",
  "reason": "This MCP is not approved by your organization.",
} if {
  input.resource.technology == "mcp"
  input.resource.name == ""
  input.mcp.method == "tools/call"
}
```

> [!TIP]
>
> Create a form with fields named `name`, `url`, and `reason` so agents can file
> requests for blocked MCP servers. Requests then reach your approval
> [workflow](https://docs.formal.ai/docs/guides/configuration/workflows.md).

## Allow Action

Explicitly permit an operation. Use in combination with default deny policies.

### Example

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

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

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

# Allow admins
session := {
  "action": "allow",
  "reason": "User is in admin group"
} if {
  "admin" in input.user.groups
}
```

## Rewrite Action

Modify a SQL query before it reaches the resource, or modify an HTTP request or response in transit.

### Parameters

| Parameter | Type | Applies to | Description |
| - | - | - | - |
| `limit` | **Integer** | SQL, request stage | Row limit to apply. Formal adds a `LIMIT` or lowers a higher one. It never raises an existing lower limit. |
| `comment` | **String** | SQL, request stage | Comment to add to the query |
| `headers` | **`Map<String, String[]>`** | HTTP-based, request and response | HTTP headers to set. Use an empty array (`[]`) to remove a header. |
| `path` | **String** | HTTP-based, request stage | Replacement URL path, such as `/v1/messages` |
| `body` | **String** | HTTP-based, request and response | Replacement for the whole body, sent as-is. `Content-Type` is unchanged. |
| `json` | **Any JSON value** | HTTP-based, request and response | Replacement body, serialized as JSON. Sets `Content-Type: application/json` unless the message already has a JSON type. |
| `post_form` | **`Map<String, String[]>`** | HTTP-based, request and response | Replacement body, URL-encoded as form fields. A field value can also be a single string. Sets `Content-Type: application/x-www-form-urlencoded` unless already set. |

HTTP-based resources include HTTP, LLM, and MCP resources.

> [!WARNING]
>
> `body`, `json`, and `post_form` each replace the whole body. Set at most one
> of them in a decision. Formal rejects a decision that sets more than one and
> does not apply it.

When several active policies rewrite the same message, Formal applies all of their header rewrites. If more than one sets a body, only one of them takes effect. Scope policies so that body rewrites don't overlap.

### Example

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

import future.keywords.if

# Add LIMIT clause to unbounded queries
request := {
  "action": "rewrite",
  "limit": 1000,
  "comment": "Auto-added row limit for safety",
} if {
  startswith(lower(input.sql_query.query), "select")
}
```

### Example: Rewrite LLM request headers

```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 LLM request bodies

String-replace sensitive values in the outbound LLM body so coding agents can continue without sending SSNs upstream. Prefer `body` rewrites over blocking the session when the goal is redaction.

```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)
}
```

## Filter Action

Remove rows from the result set based on conditions.

### Example

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

import future.keywords.if

# Filter rows unless user has open Zendesk ticket
default response := {
  "action": "filter",
  "reason": "No open tickets for this data"
}

response := {
  "action": "allow",
  "contextual_data": filtered_tickets,
  "reason": "User has open ticket"
} if {
  col := input.row[_]
  col["path"] == "main.public.pii.email"

  filtered_tickets := [obj |
    obj := data.zendesk_tickets[_]
    obj.requester_email == col.value
    obj.status == "open"
  ]

  count(filtered_tickets) > 0
}
```

## Mask Action

Redact or obfuscate sensitive data in responses.

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `type` | **String** | Masking type from [Masking Types](#masking-types). Sets the privacy level used to resolve conflicts. |
| `sub_type` | **String** | Masking method from [Masking Subtypes](#masking-subtypes). Defaults to the value of `type`. |
| `columns` | **\[]Column** | List of columns to mask |
| `redact` | **String** | Replacement string. Character-level subtypes repeat it once per masked character. |
| `characters_count` | **Integer** | Number of characters to mask, for `redact.first_n_characters` and `redact.last_n_characters` |
| `precision` | **Integer** | Digits to keep after the decimal point, for `reduce_decimal_precision` |
| `typesafe_fallback` | **String** | `fallback_to_null` or `fallback_to_default`. Setting it turns on type safety. |

With type safety on, Formal keeps typed columns valid, such as numbers, booleans, dates, JSON, and UUIDs. `nullify`, `redact`, the hash subtypes, and `reduce_decimal_precision` keep their output when the column's type can hold it. Every other mask on a typed column returns the fallback:

* `fallback_to_null` returns `NULL`.
* `fallback_to_default` returns a placeholder such as `0`, `{}`, or an all-zero UUID. Boolean columns get `NULL` instead.

Text columns are masked normally.

> [!NOTE]
>
> Formal turns on type safety only when `typesafe_fallback` is set. A `typesafe`
> key on its own has no effect.

### Masking Types

| Type | Privacy Level | Description |
| - | - | - |
| `nullify` | 4 (Highest) | Replace with NULL |
| `hash.with_salt` | 4 | Hash with random salt |
| `fake` | 3 | Generate realistic fake data |
| `redact.constant_characters` | 3 | Replace with constant string |
| `hash.no_salt` | 2 | Hash without salt (deterministic) |
| `redact.partial` | 1 | Partially redact (e.g., mask email username) |
| `none` | 0 (Lowest) | No masking |

`type` and `sub_type` do different jobs. `type` only sets the privacy level. `sub_type` picks the function that transforms the value. When you omit `sub_type`, Formal uses `type` as the subtype. That shortcut works for `nullify`, `hash.with_salt`, `hash.no_salt`, and `redact.constant_characters`. `fake` and `redact.partial` always need an explicit `sub_type`.

> [!WARNING]
>
> **Masking fails silently when a name is wrong.** Formal does not validate mask
> names when you save a policy, and it logs no error at query time.
>
> * An unknown `sub_type` leaves the value unmasked.
> * An unknown `type` has privacy level 0, so Formal drops the mask.
> * `type: "fake"` or `type: "redact.partial"` without a `sub_type` leaves the
>   value unmasked.
>
> Copy names from the tables on this page. Run the policy in **dry-run** and
> check query results before you activate it.

### Masking Subtypes

Subtypes that end in `_with_fake` replace the value with a random fake value of the same kind. Pair them with `type: "fake"`. Pair the partial subtypes, such as the email and character-level ones, with `type: "redact.partial"`.

> [accordion] Redaction, hashing, and numbers
>
> * `redact.constant_characters`: Replace the value with `redact`
> * `redact`: Replace the value with `redact`. With type safety on, keeps `redact` when the column's type can hold it, such as `-1` in an integer column
> * `replace_characters_with`: Replace every character with `redact`. With `"redact": "*"`, `secret` becomes `******`
> * `redact.first_n_characters`: Replace the first `characters_count` characters. With `"redact": "*"` and a count of 3, `hello` becomes `***lo`
> * `redact.last_n_characters`: Replace the last `characters_count` characters. With `"redact": "*"` and a count of 3, `hello` becomes `he***`
> * `mask_everything_except_last`: Replace every character except the last one. With `"redact": "*"`, `sensitive` becomes `********e`. This subtype ignores `characters_count`
> * `nullify`: Return `NULL`
> * `hash.no_salt`: Hash the value. The same input always gives the same output, so joins still work
> * `hash.with_salt`: Hash the value with a random salt. The output changes on every read
> * `reduce_decimal_precision`: Truncate to `precision` digits after the decimal point. With a precision of 2, `123.456` becomes `123.45`. Non-numeric values are unchanged

> [accordion] Email
>
> * `email_mask_username`: `jane@example.com` becomes `****@example.com`
> * `email_mask_domain_name`: `jane@example.com` becomes `jane@*******.com`. The masked domain is always `*******.com`
> * `email_mask_while_preserving`: `jane@example.com` becomes `j***@e******.com`
> * `email_mask_with_fake`: Random fake email address
>
> The first three subtypes replace every character with `*` when the value isn't an email address.

> [accordion] Personal information
>
> * `person_full_name_mask_with_fake`
> * `person_first_name_mask_with_fake`
> * `person_last_name_mask_with_fake`
> * `person_gender_mask_with_fake`
> * `person_ssn_mask_with_fake`
> * `phone_mask_with_fake`

> [accordion] Location
>
> * `postal_address_mask_with_fake`
> * `city_mask_with_fake`
> * `state_mask_with_fake`
> * `country_mask_with_fake`
> * `zip_mask_with_fake`
> * `location_mask_except_state_country`: Keep only the US state and the country from a comma-separated address. `1 Main St, Springfield, IL, USA` becomes `IL, USA`

> [accordion] Payment
>
> * `payment_credit_card_number_mask_with_fake`
> * `payment_credit_card_cvv_mask_with_fake`
> * `payment_credit_card_exp_mask_with_fake`
> * `payment_credit_card_type_mask_with_fake`
> * `payment_currency_with_fake`
> * `payment_ach_routing_with_fake`
> * `payment_ach_account_with_fake`
> * `payment_bitcoin_address_with_fake`
> * `payment_bitcoin_private_key_with_fake`

> [accordion] Network
>
> * `network_url_mask_with_fake`
> * `network_domain_mask_with_fake`
> * `network_ipv4_mask_with_fake`
> * `network_ipv6_mask_with_fake`
> * `network_mac_mask_with_fake`

> [accordion] Company
>
> * `company_name_with_fake`

> [!NOTE]
>
> Character-level subtypes repeat `redact` once per masked character. If
> `redact` is empty, those characters are removed instead of replaced. Always
> set `redact`, for example to `"*"`.

### Examples

**Mask email usernames:**

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

import future.keywords.if

response := {
  "action": "mask",
  "type": "redact.partial",
  "sub_type": "email_mask_username",
  "columns": columns
} if {
  columns := [col |
    col := input.row[_]
    col["data_label"] == "email_address"
  ]
  count(columns) > 0
}
```

**Replace PII with fake data:**

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

import future.keywords.if

response := {
  "action": "mask",
  "type": "fake",
  "sub_type": "person_full_name_mask_with_fake",
  "columns": columns
} if {
  columns := [col |
    col := input.row[_]
    col["data_label"] == "name"
  ]
  count(columns) > 0
}
```

**Redact with constant value:**

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

import future.keywords.if

response := {
  "action": "mask",
  "type": "redact.constant_characters",
  "sub_type": "redact.constant_characters",
  "redact": "[REDACTED]",
  "columns": columns
} if {
  columns := [col |
    col := input.row[_]
    col["data_label"] == "social_security_number"
  ]
  count(columns) > 0
}
```

## Encrypt & Decrypt Actions

Encrypt and decrypt sensitive HTTP values in-line, so plaintext secrets never reach places that should not see them. Formal encrypts secrets on the way out and decrypts them on the way back in, so tokens stay protected end to end.

> [!NOTE]
>
> * The `encrypt` action on the Formal Endpoint is only available on macOS.
> * The `encrypt` action on the Connector requires configuring a cloud KMS key for token encryption. See [Token Encryption](https://docs.formal.ai/docs/guides/core-concepts/connectors/token_encryption.md) for more information.

* `decrypt` runs at the **request** stage. It decrypts Formal-encrypted values before the upstream receives them. If a value fails to decrypt, the request is forwarded unchanged.
* `encrypt` runs at the **response** stage. It encrypts values before they leave the proxy. If encryption fails, the response is blocked.

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `targets` | **\[]Target** | The parts of the HTTP message to encrypt or decrypt |

Each target is an object:

| Field | Type | Description |
| - | - | - |
| `kind` | **String** | One of `header`, `cookie`, `json`, or `body` |
| `name` | **String** | Header name, cookie name, or JSON field (for example, `data.token`). Omit for `body`. |

A `cookie` target seals only the named value in response `Set-Cookie` headers and opens it in request `Cookie` headers. Other cookies and attributes are unchanged.

To select several JSON fields with one target, use a [JSONPath](https://www.rfc-editor.org/rfc/rfc9535) starting with `$`, such as `$.messages[*].content` or `$.items[?@.type == 'secret'].value`. Every selected field is encrypted or decrypted. A path that selects nothing leaves the body unchanged.

### Example: Encrypt tokens in a response

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

response := {"action": "encrypt", "targets": [
    {"kind": "json", "name": "access_token"},
    {"kind": "json", "name": "refresh_token"}
]} if {
    input.resource.technology == "http"
    input.http.method == "POST"
    input.http.path == "/token"
}
```

### Example: Encrypt every matching field

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

response := {"action": "encrypt", "targets": [
    {"kind": "json", "name": "$.credentials[*].secret"}
]} if {
    input.http.path == "/credentials"
}
```

### Example: Decrypt a request header for the upstream

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

request := {"action": "decrypt", "targets": [
    {"kind": "header", "name": "Authorization"}
]} if {
    input.http.path == "/mcp"
}
```

For an end-to-end Notion MCP walkthrough (Endpoint Secure Enclave or Connector KMS), see [Encrypt MCP OAuth Tokens](https://docs.formal.ai/docs/guides/example-use-cases/encrypt-mcp-oauth-tokens.md).

## Seal & Unseal Actions

`seal` encrypts a value like `encrypt`, and also binds it to where it was sealed and to the client process that received it. `unseal` opens a sealed value only where that binding allows. The binding is encrypted with the value, so a client can't read or change it.

> [!NOTE]
>
> `seal` and `unseal` run only on the Formal Endpoint, which knows the client process. On a Connector, `seal` blocks the response or request and `unseal` leaves values sealed. See [Platform limits](#platform-limits).

* `seal` at the **response** stage seals values before the client receives them. At the **request** stage it seals values before the upstream receives them, so the upstream only ever stores sealed values. If sealing fails, the response or request is blocked.
* `unseal` at the **request** stage opens values sealed in responses, before the upstream receives them. At the **response** stage it opens values sealed in requests, before the client receives them. A value never unseals in the direction it was sealed in. If a value fails to unseal, it is forwarded still sealed.

`decrypt` doesn't open sealed values, and `unseal` doesn't open encrypted ones.

A sealed value unseals only when all of these hold:

* **Process:** on macOS, the client process has the same code-signing identity (Team ID, code identifier and bundle identifier) as the one it was sealed for. Unsigned and ad-hoc signed processes can't seal. Linux has no process check; see [Platform limits](#platform-limits).
* **Host:** the upstream is on the site the value came from, like a cookie. A site is a registrable domain from the [Public Suffix List](https://publicsuffix.org/) (the list browsers use for cookies): a token from `auth.example.com` unseals on `api.example.com`, but not on `api.other.com`. A value sealed in a request unseals only in responses from the exact host it was sent to.
* **User:** the request comes from the same user and end user it was sealed for, as with `encrypt`.

### Platform limits

Every platform encrypts each sealed value with AES-256-GCM under a key derived from the Formal user and end user, and checks the host. They differ in what protects that key and in how strictly they check the client process:

| Platform | Key protected by | Process check | Strength |
| - | - | - | - |
| macOS | Secure Enclave P-256 inside ML-KEM-768 (hybrid) | Verified code signature: Team ID, code and bundle IDs | Enforced |
| Linux | TPM 2.0, under an ECC P-256 storage key | None, the host only | Best effort |
| Windows | Not supported | Not supported | Not supported |
| Connector | Not supported | Not supported | Not supported |

#### macOS

* **Process:** macOS verifies the client's code signature, so Formal knows which signed app received a value. A value unseals only for a process with the same Team ID (or Apple signature), code identifier and bundle identifier. Another binary can't claim that identity, and it survives app updates. Unsigned and ad-hoc signed processes can't seal.
* **Key:** the key is wrapped with a P-256 key in the Secure Enclave, then again with ML-KEM-768 (FIPS 203), a post-quantum key. Opening it needs both. The Secure Enclave key never leaves the chip, and only the signed Formal Endpoint can use it. Other apps can't unwrap it, even ones running as the same user.

#### Linux

* **Process:** Linux has no code signing. Process names, command lines and paths can be set by any program, so Formal doesn't check the process. A sealed value unseals for any client process on the device that sealed it, not only the one that received it.
* **Key:** the key is sealed into the device's TPM 2.0, under the TPM's ECC P-256 storage key, and is encrypted between the Endpoint and the TPM. It only unwraps on that TPM, so a sealed value copied to another device stays sealed. There is no post-quantum protection, since TPM 2.0 doesn't support ML-KEM.
* **Who can unwrap:** the TPM object has no password. Any program running as the same user with access to `/dev/tpmrm0` can unwrap the key, and can decrypt a sealed value it holds without going through Formal. On Linux, sealing keeps values off other devices and away from other users, but not away from other programs of the same user.
* **Setup:** the Endpoint needs read and write access to `/dev/tpmrm0`. The desktop package adds the installing user to its group; the headless package doesn't. Without a TPM, `seal` blocks the response or request.

#### Windows and the Connector

The Formal Endpoint on Windows has no key backend, and a Connector doesn't know the client process. On both, `seal` blocks the response or request and `unseal` leaves values sealed. On a Connector, use `encrypt` and `decrypt` with a [token encryption key](https://docs.formal.ai/docs/guides/core-concepts/connectors/token_encryption.md).

### Targets

`seal` and `unseal` take the same targets as `encrypt` and `decrypt`. A `seal` target can also set `constraints`:

| Field | Type | Description |
| - | - | - |
| `constraints` | **Object** | `{"hostnames": [...]}` lists the only hosts where the value may unseal, replacing the default host. |

### Example: Unseal tokens on another site

When a token is issued on one site and used on another, list the hosts it is used on in the target's `constraints`. The value then unseals only on those exact hosts, so also list the issuing host if the token goes back to it. Claude Code gets its token from `platform.claude.com` and sends it to `api.anthropic.com`:

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

response := {
    "action": "seal",
    "targets": [{
        "kind": "json",
        "name": "access_token",
        "constraints": {"hostnames": ["api.anthropic.com", "mcp-proxy.anthropic.com"]}
    }]
} if {
    input.resource.hostname == "platform.claude.com"
}

request := {
    "action": "unseal",
    "targets": [{"kind": "header", "name": "Authorization"}]
} if {
    input.resource.hostname in {"api.anthropic.com", "mcp-proxy.anthropic.com"}
}
```

### Example: Store only sealed values at an upstream

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

request := {"action": "seal", "targets": [{"kind": "json", "name": "card_number"}]} if {
    input.http.path == "/customers"
}

response := {
    "action": "unseal",
    "targets": [{"kind": "json", "name": "card_number"}]
} if {
    input.http.path == "/customers"
}
```

## MFA Action

The MFA action requires device-owner verification before proceeding with the connection.

When a policy returns the `mfa` action, the Formal Endpoint prompts for device-owner verification before the connection proceeds. On macOS this is Touch ID or the device passcode. On Windows this is Windows Hello (fingerprint, facial recognition, or PIN).

When a Connector evaluates the policy, it raises the challenge in the Control Plane and waits. The user's Formal Endpoint picks up the challenge and shows the prompt. The user needs the Endpoint running to answer it.

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `message` | **String** | Text shown in the prompt. Default: `An action via Formal requires your approval` |
| `timeout` | **Integer** | Seconds to wait for the user. Default: `60` |

If verification fails or times out, Formal blocks the connection with `MFA authentication failed or timed out. Please try again.`

> [!WARNING]
>
> MFA on Windows requires Windows Hello. It's the strongest form of device-owner verification available. A device with no Windows Hello method configured, or accessed over a remote desktop session where Windows Hello is unavailable, fails the challenge closed and is denied access.

### Example

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

import future.keywords.if

session := {
  "action": "mfa",
  "message": "Approve access to the production database",
  "timeout": 120,
  "reason": "Production access requires MFA"
} if {
  input.resource.environment == "production"
}
```

## Quarantine Action

Stop a user who shows high-risk behavior. `quarantine` is a session-stage action for SSH and Kubernetes `exec` sessions.

What happens depends on when the rule matches:

* **While a session runs:** Formal ends every active session of the user and blocks the user. Blocked users can't open SSH, Kubernetes, or RDP sessions until an admin unblocks them.
* **When an SSH session starts:** Formal refuses that session. The user is not blocked.

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `message` | **String** | Text sent to the client. Defaults to a Formal message with the policy ID and session ID. |

To unblock a user, go to [Users](https://app.formal.ai/users), open the user, and click **Unblock User**. Blocked users show a **Blocked** badge. You can also block a user manually with **Block User**.

### Example

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

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

session := {
  "action": "quarantine",
  "message": "Your access is paused. Contact the security team.",
  "reason": "Contractors cannot open SSH sessions to production"
} if {
  input.resource.technology == "ssh"
  input.resource.environment == "production"
  "contractor" in input.user.groups
}
```

## Suspend Action

End one session without blocking the user. `suspend` is a session-stage action for SSH and Kubernetes `exec` sessions.

* **While a session runs:** Formal ends that session. The user can reconnect.
* **When an SSH session starts:** Formal refuses that session.

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `message` | **String** | Text sent to the client. Defaults to a Formal message with the policy ID and session ID. |

### Example

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

import future.keywords.if

session := {
  "action": "suspend",
  "message": "Machine users cannot open interactive SSH sessions.",
  "reason": "Machine user SSH session"
} if {
  input.resource.technology == "ssh"
  input.user.type == "machine"
}
```

## Impersonate Action

Run Kubernetes API requests as the end user instead of the Connector's identity. `impersonate` is a session-stage action for Kubernetes resources. Formal adds the `Impersonate-User` and `Impersonate-Group` headers to each request it forwards. Restrict which identities the Connector can impersonate with [Kubernetes RBAC](https://docs.formal.ai/docs/guides/core-concepts/resources/kubernetes.md#kubernetes-rbac).

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `user` | **String** | Kubernetes user to impersonate |
| `groups` | **\[]String** | Kubernetes groups to impersonate |

### Example

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

import future.keywords.if

session := {
  "action": "impersonate",
  "user": input.user.username,
  "groups": input.user.groups
} if {
  input.resource.technology == "kubernetes"
}
```

The cluster must allow the Connector to impersonate users and groups. See [Kubernetes impersonation](https://docs.formal.ai/docs/guides/core-concepts/resources/kubernetes.md#impersonation) for the RBAC setup.

## Rule Conflicts and Precedence

When multiple policies apply to the same query, Formal resolves conflicts using **least privilege**:

| Scenario | Resolution |
| - | - |
| **Block vs Allow** | Block wins |
| **Multiple Filter actions** | Smallest row limit wins |
| **Multiple Mask actions** | Highest privacy level wins (nullify > constant > fake > partial) |
| **Multiple Rewrite actions** | Arbitrary (avoid conflicts with scoping) |

### Example of Conflict Resolution

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
Policy A: Mask email as ***@***.com (privacy level 3)
Policy B: Nullify email (privacy level 4)

Result: Email is nullified (higher privacy)
```

> [!TIP]
>
> Use `included_connectors` or `included_resources` to avoid unintended policy
> conflicts.

## Scoping Policies with Connectors, Resources, Spaces, and Technologies

To prevent policy conflicts when using the `default` keyword, limit which Connectors, Resources, Spaces, or technologies a policy applies to.

### Include/Exclude Connectors

Use `included_connectors` to apply a policy only to specific connectors:

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

import future.keywords.if

# Only apply to these Connectors
included_connectors := ["production-connector", "staging-connector"]

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  input.resource.technology == "postgres"
}
```

Use `excluded_connectors` to exclude specific connectors:

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

import future.keywords.if

# Exclude these Connectors
excluded_connectors := ["dev-connector"]

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  input.resource.technology == "postgres"
}
```

> [!WARNING]
>
> A single policy cannot use both `included_connectors` and
> `excluded_connectors`. Choose one or the other.

### Include/Exclude Resources

Use `included_resources` to apply a policy only to specific resources:

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

import future.keywords.if

# Only apply to specific resources
included_resources := ["production-postgres"]

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  input.user.type == "machine"
}
```

Use `excluded_resources` to exclude specific resources:

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

import future.keywords.if

# Exclude specific resources
excluded_resources := ["dev-postgres", "staging-postgres"]

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  "engineer" in input.user.groups
}
```

> [!WARNING]
>
> A single policy cannot use both `included_resources` and `excluded_resources`.
> Choose one or the other.

### Include/Exclude Spaces

Scoping by [Space](https://docs.formal.ai/docs/guides/core-concepts/spaces.md) covers every Connector and Resource the Space contains. Use `included_spaces` to apply a policy only to specific Spaces:

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

import future.keywords.if

# Only apply to these Spaces
included_spaces := ["production"]

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  input.user.type == "machine"
}
```

Use `excluded_spaces` to exclude specific Spaces:

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

import future.keywords.if

# Exclude these Spaces
excluded_spaces := ["sandbox"]

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  input.resource.technology == "postgres"
}
```

> [!WARNING]
>
> A single policy cannot use both `included_spaces` and `excluded_spaces`. Choose
> one or the other.

> [!NOTE]
>
> Connectors that belong to no Space are never in scope for `included_spaces`,
> and are always in scope for `excluded_spaces`.

### Include/Exclude Technologies

Use `included_technologies` or `excluded_technologies` to scope a policy by the Resource's technology identifier, such as `postgres`, `ssh`, or `llm`:

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

import future.keywords.if

# Only apply to SQL databases
included_technologies := ["postgres", "mysql", "snowflake"]

session := {
  "action": "block",
  "type": "block_with_formal_message"
} if {
  input.user.type == "machine"
}
```

> [!WARNING]
>
> A single policy cannot use both `included_technologies` and
> `excluded_technologies`. Choose one or the other.

## Policy Stage Configuration

Policy evaluation can also be turned off per stage for a Resource or a Connector, without editing policies. See [Policy Stage Configuration](https://docs.formal.ai/docs/guides/policies/stage-configuration.md).


## Related topics

- [Core Concepts](https://docs.formal.ai/docs/guides/getting-started/concepts.md)
- [Protect Sensitive Data](https://docs.formal.ai/docs/guides/use-cases/protect-sensitive-data.md)
- [Identities](https://docs.formal.ai/docs/guides/core-concepts/identities.md)
- [Policies](https://docs.formal.ai/docs/guides/policies/introduction.md)
- [Policy Evaluation](https://docs.formal.ai/docs/guides/policies/evaluation.md)


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