Secrets Management: SecretRefs, Snapshots, and Scrubbing

Learn how OpenClaw handles credentials with SecretRefs, runtime snapshots, and safe scrubbing. This page is for developers and operators who need to secure sensitive data in gateway configurations.

Read this when

  • Configuring SecretRefs for provider credentials and SQLite auth-profile refs
  • Storing team-wide secrets and environment values in the shared SQLite store
  • Operating secrets reload, audit, configure, and apply safely in production
  • Understanding startup fail-fast, inactive-surface filtering, and last-known-good behavior

OpenClaw lets you add credentials through additive SecretRefs, so supported secrets don't have to sit in configuration as plaintext.

Note

Plaintext remains an option. Each credential decides individually whether to use a SecretRef.

Warning

When plaintext credentials live in files the agent can inspect, they stay readable by the agent. That includes openclaw.json, .env, retired auth-profile JSON archives, or generated agents/*/agent/models.json files. Once every supported credential moves to SecretRefs and openclaw secrets audit --check shows no plaintext residue, that local blast radius shrinks.

Runtime model

  • Secrets are resolved eagerly into an in-memory runtime snapshot during activation, not lazily along request paths.
  • A cold Gateway startup isolates a retryable SecretRef failure to a known non-Gateway owner, provided that owner supports isolation. Mapped owner classes cover model providers and skills, media/TTS/cron providers, eligible auth profiles, per-agent memory, sandbox SSH, channel accounts, and manifest-declared plugin routes. The Gateway comes up, marks the owner as configured-unavailable, and logs a redacted degradation warning. Gateway ingress auth, structurally invalid refs or resolved values, fail-closed owners, and refs whose runtime owner is unmapped still halt startup.
  • Reload validates each mapped owner on its own, then publishes a single atomic snapshot. Healthy owners refresh. An eligible failed owner holds onto its last-known-good value and turns stale only when its ref identities, provider definitions, and complete non-secret owner contract stay unchanged; a failed owner that changed or is new goes cold. A strict failure rejects the reload and keeps the active snapshot intact.
  • Policy violations (like an OAuth-mode auth profile paired with SecretRef input) stop activation before the runtime swap happens.
  • Runtime requests only read the active in-memory snapshot. Model-provider SecretRef credentials move through auth storage and stream options as process-local sentinels until egress. Outbound delivery paths (Discord reply/thread delivery, Telegram action sends) read that same snapshot and don't re-resolve refs per send.
  • Read-only channel capability discovery checks each account independently. A configured-but-unavailable account doesn't hide healthy sibling accounts' message actions, though direct sends through the unavailable account still fail closed.

That keeps secret-provider outages off hot request paths.

Gateway ingress protection, structurally invalid config or resolved values, policy violations, and unknown ownership still fail closed. Isolated owners never fall back to a lower-precedence credential source.

Egress-time injection (sentinels)

For model-provider credentials backed by SecretRefs, OpenClaw mints an opaque, process-local sentinel during model-auth resolution. Auth storage, stream options, SDK configuration, logs, error objects, and most runtime introspection therefore see a value like oc-sent-v2.<authenticated-ciphertext>.end, not the provider credential. The guarded model fetch and managed local-provider health probes swap known sentinels into URL and header values immediately before each request leaves the process.

Unknown sentinel-shaped values fail closed before any network activity. OpenClaw declines to send the request rather than forwarding an unresolved sentinel to a provider. Resolved secret values are also registered for exact-value log redaction as a defense in depth measure.

Provider adapters use the latest injection point their SDK supports:

  • SDKs with a custom fetch option receive OpenClaw's guarded fetch, so the SDK keeps the sentinel.
  • SDKs without a custom fetch option unwrap the sentinel right before client construction. Plugin-owned provider streams and agent harnesses unwrap at the final core-owned handoff because those transports don't share OpenClaw's guarded fetch.

Sentinels cut plaintext exposure across the model-call chain, but they aren't process isolation. The real value still lives in same-process memory and shows up at the final adapter boundary. Plain environment credentials not configured through SecretRefs stay plaintext and sit outside this mechanism.

Set OPENCLAW_SECRET_SENTINELS=off (also accepts 0 or false, case-insensitive) to turn off sentinel minting during incident response or compatibility troubleshooting. The kill switch doesn't disable exact-value redaction registration.

Agent-access boundary

SecretRefs keep credentials out of config and generated model files, but they don't form a process-isolation boundary. A plaintext credential left on disk in a path the agent can read is still accessible via file or shell tools, bypassing API-level redaction.

For production deployments where agent-accessible files are in scope, treat migration as complete only when all of these hold:

  • Supported credentials use SecretRefs instead of plaintext values.
  • Legacy plaintext residue is scrubbed from openclaw.json, the SQLite auth-profile store, .env, and generated models.json files. Retired auth JSON is doctor-owned migration input and is never rewritten by secrets apply.
  • openclaw secrets audit --check is clean after migration.
  • Any remaining unsupported or rotating credentials are protected by OS isolation, container isolation, or an external credential proxy.

That's why the audit/configure/apply workflow acts as a security migration gate, not just a convenience helper.

Warning

SecretRefs don't make arbitrary readable files safe. Backups, copied configs, old generated model catalogs, and unsupported credential classes remain production secrets until deleted, moved outside the agent trust boundary, or isolated separately.

Active-surface filtering

SecretRefs are validated only on effectively active surfaces:

  • Enabled surfaces: retryable failures for mapped, isolatable owners enter cold or stale degradation. Strict, fail-closed, Gateway-required, or unmapped failures block startup/reload.
  • Inactive surfaces: unresolved refs don't block startup/reload; they emit a non-fatal SECRETS_REF_IGNORED_INACTIVE_SURFACE diagnostic.

Examples of inactive surfaces

  • Disabled channel/account entries.
  • Top-level channel credentials that no enabled account inherits.
  • Disabled tool/feature surfaces.
  • Web search provider-specific keys not selected by tools.web.search.provider. In auto mode (provider unset), keys are consulted by precedence for auto-detection until one resolves; after selection, non-selected provider keys are inactive.
  • Sandbox SSH auth material (agents.defaults.sandbox.ssh.identityData, certificateData, knownHostsData, plus per-agent overrides) is active only when the effective sandbox backend is ssh and sandbox mode is not off, for the default agent or an enabled agent.
  • gateway.remote.token / gateway.remote.password SecretRefs are active if any of these hold:
    • gateway.mode=remote
    • gateway.remote.url is configured
    • gateway.tailscale.mode is serve or funnel
    • In local mode without those remote surfaces: gateway.remote.token is active when token auth can win and no env/auth token is configured; gateway.remote.password is active only when password auth can win and no env/auth password is configured.
  • Active gateway.auth.token / gateway.auth.password SecretRefs stay authoritative over OPENCLAW_GATEWAY_TOKEN / OPENCLAW_GATEWAY_PASSWORD; environment credentials are fallbacks when the corresponding local config input is absent.

Gateway auth surface diagnostics

When a SecretRef is set on gateway.auth.token, gateway.auth.password, gateway.remote.token, or gateway.remote.password, gateway startup/reload logs the surface state under code SECRETS_GATEWAY_AUTH_SURFACE:

  • active: the SecretRef is part of the effective auth surface and must resolve.
  • inactive: another auth surface wins, or remote auth is disabled/not active.

The log entry includes the reason the active-surface policy used.

Onboarding reference preflight

In interactive onboarding, choosing SecretRef storage runs preflight validation before saving:

  • Environment references: the setup process checks that the variable name is legitimate and that a non-empty value is available at configuration time.
  • Provider references (file, exec, or store): the chosen provider is validated, id is resolved, and the type of the resolved value is confirmed.
  • Quickstart path: when gateway.auth.token is already a SecretRef, onboarding resolves it before probe and dashboard initialization (covering env, file, exec, and store references) through the same fail-fast mechanism.
  • Generated gateway token: setup itself mints gateway.auth.token, so reference mode has nothing to request. If OPENCLAW_GATEWAY_TOKEN is exported, an env reference to that variable is written, making a subsequent rotation authoritative; otherwise, the token is placed in the secret store under OPENCLAW_GATEWAY_TOKEN and a store reference is saved. An existing store entry is reused instead of rotated, meaning repeated setup runs never break clients that are already paired.

A failed validation displays the error and allows another attempt.

SecretRef contract

A single object structure applies everywhere:

{ source: "env" | "file" | "exec" | "store", provider: "default", id: "..." }

env

{ source: "env", provider: "default", id: "OPENAI_API_KEY" }

SecretInput fields also accept shorthand strings:

"${OPENAI_API_KEY}"
"$OPENAI_API_KEY"

Checks:

  • provider has to equal ^[a-z][a-z0-9_-]{0,63}$
  • id has to equal ^[A-Z][A-Z0-9_]{0,127}$

file

{ source: "file", provider: "filemain", id: "/providers/openai/apiKey" }

Checks:

  • provider has to equal ^[a-z][a-z0-9_-]{0,63}$
  • id must be an absolute JSON pointer (/...), or the literal value for singleValue providers
  • RFC 6901 escaping within segments: ~ turns into ~0, / turns into ~1

exec

{ source: "exec", provider: "vault", id: "providers/openai/apiKey#value" }

Checks:

  • provider has to equal ^[a-z][a-z0-9_-]{0,63}$
  • id has to equal ^[A-Za-z0-9][A-Za-z0-9._:/#-]{0,255}$ (selectors like secret#json_key are supported)
  • id cannot include . or .. as slash-delimited path segments (for instance, a/../b is disallowed)

store

{ source: "store", provider: "default", id: "OPENAI_API_KEY" }

Checks:

  • provider has to equal ^[a-z][a-z0-9_-]{0,63}$
  • id follows the environment-name grammar ^[A-Z][A-Z0-9_]{0,127}$
  • Only the Gateway-wide team scope is resolved in this release

Provider config

Define providers under secrets.providers:

{
  secrets: {
    providers: {
      default: { source: "env" },
      teamstore: { source: "store" },
      filemain: {
        source: "file",
        path: "~/.openclaw/secrets.json",
        mode: "json", // or "singleValue"
      },
      vault: {
        source: "exec",
        command: "/usr/local/bin/openclaw-vault-resolver",
        args: ["--profile", "prod"],
        passEnv: ["PATH", "VAULT_ADDR"],
        jsonOnly: true,
      },
      "team-secrets": {
        source: "exec",
        pluginIntegration: {
          pluginId: "acme-secrets",
          integrationId: "secret-store",
        },
      },
    },
    defaults: {
      env: "default",
      file: "filemain",
      exec: "vault",
      store: "teamstore",
    },
  },
}

Provider aliases are tied to their source. An explicit provider entry takes precedence when it matches; if an env or store default alias is also used by an entry from another source, that source's built-in provider wins. Non-default aliases and file or exec providers must point to an explicit entry with the matching source.

Env provider

  • An optional exact-name allowlist is available via allowlist.
  • Resolution fails when env values are missing or empty.

File provider

  • Loads the file found at path from the local filesystem.
  • With mode: "json" (the default), a JSON object payload is expected, and id gets resolved as a JSON pointer.
  • When mode: "singleValue" is used, ref id "value" is expected, and the raw file contents come back with any trailing newline stripped.
  • Ownership and permission checks must be passed by the path; timeoutMs (default 5000) and maxBytes (default 1 MiB) set the limits for the read operation.
  • On Windows, the behavior is fail-closed: if ACL verification cannot be performed for the path, resolution does not succeed. Relocate the secret to a path where OpenClaw can verify the ACLs; no provider-level workaround exists.

Exec provider

  • The configured absolute binary path runs directly, with no shell involved.
  • command has to be a regular file, not a symlink. For shims from package managers, determine the actual binary path (for instance with realpath "$(command -v vault)") and set that absolute path in the configuration. Use trustedDirs to limit executables to approved directories.
  • Supported options include timeoutMs (default 5000), noOutputTimeoutMs (default matches timeoutMs), maxOutputBytes (default 1 MiB), the env/passEnv allowlist, and trustedDirs.
  • jsonOnly comes with a default of true. When jsonOnly: false is set and only one id is requested, plain non-JSON stdout is treated as the value for that id.
  • On Windows, the behavior is fail-closed: if ACL verification cannot be performed for the command path, resolution does not succeed. Choose a command path whose ACLs OpenClaw can verify; no provider-level workaround exists.
  • Exec providers managed by plugins can rely on pluginIntegration instead of a duplicated command/args. During startup or reload, OpenClaw pulls the current command details from the installed plugin manifest; if the plugin is disabled, removed, untrusted, or stops declaring the integration, active SecretRefs on that provider fail closed.

Request payload (stdin):

{ "protocolVersion": 1, "provider": "vault", "ids": ["providers/openai/apiKey"] }

Response payload (stdout):

{ "protocolVersion": 1, "values": { "providers/openai/apiKey": "<openai-api-key>" } } // pragma: allowlist secret

Optional per-id errors:

{
  "protocolVersion": 1,
  "values": {},
  "errors": { "providers/openai/apiKey": { "code": "NOT_FOUND" } }
}

code serves as an optional machine-readable diagnostic. The recognized codes NOT_FOUND and AMBIGUOUS_DUPLICATE_KEY are shown by OpenClaw along with the provider and ref id. Other codes and free-form fields like message are tolerated for protocol-v1 compatibility but are not displayed, since resolver output may contain credential material.

Store provider

  • Values are read from OpenClaw's shared state SQLite database.
  • No connection settings exist for this provider. secrets.defaults.store picks its default alias.
  • Only team scope gets resolved in this release. Identity scope is held back for a future release.

Shared secret store

The shared secret store acts as a Gateway-wide, team-scoped location for secrets and environment values that every Gateway process using the same state database should have access to. Administer it from Settings → Secrets in the Control UI, or locally via openclaw secrets store. The CLI commands target the local state database and reject Gateway URL or token options.

Entries come with two explicit access modes. Both keep the existing secret and env storage kinds, and either kind can back a SecretRef:

  • Protected secret (kind: "secret") values become write-only once saved. Gateway list results, the Control UI, and CLI list/get output never include them; no reveal RPC exists. A protected value stays inert until a supported config field points to it with a SecretRef, or an enabled, destination-bound secret egress proxy consumes it.
  • Agent-readable environment (kind: "env") values stay visible to administrators in the Control UI and can be returned by store list and store get. OpenClaw injects them as plaintext into Gateway-hosted commands run through its exec tool, after inherited process values and before explicit per-call env. The agent is free to print, transmit, or persist these values. Protected host keys are skipped with a visible warning.

Agent-readable environment values do not reach Codex native shell, the Codex sandbox exec-server, ACP children such as Claude Code, OpenClaw sandbox exec, or remote node exec. Those paths build a different child environment. In eligible Codex app-server turns, use gateway_exec to deliberately re-enter the OpenClaw Gateway execution path; gateway_process offers the existing per-session background follow-up. Native Codex shell stays the preferred option for ordinary local work. The store snapshot is read once per agent run, so entries added or changed mid-run take effect from the next run onward.

By default, secret entries never get injected into subprocess environments. When the default-off secret egress proxy is enabled, Gateway-hosted exec commands receive process-local sentinels instead of plaintext values.

Names follow the same uppercase grammar as env SecretRefs, and each UTF-8 value is capped at 64 KiB (65,536 bytes). A secret entry must include a value; empty secrets are rejected because they would only show up as a confusing downstream auth failure. env entries may be empty. This accommodates PEM keys and service-account JSON without inheriting the smaller limits of ordinary environment variables.

Reference an entry from openclaw.json with the store source:

{
  models: {
    providers: {
      openai: {
        apiKey: { source: "store", provider: "default", id: "OPENAI_API_KEY" },
      },
    },
  },
}

Control UI set/delete operations refresh the active secrets runtime automatically when the changed name is referenced by a store SecretRef in the active source config. Names that are not referenced skip that work. Direct CLI writes remain an offline/local path; after changing a config-referenced value with the CLI, run openclaw secrets reload so the active in-memory snapshot picks it up.

Warning

Store values are not encrypted at rest. They are stored unencrypted in the shared state SQLite database (state/openclaw.sqlite), protected by the same 0600 file and 0700 directory permissions as other credentials in that database. Operators who need stronger storage isolation should use an external exec provider such as the 1Password plugin or Vault SecretRefs.

Secret egress proxy

The secret egress proxy allows agent subprocesses hosted by the Gateway to reference shared-store secret entries without ever seeing their plaintext. OpenClaw places the already-authenticated sentinel into the subprocess environment, and a loopback proxy owned by the Gateway swaps it out in request URLs, headers, and streamed bodies right before traffic leaves the system.

Every secret must also declare the precise HTTPS hosts where substitution is permitted. Hostnames are stored in lowercase ASCII/punycode form and compared exactly; wildcards, suffix matching, and ports are unsupported. A secret with no allowed hosts is never substituted. To bind a host without altering the stored value:

openclaw secrets store set OPENAI_API_KEY --allow-host api.openai.com

Invoke --allow-host again to bind multiple hosts, or use --clear-allowed-hosts to clear all bindings. A refused request identifies the secret and outputs the exact store set ... --allow-host ... command required for that destination.

Turn it on explicitly, then restart the Gateway:

openclaw config set secrets.egressProxy.enabled true --strict-json
openclaw gateway restart

As an example, bind an OpenAI key to its API host and activate the proxy:

openclaw secrets store set OPENAI_API_KEY --allow-host api.openai.com
openclaw config set secrets.egressProxy.enabled true --strict-json

Once the Gateway has restarted, an agent hosted by it can execute:

curl -sS https://api.openai.com/v1/models -H "Authorization: Bearer $OPENAI_API_KEY"

Within the agent environment, $OPENAI_API_KEY acts as an oc-sent-v2...end sentinel. The proxy replaces it with the stored value only for api.openai.com. A request aimed at an unbound host gets refused with Secret "OPENAI_API_KEY" is not allowed for host "<host>". Run: openclaw secrets store set OPENAI_API_KEY --allow-host <host>.

Equivalent configuration:

{
  secrets: {
    egressProxy: {
      enabled: true,
      bypassHosts: ["pinned-api.example.com"],
    },
  },
}

When enabled, OpenClaw injects these values into Gateway-hosted exec environments:

  • HTTPS_PROXY and HTTP_PROXY, with per-run credentials embedded in the loopback proxy URL
  • NODE_USE_ENV_PROXY=1, which lets supported Node.js global fetch clients respect HTTP_PROXY and HTTPS_PROXY without relying on NODE_OPTIONS
  • NODE_EXTRA_CA_CERTS, SSL_CERT_FILE, CURL_CA_BUNDLE, and REQUESTS_CA_BUNDLE, pointing at the ephemeral CA certificate
  • each team-store secret entry as an oc-sent-v2...end sentinel; env entries retain their prior behavior and precedence

Proxy authentication relies on standard Basic proxy auth with username openclaw and a random per-run password. The token expires when the exact agent run closes, including cancellation and replacement. Base64 is not encryption: the listener binds only to loopback, and a process able to read the proxy token from the agent environment can already read the sentinels there. Missing, wrong, or expired credentials receive 407 Proxy Authentication Required and are never forwarded.

The run snapshot records each sentinel alongside its secret name and allowed hosts. After proxy authentication, the proxy finds the matched sentinel in that run's registration and authorizes the normalized destination hostname before decrypting the sentinel. A sentinel that is unregistered, unresolved, unbound, or bound to a different host is refused before its plaintext is forwarded.

Warning

Destination binding does not make an allowed host trustworthy. A bound service that reflects request credentials can still return the plaintext to the agent. DNS-level compromise can redirect a permitted hostname because policy is hostname-based, not an IP pin. Non-HTTPS requests are refused rather than protected, and HTTPS interception still has the protocol limits below. Use external network policy or process isolation when those threats are in scope.

The CA is generated once per Gateway start under the state directory. Its directory is mode 0700, its private keys are mode 0600, it is removed during Gateway shutdown, and OpenClaw never installs it in a system trust store. Requests fail closed when a sentinel cannot be authenticated or resolved; the proxy never forwards or silently strips an unresolved sentinel. Request bodies are scanned as a stream with a bounded carry window, so substitution also works when a sentinel crosses chunk boundaries or appears in a large upload.

bypassHosts contains exact hostnames that must remain end-to-end TLS for certificate-pinned clients. Those hosts use an authenticated blind CONNECT tunnel. No substitution is possible inside the tunnel; a sentinel sent there is safe by construction because it is authenticated ciphertext rather than a credential, so the vendor sees an invalid credential and rejects it.

Current limits:

  • HTTP/2 upstream connections are not supported; the proxy uses HTTP/1.1 upstream.
  • WebSocket rewriting is not supported.
  • Non-443 HTTPS substitution is not a supported compatibility target.
  • Identity-scoped secrets are not supported; only the team store participates.
  • Allowed-host policy is exact-hostname authorization only. It does not validate the resolved IP or prevent an allowed origin from reflecting credentials.
  • Plain HTTP is refused; it is not upgraded or substituted.
  • Secret egress applies only to Gateway-hosted exec. Sandbox and remote node exec receive neither proxy variables nor sentinels, so shared-store secret entries are unavailable there. Provider-native harness subprocesses also do not use this proxy.
  • Background subprocesses lose proxy authorization when their owning agent run ends, even if the process itself is still alive.

File-backed API keys

Avoid placing file:... strings in the config env block. That block is literal and non-overriding, so file:... is never resolved there.

Use a file SecretRef on a supported credential field instead:

{
  secrets: {
    providers: {
      xai_key_file: {
        source: "file",
        path: "~/.openclaw/secrets/xai-api-key.txt",
        mode: "singleValue",
      },
    },
  },
  models: {
    providers: {
      xai: {
        apiKey: { source: "file", provider: "xai_key_file", id: "value" },
      },
    },
  },
}

For mode: "singleValue", the SecretRef id is "value". For mode: "json", use an absolute JSON pointer such as "/providers/xai/apiKey".

See SecretRef Credential Surface for the fields that accept SecretRefs.

Exec integration examples

For a dedicated 1Password guide covering service accounts, the bundled agent skill, and troubleshooting, see 1Password.

1Password

{
  plugins: {
    entries: {
      onepassword: {
        enabled: true,
      },
    },
  },
  secrets: {
    providers: {
      onepassword: {
        source: "exec",
        pluginIntegration: {
          pluginId: "onepassword",
          integrationId: "onepassword",
        },
      },
    },
  },
  models: {
    providers: {
      openai: {
        baseUrl: "https://api.openai.com/v1",
        models: [{ id: "gpt-5", name: "gpt-5" }],
        apiKey: {
          source: "exec",
          provider: "onepassword",
          id: "op://Engineering/OpenAI/apiKey",
        },
      },
    },
  },
}

The bundled 1Password plugin uses the official op CLI and the plugin's service-account token file.

Bitwarden Secrets Manager (bws)

Use a resolver wrapper to map SecretRef ids to Bitwarden Secrets Manager item keys. The repository includes scripts/secrets/openclaw-bws-resolver.mjs; install or copy it to an absolute trusted path on the host that runs the Gateway.

Requirements:

  • Bitwarden Secrets Manager CLI (bws) installed on the Gateway host.
  • BWS_ACCESS_TOKEN available to the Gateway service.
  • PATH passed to the resolver, or BWS_BIN set to the absolute bws binary path.
  • BWS_SERVER_URL set in the environment when using a self-hosted Bitwarden instance.
{
  secrets: {
    providers: {
      bws: {
        source: "exec",
        command: "/usr/local/bin/openclaw-bws-resolver.mjs",
        passEnv: ["BWS_ACCESS_TOKEN", "BWS_SERVER_URL", "PATH", "BWS_BIN"],
        jsonOnly: true,
      },
    },
  },
  models: {
    providers: {
      openai: {
        baseUrl: "https://api.openai.com/v1",
        models: [{ id: "gpt-5", name: "gpt-5" }],
        apiKey: {
          source: "exec",
          provider: "bws",
          id: "openclaw/providers/openai/apiKey",
        },
      },
    },
  },
}

The resolver groups requested ids into batches, executes bws secret list, and retrieves values for the corresponding secret key fields. Choose keys that meet the exec SecretRef id contract, for instance openclaw/providers/openai/apiKey; keys formatted like environment variables with underscores are rejected prior to resolver execution. When multiple visible Bitwarden secrets match the requested key, the resolver marks that id as ambiguous rather than making a guess. After making configuration changes, confirm the resolver path:

openclaw secrets audit --allow-exec

HashiCorp Vault CLI

{
  secrets: {
    providers: {
      vault_openai: {
        source: "exec",
        command: "/absolute/non-symlink/path/to/vault",
        trustedDirs: ["/absolute/non-symlink/path/to"],
        args: ["kv", "get", "-field=OPENAI_API_KEY", "secret/openclaw"],
        passEnv: ["VAULT_ADDR", "VAULT_TOKEN"],
        jsonOnly: false,
      },
    },
  },
  models: {
    providers: {
      openai: {
        baseUrl: "https://api.openai.com/v1",
        models: [{ id: "gpt-5", name: "gpt-5" }],
        apiKey: { source: "exec", provider: "vault_openai", id: "value" },
      },
    },
  },
}

password-store (pass)

A compact resolver wrapper can map SecretRef ids straight to pass entries. Place this as an executable at an absolute path that satisfies your exec-provider path checks, such as /usr/local/bin/openclaw-pass-resolver. The #!/usr/bin/env node shebang resolves node from the resolver process PATH, so add PATH to passEnv. If pass is absent from that PATH, set PASS_BIN in the parent environment and also include it in passEnv:

#!/usr/bin/env node
const { spawnSync } = require("node:child_process");

let stdin = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
  stdin += chunk;
});
process.stdin.on("error", (err) => {
  process.stderr.write(`${err.message}\n`);
  process.exit(1);
});
process.stdin.on("end", () => {
  let request;
  try {
    request = JSON.parse(stdin || "{}");
  } catch (err) {
    process.stderr.write(`Failed to parse request: ${err.message}\n`);
    process.exit(1);
  }

  const passBin = process.env.PASS_BIN || "pass";
  const values = {};
  const errors = {};

  for (const id of request.ids ?? []) {
    const result = spawnSync(passBin, ["show", id], { encoding: "utf8" });
    if (result.status === 0) {
      values[id] = result.stdout.split(/\r?\n/, 1)[0] ?? "";
    } else {
      errors[id] = { message: (result.stderr || `pass exited ${result.status}`).trim() };
    }
  }

  process.stdout.write(JSON.stringify({ protocolVersion: 1, values, errors }));
});

Next, set up the exec provider and direct apiKey to the pass entry path:

{
  secrets: {
    providers: {
      pass_store: {
        source: "exec",
        command: "/usr/local/bin/openclaw-pass-resolver",
        passEnv: ["PATH", "HOME", "GNUPGHOME", "GPG_TTY", "PASSWORD_STORE_DIR", "PASS_BIN"],
        jsonOnly: true,
      },
    },
  },
  models: {
    providers: {
      openai: {
        baseUrl: "https://api.openai.com/v1",
        models: [{ id: "gpt-5", name: "gpt-5" }],
        apiKey: {
          source: "exec",
          provider: "pass_store",
          id: "openclaw/providers/openai/apiKey",
        },
      },
    },
  },
}

Put the secret on the first line of the pass entry, or adjust the wrapper to emit the complete pass show output instead. After updating config, validate both the static audit and the exec resolver path:

openclaw secrets audit --check
openclaw secrets audit --allow-exec

sops

{
  secrets: {
    providers: {
      sops_openai: {
        source: "exec",
        command: "/absolute/non-symlink/path/to/sops",
        trustedDirs: ["/absolute/non-symlink/path/to"],
        args: ["-d", "--extract", '["providers"]["openai"]["apiKey"]', "/path/to/secrets.enc.json"],
        passEnv: ["SOPS_AGE_KEY_FILE"],
        jsonOnly: false,
      },
    },
  },
  models: {
    providers: {
      openai: {
        baseUrl: "https://api.openai.com/v1",
        models: [{ id: "gpt-5", name: "gpt-5" }],
        apiKey: { source: "exec", provider: "sops_openai", id: "value" },
      },
    },
  },
}

MCP server environment variables

Environment variables for the MCP server set through plugins.entries.acpx.config.mcpServers accept SecretInput, so API keys and tokens never appear in plaintext config:

{
  plugins: {
    entries: {
      acpx: {
        enabled: true,
        config: {
          mcpServers: {
            github: {
              command: "npx",
              args: ["-y", "@modelcontextprotocol/server-github"],
              env: {
                GITHUB_PERSONAL_ACCESS_TOKEN: {
                  source: "env",
                  provider: "default",
                  id: "MCP_GITHUB_PAT",
                },
              },
            },
          },
        },
      },
    },
  },
}

Plaintext string values remain supported. Env-template references like ${MCP_SERVER_API_KEY} and SecretRef objects are resolved during gateway activation, prior to the MCP server process starting. As with other SecretRef surfaces, unresolved refs only prevent activation when the acpx plugin is effectively active.

Sandbox SSH auth material

The core ssh sandbox backend also handles SecretRefs for SSH authentication material:

{
  agents: {
    defaults: {
      sandbox: {
        mode: "all",
        backend: "ssh",
        ssh: {
          target: "user@gateway-host:22",
          identityData: { source: "env", provider: "default", id: "SSH_IDENTITY" },
          certificateData: { source: "env", provider: "default", id: "SSH_CERTIFICATE" },
          knownHostsData: { source: "env", provider: "default", id: "SSH_KNOWN_HOSTS" },
        },
      },
    },
  },
}

Behavior at runtime:

  • OpenClaw resolves these refs during sandbox activation, not lazily on each SSH call.
  • Resolved values are placed in a temp directory with restrictive file permissions (0o600) and are used in the generated SSH config.
  • If the effective sandbox backend is not ssh (or sandbox mode is off), these refs stay inactive and do not block startup.

Supported credential surface

Canonical supported and unsupported credentials are listed in SecretRef Credential Surface.

Note

Runtime-minted or rotating credentials and OAuth refresh material are intentionally excluded from read-only SecretRef resolution.

Required behavior and precedence

  • Field without a ref: unchanged.
  • Field with a ref: required on active surfaces during activation.
  • If both plaintext and ref are present, the ref takes precedence on supported precedence paths.
  • The redaction sentinel __OPENCLAW_REDACTED__ is reserved for internal config redaction/restore and is rejected as literal submitted config data.

Warning and audit signals:

  • SECRETS_REF_OVERRIDES_PLAINTEXT (runtime warning)
  • REF_SHADOWED (audit finding when SQLite auth-profile credentials take precedence over openclaw.json refs)
  • STORE_PLAINTEXT_RESIDUE (audit finding when a stored name still has an equivalent plaintext config value)

Google Chat serviceAccount accepts inline JSON or a SecretRef. Doctor moves the retired sibling serviceAccountRef into this canonical field when it is unset.

Activation triggers

Secret activation runs on:

  • Startup (preflight plus final activation)
  • Config reload hot-apply path
  • Config reload restart-check path
  • Manual reload via secrets.reload
  • Gateway config write RPC preflight (config.set / config.apply / config.patch), validating active-surface SecretRefs within the submitted config payload before persisting edits

Activation contract:

  • Success swaps the snapshot atomically.
  • A strict startup failure aborts Gateway startup.
  • During cold startup, a retryable resolution failure for a mapped, isolatable non-Gateway owner may publish the snapshot with that exact owner configured-unavailable. Requests for the owner fail with SECRET_SURFACE_UNAVAILABLE; model-provider owners do not fall back to environment or auth-profile credentials after an explicit ref fails.
  • Reload and restart-check isolate eligible mapped owners. Unchanged ref identities with unchanged provider definitions and an unchanged complete non-secret owner contract retain their exact last-known-good values as stale; changed or newly configured unresolved refs publish cold for only that owner. A strict reload failure preserves the previously active snapshot.
  • config.set, config.apply, and config.patch accept syntactically valid unresolved refs for isolatable owners and return a redacted degradedSecretOwners report. Gateway ingress auth, structurally invalid config or resolved values, policy violations, and unknown owners still reject before disk mutation.
  • Healthy sibling owners resolve and publish normally even when another owner is cold or stale.
  • Providing an explicit per-call channel token to an outbound helper/tool call does not trigger SecretRef activation; activation points remain startup, reload, and explicit secrets.reload.

Degraded and recovered signals

When activation at reload time fails after a previously healthy state, OpenClaw switches into a degraded secrets condition and fires one-shot system events along with log codes:

  • SECRETS_RELOADER_DEGRADED
  • SECRETS_RELOADER_RECOVERED

How it behaves:

  • Degraded: healthy owners keep refreshing, stale owners retain their last-known-good values, and cold owners stay inaccessible.
  • Recovered: triggered a single time after the next successful activation.
  • If failures keep happening while already degraded, warnings are logged but the event is not sent again.
  • A hard startup failure never produces a degraded event, since runtime never reached an active state. A successful startup with cold owners logs the owner degradation but does not emit a reloader event.
  • For ref-scoped startup and reload failures, a structured SECRETS_DEGRADED warning is emitted per affected owner. Provider-scoped outages produce a single SECRETS_PROVIDER_DEGRADED warning listing the provider and every affected owner, instead of repeating the provider failure for each owner. Warnings carry a redacted reason, cold or stale owner state, and the openclaw secrets reload retry hint. Resolved values and SecretRef ids are never included.
  • openclaw doctor shows cold and stale owners with their affected config paths, redacted reason, and retry guidance.

Command-path resolution

Command paths can choose to support SecretRef resolution through a gateway snapshot RPC. Two broad categories apply:

Strict command paths

Examples include openclaw memory remote-memory paths and openclaw qr --remote when remote shared-secret refs are needed. These read from the active snapshot and fail immediately if a required SecretRef is missing.

Read-only command paths

Examples include openclaw status, openclaw status --all, openclaw channels status, openclaw channels resolve, openclaw security audit, and read-only doctor/config repair flows. These also prefer the active snapshot, but fall back to degraded operation instead of aborting when a targeted SecretRef is unavailable.

Read-only behavior:

  • With the gateway running, these commands read from the active snapshot first.
  • If gateway resolution is incomplete or the gateway is down, they try a targeted local fallback for that command surface.
  • If a targeted SecretRef remains unavailable, the command proceeds with degraded read-only output and a clear diagnostic noting the ref is configured but not reachable in this command path.
  • This degraded mode is scoped to the command only; it does not weaken runtime startup, reload, or send/auth paths.

Additional notes:

  • Snapshot refresh after backend secret rotation is handled by openclaw secrets reload.
  • Gateway RPC method used by these command paths: secrets.resolve.

Audit and configure workflow

Default operator flow:

Audit current state

openclaw secrets audit --check

Configure and apply SecretRefs

openclaw secrets configure --apply

Re-audit

openclaw secrets audit --check

Do not consider the migration finished until the re-audit comes back clean. If the audit still finds plaintext values at rest, the agent-access risk persists even when runtime APIs return redacted values.

If you save a plan instead of applying during configure, use openclaw secrets apply --from <plan-path> to apply that saved plan before the re-audit.

secrets audit

Findings include:

  • Plaintext values at rest (openclaw.json, SQLite auth-profile rows, .env, and generated agents/*/agent/models.json).
  • Plaintext sensitive provider header residues in generated models.json entries.
  • Unresolved refs.
  • Precedence shadowing (SQLite auth profiles taking priority over openclaw.json refs).
  • Store residue (a stored name still has an equivalent plaintext value in config).

Exec note: by default, audit skips exec SecretRef resolvability checks to avoid command side effects. Use openclaw secrets audit --allow-exec to execute exec providers during audit.

Header residue note: sensitive provider header detection is name-heuristic based (common auth/credential header names and fragments such as authorization, x-api-key, token, secret, password, and credential).

secrets configure

Interactive helper that:

  • Configures secrets.providers first (env/file/exec/store, add/edit/remove).
  • Lets you select supported secret-bearing fields in openclaw.json plus the SQLite auth-profile store for one agent scope.
  • Can create a new auth-profile mapping directly in the target picker.
  • Captures SecretRef details (source, provider, id).
  • Runs preflight resolution and can apply immediately.

Exec note: preflight skips exec SecretRef checks unless --allow-exec is set. If you apply directly from configure --apply and the plan includes exec refs/providers, keep --allow-exec set for the apply step too.

Helpful modes:

  • openclaw secrets configure --providers-only
  • openclaw secrets configure --skip-provider-setup
  • openclaw secrets configure --agent <id>

configure apply defaults:

  • Scrub matching static credentials from SQLite auth-profile rows for targeted providers.
  • Leave retired auth.json untouched; run openclaw doctor --fix to migrate and archive it.
  • Scrub matching known secret lines from the effective state and active-config .env files (deduplicated when both paths match).

secrets apply

Once a plan has been saved, you can put it into effect:

openclaw secrets apply --from /tmp/openclaw-secrets-plan.json
openclaw secrets apply --from /tmp/openclaw-secrets-plan.json --allow-exec
openclaw secrets apply --from /tmp/openclaw-secrets-plan.json --dry-run
openclaw secrets apply --from /tmp/openclaw-secrets-plan.json --dry-run --allow-exec

A note on execution: unless --allow-exec is configured, dry-run mode skips exec validation; write mode, on the other hand, rejects any plan that includes exec SecretRefs or providers unless --allow-exec is configured.

For the precise requirements around target/path contracts and the exact conditions under which rejection occurs, refer to Secrets Apply Plan Contract.

One-way safety policy

Warning

OpenClaw deliberately avoids creating rollback backups that would hold historical plaintext secret values.

How safety is enforced:

  • Write mode only proceeds after preflight checks pass.
  • Runtime activation gets validated before anything is committed.
  • File updates during apply rely on atomic replacement, with a best-effort restore if something fails.

Legacy auth compatibility notes

For static credentials, the runtime no longer depends on plaintext legacy auth storage.

  • The runtime pulls credentials from the resolved in-memory snapshot.
  • Legacy static api_key entries get scrubbed as soon as they are detected.
  • Compatibility handling tied to OAuth stays separate.

Control UI

Use Settings → Secrets to view, create, modify, bulk-import, or soft-delete entries scoped to the team. Pick Protected secret for write-only values that SecretRefs or destination-bound Gateway egress rely on. Choose Agent-readable environment only when Gateway-hosted agent commands need plaintext access and the agent could print, transmit, or store it. Bulk Add accepts dotenv NAME=VALUE assignments, including quoted multiline values. When Protect credential-like names automatically is on, names that look like credentials default to protected mode.

This store page handles values exclusively. To wire up the corresponding store SecretRef on a supported field, use its settings form or the raw editor. Identity-scoped entries are reserved for a future release and do not show up on this page.

5,993 words · updated Aug 25, 2026