Beyond Basic Filters: Implementing Custom Regex Guardrails in Amazon Bedrock

I have spent a significant amount of time fighting with LLM outputs that look great on the surface but leak internal data the moment they hit a production environment. Most people start with the default PII filters provided by Amazon Bedrock Guardrails [1]. Those defaults are fine for catching a standard email address or a US Social Security number, but they are useless when you are dealing with internal project codes, proprietary account IDs, or specific hardware serial numbers that follow a strict company format. If your data looks like ‘PROJ-99-XRAY-2024’ instead of a standard credit card number, the default filters will let it slide right through to the end user.

The Problem with Generic PII Filters

Generic filters are built for the average case. They assume that ‘sensitive data’ means the stuff that identity thieves want. But for an engineer building an internal tool, sensitive data is often anything that identifies a specific internal asset or a secret project. I’ve seen cases where a model accidentally leaked a proprietary internal server naming convention because the guardrail was only looking for standard IP addresses. The model wasn’t ‘hallucinating’ the data; it was simply recalling a pattern it saw in the training data or the RAG context, and the generic filter didn’t recognize it as a secret.

This is where custom regex guardrails come in. By defining your own regular expressions, you move from a generic security posture to one that is tailored to your actual data schema. You aren’t just blocking ’emails’; you are blocking ’emails that end in @secret-project.internal’.

The real pain point here isn’t the AWS console—which is relatively straightforward—but the regex itself. Most engineers haven’t written a complex regular expression in years, and the temptation to use a ‘lazy’ regex is high. If you use something too broad, you end up with a ‘blocked’ response for perfectly valid prompts. If you are too restrictive, the data leaks. It is a balancing act of precision and recall that requires a bit of trial and error.

Designing Your Custom Patterns

Before you touch the Bedrock console, you need to map out exactly what you are trying to block. I’d argue that the biggest mistake people make is trying to write one giant regex to catch everything. That is a recipe for a maintenance nightmare. Instead, break your patterns down by data type. If you have project IDs, account numbers, and internal IP ranges, create three separate regex entries.

Let’s take a hypothetical internal project ID: ‘PRJ’ followed by a dash, four digits, another dash, and a two-letter uppercase code. A naive regex might be `PRJ-\d{4}-[A-Z]{2}`. This works, but it might catch things that aren’t actually IDs if they happen to follow that pattern in a different context. To tighten this up, I always use word boundaries. Adding `\b` to the start and end ensures that you aren’t catching a substring of a larger, unrelated string.

\bPRJ-\d{4}-[A-Z]{2}\b

Another common issue is handling variations in formatting. Users might put spaces where there should be dashes, or they might use lowercase letters. Depending on how strict you want to be, you might want to allow for optional whitespace or case-insensitive matching. However, in a security context, I usually prefer strictness. If the data is strictly formatted in your database, your guardrail should reflect that strictness. If you start making the regex too flexible, you increase the risk of false positives, which frustrates the end user.

I’ve found that the most effective way to test these is to build a ‘gauntlet’ file—a list of 100 strings that include valid IDs, nearly-valid IDs, and completely random strings. Run your regex against this list before you ever deploy it to Bedrock. If your regex flags a random string as a project ID, you need to refine your pattern.

Setting Up the Guardrail in Bedrock

Once you have your patterns, you implement them through the Amazon Bedrock Guardrails service [1]. The process is centered around the ‘Sensitive Information Filter’. Within this section, you can choose from predefined PII types, but the real power is in the ‘Custom’ option. When you add a custom pattern, you give it a name—something like ‘InternalProjectID’—and then paste your regex.

The interesting part is how Bedrock handles the action. You can choose to mask the data or block the entire response. Masking is usually the better choice for developer tools. If a user asks a question and the model’s response contains a project ID, replacing that ID with `[SENSITIVE_DATA]` allows the rest of the answer to remain useful while still protecting the secret. Blocking the entire response is a hammer; masking is a scalpel.

I’ve noticed that some teams forget to configure the ‘Blocked response’ message. By default, the system provides a generic message, but you should customize this. If a user’s prompt is blocked because it contains a forbidden pattern, the message should be clear but not overly descriptive. Don’t tell them exactly which regex they tripped; just tell them that the prompt contains prohibited internal identifiers.

Here is the general workflow for getting this into production:

  • Audit your internal data to identify the 3-5 most common proprietary formats that need protection.
  • Write and validate regex patterns using a local test suite to minimize false positives.
  • Create a new Guardrail in the Bedrock console and add these as Custom Sensitive Information filters.
  • Test the guardrail using the Bedrock Playground with a variety of prompts that should and should not be blocked.
  • Associate the Guardrail ID with your model invocation calls via the API or SDK.
  • Monitor the logs for ‘blocked’ events to identify if your regex is too aggressive.

Integrating with the API

Adding the guardrail in the console is only half the battle. You have to actually tell your application to use it. When you call the `InvokeModel` or `InvokeModelWithResponseStream` API, you don’t just send the prompt. You include the `guardrailIdentifier` and the `guardrailVersion`. This is a critical step. If you update your regex patterns and create a new version of the guardrail, your application will keep using the old version until you update the identifier in your code.

I strongly recommend using a versioning strategy here. Don’t just point to the ‘latest’ version if that’s an option; point to a specific version number. This prevents a scenario where a colleague updates a regex pattern, accidentally introduces a massive false-positive rate, and suddenly your entire production application starts returning ‘Blocked’ messages for every single query.

const response = await bedrockRuntime.invokeModel({ 
  modelId: 'nova-pro-v1', 
  contentType: 'application/json', 
  accept: 'application/json', 
  body: JSON.stringify({
    prompt: userPrompt,
    guardrailIdentifier: 'guard-abc123xyz',
    guardrailVersion: '1'
  })
});

One technical detail that often trips people up is the difference between prompt filtering and response filtering. Bedrock Guardrails check both. If a user tries to ‘jailbreak’ the model by asking it to ‘repeat the project ID for Project X’, the guardrail can catch the project ID in the prompt and block it before it even reaches the model. Conversely, if the model generates a project ID in its response, the guardrail catches it before the user sees it. This dual-layer protection is why custom regex is so much more effective than trying to handle this in the system prompt.

The Danger of Over-Filtering

There is a psychological component to guardrails that engineers often ignore. If you make your regex patterns too broad, you create a ‘censorship’ feel in the application. Users start to feel like the AI is broken or overly restrictive. I remember a project where we were blocking any string that looked like a hexadecimal color code because we thought it might be a memory address leak. We ended up blocking every single time the model tried to describe a UI element’s color. It was a disaster for the user experience.

The more interesting problem is the ‘leakage’ that happens through paraphrasing. Regex is a pattern matcher; it is not a semantic analyzer. If your regex blocks ‘PRJ-1234-AB’, it will not block ‘Project one two three four Alpha Bravo’. This is a fundamental limitation of regex-based guardrails. You cannot rely on regex for semantic safety. For that, you need the content filters and toxicity filters that Bedrock provides as part of the broader governance suite [1].

I’ve found that the best approach is a layered defense. Use the built-in toxicity and hate speech filters for general safety, use custom regex for strict data patterns, and use a well-crafted system prompt to tell the model *not* to disclose internal IDs in the first place. The regex is your last line of defense, not your only one.

Maintenance and Iteration

Custom guardrails are not a ‘set it and forget it’ feature. Your data formats will change. You might start a new project with a different ID scheme, or you might find that a previously safe pattern is now being used for something else. I suggest treating your regex patterns as code. Store them in a Git repository, version them, and have a peer review process for any changes.

When you update a pattern, don’t just push it to production. Use the Bedrock playground to run a ‘regression test’. Take the prompts that were correctly allowed in the previous version and make sure they are still allowed. Take the prompts that were correctly blocked and make sure they are still blocked. This prevents the ‘whack-a-mole’ effect where fixing one leak creates three new false positives.

Finally, keep an eye on your CloudWatch logs. If you see a spike in blocked requests, it’s usually a sign that either a user is trying to probe your system or your regex has become too aggressive. Monitoring these metrics is the only way to know if your governance strategy is actually working or if it’s just getting in the way of your users.

Ultimately, the goal of using custom regex in Bedrock Guardrails is to create a safety net that is invisible to the user but impenetrable to the data. It takes some effort to get the patterns right, but it is the only way to ensure that your generative AI application doesn’t become a liability for your organization [1].

Sources

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.