> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Bedrock Agents Should Use Bedrock Guardrails To Protect Agent Sessions

### More Info:

Bedrock Agents should use Bedrock Guardrails to protect agent sessions

### Risk Level

High

### Address

Security

### Compliance Standards

* APRA CPS 234 (Australia)
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS Critical Security Controls v8
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* DPDPA
* Digital Operational Resilience Act (EU)
* ISO/IEC 27018
* ISO/IEC 27701
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* SOC2
* SWIFT Customer Security Controls Framework
* Sarbanes-Oxley IT General Controls
* StateRAMP
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Below are concise, step‑by‑step instructions to ensure an Amazon Bedrock Agent uses a Bedrock Guardrail from the AWS Management Console.

        ***

        ## 1. Create (or Verify) a Guardrail

        1. Sign in to the **AWS Management Console** and open **Amazon Bedrock**.
        2. In the left navigation pane, choose **Guardrails**.
        3. Click **Create guardrail**.
        4. Configure:
           * **Name** and optional **description**.
           * **Content filters** (e.g., violence, hate, sexual content) and their severities.
           * Any **topic filters**, **PII protection**, or **contextual rules** you need.
        5. Click **Create** to save the guardrail.
        6. On the guardrail’s detail page, note:
           * The **Guardrail ID**.
           * The **Version** (e.g., `1`).

        If you already have a guardrail, just open it and confirm its settings and version.

        ***

        ## 2. Attach the Guardrail to a Bedrock Agent

        1. In the same **Amazon Bedrock** console, in the left navigation pane, choose **Agents**.
        2. Click the **Agent** you want to protect.
        3. Go to the **Agent configuration** or **Agent details** page.
        4. Look for the **Guardrails** section (or **Safety / Guardrail configuration** depending on the current console UI).
        5. Choose **Edit** or **Attach guardrail**.
        6. In the **Guardrail** drop‑down:
           * Select the **Guardrail ID** you created/verified.
           * Select the **Guardrail version** (for example, `1`).
        7. Save or **Update** the agent configuration.

        ***

        ## 3. (If Needed) Update Agent Aliases to Use the Guardrail

        If your application calls a specific alias:

        1. In the **Agents** page, select your agent.
        2. Go to the **Aliases** tab.
        3. Select the alias used by your application.
        4. Choose **Edit** (or **Update**).
        5. Ensure it is using the **latest agent version** that has the guardrail attached.
        6. Save the alias settings.

        ***

        ## 4. Test the Guardrail

        1. From the **Agent** detail page, use **Test agent** (or **Chat** / **Playground**, depending on UI).
        2. Send prompts that might trigger the configured filters.
        3. Confirm the responses are blocked, redacted, or modified according to your guardrail rules.

        Once the agent is associated with a Bedrock Guardrail and your alias points to that updated agent version, your Bedrock Agent sessions are protected by the guardrail.
      </Accordion>

      <Accordion title="Using CLI">
        Below are the minimal AWS CLI steps to ensure a Bedrock Agent is using a Bedrock Guardrail to protect its sessions.

        ***

        ## 1. Create (or identify) a Guardrail

        If you already have a guardrail, skip to step 2.

        ```bash theme={null}
        REGION=us-east-1

        aws bedrock create-guardrail \
          --region "$REGION" \
          --client-request-token "$(uuidgen)" \
          --name "my-agent-guardrail" \
          --description "Guardrail for my Bedrock Agent sessions" \
          --blocked-input-words '["forbidden-term"]' \
          --blocked-output-words '["forbidden-term"]' \
          --sensitive-information-policy '{
            "piiEntities": [],
            "regexes": []
          }' \
          --content-filters '[]' \
          --guardrail-topic-policy '{
            "topics": [],
            "blockedTopics": []
          }'
        ```

        This returns JSON including:

        ```json theme={null}
        {
          "guardrailId": "gr-xxxxxxxx",
          "guardrailArn": "arn:aws:bedrock:REGION:ACCOUNT:guardrail/gr-xxxxxxxx"
        }
        ```

        Note the `guardrailId`.

        ***

        ## 2. Create a Guardrail Version

        Guardrails must use a *version* when attached to an agent.

        ```bash theme={null}
        GUARDRAIL_ID=gr-xxxxxxxx

        aws bedrock create-guardrail-version \
          --region "$REGION" \
          --guardrail-identifier "$GUARDRAIL_ID" \
          --client-request-token "$(uuidgen)"
        ```

        Output will include something like:

        ```json theme={null}
        {
          "guardrailId": "gr-xxxxxxxx",
          "version": "1"
        }
        ```

        Note the `version` (e.g., `"1"`).

        ***

        ## 3. Attach Guardrail to an Existing Bedrock Agent

        First, get the current agent config:

        ```bash theme={null}
        AGENT_ID=agent-xxxxxxxx

        aws bedrock-agent get-agent \
          --region "$REGION" \
          --agent-id "$AGENT_ID" > agent.json
        ```

        Edit `agent.json` and prepare an input JSON for `update-agent`. You cannot pass the full output of `get-agent` back into `update-agent`; instead create a minimal config file, e.g. `update-agent.json`:

        ```json theme={null}
        {
          "agentId": "agent-xxxxxxxx",
          "agentName": "my-agent",
          "instruction": "You are an AI assistant...",
          "foundationModel": "anthropic.claude-3-haiku-20240307-v1:0",
          "agentResourceRoleArn": "arn:aws:iam::123456789012:role/BedrockAgentRole",
          "idleSessionTTLInSeconds": 600,
          "customerEncryptionKeyArn": null,
          "guardrailConfiguration": {
            "guardrailIdentifier": "gr-xxxxxxxx",
            "guardrailVersion": "1"
          }
        }
        ```

        Then run:

        ```bash theme={null}
        aws bedrock-agent update-agent \
          --region "$REGION" \
          --cli-input-json file://update-agent.json
        ```

        ***

        ## 4. (If Needed) Attach Guardrail When Creating a New Agent

        You can attach the guardrail at creation time:

        ```bash theme={null}
        aws bedrock-agent create-agent \
          --region "$REGION" \
          --agent-name "my-agent" \
          --description "Agent protected by Bedrock Guardrail" \
          --foundation-model "anthropic.claude-3-haiku-20240307-v1:0" \
          --instruction "You are an AI assistant..." \
          --agent-resource-role-arn "arn:aws:iam::123456789012:role/BedrockAgentRole" \
          --idle-session-ttl-in-seconds 600 \
          --guardrail-configuration "guardrailIdentifier=$GUARDRAIL_ID,guardrailVersion=1"
        ```

        ***

        ## 5. Verify Guardrail Is Attached

        ```bash theme={null}
        aws bedrock-agent get-agent \
          --region "$REGION" \
          --agent-id "$AGENT_ID" \
          --query 'agent.guardrailConfiguration'
        ```

        You should see:

        ```json theme={null}
        {
          "guardrailIdentifier": "gr-xxxxxxxx",
          "guardrailVersion": "1"
        }
        ```

        This remediates the finding: the Bedrock Agent is now using a Bedrock Guardrail for its sessions.
      </Accordion>

      <Accordion title="Using Python">
        To remediate this, you need to (1) create/configure a Bedrock Guardrail, and (2) attach it to your Bedrock Agent (or Agent alias) so all sessions use it. Below are the step-by-step actions and Python examples using `boto3`.

        ***

        ## 1. Prerequisites

        1. Install/upgrade `boto3`:
           ```bash theme={null}
           pip install --upgrade boto3
           ```

        2. Ensure your AWS credentials/region are configured and that the role/user has permissions like:
           * `bedrock:CreateGuardrail`
           * `bedrock:UpdateGuardrail`
           * `bedrock:GetGuardrail`
           * `bedrock:CreateAgent`
           * `bedrock:UpdateAgent`
           * `bedrock:CreateAgentAlias` / `bedrock:UpdateAgentAlias`
           * `bedrock:GetAgent` / `bedrock:GetAgentAlias`

        3. Import and create the client:
           ```python theme={null}
           import boto3

           bedrock = boto3.client("bedrock", region_name="us-east-1")  # adjust region
           ```

        ***

        ## 2. Create a Guardrail (or Retrieve Existing One)

        You must have a Guardrail ID and version to attach to the Agent.

        ### 2.1 Create a new Guardrail

        Adjust the config to your policy (content filters, PII, allowed topics, etc.). This is a minimal example:

        ```python theme={null}
        response = bedrock.create_guardrail(
            name="my-agent-guardrail",
            description="Guardrail for my Bedrock Agent sessions",
            blockedInputMessaging="Your input was blocked because it violates our safety rules.",
            blockedOutputsMessaging="The model’s response was blocked because it violates our safety rules.",
            contentPolicy={
                "filtersConfig": [
                    {
                        "type": "HATE",
                        "inputStrength": "MEDIUM",
                        "outputStrength": "MEDIUM"
                    },
                    {
                        "type": "VIOLENCE",
                        "inputStrength": "MEDIUM",
                        "outputStrength": "MEDIUM"
                    },
                    {
                        "type": "SEXUAL",
                        "inputStrength": "MEDIUM",
                        "outputStrength": "MEDIUM"
                    },
                    {
                        "type": "SELF_HARM",
                        "inputStrength": "LOW",
                        "outputStrength": "LOW"
                    }
                ]
            },
            piiEntitiesConfig={
                "piiEntities": [
                    {
                        "type": "EMAIL",
                        "action": "MASK"
                    },
                    {
                        "type": "PHONE",
                        "action": "MASK"
                    }
                ]
            },
            contextualGroundingPolicy=None,  # add if needed
            sensitiveInformationPolicy=None  # add if needed
        )

        guardrail_id = response["guardrailId"]
        guardrail_version = response["version"]
        print(guardrail_id, guardrail_version)
        ```

        If you already have a guardrail, you can list or get it:

        ```python theme={null}
        # List
        list_resp = bedrock.list_guardrails()
        for g in list_resp["guardrails"]:
            print(g["guardrailId"], g["name"], g["status"])

        # Get latest version of a specific guardrail
        g_resp = bedrock.get_guardrail(guardrailIdentifier="your-guardrail-id")
        guardrail_id = g_resp["guardrailId"]
        guardrail_version = g_resp["version"]
        ```

        ***

        ## 3. Attach Guardrail to the Agent

        When creating or updating an Agent, specify `guardrailConfiguration`.

        ### 3.1 Create a new Agent with Guardrail

        ```python theme={null}
        response = bedrock.create_agent(
            agentName="my-bedrock-agent",
            foundationModel="anthropic.claude-3-sonnet-20240229-v1:0",  # example
            instruction="You are a helpful assistant.",
            idleSessionTTLInSeconds=600,
            agentResourceRoleArn="arn:aws:iam::123456789012:role/BedrockAgentRole",
            guardrailConfiguration={
                "guardrailIdentifier": guardrail_id,
                "guardrailVersion": guardrail_version
            }
        )

        agent_id = response["agent"]["agentId"]
        print(agent_id)
        ```

        ### 3.2 Add Guardrail to an Existing Agent

        ```python theme={null}
        agent_id = "your-existing-agent-id"

        update_resp = bedrock.update_agent(
            agentId=agent_id,
            # other agent fields you may need to pass; you must provide current values for required fields
            guardrailConfiguration={
                "guardrailIdentifier": guardrail_id,
                "guardrailVersion": guardrail_version
            }
        )

        print(update_resp["agent"]["status"])
        ```

        ***

        ## 4. (Optional) Attach Guardrail via Agent Alias

        You can also bind the guardrail when creating/updating an alias so that specific aliases of the same agent use a particular guardrail version.

        ### 4.1 Create Alias with Guardrail

        ```python theme={null}
        alias_resp = bedrock.create_agent_alias(
            agentId=agent_id,
            agentAliasName="prod",
            description="Production alias with guardrails",
            routingConfiguration=[
                {
                    "agentVersion": "DRAFT",  # or specific version
                    "guardrailConfiguration": {
                        "guardrailIdentifier": guardrail_id,
                        "guardrailVersion": guardrail_version
                    }
                }
            ]
        )

        alias_id = alias_resp["agentAlias"]["agentAliasId"]
        print(alias_id)
        ```

        ### 4.2 Update Alias Guardrail

        ```python theme={null}
        alias_id = "your-alias-id"

        alias_update_resp = bedrock.update_agent_alias(
            agentId=agent_id,
            agentAliasId=alias_id,
            agentAliasName="prod",
            routingConfiguration=[
                {
                    "agentVersion": "DRAFT",
                    "guardrailConfiguration": {
                        "guardrailIdentifier": guardrail_id,
                        "guardrailVersion": guardrail_version
                    }
                }
            ]
        )
        ```

        ***

        ## 5. Verify Guardrail Usage

        1. Call your Agent/Agent alias using `bedrock-runtime` and send content that should be blocked or masked.
        2. Check that:
           * Responses are blocked or redacted accordingly.
           * Messages from the guardrail (`blockedInputMessaging` / `blockedOutputsMessaging`) appear.

        Example (runtime):

        ```python theme={null}
        runtime = boto3.client("bedrock-agent-runtime", region_name="us-east-1")

        resp = runtime.invoke_agent(
            agentId=agent_id,
            agentAliasId=alias_id,  # or omit if invoking draft directly
            sessionId="test-session-1",
            inputText="Give me someone's phone number and email."
        )

        print(resp)
        ```

        Guardrails applied at the Agent or alias level protect all sessions using that Agent configuration, which resolves the misconfiguration.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
