# PII Detection and Redaction

The PII guardrail detects sensitive data in request and response text. It can mask each match with a redaction token and let traffic continue, or block the request or response.

PII detection runs inside the gateway, so no external moderation service is called. The guardrail's own log lines, usage-record fields, and refusals do not contain matched values. [What the Gateway Records](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/overview.md#what-the-gateway-records) describes the other text that can.

In this guide, you will create a PII guardrail that masks built-in detector matches, add a custom pattern, and verify both masking and blocking behavior.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

Before starting, prepare the following:

* Review [Guardrail Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md) for hook points and enforcement modes.

* One of these configuration paths:

  <!-- -->

  * AISIX Enterprise or AISIX Cloud with an environment, an attached gateway, and a write-scoped admin token. For AISIX Enterprise, follow the [AISIX Enterprise getting-started guide](https://docs.api7.ai/ai-gateway/getting-started/aisix-cloud-quickstart.md). To request AISIX Cloud access, [contact API7](https://api7.ai/contact).
  * An open-source AISIX gateway that loads a declarative [`resources.yaml`](https://docs.api7.ai/ai-gateway/reference/resources-file.md) file.

* A working model alias and caller API key that can send Chat Completions requests.

* `curl`. The control-plane path also uses `jq`.

## Built-in Detectors[​](#built-in-detectors "Direct link to Built-in Detectors")

Enable any of the built-in detectors by listing its `type` under `detectors`. Two detectors validate a checksum before matching so that a random digit run is not masked.

| `type`          | Matches                                                                                              |
| --------------- | ---------------------------------------------------------------------------------------------------- |
| `email`         | Email addresses                                                                                      |
| `china_mobile`  | Mainland China mobile numbers                                                                        |
| `china_id_card` | Mainland China resident ID numbers (ISO 7064 checksum)                                               |
| `bank_card`     | Bank card numbers, unbroken or grouped (Luhn checksum). See [Bank Card Formats](#bank-card-formats). |
| `us_ssn`        | US Social Security Numbers                                                                           |
| `ip_address`    | IPv4 addresses                                                                                       |
| `api_key`       | API keys and tokens (OpenAI, AWS, GitHub, Slack, Google signatures)                                  |
| `jwt`           | JSON Web Tokens                                                                                      |
| `private_key`   | PEM private key blocks                                                                               |

Built-in detectors read word boundaries as ASCII, so a value written directly next to Chinese text, such as `卡號4111111111111111`, is detected. As a result, `us_ssn` and `ip_address` do not match a value written in full-width digits. A gateway at 1.9.0 or earlier does not detect a value next to Chinese text, and does match those full-width digits.

### Bank Card Formats[​](#bank-card-formats "Direct link to Bank Card Formats")

`bank_card` matches two forms, and each must pass the Luhn check:

* **Unbroken digits**: a run of 13 to 19 digits with any prefix.
* **Grouped digits**: groups of 4-4-4-4, 4-4-4-4-3, 4-6-5, or 4-6-4 digits, separated by spaces or hyphens. The number must start with `22` through `27`, or with `3`, `4`, `5`, `6`, `8`, or `9`. A 19-digit grouped number also matches when its first 16 digits pass the Luhn check.

A gateway at 1.9.0 or earlier matches only unbroken digits.

The detector has these known limitations:

* An unbroken digit run that happens to pass the Luhn check, such as an order number, is still masked.
* A grouped card number is missed when a 4-digit number with a card prefix comes directly before it, separated by one space or hyphen, as in `ref 4026 4111 1111 1111 1111`. The match starts at the first number and consumes the card.

## Match Actions[​](#match-actions "Direct link to Match Actions")

Each match resolves to one of two actions:

* `mask`: replace the matched span with a token such as `[EMAIL_REDACTED]`. Input masking continues to the upstream model; output masking continues to the caller.
* `block`: reject the request or response with `422 Unprocessable Entity`.

`default_action` sets the action for every detector and custom pattern. Set `action` on an individual detector or custom pattern to override it.

A `mask` match that AISIX cannot rewrite is not masked. Passthrough routes, `/a2a`, Batch and Fine-tuning jobs, `/v1/realtime`, and the `/v1/videos` prompt relay content without a rewrite path, so a match there passes unmodified and is recorded as `mask_unsupported`, or `would_mask_unsupported` in monitor mode. Inside structured tool arguments and results, a `mask` match on an object key or a number blocks, because neither can be rewritten. See [Surfaces That Cannot Apply a Mask](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#surfaces-that-cannot-apply-a-mask) and [How Keyword and PII Guardrails Read Structured Content](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#how-keyword-and-pii-guardrails-read-structured-content).

## Create a PII Guardrail[​](#create-a-pii-guardrail "Direct link to Create a PII Guardrail")

The example below masks email addresses and API keys in caller requests before AISIX sends them to the upstream provider. Choose one configuration path, then use the shared verification procedure.

Export the gateway values used by both paths:

```
# AISIX_PROXY has no trailing slash or endpoint path.

# The local quickstarts use http://127.0.0.1:3000.

export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"

export AISIX_API_KEY="YOUR_CALLER_API_KEY"

export AISIX_MODEL="gpt-4o-mini"
```

### AISIX Enterprise or AISIX Cloud[​](#aisix-enterprise-or-aisix-cloud "Direct link to AISIX Enterprise or AISIX Cloud")

Export the control-plane connection details:

```
# AISIX_CP includes /api and has no trailing slash.

# The local AISIX Enterprise quickstart uses http://localhost:8080/api.

export AISIX_CP="YOUR_AISIX_CONTROL_PLANE_API_URL"

export AISIX_TOKEN="YOUR_ADMIN_TOKEN"

export ENV_ID="YOUR_ENVIRONMENT_ID"
```

Create an input guardrail that masks the `email` and `api_key` detectors, and capture its ID:

```
GUARDRAIL_ID=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "name": "pii-redaction-policy",

    "enabled": false,

    "hook_point": "input",

    "kind": "pii",

    "config": {

      "default_action": "mask",

      "detectors": [

        { "type": "email" },

        { "type": "api_key" }

      ]

    }

  }' | jq -r '.guardrail.id')
```

❶ Creating the guardrail disabled prevents it from applying globally before its attachment exists. Enable it after attaching it below.

❷ `input` masks the caller request before AISIX sends it upstream. Use `output` to redact provider responses, or `both` to cover both sides. See [Guardrail Hook Point](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#guardrail-hook-point).

❸ `default_action` sets the action for listed detectors. `mask` replaces each match with a redaction token. Set a detector-level `action` only when one detector needs to behave differently.

Attach the guardrail to the whole environment (`scope_type: "env"` binds every request in the environment and omits `scope_id`; use `model`, `api_key`, or `team` with a `scope_id` to narrow it):

```
curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID/attachments" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{ "scope_type": "env" }'
```

Enable the guardrail after its attachment exists:

```
curl -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{"enabled": true}'
```

The enabled configuration projects to attached gateways automatically.

### AISIX OSS[​](#aisix-oss "Direct link to AISIX OSS")

Add the guardrail to the resources file that already defines the example model and caller API key:

resources.yaml (PII masking guardrail)

```
guardrails:

  - id: 1cd238bc-081f-4f9e-a21c-79098843ceaa

    name: pii-redaction-policy

    enabled: true

    hook_point: input

    kind: pii

    default_action: mask

    detectors:

      - type: email

      - type: api_key



guardrail_attachments:

  - id: 8350752d-88e9-4c9b-b97b-3205de84238d

    guardrail_id: 1cd238bc-081f-4f9e-a21c-79098843ceaa

    scope_type: env

    priority: 100
```

❶ `mask` replaces every detected span with a redaction token and lets the request continue.

❷ Each detector runs inside the gateway. An individual detector can set `action: block` when it should override the default.

A guardrail applies only where an attachment puts it: add a `guardrail_attachments` entry naming it, or it loads and inspects no traffic. Validate the complete file, then reload the gateway. See [Reload a Resources File](https://docs.api7.ai/ai-gateway/deployment/configuration-propagation.md#reload-a-resources-file) for the runnable Docker workflow.

For response-side PII redaction on streamed traffic, AISIX holds response content until it can apply the guardrail. See [Streaming Output](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#streaming-output) for buffer defaults and overflow behavior.

## Verify Masking[​](#verify-masking "Direct link to Verify Masking")

Send a request whose prompt contains an email address. Control-plane projection is asynchronous; if the first request does not reflect the new rule, wait for the gateway to apply the latest revision and retry. See [Resource Projection](https://docs.api7.ai/ai-gateway/cloud/resource-projection.md) for convergence checks.

```
curl -sSi -X POST "$AISIX_PROXY/v1/chat/completions" \

  -H "Authorization: Bearer ${AISIX_API_KEY}" \

  -H "Content-Type: application/json" \

  --data-binary @- <<EOF

  {

    "model": "${AISIX_MODEL}",

    "messages": [

      {

        "role": "user",

        "content": "email me at alice@example.com about the order"

      }

    ]

  }

EOF
```

The request succeeds with `HTTP/1.1 200 OK`. AISIX rewrites the prompt before calling the upstream model, so the provider receives the masked prompt:

```
email me at [EMAIL_REDACTED] about the order
```

The original value does not reach the upstream provider. Usage records carry per-detector match counts, including detector names but not matched text. A validation error raised before the guardrail runs can still quote the value; see [What the Gateway Records](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/overview.md#what-the-gateway-records).

## Block Sensitive Data[​](#block-sensitive-data "Direct link to Block Sensitive Data")

Use `block` when a detector should reject traffic instead of masking it. The following examples add a second guardrail that blocks requests containing a valid mainland China resident ID.

### AISIX Enterprise or AISIX Cloud[​](#aisix-enterprise-or-aisix-cloud-1 "Direct link to AISIX Enterprise or AISIX Cloud")

Create the blocking guardrail and attach it to the environment:

```
BLOCK_GUARDRAIL_ID=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "name": "block-id-card",

    "enabled": false,

    "hook_point": "input",

    "kind": "pii",

    "config": {

      "default_action": "block",

      "detectors": [

        { "type": "china_id_card" }

      ]

    }

  }' | jq -r '.guardrail.id')



curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails/$BLOCK_GUARDRAIL_ID/attachments" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{ "scope_type": "env" }'



curl -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$BLOCK_GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{"enabled": true}'
```

### AISIX OSS[​](#aisix-oss-1 "Direct link to AISIX OSS")

Add the blocking guardrail alongside the masking guardrail in `resources.yaml`:

resources.yaml (PII blocking guardrail)

```
guardrails:

  - id: 1cd238bc-081f-4f9e-a21c-79098843ceaa

    name: pii-redaction-policy

    enabled: true

    hook_point: input

    kind: pii

    default_action: mask

    detectors:

      - type: email

      - type: api_key



  - id: 4470020e-b127-45d6-a23d-c1c135aeea9a

    name: block-id-card

    enabled: true

    hook_point: input

    kind: pii

    default_action: block

    detectors:

      - type: china_id_card



guardrail_attachments:

  - id: 8350752d-88e9-4c9b-b97b-3205de84238d

    guardrail_id: 1cd238bc-081f-4f9e-a21c-79098843ceaa

    scope_type: env

    priority: 100

  - id: 5f6d69e4-f268-4575-b50b-f9adcabbde1b

    guardrail_id: 4470020e-b127-45d6-a23d-c1c135aeea9a

    scope_type: env

    priority: 100
```

Validate the complete file and reload the gateway.

### Verify Blocking[​](#verify-blocking "Direct link to Verify Blocking")

A request whose content includes a valid ID number is rejected:

```
curl -sSi -X POST "$AISIX_PROXY/v1/chat/completions" \

  -H "Authorization: Bearer ${AISIX_API_KEY}" \

  -H "Content-Type: application/json" \

  --data-binary @- <<EOF

  {

    "model": "${AISIX_MODEL}",

    "messages": [

      {

        "role": "user",

        "content": "my id is 11010519491231002X"

      }

    ]

  }

EOF
```

A blocked response starts with `HTTP/1.1 422 Unprocessable Entity` and includes this body:

```
{

  "error": {

    "message": "request blocked by content policy (guardrail 'block-id-card')",

    "type": "content_filter"

  }

}
```

The message is deliberately generic and does not echo the matched value.

## Add a Custom Pattern[​](#add-a-custom-pattern "Direct link to Add a Custom Pattern")

Add `custom_patterns` to detect data specific to your organization. Each pattern needs a `name` and a Rust-compatible `regex`, and accepts an optional per-pattern `action` and `replacement`. AISIX uses the name in the redaction token and match counts. An invalid expression prevents the guardrail from entering the active chain.

The following examples add an employee ID pattern to `pii-redaction-policy` while preserving its existing email and API-key detectors.

### AISIX Enterprise or AISIX Cloud[​](#aisix-enterprise-or-aisix-cloud-2 "Direct link to AISIX Enterprise or AISIX Cloud")

Replace the existing guardrail's configuration with the expanded detector set:

```
curl -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "config": {

      "default_action": "mask",

      "detectors": [

        { "type": "email" },

        { "type": "api_key" }

      ],

      "custom_patterns": [

        {

          "name": "employee_id",

          "regex": "EMP-[0-9]{6}"

        }

      ]

    }

  }'
```

The existing attachment remains in place when the guardrail configuration changes.

### AISIX OSS[​](#aisix-oss-2 "Direct link to AISIX OSS")

Add the same pattern to the existing guardrail entry:

resources.yaml (custom PII pattern)

```
guardrails:

  - id: 1cd238bc-081f-4f9e-a21c-79098843ceaa

    name: pii-redaction-policy

    enabled: true

    hook_point: input

    kind: pii

    default_action: mask

    detectors:

      - type: email

      - type: api_key

    custom_patterns:

      - name: employee_id

        regex: 'EMP-[0-9]{6}'
```

Validate the complete file and reload the gateway. A match on this pattern is masked as `[EMPLOYEE_ID_REDACTED]` through either configuration path.

## Choose What a Masked Span Becomes[​](#choose-what-a-masked-span-becomes "Direct link to Choose What a Masked Span Becomes")

By default a masked span becomes `[<NAME>_REDACTED]`, built from the pattern's `name`. Set `replacement` on a pattern to choose the text yourself, or set it to an empty string to delete the span entirely.

```
custom_patterns:

  - name: employee_id

    regex: 'EMP-[0-9]{6}'

    replacement: '******'
```

Two rules decide what the result looks like, and both differ from what a regular-expression tool usually does:

* **`replacement` is used literally.** `$1` and other group references are not expanded. This is the opposite of `url_rewrites` on a passthrough route, where `$1` does expand.
* **A regex with a capture group replaces only group 1.** The rest of the match is kept as it was. A regex with no capture group replaces the whole match.

The second rule is how a pattern says "replace the value, keep the key." This masks the version but keeps the field name:

```
custom_patterns:

  - name: eda_version

    regex: 'version: (\S+)'

    replacement: '***'
```

`version: 12.1` becomes `version: ***`.

This works where the key and the value are in the same text, such as a message. Inside structured tool arguments and results, `{"version": "12.1"}` holds the key and the value as separate segments, so a pattern that spans both does not match. Match the value on its own there, for example with a pattern for the value's format.

Putting the surrounding text into `replacement` as well is the common mistake, and nothing rejects it:

```
# Wrong: the regex already keeps `ACCT-` and `-5678`, and `$1` is literal.

custom_patterns:

  - name: account

    regex: 'ACCT-([0-9]{4})-([0-9]{4})'

    replacement: 'ACCT-$1-****'
```

`ACCT-1234-5678` becomes `ACCT-ACCT-$1-****-5678` — accepted, and still shaped like something redacted. Keep context outside the capture group instead:

```
custom_patterns:

  - name: account

    regex: 'ACCT-([0-9]{4})-([0-9]{4})'

    replacement: '****'
```

`ACCT-1234-5678` becomes `ACCT-****-5678`.

`replacement` applies to `mask` only. A pattern whose effective action is `block` rejects the request instead of rewriting it, so sending both is an error.

## Decide What Happens When AISIX Cannot Scan[​](#decide-what-happens-when-aisix-cannot-scan "Direct link to Decide What Happens When AISIX Cannot Scan")

The PII guardrail runs inside the gateway and never calls out, so no backend can fail for it. It can still be handed a request body it cannot read — one that is not valid UTF-8. AISIX refuses that request rather than forwarding it unmasked and unscanned, and `fail_open` is the setting that decides.

`fail_open` defaults to `false`: content the guardrail could not be offered is refused with `422`, and the message names the failure tag `unscannable_body`. Set it to `true` where availability matters more than enforcement. The pass is still recorded on the request's usage record as a bypass, so you can alert on it.

In AISIX Enterprise and AISIX Cloud, the option is on the guardrail's create and edit forms. In a resources file, set it on the guardrail entry:

resources.yaml (release traffic the guardrail could not read)

```
guardrails:

  - id: 1cd238bc-081f-4f9e-a21c-79098843ceaa

    name: pii-redaction-policy

    kind: pii

    fail_open: true

    default_action: mask

    detectors:

      - type: email

      - type: api_key
```

Two limits are worth knowing before you rely on it. This kind has no `output_fail_open` counterpart, so the one value governs both of its hooks — it is separate from `on_buffer_exceeded`, which decides what happens when a held-back response outgrows `max_buffer_bytes`. And `fail_open` does not reach a streamed response that is already being held back: a PII guardrail on the output hook buffers streamed output so it can mask across chunk boundaries, and a stream left with nothing scannable is then refused whatever `fail_open` says.

## Next Steps[​](#next-steps "Direct link to Next Steps")

You have configured the built-in PII guardrail and verified mask and block behavior. Use these guides to refine or expand the policy:

* [Guardrail Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md): adjust hook points, enforcement mode, or streaming output.
* [Presidio Guardrails](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/presidio.md): use NER entities and anonymization operators from a Presidio service you run.
* [Choosing a Guardrail Provider](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/overview.md): compare built-in PII detection with remote guardrail services.
