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

# HTTP

> How to connect to an HTTP Resource using the Formal Connector

> [!WARNING]
>
> The connector runs a healthcheck server on port 8080 to let clients determine if the proxy is operational. As a result, you cannot create a listener on port 8080 to connect to an HTTP resource.

## Connect to an HTTP Resource

To connect to an HTTP Resource, follow these steps:

1. **Adjust the Hostname**: In your API request, modify the hostname to point to the Connector. Replace the hostname with the http resource name you have specified in the resources section of the Control Plane or Terraform. If the hostname of your connector is `formalcloud.net`, and your http resource name is `stripe`, you can replace the request URL with the following:

   * Old Way:
     `https://api.stripe.com/v1/customers`
   * New Way (Using the Connector):
     `https://stripe.formalcloud.net/v1/customers`

![](https://mintcdn.com/formal/z9GNtynV1YHUDYCN/assets/images/http-example.png?fit=max\&auto=format\&n=z9GNtynV1YHUDYCN\&q=85\&s=e783048b95bc79670ed06d1577427f87)

2. **Tool of Your Preference**: Use your preferred API tool to send requests through the Connector. This can be tools like Postman, cURL, or any other HTTP client that allows you to specify the API endpoint. In order to see the user who made the request, you can set `X-Formal-User-Username` and `X-Formal-User-Password` in the request headers.

## Headers sent to the Resource

The Connector tells the Resource who sent each request:

* `X-Forwarded-For` and `X-Real-IP` carry the client's IP address. The Connector replaces any values the client sent in these headers.
* `X-Formal-User-Username` carries the user's Formal username, if the request has one.
* `X-Formal-End-User-Identity` carries the email of the end user a machine user acts for, if the machine user names one. The Connector removes this header from requests by human users and anonymous requests.

To stop the Connector from sending the client's IP address, turn off **Forward client IP** in the Resource's settings, or set `forward_client_ip_headers` to `false` on the `formal_resource` in Terraform. To stop it from sending `X-Formal-User-Username` and `X-Formal-End-User-Identity`, turn off **Forward username**, or set `forward_username_header` to `false`.

## Payload Encryption

The Connector can encrypt request and response payloads before they're sent to the Formal Control Plane. This ensures that Formal won't have access to any transmitted data. Create a [log schema](https://docs.formal.ai/docs/guides/observability/log-schemas.md#http-bodies) to enable payload encryption.

### Decrypting the logs in Formal UI

1. First, deploy the AWS Lambda function using the code found [here](https://github.com/formalco/decryptor).
2. Then, navigate to a specific HTTP Log and hit the `Decrypt Response Body` or `Decrypt Request Body` to input the URL of the Lambda function directly in the UI.

You can watch a demo of this feature [here](https://www.loom.com/share/520863bc10fb40e88b6d0a697175a983?sid=db5c0266-dc25-4bd6-9e1e-d4571009d90e).

## HTTP Payload Size Limitation

To ensure efficient and streamlined logging while preventing potential issues related to large data volumes, you can limit the size of HTTP request and response payloads in logs. Create a [log schema](https://docs.formal.ai/docs/guides/observability/log-schemas.md#schema-actions) with a `truncate` action on the body fields, such as `log.request.http.body.received`.

## Multiple Resources

The Connector supports connecting multiple downstream APIs to the same Connector.

For example, using a Connector with the hostname `test-http-proxy.formalcloud.net`, you can query:

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
- `stripe.test-http-proxy.formalcloud.net`
- `openai.test-http-proxy.formalcloud.net`
```

Which will then redirect traffic to the following resources:

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
- api.stripe.com
- api.openai.com
```

**1. First Step**

Configure your DNS entries with the subdomains.

**2. Second Step**

Create HTTP resources with names matching the subdomains used in the hostname of the Connector. In the example provided, the names of the resources should be `openai` and `stripe`.

**3. Third Step**

Link multiple resources to the same port.

> [!NOTE]
>
> The TLS Certificate must be a wildcard certificate and should cover every subdomain.

## Policy Evaluation

Formal supports the following policy evaluation stages for HTTP:

* **Session**: Evaluate and enforce policies at connection time. Actions: `allow`, `block`.
* **Request**: Evaluate and enforce policies before request execution. Actions: `allow`, `block`, `rewrite`, `decrypt`.
* **Response**: Evaluate and enforce policies after data retrieval. Actions: `allow`, `filter`, `mask`, `rewrite`, `encrypt`.

Use `encrypt` and `decrypt` to seal secrets such as OAuth tokens on the Connector. See [Token Encryption](https://docs.formal.ai/docs/guides/core-concepts/connectors/token_encryption.md) and [Encrypt & Decrypt](https://docs.formal.ai/docs/guides/policies/enforcement.md#encrypt--decrypt-actions). For an MCP worked example, see [Encrypt MCP OAuth Tokens](https://docs.formal.ai/docs/guides/example-use-cases/encrypt-mcp-oauth-tokens.md).

### Header Rewrites

The `rewrite` action at the request stage adds, replaces, or removes HTTP headers before the request reaches the upstream service. Common use cases include injecting authentication tokens, enforcing organization-level API restrictions, and stripping internal headers. For Anthropic tenant restrictions, see [Restrict Anthropic Sign-Ins to One Org](https://docs.formal.ai/docs/guides/example-use-cases/restrict-anthropic-sign-ins.md).

> [!NOTE]
>
> Header names in `input.http.headers` are normalized to lowercase. The rewrite applies canonical HTTP casing before forwarding (e.g., `x-custom-header` becomes `X-Custom-Header`).

#### Add a header

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

import future.keywords.if

rewritten_headers := object.union(input.http.headers, {
  "x-org-id": ["org-123"],
})

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

Header values must be arrays of strings. `object.union` merges the new headers into the existing `input.http.headers`; keys in the second object overwrite keys in the first.

#### Replace an existing header

The same `object.union` pattern overwrites a header value:

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

import future.keywords.if

rewritten_headers := object.union(input.http.headers, {
  "authorization": ["Bearer <YOUR_SERVICE_TOKEN>"],
})

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

#### Remove a header

Setting a header to an empty array removes it before the request is forwarded:

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

import future.keywords.if

rewritten_headers := object.union(input.http.headers, {
  "x-debug": [],
})

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

> [!TIP]
>
> Formal logs both received and sent headers for each request. Rewrite behavior is visible in the [Logs](https://docs.formal.ai/docs/guides/observability/logs.md) page.

### Body Rewrites

The `rewrite` action can replace an entire HTTP request or response body.
At each stage, `input.http` describes the message being evaluated.

Each rewrite action supports one body field:

| Field | Policy input | Behavior |
| - | - | - |
| `body` | `input.http.body` | Writes the string exactly. |
| `json` | `input.http.json` | Serializes a JSON value. |
| `post_form` | `input.http.post_form` | Rewrites HTML form fields. |

Formal rejects actions that set more than one of `body`, `json`, or `post_form`.

#### Text bodies

The `body` field replaces plain text, XML, or another body represented as a string:

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

import future.keywords.if

request := {
  "action": "rewrite",
  "body": "replacement text",
} if {
  input.resource.technology == "http"
  input.http.path == "/messages"
}
```

An empty string clears the body.

#### JSON bodies

The request or response must contain valid JSON and use a JSON content type.
Formal then exposes the parsed value as `input.http.json`.

`object.union` replaces selected fields while preserving the remaining object:

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

import future.keywords.if

rewritten_json := object.union(input.http.json, {
  "password": "redacted",
})

request := {
  "action": "rewrite",
  "json": rewritten_json,
} if {
  input.resource.technology == "http"
  input.http.path == "/users"
}
```

Rego's
[`json.patch`](https://www.openpolicyagent.org/docs/policy-reference/builtins/object#builtin-json-patch)
built-in supports nested changes and array operations.
It accepts standard [JSON Patch](https://jsonpatch.com/) operations.

The following patch replaces a nested value, removes a field, and appends an array item:

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

import future.keywords.if

patched_json := json.patch(input.http.json, [
  {
    "op": "replace",
    "path": "/profile/email",
    "value": "redacted",
  },
  {
    "op": "remove",
    "path": "/internal_note",
  },
  {
    "op": "add",
    "path": "/labels/-",
    "value": "reviewed",
  },
])

request := {
  "action": "rewrite",
  "json": patched_json,
} if {
  input.resource.technology == "http"
  input.http.path == "/users"
}
```

Patch paths use slash-separated keys, such as `/profile/email`.
All operations apply atomically.
If any operation fails, `json.patch` is undefined and this rewrite does not apply.

The Rego documentation describes
[JSON object syntax and access](https://www.openpolicyagent.org/docs/policy-language/#objects).
Its [object built-ins](https://www.openpolicyagent.org/docs/policy-reference/builtins/object)
include `object.get`, `object.remove`, `object.union`, and related functions.

If the body or content type does not qualify, `input.http.json` is absent.
The raw string remains available as `input.http.body`.

#### HTML form bodies

Formal exposes parsed HTML form fields as `input.http.post_form`.
Each field contains an array because a form can repeat keys.

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

import future.keywords.if

rewritten_form := object.union(input.http.post_form, {
  "password": ["redacted"],
})

request := {
  "action": "rewrite",
  "post_form": rewritten_form,
} if {
  input.resource.technology == "http"
  input.http.path == "/login"
}
```

Repeated values use string arrays, such as `{"scope": ["read", "write"]}`.

#### Response bodies

A `response` rule supports the same fields.
At this stage, `input.http.body`, `input.http.json`, and `input.http.post_form` describe the upstream response.

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

import future.keywords.if

response := {
  "action": "rewrite",
  "json": object.union(input.http.json, {
    "internal_note": "redacted",
  }),
} if {
  input.resource.technology == "http"
  input.http.path == "/accounts"
}
```

> [!TIP]
>
> Formal logs the original body as received and the rewritten body as sent.
> The [Logs](https://docs.formal.ai/docs/guides/observability/logs.md) page displays both values.

## Authentication

The Connector supports forwarding HTTP authentication headers transparently from HTTP clients. In addition, the Connector supports adding HTTP authentication headers that
the HTTP client does not have access to using Native Users.

### Native Users

The connector can inject credentials for the upstream Resource using Native
Users.
Choose one of these typed credential methods:

* **HTTP Basic** injects a username and password into a named header.
* **HTTP Bearer** injects a bearer token into a named header.
* **API Key (Header)** injects a key into a named request header.
* **API Key (Query)** injects a key into a named query parameter.

#### Terraform

Use the Terraform block that matches the credential method.

##### HTTP Basic

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_native_user_v3" "http_basic" {
  resource_id = formal_resource.api.id
  label       = "basic-auth"

  http_basic {
    header   = "Authorization"
    username = "api_user"
    password {
      environment_variable = "HTTP_BASIC_PASSWORD"
    }
  }
}
```

##### HTTP Bearer

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_native_user_v3" "http_bearer" {
  resource_id = formal_resource.api.id
  label       = "bearer"

  http_bearer {
    header = "Authorization"
    token {
      environment_variable = "HTTP_BEARER_TOKEN"
    }
  }
}
```

##### API Key (Header)

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_native_user_v3" "http_api_key_header" {
  resource_id = formal_resource.api.id
  label       = "header-api-key"

  http_api_key_header {
    key = "X-Api-Key"
    value {
      environment_variable = "HTTP_API_KEY_HEADER"
    }
  }
}
```

##### API Key (Query)

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_native_user_v3" "http_api_key_query" {
  resource_id = formal_resource.api.id
  label       = "query-api-key"

  http_api_key_query {
    key = "api_key"
    value {
      environment_variable = "HTTP_API_KEY_QUERY"
    }
  }
}
```

Each secret can be stored in the Formal control plane, read from a Connector
environment variable, or returned by a connection-time hook.

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.

> [!NOTE]
>
> If an HTTP Resource has no Native Users configured, the Connector forwards
> requests upstream without injecting credentials.

### Linked accounts

Instead of a shared native user, the Connector can send each user's own OAuth token for the upstream API. Each user links their account once in the Catalog. For APIs such as GitHub that publish no protected resource metadata, set the provider's authorization server. See [OAuth and Linked Accounts](https://docs.formal.ai/docs/guides/core-concepts/resources/oauth.md).

### Seal client-held tokens

To seal client-held OAuth tokens so they leave the Connector as `formalsealed:` envelopes, configure [Token Encryption](https://docs.formal.ai/docs/guides/core-concepts/connectors/token_encryption.md) and use the HTTP `encrypt` and `decrypt` policy actions.


## Related topics

- [HTTP API](https://docs.formal.ai/docs/guides/configuration/sdks/http-api.md)
- [CLI Reference](https://docs.formal.ai/docs/guides/client-apps/cli.md)
- [Formal API](https://docs.formal.ai/docs/api/introduction.md)
- [Smart Routing](https://docs.formal.ai/docs/guides/core-concepts/resources/smart-routing.md)
- [Kubernetes Operator Custom Resources](https://docs.formal.ai/docs/guides/core-concepts/kubernetes-operator/custom-resources.md)


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