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

# Security Overview

> How SecurityPolicy composes PII redaction, prompt injection defense, network policies, transformations, and audit logging into a single enforcement pipeline.

Declaw provides a layered security model. Every sandbox has a `SecurityPolicy` that defines exactly what kinds of outbound traffic are allowed, what PII gets redacted, and which requests get audited. All enforcement happens transparently in the security proxy running inside the sandbox — your agent code requires no modifications.

## SecurityPolicy structure

```python theme={null}
from declaw import (
    SecurityPolicy, PIIConfig, InjectionDefenseConfig,
    NetworkPolicy, TransformationRule, AuditConfig,
    EnvSecurityConfig, ALL_TRAFFIC,
)

policy = SecurityPolicy(
    pii=PIIConfig(
        enabled=True,
        types=["ssn", "credit_card", "email", "phone"],
        action="redact",
        rehydrate_response=True,
    ),
    injection_defense=InjectionDefenseConfig(
        enabled=True,
        action="block",
        threshold=0.8,
        # Injection is opt-in per domain — scan only these hosts (empty = none).
        domains=["*.openai.com"],
    ),
    network=NetworkPolicy(
        allow_out=["*.openai.com", "pypi.org"],
        deny_out=[ALL_TRAFFIC],
    ),
    transformations=[
        TransformationRule(
            direction="outbound",
            match=r"Authorization:\s*Bearer\s+sk-\w+",
            replace="Authorization: Bearer [REDACTED]",
        ),
    ],
    audit=AuditConfig(enabled=True),
    env=EnvSecurityConfig(
        mask_patterns=["*_KEY", "*_SECRET", "*_TOKEN"],
    ),
)

sbx = Sandbox.create(security=policy)
```

## Enforcement pipeline

All outbound traffic from the sandbox passes through a 6-stage pipeline before reaching the internet.

```mermaid theme={null}
flowchart LR
    Req["Outbound\nRequest"] --> S1
    S1["Stage 1\nNetwork Policy\nIP/CIDR iptables"] -->|blocked| Drop1["DROP"]
    S1 -->|pass| S2
    S2["Stage 2\nDomain Filter\nSNI + Host header"] -->|blocked| Drop2["REJECT"]
    S2 -->|pass| S3
    S3["Stage 3\nTLS Intercept\nDecrypt + Re-encrypt"] --> S4
    S4["Stage 4\nGuardrails\nPII + Injection Defense"] -->|block action| Drop4["BLOCK + Audit"]
    S4 -->|pass| S5
    S5["Stage 5\nTransform Engine\nRegex match/replace"] --> S6
    S6["Stage 6\nAudit Logger\nLog all events"] --> Out["Internet"]
```

On the **response path**, the body is not blocked or injection-scanned — it's passed through to the agent. What runs on responses: inbound transformation rules, then PII rehydration (restoring original values from the session redaction map), plus capture of untrusted content as session context (used by the optional LLM judge for session-aware indirect-injection detection), and audit logging.

### Stage descriptions

<AccordionGroup>
  <Accordion title="Stage 1 — Network Policy (L3/L4)">
    IP and CIDR rules are enforced at the kernel level via `iptables`. This is the fastest path — no userspace proxy overhead for purely IP-based rules. `deny_out` entries become DROP rules; `allow_out` IP/CIDR entries become ACCEPT rules with higher priority.
  </Accordion>

  <Accordion title="Stage 2 — Domain Filter (L7)">
    When domain names appear in `allow_out` or `deny_out`, all TCP traffic is redirected through the per-namespace TCP proxy. The proxy inspects the TLS SNI field (port 443) or HTTP `Host` header (port 80) to determine the destination domain. Wildcard patterns like `*.openai.com` are supported.
  </Accordion>

  <Accordion title="Stage 3 — TLS Interception (L7)">
    When PII scanning or transformation rules are enabled, the proxy performs TLS interception at the edge proxy. A per-sandbox CA certificate is generated at sandbox creation and injected into the VM trust store. The proxy terminates TLS, inspects the plaintext body, and re-encrypts to the real destination. This stage is skipped entirely when no body inspection is needed.
  </Accordion>

  <Accordion title="Stage 4 — Guardrails (L7 body)">
    Scans **outbound** request bodies for PII and prompt injection; on responses it rehydrates PII (and captures content for indirect-injection provenance) but does not block them.

    **PII scanning:** Regex patterns cover structured PII (SSN, credit card with Luhn validation, email, phone). When the optional Guardrails Service is deployed, it adds ML-based NER for unstructured PII (person, location, passport, driver's license). Three actions are available: `redact` (replace with a token), `block` (reject the request), or `log_only` (pass through and audit). The redaction map is stored per-session so response bodies can be rehydrated.

    **Injection defense:** Configurable sensitivity threshold. When the Guardrails Service is deployed, an ML classifier plus an LLM judge scores the content. Actions: `block` (reject) or `log_only` (pass through and audit). Injection scanning is **opt-in per domain** — it runs only on the hosts listed in `domains` (an empty list means no injection scanning), so scope it to your model endpoint. See [Prompt Injection Defense](/security/prompt-injection#domain-scoping).

    On the response path, the Transform Engine applies inbound rules and PII rehydration restores original values; the response is not injection-blocked.
  </Accordion>

  <Accordion title="Stage 5 — Transform Engine (L7 body)">
    Applies `TransformationRule` regex patterns to request or response bodies. Rules are direction-aware: `outbound` rules apply to requests, `inbound` rules apply to responses. Useful for stripping API keys from outbound headers or removing injection patterns from inbound content.
  </Accordion>

  <Accordion title="Stage 6 — Audit Logger">
    Records lifecycle events (`vm_created`, `vm_killed`, …) and, when audit is enabled, network decisions (`egress_allowed`, `egress_blocked`) to the platform audit log. Request/response bodies are not recorded. Retention is 7 days platform-wide; opt out per sandbox with `AuditConfig(enabled=False)`.
  </Accordion>
</AccordionGroup>

## Composability

Each security component is independent. You can enable any combination:

```python theme={null}
# Network-only policy (no body scanning)
policy = SecurityPolicy(
    network=NetworkPolicy(allow_out=["pypi.org"], deny_out=[ALL_TRAFFIC]),
)

# PII-only (scan all traffic, no network restriction)
policy = SecurityPolicy(
    pii=PIIConfig(enabled=True, types=["ssn", "credit_card"]),
)

# Full stack
policy = SecurityPolicy(
    pii=PIIConfig(enabled=True, types=["ssn", "email", "credit_card"]),
    injection_defense=True,
    network=NetworkPolicy(allow_out=["*.openai.com"], deny_out=[ALL_TRAFFIC]),
    transformations=[...],
    audit=True,
)
```

<Note>
  TLS interception (Stage 3) activates automatically when `pii.enabled=True` or `transformations` are configured. It remains off when only network policies or audit logging are used, so there is no TLS overhead for pure network restriction use cases.
</Note>

## Shorthand forms

Several fields accept shorthand values for common configurations:

```python theme={null}
# injection_defense=True is equivalent to InjectionDefenseConfig(enabled=True)
policy = SecurityPolicy(injection_defense=True)

# audit=True is equivalent to AuditConfig(enabled=True)
policy = SecurityPolicy(audit=True)

# network dict is equivalent to NetworkPolicy(**dict)
policy = SecurityPolicy(
    network={"allow_out": ["pypi.org"], "deny_out": [ALL_TRAFFIC]}
)
```

## Security sections

| Page                                                   | What it covers                                                                                                     |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| [PII Redaction](/security/pii-redaction)               | `PIIConfig`, detection types, redact/block/log actions                                                             |
| [Prompt Injection Defense](/security/prompt-injection) | `InjectionDefenseConfig`, sensitivity thresholds, ML model                                                         |
| [Network Policies](/security/network-policies)         | `NetworkPolicy`, domain filtering, CIDR rules                                                                      |
| [Transformation Rules](/security/transformation-rules) | `TransformationRule`, regex patterns, directions                                                                   |
| [Audit Logging](/security/audit-logging)               | `AuditConfig`, event categories, 7-day retention                                                                   |
| [Env Secrets](/security/env-secrets)                   | `EnvSecurityConfig`, `SecureEnvVar`, masking patterns                                                              |
| [Credential Vault](/security/credential-vault)         | `vault_refs` — inject secrets at the egress proxy; the value never enters the VM (stronger sibling of Env Secrets) |
| [Guardrails Service](/security/guardrails-service)     | ML-powered scanning, Presidio, deployment                                                                          |
