> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch32-security-model/32.6-source-deep-dive-admission-secrets-and-audit.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 32.6 Source Deep Dive: Admission, Secrets, and the Audit Triad

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~234,000 tokens, Output \~15,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§44.4 described OpenClaw's trust model from the altitude of a design theme. This section reads its three implementations in source: **channel admission** (who may talk to the agent), **secrets** (how credentials avoid touching disk), and **security audit** (turning the threat model into checkable items).

## 32.6.1 First, the Complete Boundary Picture

```mermaid
flowchart LR
    subgraph untrusted["Untrusted zone"]
        U1["DM from a stranger"]
        U2["Group members"]
        U3["webhook / email / web content"]
        U4["model output (injectable)"]
    end
    subgraph gates["Boundary mechanisms"]
        G1["dmPolicy: pairing/allowlist<br/>src/security/dm-policy-shared.ts"]
        G2["groupPolicy + groupAllowFrom<br/>(does not inherit DM pairing)"]
        G3["external-content wrapping<br/>random-id markers + alerts"]
        G4["tool policy / exec approvals<br/>/ sandbox (optional)"]
    end
    subgraph trusted["Trusted zone (same OS process boundary)"]
        T1["Gateway + authenticated callers"]
        T2["plugins (in-process TCB)"]
        T3["~/.openclaw config and state"]
        T4["successfully paired nodes"]
    end
    U1 --> G1 --> T1
    U2 --> G2 --> T1
    U3 --> G3 --> U4
    U4 --> G4 --> T1
    T1 --- T2 --- T3 --- T4
```

Note where `U4` (model output) sits: **in the untrusted zone.**

`SECURITY.md:156-160`, verbatim:

> The model/agent is **not** a trusted principal. Assume prompt/content injection can manipulate behavior. Security boundaries come from host/config trust, auth, tool policy, sandboxing, and exec approvals. Prompt injection by itself is not a vulnerability report unless it crosses one of those boundaries.

**Prompt injection is assumed to be inevitable.** The defense isn't "keep the model from being fooled" — it's making sure a fooled model can't accomplish anything:

```
tool policy       limits what it can call
exec approvals    limits what it can run
sandbox           limits where it runs
channel allowlist limits who can fool it
```

The docs add a practical recommendation: **weaker models are easier to inject, so tool-enabled agents should use strong model tiers plus strict tool policy.**

## 32.6.2 Channel Admission: Strangers in DMs and Group Chats

All channels share one admission decision, at the core of `resolveDmGroupAccessDecision` (`src/security/dm-policy-shared.ts:105-196`).

### The default is `dmPolicy = "pairing"`

A stranger's DM gets **a pairing-code challenge, not an agent reply**:

```ts
// src/security/dm-policy-shared.ts:177-190 (excerpt)
if (params.isSenderAllowed(effectiveAllowFrom)) {
  return {
    decision: "allow",
    reasonCode: DM_GROUP_ACCESS_REASON.DM_POLICY_ALLOWLISTED,
    reason: `dmPolicy=${dmPolicy} (allowlisted)`,
  };
}
if (dmPolicy === "pairing") {
  return {
    decision: "pairing",
    reasonCode: DM_GROUP_ACCESS_REASON.DM_POLICY_PAIRING_REQUIRED,
    reason: "dmPolicy=pairing (not allowlisted)",
  };
}
```

Only after the operator confirms the code on the trusted side does the sender enter the allowlist store.

### Pairing implementation details

`src/pairing/`:

| Detail                  | Value                                          | Reason                                                         |
| ----------------------- | ---------------------------------------------- | -------------------------------------------------------------- |
| Code length             | 8 characters                                   | —                                                              |
| Alphabet                | **Confusable characters removed** (no I/O/0/1) | Users have to transcribe this code                             |
| TTL                     | 1 hour                                         | —                                                              |
| Max pending per channel | **3** (`pairing-store.ts:13-16`)               | **Preventing strangers from spamming the operator with codes** |

Storage is split per channel/account under the credentials directory, **with filenames sanitized against path traversal** (`pairing-store.ts:64-74`), and writes taken under a file lock.

`issuePairingChallenge` (`pairing-challenge.ts:24-48`) makes every channel go through one "create if absent + reply with unified wording" flow, **leaving channels no room to improvise** — the same instinct as §21.5.6's shared implementation for security-critical logic.

### Group adjudication is independent of DMs

`groupPolicy` defaults to allowlist. One easily missed but crucial rule:

```
Group control-command authorization does not inherit the DM pairing store
```

Verbatim comment (`dm-policy-shared.ts:262-266`):

> Group command authorization must not inherit DM pairing-store approvals.

**A user paired through DMs does not automatically gain the ability to issue control commands to the bot in a group.** Group commands recognize only the `allowFrom` written in the config file.

> **Remember it as one line: pairing is session admission, not permission granting.**
>
> The distinction matters. DM pairing means "I allow you to talk to my agent"; typing `/config set` in a group means "I allow you to change my system configuration." They shouldn't be the same thing.

### Wrapping external content

`src/security/external-content.ts` handles email, webhooks, scraped pages, and similar:

| Mechanism                                 | Details                                                                                                                                                                 |
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Random-id delimiters**                  | Wrapped in markers carrying a **random 16-hex-digit id** (`:53-66`) — an attacker can't predict the id and therefore can't forge a closing marker to escape the wrapper |
| **Angle-bracket homoglyph normalization** | A dozen-plus mappings for full-width forms, CJK brackets, and so on (`:105-120`), blocking Unicode-variant evasion                                                      |
| **14 injection pattern checks**           | `ignore previous instructions`, forged `[System]` blocks, and similar (`:17-32`) — **alerts only, no blocking**                                                         |

The first is clever. A fixed marker (say `<external>...</external>`) can be forged: an attacker writes `</external>` in the email body and everything after escapes the wrapper. A random id defeats that.

The third — alert without blocking — matches the overall philosophy (§44.4): **injection is inevitable; boundaries do the catching.** Blocking would generate a flood of false positives and, worse, create the illusion that injection has been solved.

## 32.6.3 Secrets: Three Lines of Defense

`src/secrets/` (9,261 lines) solves one concrete problem: **credentials must be usable at runtime yet must not sit in config files, logs, or model context.**

### Line one: SecretRef indirection

Config files hold references, not plaintext (`src/config/types.secrets.ts:1-16`):

```ts
{ source: "env" | "file" | "exec", id, provider }
```

| source | Meaning                                                 |
| ------ | ------------------------------------------------------- |
| `env`  | Environment variable                                    |
| `file` | A field in a JSON/env file (addressed by json-pointer)  |
| `exec` | An external command (e.g. `op read`, the 1Password CLI) |

The resolver works under a **complete resource budget** (`src/secrets/resolve.ts:31-37`):

```
file size cap        1 MiB
exec timeout         5 seconds
exec output cap      1 MiB
refs per provider    at most 512
batch cap            256 KiB
```

**What it defends against: a malicious or broken secret provider dragging the Gateway down.**

> An easily overlooked attack surface: `exec`-type SecretRefs run external commands. If that command hangs or emits unbounded output, an unbudgeted resolver takes the whole gateway with it. **Anywhere you invoke an external program you need a timeout and an output cap.**

`file` providers additionally check permissions before resolving (referencing `inspectPathPermissions`) — a world-readable key file should be flagged.

### Line two: the dual-snapshot runtime

`prepareSecretsRuntimeSnapshot` (`src/secrets/runtime.ts:102-166`) maintains **two deep clones**:

```ts
// src/secrets/runtime.ts:108-118 (excerpt)
const sourceConfig = structuredClone(params.config);      // original config with refs
const resolvedConfig = structuredClone(params.config);    // resolved config with plaintext
const context = createResolverContext({
  sourceConfig,
  env: params.env ?? process.env,
});

collectConfigAssignments({
  config: resolvedConfig,
  context,
});
```

The rule is clear:

| Purpose                                                 | Which snapshot               |
| ------------------------------------------------------- | ---------------------------- |
| Actually calling APIs at runtime                        | `resolvedConfig` (plaintext) |
| **Writing to disk / displaying in UI / diffing config** | **`sourceConfig` (refs)**    |

**Plaintext exists only in the in-memory snapshot.**

The reverse tool: `openclaw secrets configure` scans config for plaintext (`credential-matrix.ts` enumerates every known credential location), moves it into a provider, and replaces it with a ref.

> This dual snapshot is the foundation for §45.1's sixth pattern (merge-patch + env-ref write-back). Without it, any programmatic config write would expand a user's `${OPENAI_KEY}` into plaintext on disk.

### Line three: log and tool-output redaction

`src/logging/redact.ts` is **on by default** (`redactSensitive: "tools"` mode).

Twenty built-in patterns (`redact.ts:15-40`) cover:

```
ENV assignments / JSON fields / CLI flags / Bearer headers / PEM blocks
and common prefixes: sk- / ghp_ / xoxb- / AIza / Telegram bot tokens
```

On a match it **keeps the first 6 and last 4 characters and masks the rest** (`redact.ts:68-75`) — retaining enough for an operator to identify *which* key without exposing the credential.

Two defensive details:

* Custom patterns are compiled through `compileSafeRegex`;
* Replacement runs through `replacePatternBounded` with **bounded execution**.

**An operator can configure a catastrophically backtracking regex without DoS-ing the logging pipeline.**

> That's the concrete case behind `SECURITY.md`'s "operator-config-induced ReDoS isn't a vulnerability, but is still fixed as hardening" (§44.4.3). **Being out of scope doesn't mean unfixed** — an important distinction.

### One boundary that must be stated plainly

**Redaction is a best-effort last line, not the primary defense.**

The primary defense is "plaintext shouldn't be in the context at all":

* Tool results pass through a `tool_result_persist` hook that can trim fields before persistence;
* And **plugins see the resolved config through `api.config`** (they need credentials to work — part of TCB status, §21.5.6).

### `secrets audit`: four finding codes

`openclaw secrets audit` (`src/secrets/audit.ts:40-44`) runs independently of the security audit:

| Code              | Meaning                                              |
| ----------------- | ---------------------------------------------------- |
| `PLAINTEXT_FOUND` | Plaintext still present in config or auth storage    |
| `REF_UNRESOLVED`  | A reference that won't resolve                       |
| `REF_SHADOWED`    | **A ref shadowed by plaintext at the same location** |
| `LEGACY_RESIDUE`  | Leftover credential files from an older version      |

`REF_SHADOWED` is a thoughtful check: you configured a ref, but the old plaintext is still at the same location and *that's* what takes effect — **you think you finished migrating and you didn't.**

## 32.6.4 security audit: Productizing the Threat Model

`openclaw security audit` (entry `src/security/audit.ts`, roughly 5,000 lines including the audit-extra family) **translates `SECURITY.md`'s abstract boundaries into 80-plus concrete checks**, emitting `info` / `warn` / `critical` findings.

Grouped by checkId prefix:

| Prefix                                            | What it checks                                                                                                                                                                                                                            |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fs.*`                                            | **Permission bits and symlinks** on the state dir, config, credentials, logs, and session storage (a world-writable state dir is **critical**, `audit.ts:230-243`); Windows uses icacls                                                   |
| `gateway.*`                                       | Binding and auth combinations (non-loopback without auth, short tokens, incomplete trusted-proxy config, Tailscale funnel exposure, Control UI with device auth off or wildcard origins)                                                  |
| `channels.*`                                      | Wildcards in `allowFrom`, **fragile name-based entries**, native commands without an allowlist                                                                                                                                            |
| `plugins.*`                                       | Missing allowlist, install-record drift, **static scanning of entry code**                                                                                                                                                                |
| `hooks.*` / `models.*` / `logging.*` / `config.*` | Webhook tokens reusing the gateway token, **`models.weak_tier` (a weak model tier running a tool-enabled agent — an injection-resistance check!)**, `logging.redact_off`, and a full enumeration of explicitly enabled `dangerous*` flags |
| `sandbox.*`                                       | Container security hash epoch expiry, observation ports published to non-loopback (critical)                                                                                                                                              |

The "fragile name-based entries" under `channels.*` deserve a note: putting display names in an allowlist (rather than stable IDs) is dangerous — **anyone can change their display name to match.**

`models.weak_tier` is more interesting still: it makes **"you're running a tool-enabled agent on a model that's easy to inject"** a security check. Folding model capability into a security assessment is a rare move.

### Context-dependent severity

The plugin allowlist check best illustrates the design's quality — **the same absence changes severity with context**:

```ts
// src/security/audit-extra.async.ts:610-620 (excerpt)
findings.push({
  checkId: "plugins.extensions_no_allowlist",
  severity: skillCommandsLikelyExposed ? "critical" : "warn",
  title: "Extensions exist but plugins.allow is not set",
  detail:
    `Found ${pluginDirs.length} extension(s) under ${extensionsDir}. ` +
    `Without plugins.allow, any discovered plugin id may load...` +
```

Normally `warn`; **but once it detects Discord/Telegram/Slack tokens configured&#x20;*****and*****&#x20;native skill commands enabled, it escalates to `critical`.**

> **This is what a security tool should look like: severity depends on actual exposure, not on the check itself.**
>
> An instance running only locally with no channels attached genuinely isn't much at risk from a missing plugin allowlist; an instance with three public channels attached has a high-severity problem from the same absence. A scanner with fixed severities gives both the same score, and users quickly learn to ignore it.

### The code scanner

`src/security/skill-scanner.ts:149-202` (serving both skills and plugin entry points) is a set of context-conditioned heuristics:

```
child_process exec/spawn family
eval / new Function
mining signatures (stratum / xmrig)
obfuscated strings with 6+ consecutive hex escapes
base64 decoding of 200+ characters
process.env harvesting
```

**It can't offer guarantees** — but combined with provenance warnings (§21.5.4), it's enough to make a casually installed plugin show up in the audit report.

`--deep` adds real Gateway probing (with timeouts), and `--fix` (`src/security/fix.ts`) can automatically repair permission-class issues.

### The auditor's self-awareness

One thing worth praising: **check descriptions align strictly with `SECURITY.md`'s out-of-scope list**, and heuristic gaps ("obfuscation-pattern parity gaps") are explicitly defined as hardening rather than vulnerabilities.

> **The tool doesn't pretend to be a boundary.**
>
> That sentence works as a design principle for security tooling generally. A scanner that describes every warning as a "vulnerability" makes users either panic or go numb — and both reactions destroy the tool's value.

## 32.6.5 Three Known Weaknesses

From §45.2, with detail:

**1. One plugin means total compromise, with no mitigation.**

`runtime.config.writeConfigFile` lets a plugin rewrite **any config, including `plugins.allow` itself**, and `modelAuth` can fetch any provider's credentials.

Allowlists and provenance only guard against *accidental loading*; **they can't guard against misjudgment.**

> Directions worth considering medium-term: require secondary confirmation for `writeConfigFile` on sensitive paths (`plugins.*`, `gateway.auth.*`); or add a "plugin behavior baseline" cross-report to audit (which plugin registered an `llm_input` hook *and* accessed `process.env`).

**2. Redaction is regex heuristics.**

A new provider's token prefix isn't caught until it's added. `redactSensitive` has only `off` / `tools` — **no stronger tier covering non-tool log surfaces.**

**3. `plugins.allow` defaulting to empty is a usability compromise.**

First-run needs no configuration, but it means the default posture is **"discovered equals loaded"** across all four sources, backed only by a startup warning and audit reminders.

> Promoting "non-bundled plugins exist with no allowlist" from warn to **blocking by default** (or a first-run interactive confirmation) is probably the cheapest available hardening.

**4. Keeping audit items in sync with the implementation gets costlier as features grow.**

80-plus checks are **maintained by hand** across five files, with no mechanical link to the config schema. New dangerous flags depend on a developer remembering to register them in `dangerous-config-flags.ts`.

> This kind of "checklist security" ultimately needs **generated or test-enforced consistency** — exactly where §44.3's "declaration table + build-time self-check" should be applied. Within the same repository, chat commands got it (five frontends with a build-time check); security checks haven't.

***

## Section Summary

1. **Model output lives in the untrusted zone** — prompt injection is assumed inevitable, and the defense is making a fooled model unable to accomplish anything (tool policy limits what it calls, exec approvals what it runs, sandbox where it runs, allowlists who can fool it). The docs recommend **strong model tiers plus strict tool policy for tool-enabled agents**.
2. **DMs default to `pairing`**: strangers get a code, not a reply; 8 characters with **confusables removed**, 1-hour TTL, **at most 3 pending per channel against code spam**; every channel goes through one challenge flow with no room to improvise.
3. **Group command authorization does not inherit DM pairing** — **pairing is session admission, not permission granting.**
4. **External content is delimited by a random 16-hex id** (an attacker can't forge a closing marker to escape) plus **angle-bracket homoglyph normalization** (blocking Unicode-variant evasion), with 14 injection patterns that **alert without blocking**.
5. **Three secret layers**: SecretRef indirection (**exec type must have a timeout and output cap**) → **dual snapshot** (plaintext only in memory; writes, displays, and diffs all use refs) → log redaction (first 6 and last 4 retained, **bounded regex so it can't DoS itself**).
6. **The `REF_SHADOWED` check** catches "you configured a ref but plaintext at the same location is what actually takes effect" — **thinking you migrated when you didn't**.
7. **security audit translates `SECURITY.md` into 80-plus checks**; **severity varies with actual exposure** (missing plugin allowlist: warn normally, critical once public channels are attached with native commands enabled) — fixed-severity scanners get ignored.
8. **`models.weak_tier` makes "model injection resistance" a security check** — rare but correct.
9. **The tool doesn't pretend to be a boundary**: check descriptions align strictly with the out-of-scope list, and heuristic gaps are explicitly labeled hardening rather than vulnerabilities.
10. **Four weaknesses**: no mitigation for total plugin compromise, redaction being regex heuristics with only two tiers, **`plugins.allow` defaulting to empty making "discovered equals loaded"**, and 80-plus hand-maintained checks with no mechanical link to the schema (exactly where "declaration table + build-time self-check" should apply).
