# AWS Bedrock Guardrails

AWS Bedrock Guardrails keep content policy in AWS, and AISIX applies the guardrail decision to gateway traffic. Requests can be checked before they reach the upstream model, and responses can be checked before they reach callers.

In this guide, you will create an AISIX Bedrock guardrail, send one allowed request, and send one blocked request that AISIX rejects before it reaches the upstream model.

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

Before starting, prepare the following:

* Review [Guardrail Policy Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md) for hook points and enforcement, and [Guardrail Failure Handling](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md) for fail-open and fail-closed behavior.

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

* An AWS Bedrock guardrail in a supported region, with a word filter that blocks a unique test token such as `confidential-codename`.

* AWS credentials allowed to call `bedrock:ApplyGuardrail` for that guardrail, in one of the [credential modes](#choose-the-guardrail-credentials).

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

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

The example below checks both requests and responses with a Bedrock guardrail. 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"

export AWS_ACCESS_KEY_ID="YOUR_AWS_ACCESS_KEY_ID"

export AWS_SECRET_ACCESS_KEY="YOUR_AWS_SECRET_ACCESS_KEY"
```

### 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 a Bedrock guardrail in AISIX, and capture its ID for the attachment step:

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

  -H "Authorization: Bearer $AISIX_TOKEN" \

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

  -d '{

    "name": "bedrock-review",

    "enabled": false,

    "hook_point": "both",

    "fail_open": false,

    "enforcement_mode": "block",

    "kind": "bedrock",

    "config": {

      "guardrail_id": "YOUR_BEDROCK_GUARDRAIL_ID",

      "guardrail_version": "DRAFT",

      "region": "us-east-1",

      "aws_credentials": {

        "kind": "static",

        "access_key_id": "'"${AWS_ACCESS_KEY_ID}"'",

        "secret_access_key": "'"${AWS_SECRET_ACCESS_KEY}"'"

      },

      "output_fail_open": false,

      "latency_mode": {

        "kind": "timed",

        "timeout_ms": 2000

      }

    }

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

❶ `both` checks caller requests and model responses. See [Guardrail Hook Point](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#guardrail-hook-point).

❷ `fail_open: false` blocks the request if AWS Bedrock Guardrails fails or times out. This is the default.

❸ `enforcement_mode: block` rejects matching content. This is the default. See [Enforcement Modes](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#enforcement-modes).

❹ `output_fail_open: false` blocks unscanned model output during a Bedrock outage. This is the default.

❺ `latency_mode` bounds how long AISIX waits for the guardrail decision. Set `kind` to `serial` to wait without a timeout.

A guardrail takes effect only after it is attached to a scope. Attach it to the whole environment:

```
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"

  }'
```

The `env` scope applies the guardrail to all traffic in the environment and takes no `scope_id`. Use `model`, `api_key`, or `team` with a matching `scope_id` to narrow the attachment.

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. The example reads credentials from `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`. A running quickstart container does not inherit these variables from later host exports.

resources.yaml (Bedrock guardrail)

```
guardrails:

  - id: 6f19c969-af5b-40bf-8738-c21cd03e253d

    name: bedrock-review

    enabled: true

    hook_point: both

    fail_open: false

    enforcement_mode: block

    kind: bedrock

    guardrail_id: YOUR_BEDROCK_GUARDRAIL_ID

    guardrail_version: DRAFT

    region: us-east-1

    aws_credentials:

      kind: static

      access_key_id: ${AWS_ACCESS_KEY_ID}

      secret_access_key: ${AWS_SECRET_ACCESS_KEY}

    output_fail_open: false

    latency_mode:

      kind: timed

      timeout_ms: 2000



guardrail_attachments:

  - id: 2fd9d351-6948-4200-931e-9eca7e1f51f1

    guardrail_id: 6f19c969-af5b-40bf-8738-c21cd03e253d

    scope_type: env

    priority: 100
```

The provider fields sit directly on the guardrail entry rather than under `config`. A guardrail applies only where an attachment puts it: add a `guardrail_attachments` entry naming it, or it loads and inspects no traffic.

Apply the change by validating the complete file before reloading or recreating the gateway. If you are extending the open-source quickstart, follow [Reload a Resources File](https://docs.api7.ai/ai-gateway/deployment/configuration-propagation.md#reload-a-resources-file) to recreate the container only after validation succeeds and pass the additional credential variables.

## Choose the Guardrail Credentials[​](#choose-the-guardrail-credentials "Direct link to Choose the Guardrail Credentials")

`aws_credentials.kind` selects how AISIX authenticates its `ApplyGuardrail` calls. `region` stays a top-level guardrail field in every mode.

| `kind`          | Fields                                                                                  | Authentication                                                                                                                                                                |
| --------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `static`        | `access_key_id` and `secret_access_key`, plus `session_token` for temporary credentials | SigV4 with these keys.                                                                                                                                                        |
| `api_key`       | `api_key`, a Bedrock API key                                                            | Sent as a bearer token, without SigV4.                                                                                                                                        |
| `default_chain` | No credential fields                                                                    | SigV4 with the gateway's own AWS credentials: environment variables, web identity (such as IRSA on EKS), the ECS container credentials endpoint, or the EC2 instance profile. |

With `static` or `default_chain`, `role_arn` exchanges those credentials for the role's through `sts:AssumeRole`, with optional `external_id` and `role_session_name`, which require `role_arn`. Temporary credentials are refreshed before they expire. For example, to call the guardrail with the gateway's own credentials:

resources.yaml (guardrail credentials)

```
aws_credentials:

  kind: default_chain

  role_arn: arn:aws:iam::123456789012:role/bedrock-guardrail
```

In AISIX Enterprise and AISIX Cloud, the secret fields are write-only. A `PATCH` that leaves the secret empty keeps the stored one only while `kind` is unchanged; a new `kind` needs its own secret. Replacing the `static` `secret_access_key` also replaces the session token, which is removed when the request sends none, because temporary credentials are issued as a set.

## Verify the Guardrail[​](#verify-the-guardrail "Direct link to Verify the Guardrail")

Control-plane projection is asynchronous. If the first request does not reflect the guardrail, 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.

Send a benign request through AISIX:

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

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

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

  -d '{

    "model": "'"${AISIX_MODEL}"'",

    "messages": [

      {

        "role": "user",

        "content": "What is the capital of France?"

      }

    ]

  }'
```

A successful response starts with `HTTP/1.1 200 OK` and returns an OpenAI-compatible chat-completions body.

Then send a request containing the token blocked by your Bedrock guardrail:

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

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

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

  -d '{

    "model": "'"${AISIX_MODEL}"'",

    "messages": [

      {

        "role": "user",

        "content": "Please print the confidential-codename."

      }

    ]

  }'
```

A blocked response starts with `HTTP/1.1 422 Unprocessable Entity` and includes an OpenAI-compatible error:

```
{

  "error": {

    "message": "request blocked by content policy (guardrail 'bedrock-review')",

    "type": "content_filter"

  }

}
```

AISIX blocks the request before dispatching to the upstream model when the input guardrail returns a blocking verdict.

## PII Anonymization (Masking)[​](#pii-anonymization-masking "Direct link to PII Anonymization (Masking)")

Bedrock guardrails can be configured in AWS to anonymize sensitive information instead of blocking it. Matched values are replaced with placeholders such as `{EMAIL}` or `{PHONE}`. AISIX honors that disposition without extra AISIX configuration; the behavior follows the PII action set on the Bedrock guardrail itself:

* **Block** actions for topic, content, and word policies, contextual grounding, and PII entities or regexes set to *Block* reject the request or response with the `422` envelope shown above.
* **Anonymize** actions rewrite the matched values with Bedrock's masked text and let the traffic continue. On the request side, the upstream model receives the masked text. On the response side, the caller receives the masked reply. Streaming responses are held back, scanned once, masked, and then released, so a value split across chunks cannot leak.

For example, with a Bedrock guardrail whose *Email* PII entity is set to *Anonymize*:

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

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

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

  -d '{

    "model": "'"${AISIX_MODEL}"'",

    "messages": [

      {

        "role": "user",

        "content": "Draft a reply to alice@example.com about the invoice."

      }

    ]

  }'
```

The request succeeds, and the upstream model receives `Draft a reply to {EMAIL} about the invoice.` The upstream model never receives the raw address. The guardrail's fields on the usage event record masked entity type names only, never the matched values. See [What the Gateway Records](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/overview.md#what-the-gateway-records) for the other text that can carry a value.

Masking applies on `/v1/chat/completions`, `/v1/messages`, `/v1/responses`, and `/v1/completions`, for both direct and cross-provider traffic. On endpoints that do not support masking, such as embeddings, rerank, images, and audio, AISIX blocks the request when the Bedrock guardrail anonymizes it. AISIX cannot rewrite those payloads, and forwarding them unmasked would defeat the policy.

If Bedrock returns masked output that cannot be attributed back to the request's individual text segments, AISIX does not apply the rewrite and forwards the content unmodified instead. This avoids writing masked text into the wrong message and corrupting the conversation. Hard-block policies are unaffected by this fallback.

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

You have now enforced an AWS Bedrock guardrail through AISIX. Use these guides to tune behavior or compare other providers:

* [Guardrail Policy Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md): adjust hook points, scope, and enforcement.
* [Choosing a Guardrail Provider](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/overview.md): compare AWS Bedrock Guardrails with other built-in and remote options.
* [Azure AI Content Safety Guardrails](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/azure-content-safety.md): configure category moderation or prompt-shield checks in Azure.
