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

# Policies

> Write Rego policies that block, mask, filter, and rewrite traffic through Formal

## What are Policies?

Formal's policy system uses [Open Policy Agent (OPA)](https://www.openpolicyagent.org/), an open-source policy engine that enables you to express access control rules as code. Policies are evaluated in real-time as users connect to resources and execute queries.

Your policies can:

* **Block** connections to resources or specific tables/schemas
* **Redact** query results automatically
* **Encrypt and decrypt** HTTP secrets (for example OAuth tokens) with `encrypt` / `decrypt`
* **Rewrite** queries before they reach the database
* **Filter and limit** result sets
* **Enforce MFA** for sensitive operations

## How Policies Work

Policies are written in [Rego](https://www.openpolicyagent.org/docs/latest/policy-language/), OPA's purpose-built language for access control. They are evaluated at three stages:

1. **Session** - When a connection is established
2. **Request** - Before a query reaches the resource
3. **Response** - When data returns from the resource

Each stage has specific actions available based on when the policy is evaluated. See [Enforcement](https://docs.formal.ai/docs/guides/policies/enforcement.md) for details on available actions.

## Policy Structure

Every policy consists of these essential components:

> [accordion] Name
>
> A **unique identifier** for the policy. No two policies can share the same
> name.

> [accordion] Description
>
> A **clear explanation** of the policy's purpose and scope. This helps other
> admins understand what the policy does.

> [accordion] Code
>
> The **policy logic**, written in
> [Rego](https://www.openpolicyagent.org/docs/latest/policy-language/), OPA's
> purpose-built language for access control.

## Policy Status

Policies can be in one of three states:

| Status | Description | Use Case |
| - | - | - |
| **Draft** | Under development, not enforced | Writing and testing new policies |
| **Dry-run** | Logs violations without enforcing | Testing policies with real traffic before enforcement |
| **Active** | Fully enforced and monitoring | Production enforcement |

> [!TIP]
>
> Use **dry-run** mode to test policies against real traffic without impacting
> users. Review the logs to ensure the policy works as intended before
> activating it.

## Policy Tags

Tags are key/value metadata on a policy, such as `team = "data-platform"`. A policy can have up to 500 tags. Tags don't change how a policy is evaluated.

Set tags with the API or Terraform:

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_policy" "block_deletes" {
  name   = "block-production-deletes"
  status = "active"
  code   = file("${path.module}/policies/block-deletes.rego")

  tags = {
    team   = "data-platform"
    ticket = "SEC-123"
  }
}
```

### Generated Policies

Product features create policies for you, such as [Guardrails](https://docs.formal.ai/docs/guides/ai-governance/guardrails.md) and Catalog [access controls](https://docs.formal.ai/docs/guides/ai-governance/catalog.md#access-controls). Formal marks them with reserved tags:

| Tag | Value |
| - | - |
| `formal:generated` | `true` |
| `formal:generated-policy:kind` | The feature that owns the policy, such as `guardrails:unknown-mcp`, `guardrails:unknown-skill`, `registry:mcp-access`, or `registry:skill-access` |
| `formal:generated-policy:key` | The item the policy belongs to, such as an MCP server or a skill |

Change generated policies from the feature that owns them. Don't use the `formal:generated` prefix for your own tags.

## End-User Identity Propagation

Formal can extract end-user identity from applications like Looker, Metabase, or Retool, enabling policies that work for both direct connections and application-mediated access:

* **Direct connection**: Alice uses `psql` to query a resource → user and end-user are both Alice
* **Application connection**: Katie uses Metabase → user is the machine user, end-user is Katie

This allows you to write policies that consider the actual person behind the query, even when they're using a BI tool.

## Quick Example

Block all connections by default, but allow admins using a specific machine user:

```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": "Admin access via authorized app"
} if {
  "admin" in input.end_user.groups
  input.user.username == "idp:formal:machine:backoffice"
  not input.end_user.email == "john.doe@joinformal.com"
}
```

## Managing Policies

> [tab] Control Plane
>
> 1. Navigate to [Policies](https://app.formal.ai/policies)
> 2. Click **Create Policy**
> 3. Fill in name and description
> 4. Write Rego code in the editor
> 5. Set status (Draft, Dry-run, or Active)
> 6. Click **Create Policy** to save

> [tab] Terraform
>
> ```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> resource "formal_policy" "block_deletes" {
>   name        = "block-production-deletes"
>   description = "Prevent DELETE statements in production"
>   status      = "active"
>
>   code = <<-EOT
>     package formal.v2
>
>     import future.keywords.if
>
>     request := {
>       "action": "block",
>       "type": "block_with_formal_message",
>       "reason": "DELETE not allowed in production"
>     } if {
>       input.resource.environment == "production"
>       input.sql_query.statement_type == "DELETE"
>     }
>   EOT
> }
> ```

## Best Practices

> [accordion] Start with Dry-Run
>
> Always test new policies in dry-run mode first. Review logs to ensure they
> work as expected before activating.

> [accordion] Use Groups for User Policies
>
> Instead of writing policies for individual users, use groups. This makes
> policies scalable and easier to maintain.

> [accordion] Document Your Policies
>
> Write clear descriptions and use meaningful reason fields. Future you (and
> your team) will thank you during audits.

> [accordion] Leverage External Data
>
> Use [Hooks](https://docs.formal.ai/docs/guides/policies/hooks.md) to fetch dynamic approval lists,
> compliance data, or business logic from external systems.

## Learn More

> [card] [Policy Evaluation](https://docs.formal.ai/docs/guides/policies/evaluation.md)
>
> Input data, evaluation stages, and available context

> [card] [Enforcement](https://docs.formal.ai/docs/guides/policies/enforcement.md)
>
> Actions including encrypt, decrypt, block, mask, and rewrite

> [card] [Encrypt MCP OAuth Tokens](https://docs.formal.ai/docs/guides/example-use-cases/encrypt-mcp-oauth-tokens.md)
>
> Seal Notion MCP OAuth tokens on the Endpoint or Connector

> [card] [Restrict Anthropic Sign-Ins](https://docs.formal.ai/docs/guides/example-use-cases/restrict-anthropic-sign-ins.md)
>
> Allow Claude sign-ins only for your Anthropic organization ID

> [card] [Restrict Codex Desktop Egress](https://docs.formal.ai/docs/guides/example-use-cases/restrict-codex-desktop-egress.md)
>
> Allow Codex Desktop egress only through LLM and named MCP resources

> [card] [Examples](https://docs.formal.ai/docs/guides/policies/examples.md)
>
> Real-world policy examples and common use cases


## Related topics

- [Triggered Policies and Policy Suspensions](https://docs.formal.ai/docs/guides/policies/suspensions.md)
- [Policy Operations](https://docs.formal.ai/docs/guides/policies/operations.md)
- [Policy Hooks](https://docs.formal.ai/docs/guides/policies/hooks.md)
- [Policy Enforcement](https://docs.formal.ai/docs/guides/policies/enforcement.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.