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

# Transformation Rules

> Rewrite request and response bodies using regex-based transformation rules with direction-aware application.

Transformation rules let you rewrite HTTP request and response bodies using regular expressions. They are direction-aware: `outbound` rules apply before a request leaves the sandbox, and `inbound` rules apply before a response reaches your agent code. Use them to strip credentials from outbound headers, mask tokens in logs, or remove known injection patterns from responses.

## Basic configuration

```python theme={null}
from declaw import Sandbox, SecurityPolicy, TransformationRule

sbx = Sandbox.create(
    security=SecurityPolicy(
        transformations=[
            TransformationRule(
                direction="outbound",
                match=r"Authorization:\s*Bearer\s+sk-\w+",
                replace="Authorization: Bearer [REDACTED]",
            ),
        ]
    )
)
```

## TransformationRule model

| Field       | Type                 | Description                                                            |
| ----------- | -------------------- | ---------------------------------------------------------------------- |
| `direction` | `TransformDirection` | `"outbound"`, `"inbound"`, or `"both"`                                 |
| `match`     | `str`                | Python `re`-compatible regex pattern                                   |
| `replace`   | `str`                | Replacement string; supports capture group backreferences (`\1`, `\2`) |

## TransformDirection enum

| Value      | When applied                                              |
| ---------- | --------------------------------------------------------- |
| `outbound` | Applied to request bodies before they leave the sandbox   |
| `inbound`  | Applied to response bodies before they reach the workload |
| `both`     | Applied in both directions                                |

## Multiple rules

Rules are applied in the order they are listed.

```python theme={null}
policy = SecurityPolicy(
    transformations=[
        # Strip Bearer tokens from Authorization headers
        TransformationRule(
            direction="outbound",
            match=r"(Authorization:\s*Bearer\s+)[A-Za-z0-9\-._~+/]+=*",
            replace=r"\1[REDACTED]",
        ),
        # Remove API key query parameters
        TransformationRule(
            direction="outbound",
            match=r"api_key=[A-Za-z0-9]+",
            replace="api_key=[REDACTED]",
        ),
        # Strip injection patterns from inbound content
        TransformationRule(
            direction="inbound",
            match=r"(?i)ignore\s+(all\s+)?previous\s+instructions[^.]*\.",
            replace="[CONTENT_REMOVED]",
        ),
    ]
)
```

## Common patterns

<AccordionGroup>
  <Accordion title="Strip API keys from Authorization headers">
    ```python theme={null}
    TransformationRule(
        direction="outbound",
        match=r"(Authorization:\s*Bearer\s+)(sk-[A-Za-z0-9]+)",
        replace=r"\1[REDACTED]",
    )
    ```
  </Accordion>

  <Accordion title="Mask database connection strings">
    ```python theme={null}
    TransformationRule(
        direction="outbound",
        match=r"(postgres://[^:]+:)[^@]+(@)",
        replace=r"\1[PASSWORD]\2",
    )
    ```
  </Accordion>

  <Accordion title="Remove prompt injection patterns from responses">
    ```python theme={null}
    TransformationRule(
        direction="inbound",
        match=r"(?i)(ignore|disregard|forget)\s+(all\s+)?(previous|prior)\s+(instructions?|commands?|prompts?)",
        replace="[INJECTION_REMOVED]",
    )
    ```
  </Accordion>

  <Accordion title="Strip system prompt extraction attempts">
    ```python theme={null}
    TransformationRule(
        direction="inbound",
        match=r"(?i)(print|reveal|show|display|output)\s+(your\s+)?(system\s+prompt|instructions|context)",
        replace="[INJECTION_REMOVED]",
    )
    ```
  </Accordion>

  <Accordion title="Mask Social Security Numbers (deterministic)">
    ```python theme={null}
    TransformationRule(
        direction="both",
        match=r"\b\d{3}-\d{2}-\d{4}\b",
        replace="[SSN_REDACTED]",
    )
    ```

    <Note>
      For SSN redaction with response rehydration, use `PIIConfig` instead. Transformation rules are one-way and do not support rehydration.
    </Note>
  </Accordion>

  <Accordion title="Remove invisible Unicode injection characters">
    Attackers sometimes embed invisible Unicode characters in text to manipulate LLM context windows.

    ```python theme={null}
    TransformationRule(
        direction="inbound",
        match=r"[\u200b\u200c\u200d\u2060\ufeff\u00ad]",
        replace="",
    )
    ```
  </Accordion>
</AccordionGroup>

## Combining with PII redaction

Transformation rules complement PII redaction. Use PII redaction for structured sensitive data (SSNs, credit cards) that benefits from response rehydration, and transformation rules for patterns that should be permanently removed.

```python theme={null}
policy = SecurityPolicy(
    pii=PIIConfig(
        enabled=True,
        types=["ssn", "credit_card"],
        action="redact",
        rehydrate_response=True,   # SSNs come back in responses
    ),
    transformations=[
        # API keys are permanently stripped — no rehydration needed
        TransformationRule(
            direction="outbound",
            match=r"OPENAI_API_KEY=['\"]?[A-Za-z0-9\-]+['\"]?",
            replace="OPENAI_API_KEY=[REDACTED]",
        ),
    ],
)
```

## When TLS interception activates

Transformation rules require reading the request or response body, which means the security proxy must decrypt HTTPS traffic. TLS interception (Stage 3 of the pipeline) activates automatically when any transformation rules are configured.

A per-sandbox CA certificate is generated at creation time and injected into the VM trust store. The proxy terminates TLS from the sandbox, applies transformations, and re-encrypts to the real destination. The agent code sees the destination's certificate as usual.

<Info>
  Regex patterns use Go's `regexp` package syntax, which is RE2-compatible. Backtracking patterns like `(.+)+` are not supported. Test your patterns at [regex101.com](https://regex101.com) with the Go flavor selected.
</Info>

## Order of operations

When both PII redaction and transformation rules are active:

1. **Outbound**: Transformation rules apply first, then PII scanning on the transformed body.
2. **Inbound**: Injection defense runs, then transformation rules, then PII rehydration restores tokens.

This means transformation rules can be used to pre-process content before PII scanning, and PII rehydration always runs last so tokens are correctly restored in the final response.
