# Noirdoc Shield

> Stateless input inspection on German infrastructure: redact or block secrets, PII, names, prompt injections and custom blocklist patterns.

- **Source:** https://www.noirdoc.de/en/docs/shield/
- **API base URL:** `https://api.noirdoc.de/v1`

Noirdoc Shield inspects inbound requests statelessly on German infrastructure before data leaves the gateway towards a model provider. Depending on each filter, Shield either redacts matches in-place with fixed category placeholders such as `[PERSON]` or `[IBAN]`, or blocks the request before forwarding with status 403 (`shield_violation`).

> **Your input:** Confirm to Anna Schmidt that payment arrived on DE89 3704 0044 0532 0130 00.
> **Sent to the model:** Confirm to [PERSON] that payment arrived on [IBAN].

> **Billing:** Input inspection costs +€0.40 per 1M inspected input tokens across all active filters — including
> on BYOK routes and status 403 (`shield_violation`) blocks. `/v1/messages/count_tokens` and
> `/v1/responses/input_tokens` are charged €0.00.

## Protection filters

Under **Models → Shield** and via `/v1/shield/policy`, admins configure five independent protection filters. Shield stores no mapping table in Redis, prepends no system prompt, and streams model responses, `tool_calls` / `tool_use` blocks and citations straight through with zero sentence-buffering latency:

#### Secrets & API Keys (`secrets`)

*Default: block · off · redact · block* — `[SECRET]`

Detects API keys, private keys, cloud tokens, credentials and high-entropy secrets across all
message roles.
#### Financial & Contact Data (`pii`)

*Default: redact · off · redact · block* — `[IBAN]`, `[CREDIT_CARD]`, `[EMAIL]`, `[PHONE]`, `[TAX_ID]`, `[TAX_NUMBER]`, `[VAT_ID]`, `[SSN]`, `[DATE_OF_BIRTH]`

Detects bank accounts, payment cards, contact details, tax and social security numbers, and
dates of birth across all roles.
#### Names & Addresses (`ner`)

*Default: redact · off · redact · block* — `[PERSON]`, `[ADDRESS]`

Detects personal names and postal addresses via named-entity recognition across all roles.
#### Prompt Injection (`injection`)

*Default: block · off · block*

No `redact` action. Evaluated only on untrusted roles (`user` and `tool` / function outputs);
`system`, `developer` and `assistant` are exempt.
#### Custom Blocklist (`custom`)

*Default: redact · off · redact · block* — `[CUSTOM]`

Evaluates up to 100 entries in `custom_patterns` (2–256 characters each): case-insensitive
literal substrings such as `"Projekt Helios"` or linear-time regular expressions prefixed with
`re:` such as `"re:AZ-[0-9]{4}-[0-9]{5}"`.

While `injection` evaluates only `user` and `tool` segments, `secrets`, `pii`, `ner` and `custom` inspect every role. When local tools in your application need to resolve real records after a model tool call, pass internal record IDs (for example `contact_id: "c_8492"`) rather than plaintext names or IBANs.

#### RE2 syntax and custom_patterns rules

- **Limits:** 0 to 100 entries in `custom_patterns`, each 2 to 256 characters long.
- **Literals:** Without a prefix, Shield matches case-insensitive substrings (for example `"Projekt Helios"`).
- **Regular expressions (`re:`):** Evaluated in linear time with RE2 semantics — no lookarounds, no backreferences and no patterns matching the empty string (invalid patterns are rejected on save or in `/v1/shield/inspect` with status 422 `shield_policy_invalid`).

## Policy and precedence

Enable Shield per request via the `X-Noirdoc-Shield` header, permanently via `default_headers` / `defaultHeaders` on an SDK client, per API key, per request tag, or across your organisation under **Models → Shield**:

**Python**

```python
from openai import OpenAI

client = OpenAI(base_url="https://api.noirdoc.de/v1")

raw = client.chat.completions.with_raw_response.create(
    model="qwen3.8-27b",
    messages=[{"role": "user", "content": "Anna Schmidt, +49 30 901820"}],
    extra_headers={"X-Noirdoc-Shield": "on"},
)
print(raw.headers.get("x-noirdoc-shield"))  # "redacted=2"
```

**TypeScript**

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.noirdoc.de/v1" });
const prompt = "Anna Schmidt, +49 30 901820";

const { data, response } = await client.chat.completions
  .create(
    {
      model: "qwen3.8-27b",
      messages: [{ role: "user", content: prompt }],
    },
    { headers: { "X-Noirdoc-Shield": "on" } },
  )
  .withResponse();
console.log(response.headers.get("x-noirdoc-shield"));
```

**curl**

```bash
curl -si https://api.noirdoc.de/v1/chat/completions \
  -H "Authorization: Bearer $NOIRDOC_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-Noirdoc-Shield: on" \
  -d '{
    "model": "qwen3.8-27b",
    "messages": [
      {"role": "user", "content": "Anna Schmidt, +49 30 901820"}
    ]
  }'
```

**200 Response**

```jsonc
// 200 OK · X-Noirdoc-Shield: redacted=2 · X-Noirdoc-Masked: true
{
  "id": "chatcmpl-9a41c2",
  "object": "chat.completion",
  "model": "qwen3.8-27b",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Callback noted for [PERSON] on [PHONE].",
      },
      "finish_reason": "stop",
    },
  ],
}
```

**403 shield_violation**

```jsonc
// 403 Forbidden · Blocked by a filter with action "block"
{
  "error": {
    "type": "permission_error",
    "code": "shield_violation",
    "message": "Request blocked by Noirdoc Shield (secrets).",
    "param": null,
  },
}
```

When all inspectable content has been checked, the response carries `X-Noirdoc-Shield: redacted=<n>` (`0` when nothing matched) and `X-Noirdoc-Masked: true`; if non-enforced requests include uninspectable binary or media attachments, the response carries `X-Noirdoc-Shield: partial; redacted=<n>` and `X-Noirdoc-Masked: false`.

Under **Models → Shield**, admins choose the organisation's default mode (`default_off` **On demand** as default for new organisations, `default_on` **On by default** / alias `advisory`, or `enforced` **Enforced**). On every request, the gateway evaluates five levels in order:

| Step | Level                           | Rule                                                                                                                                                                            |
| ---- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1    | Active filters                  | If all five filters are `off`, Shield is inactive. Saving `enforced` with all five filters `off` is rejected with status 422 (`shield_policy_invalid`).                         |
| 2    | Organisation `enforced`         | Shield inspects every request mandatorily; API keys, request tags and headers cannot switch it off.                                                                             |
| 3    | API key (`shield_mode`)         | Under **Models → API keys**, `on` (**On**) or `off` (**Off**) decides; `inherit` (**Inherit**) defers to step 4.                                                                |
| 4    | Request tags (`X-Noirdoc-Tags`) | `shield_mode` configured under **Models → Tags** or `/v1/tags`; with multiple tags attached, any `on` wins over `off`, while `inherit` defers.                                  |
| 5    | Header & organisation default   | `X-Noirdoc-Shield: on` or `off` (case-insensitive, stripped before forwarding; `X-Noirdoc-Mask` acts as an alias on Shield organisations) overrides `default_on`/`default_off`. |

## Inspected fields and attachments

Shield inspects text segments and inline UTF-8 text attachments decoded under 4 MiB (`text/*`, JSON, XML, CSV, Markdown, YAML as Base64 `data:` URLs or Messages text `document` blocks), while leaving `tools[]` definitions, output schemas (`response_format`, `text.format`) and signed `thinking` blocks untouched:

#### Chat Completions (`/v1/chat/completions`)

Inspects `messages[].content` (`string` and `text` parts; `system`, `developer` and `assistant`
exempt from `injection`, missing/unknown roles mapped to `user`, `tool`/`function` mapped to
`tool`), all JSON string values in `messages[].tool_calls[].function.arguments` (`assistant`),
`prediction.content` (`user`), and inline UTF-8 `file` parts under 4 MiB (file text always
`tool`, `filename` per message role).
#### Responses (`/v1/responses`)

Inspects `instructions` (`system`), string `input` (`user`) or
message/`input_text`/`output_text` items, JSON string values in `function_call.arguments`
(`assistant`), `function_call_output.output` (`tool`), and inline UTF-8 `input_file` parts under
4 MiB (`tool`). `/v1/responses/input_tokens` skips Shield free of charge.
#### Messages (`/v1/messages`)

Inspects `system`, `messages[].content`, string values in `tool_use.input` (`assistant`),
`tool_result.content` (`tool`), code-execution blocks (`server_tool_use`,
`bash_code_execution_tool_result`, `text_editor_code_execution_tool_result`), `document` blocks
with text/Base64 UTF-8 under 4 MiB plus `title` and `context`, `search_result` blocks, and
`citations[]` (`cited_text`, `document_title`). `/v1/messages/count_tokens` skips Shield free of
charge.
#### Embeddings (`/v1/embeddings`)

Inspects `input` as string, `string[]`, string fields of multimodal objects (excluding
`image`/`image_url`) and integer token arrays (decoded via `tiktoken`, inspected and re-encoded
into token IDs; undecodable arrays fail with status 422 `shield_uninspectable_content` under
`enforced`). All segments run as role `user`.
#### Rerank (`/v1/rerank`)

Inspects `query` (role `user`), `instruction` and `documents[]` (strings and text fields of
document objects, excluding `image`/`image_url`).
#### Media, Files & Skills (`/v1/audio/* · /v1/images/generations · /v1/files · /v1/skills`)

*Not inspected*

Under `enforced`, with `X-Noirdoc-Mask: on`, and on `/v1/images/generations` with
`X-Noirdoc-Shield: on`, content-bearing calls return status 403
(`masking_not_supported_for_endpoint`). Reading, listing, downloading and deleting on
`/v1/files` and `/v1/skills` remain permitted.

Before Shield runs, **Models → Gateway** enforces **Allow file and image attachments in requests** (`allow_file_content`, default: on; when off, any request containing file, image or audio parts returns status 403 `file_content_not_allowed`). When `allow_file_content` is enabled, Shield handles attachments by type:

| Attachment type                                                                                                                                                    | `default_on` / `on`                                                                                                          | `enforced`                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Inline UTF-8 text files (< 4 MiB decoded)                                                                                                                          | Decoded, inspected and sanitised in-place (`X-Noirdoc-Shield: redacted=<n>`, `X-Noirdoc-Masked: true`)                       | Fully inspected and permitted                                                              |
| Binary documents (PDF, DOCX, XLSX, PPTX), media (`image_url`, `image`, `input_image`, `input_audio`), references (`file_id`, URL), files >= 4 MiB or invalid UTF-8 | Text fields inspected; attachment forwarded unchanged (`X-Noirdoc-Shield: partial; redacted=<n>`, `X-Noirdoc-Masked: false`) | Status 422 `shield_uninspectable_content` (extract PDF/Office text client-side beforehand) |

> **Tool definitions:** Do not place names, matter references, addresses or secrets in `tools[]` descriptions, parameter
> schemas or `enum` values. Always pass confidential values inside message or tool content where
> Shield inspects them.

## Standalone text inspection

Inspect text directly on German infrastructure without a model call before storing free text in vector databases, search indexes or external tools (+€0.40 per 1M input tokens).

**POST** `https://api.noirdoc.de/v1/shield/inspect`

**Python**

```python
import os
import httpx

resp = httpx.post(
    "https://api.noirdoc.de/v1/shield/inspect",
    headers={
        "Authorization": f"Bearer {os.environ['NOIRDOC_API_KEY']}",
        "X-Noirdoc-Tags": "mandat-2026-042",
    },
    json={
        "input": [
            "Client in matter: Anna Schmidt",
            "Bank account: DE89 3704 0044 0532 0130 00",
            "Note on Projekt Helios, file AZ-2026-00418.",
        ],
        "role": "user",
        "policy": {
            "rules": {"custom": "redact"},
            "custom_patterns": [
                "Projekt Helios",
                "re:AZ-[0-9]{4}-[0-9]{5}",
            ],
        },
    },
)
data = resp.json()
```

**TypeScript**

```ts
const resp = await fetch("https://api.noirdoc.de/v1/shield/inspect", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.NOIRDOC_API_KEY}`,
    "X-Noirdoc-Tags": "mandat-2026-042",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    input: [
      "Client in matter: Anna Schmidt",
      "Bank account: DE89 3704 0044 0532 0130 00",
      "Note on Projekt Helios, file AZ-2026-00418.",
    ],
    role: "user",
    policy: {
      rules: { custom: "redact" },
      custom_patterns: ["Projekt Helios", "re:AZ-[0-9]{4}-[0-9]{5}"],
    },
  }),
});
const data = await resp.json();
```

**curl**

```bash
curl https://api.noirdoc.de/v1/shield/inspect \
  -H "Authorization: Bearer $NOIRDOC_API_KEY" \
  -H "X-Noirdoc-Tags: mandat-2026-042" \
  -H "Content-Type: application/json" \
  -d '{
    "input": [
      "Client in matter: Anna Schmidt",
      "Bank account: DE89 3704 0044 0532 0130 00",
      "Note on Projekt Helios, file AZ-2026-00418."
    ],
    "role": "user",
    "policy": {
      "rules": { "custom": "redact" },
      "custom_patterns": ["Projekt Helios", "re:AZ-[0-9]{4}-[0-9]{5}"]
    }
  }'
```

**Response**

```json
{
  "id": "shld_7f3c9a12e4b048d19c2a6e10",
  "model": "noirdoc-shield-v1",
  "action": "redact",
  "flagged": true,
  "output": [
    "Client in matter: [PERSON]",
    "Bank account: [IBAN]",
    "Note on [CUSTOM], file [CUSTOM]."
  ],
  "findings": [
    {
      "category": "ner",
      "label": "PERSON",
      "kind": "PERSON",
      "action": "redact",
      "replacement": "[PERSON]",
      "start": 18,
      "end": 30,
      "index": 0
    }
  ],
  "findings_truncated": false,
  "usage": { "input_tokens": 41 }
}
```

The endpoint returns HTTP 200 OK even when `action` is `"block"` and runs without short-circuiting (`short_circuit=false`) so `findings` lists every match.

| Field                                     | Direction          | Rule                                                                                                                                                                                                                                                                                            |
| ----------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `input`                                   | Request (required) | Non-empty string or array of 1 to 64 non-empty strings, up to 256 KB (262,144 bytes UTF-8) in total (status 413 `shield_input_too_large` above that).                                                                                                                                           |
| `role`                                    | Request (optional) | `"user"` (default), `"tool"`, `"system"` or `"assistant"`. `injection` inspects `"user"` and `"tool"`.                                                                                                                                                                                          |
| `policy`                                  | Request (optional) | Per-call override `{"rules"?: {...}, "custom_patterns"?: [...]}` (or a flat rule map without `custom_patterns`; mixing both returns status 422 `shield_policy_invalid`). Under `enforced`, `policy` cannot weaken active rules or omit stored `custom_patterns` (403 `shield_policy_enforced`). |
| `action`, `flagged`, `output`             | Response (200 OK)  | `action` is `"pass"`, `"redact"` or `"block"`; `flagged` is `true` on any match; `output` returns the sanitised `string` or `string[]` matching `input`.                                                                                                                                        |
| `findings`, `findings_truncated`, `usage` | Response (200 OK)  | Matches with `category`, `label`, `kind`, `action`, `replacement`, `start`, `end`, `index` (0-based array index); `usage.input_tokens` states billed tokens (minimum 1).                                                                                                                        |

## Manage policy via API

**GET** `https://api.noirdoc.de/v1/shield/policy`
**PUT** `https://api.noirdoc.de/v1/shield/policy`
**PATCH** `https://api.noirdoc.de/v1/shield/policy`

Reads or updates your organisation's Shield policy. All three methods require **Manage Shield policy via API** (`can_manage_shield = true`) on the calling API key under **Models → API keys** (status 403 `insufficient_key_permissions`); a key pinned to `shield_mode: "on"` cannot weaken the policy.

**Python**

```python
import os
import httpx

resp = httpx.patch(
    "https://api.noirdoc.de/v1/shield/policy",
    headers={"Authorization": f"Bearer {os.environ['NOIRDOC_API_KEY']}"},
    json={
        "mode": "default_on",
        "rules": {"pii": "redact", "custom": "block"},
        "custom_patterns": [
            "Projekt Helios",
            "re:AZ-[0-9]{4}-[0-9]{5}",
        ],
    },
)
policy = resp.json()
```

**TypeScript**

```ts
const resp = await fetch("https://api.noirdoc.de/v1/shield/policy", {
  method: "PATCH",
  headers: {
    Authorization: `Bearer ${process.env.NOIRDOC_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    mode: "default_on",
    rules: { pii: "redact", custom: "block" },
    custom_patterns: ["Projekt Helios", "re:AZ-[0-9]{4}-[0-9]{5}"],
  }),
});
const policy = await resp.json();
```

**curl**

```bash
curl -X PATCH https://api.noirdoc.de/v1/shield/policy \
  -H "Authorization: Bearer $NOIRDOC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "default_on",
    "rules": { "pii": "redact", "custom": "block" },
    "custom_patterns": ["Projekt Helios", "re:AZ-[0-9]{4}-[0-9]{5}"]
  }'
```

**Response**

```json
{
  "mode": "default_on",
  "shield_policy": "default_on",
  "rules": {
    "secrets": "block",
    "pii": "redact",
    "ner": "redact",
    "injection": "block",
    "custom": "block"
  },
  "custom_patterns": ["Projekt Helios", "re:AZ-[0-9]{4}-[0-9]{5}"],
  "price_per_1m_input_tokens_eur": "0.40",
  "legacy_mask_active": false,
  "legacy_mask_sunset_at": "2026-11-30T23:59:59Z"
}
```

| Method / field              | Behaviour                                                                                                                                            |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode` (`shield_policy`)    | `"default_off"`, `"default_on"` or `"enforced"` (aliases `"off"`, `"advisory"` and `mask_policy` are accepted).                                      |
| `PUT` vs `PATCH` on `rules` | `PUT` resets omitted rule keys to their Shield defaults; `PATCH` merges provided rule keys into the stored state.                                    |
| `custom_patterns`           | 0 to 100 patterns of 2–256 characters; when passed to `PATCH`, replaces the stored list completely, and when omitted leaves it unchanged.            |
| One-way migration           | Any successful `PUT` or `PATCH /v1/shield/policy` permanently switches a pre-existing organisation off legacy masking (`legacy_mask_active: false`). |

| Status | Code | Meaning |
| --- | --- | --- |
| 400 | `invalid_request_error` | A parameter on `/v1/shield/inspect` or `/v1/shield/policy` is invalid (such as an empty `input` or one over 256 KB, more than 64 entries, an unknown rule or an invalid custom pattern), or the JSON body is nested too deeply for Shield extraction. |
| 403 | `shield_violation` | Noirdoc Shield blocked the request before forwarding to the provider because an active protection filter configured with `block` matched; `message` names the triggered rule (`secrets`, `pii`, `ner`, `injection` or `custom`). |
| 403 | `shield_policy_enforced` | The organisation's Shield policy is `enforced`, and the request to `/v1/shield/inspect` tries to weaken an active rule or omit custom patterns via `policy`. |
| 403 | `masking_not_supported_for_endpoint` | The endpoint supports neither Noirdoc Shield nor legacy masking, yet the policy is `enforced` or the request sends `X-Noirdoc-Mask: on` (and on `/v1/images/generations` also `X-Noirdoc-Shield: on`). During the legacy masking transition until 30.11.2026, this also affects `/v1/embeddings` and `/v1/rerank` on pre-existing organisations that have not switched to Shield yet. |
| 403 | `file_content_not_allowed` | The request contains files, images or audio, and the organisation does not allow file content. |
| 403 | `insufficient_key_permissions` | The API key lacks permission for `/v1/tags` (`can_manage_tags`) or `/v1/shield/policy` (`can_manage_shield`), a key pinned to `shield_mode: on` tries to weaken the Shield policy or a tag's `shield_mode`, or the tag requests broader models, providers or compliance rules than the calling key itself holds. |
| 413 | `shield_input_too_large` | The text to inspect in this request exceeds the Shield service limit of 4 MiB of encoded text in a single call. |
| 422 | `shield_uninspectable_content` | The Shield policy is `enforced`, and the request carries content that Shield cannot inspect as text (`binary_document` such as PDF or Office, `media_not_inspectable` such as images, audio or video, `file_reference` by ID or URL, `file_too_large` at 4 MiB or above, `file_not_decodable` or `unrecognised_content`). The gateway did not forward the request. |
| 422 | `shield_policy_invalid` | The submitted Shield policy is inconsistent, such as `enforced` with all five protection filters set to `off`, or mixing `rules`/`custom_patterns` with flat rule keys. |
| 422 | `shield_config_invalid` | The organisation's stored Shield configuration is invalid (for example `enforced` without any active protection filter, or a pattern that fails compilation); the gateway did not forward the request. |
| 503 | `shield_unavailable` | The Noirdoc Shield inspection service is temporarily unreachable; the gateway never forwards a request that requires inspection uninspected (fail-closed). The response contains `Retry-After` with 5 seconds. |

## Legacy masking (sunset 30 November 2026)

> **Legacy masking sunset on 30 November 2026:** Pre-existing organisations configured for reversible masking (`<<PERSON_1>>`) continue running unchanged until **30 November 2026** (`2026-11-30T23:59:59Z`). After that timestamp, all remaining organisations switch automatically to Noirdoc Shield.

During the transition window, every legacy-masked response includes RFC 8594 headers:

**Transition response headers**

```http
Deprecation: true
Sunset: Mon, 30 Nov 2026 23:59:59 GMT
X-Noirdoc-Masked: true
```

#### Transition behaviour, parallel testing and migration details

- **Transition scope:** Encrypted Redis mappings for `<<PERSON_1>>` placeholders, sentence-buffered streaming and Base64 `file_analysis_mode` on Chat, Responses and Messages continue at €0.00 surcharge during the transition window. `/v1/embeddings` and `/v1/rerank` do not support legacy masking; legacy PDF/DOCX/XLSX analysis uses status 403 (`file_pii_blocked`) and 422 (`file_unprocessable`).
- **Parallel testing:** Test Noirdoc Shield in parallel via `X-Noirdoc-Shield: on` per request, `shield_mode: "on"` on selected keys or tags, or `POST /v1/shield/inspect` while `X-Noirdoc-Mask` continues to control legacy masking.
- **Permanent switch:** Admins can switch permanently at any time under **Models → Shield** (**Switch to Noirdoc Shield now**) or via `PUT` / `PATCH /v1/shield/policy`.
