Skip to content

Commit 2b263ad

Browse files
fix(secrets): preflight exec provider command paths before config acceptance (#117128)
* fix(secrets): preflight exec provider command paths before config acceptance Schema validation and config writes accepted exec SecretRef command paths that gateway cold start rejects (symlink, missing, unsafe permissions/ownership), so a config that printed "Config valid" could crash the gateway on the next restart. Share one non-executing exec-provider command-path validator (`src/secrets/exec-provider-path-validation.ts`, extracted from `resolve.ts` `assertSecurePath`) across cold-start activation, `openclaw config validate`, and supported config writes so all three surfaces return the same verdict for manual exec SecretRef providers. - New `src/secrets/exec-provider-path-validation.ts` (`assertSecureExecCommandPath`); `resolve.ts` imports and calls it, deleting the duplicated logic. - `config validate` calls `collectManualExecProviderCommandPathErrors` with `validateAllProviders: true` so the strict validation command checks every configured manual exec provider. Config writes (`config set/patch/dry-run`) use targeted preflight instead — they check only providers touched by the operation, or all providers when the write edits the `secrets.providers` collection itself — so an unrelated routine write is not blocked by a dormant inactive provider that gateway startup would skip. A shared `collectTouchedProviders` helper deduplicates the touch-collection logic this function and `collectPluginIntegrationProviderErrors` both need. - Guards against non-object provider values so a value-mode write setting a provider to `null`/primitive no longer throws a raw TypeError. - Docs aligned with the exact permission rule, symlink rejection, and that `config validate` checks every provider while writes use targeted preflight. The extracted validator stays at parity with current `resolve.ts` cold-start activation: absolute path, non-symlink, trusted-directory containment, non-writable-by-others permissions, current-user ownership, and Windows ACL availability. It deliberately does not add a regular-file or owner-execute-bit requirement, so cold start (which now calls the shared validator) does not grow stricter and block existing configurations without an upgrade path. Tightening the executable policy is upgrade-sensitive and left to maintainers (the issue carries `needs-product-decision` / `needs-security-review`). Scope is limited to manual exec SecretRef providers as reported in #117051. Plugin-integration materialized-command parity, the deprecated `allowInsecurePath` manifest field, `checks.schema` semantic widening, and dead CLI flag retirement from earlier revisions are intentionally left out for the same boundary reason. Closes #117051 * refactor(config): unify secret provider preflight and mutations Share one provider issue collector and one set/patch/unset write lifecycle. Preserve validation JSON and targeted recovery, and carry provider metadata through patch deletions. Keep startup path policy unchanged. Co-authored-by: SunnyShu0925 <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 7a288ed commit 2b263ad

12 files changed

Lines changed: 715 additions & 239 deletions

‎docs/cli/config.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,22 @@ machine-output spelling and keeps stdout reserved for the schema document.
114114

115115
Validates the current config against the active schema without starting the gateway. It also checks provider/source compatibility for every registry-declared SecretRef, including disabled plugin or channel configuration. This strict command can report an inactive mismatch that does not block normal Gateway startup, where SecretRef resolution remains limited to effectively active surfaces.
116116

117+
After schema validation, it checks every configured manual exec provider's command path using the same non-executing trust checks as startup: file presence, symlinks, trusted directories, permissions, ownership, and Windows ACL availability. `config set`, `config patch`, and `config unset` apply these checks only to providers changed or referenced by the operation, including during dry runs. Replacing the `secrets` or `secrets.providers` collection checks every remaining provider. An unrelated inactive provider does not block targeted repairs or removal of that provider.
118+
119+
Path validation does not execute providers or verify their output. Passing it does not guarantee successful secret resolution; exec dry runs require `--allow-exec` to test that separately.
120+
117121
```bash
118122
openclaw config validate
119123
openclaw config validate --json
120124
```
121125

126+
<Note>
127+
The exec-provider checks inspect the filesystem of the host where the CLI
128+
runs. Run `config validate` on the gateway host itself (or on a host with
129+
matching command paths, ownership, and ACLs). Paths and permissions can change
130+
after validation; startup checks them again before execution.
131+
</Note>
132+
122133
<Note>
123134
If validation is already failing, start with `openclaw configure` or `openclaw doctor --fix`. `openclaw chat` does not bypass the invalid-config guard.
124135
</Note>
@@ -364,7 +375,7 @@ openclaw config set channels.discord.token \
364375
- Builder mode: runs SecretRef resolvability checks for changed refs/providers.
365376
- JSON mode (`--strict-json`, `--json`, or batch mode): runs schema validation plus SecretRef resolvability checks.
366377
- Policy validation runs against the full post-change config, so parent-object writes (for example setting `hooks` as an object) cannot bypass unsupported-surface validation.
367-
- Exec SecretRef checks are skipped by default to avoid command side effects; pass `--allow-exec` to opt in (this may execute provider commands). `--allow-exec` is dry-run only and errors without `--dry-run`.
378+
- Exec command-path trust checks run without executing providers. Exec SecretRef resolvability checks are skipped by default to avoid command side effects; pass `--allow-exec` to opt in (this may execute provider commands). `--allow-exec` is dry-run only and errors without `--dry-run`.
368379

369380
</Accordion>
370381
<Accordion title="--dry-run --json fields">

‎docs/cli/secrets.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ Notes:
217217

218218
### Exec provider safety
219219

220-
Package managers often expose symlinked command paths. Resolve the real binary path (for example with `realpath "$(command -v vault)"`) and configure that absolute, non-symlink path; use `trustedDirs` to restrict executables to approved directories. On Windows, provider paths fail closed when ACL verification is unavailable, with no provider-level bypass.
220+
Package managers often expose symlinked command paths. Resolve the real binary path (for example with `realpath "$(command -v vault)"`) and configure that absolute, non-symlink path; use `trustedDirs` to restrict executables to approved directories. Run `openclaw config validate` on the Gateway host to check manual exec command paths without executing providers. On Windows, provider paths fail closed when ACL verification is unavailable, with no provider-level bypass.
221221

222222
## Apply a saved plan
223223

‎docs/gateway/configuration-reference.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1573,8 +1573,8 @@ Notes:
15731573
- `file` provider supports `mode: "json"` and `mode: "singleValue"` (`id` must be `"value"` in singleValue mode).
15741574
- File and exec provider paths fail closed when Windows ACL verification is unavailable. Use paths whose ACLs OpenClaw can verify; there is no provider-level bypass.
15751575
- `exec` provider requires an absolute `command` path and uses protocol payloads on stdin/stdout.
1576-
- Symlink command paths are rejected. Configure the resolved absolute binary path instead.
1577-
- If `trustedDirs` is configured, the command path must be inside an approved directory.
1576+
- Symlink command paths are rejected. Configure the resolved absolute binary path instead; it must not be group- or world-writable and, on POSIX, must be owned by the current user.
1577+
- If `trustedDirs` is configured, the command path (after `~` expansion) must be inside an approved directory; symlinked commands are rejected before this check, so the configured path itself is what `trustedDirs` constrains.
15781578
- `exec` child environment is minimal by default; pass required variables explicitly with `passEnv`.
15791579
- Secret refs are resolved at activation time into an in-memory snapshot, then request paths read the snapshot only.
15801580
- Active-surface filtering applies during activation: unresolved refs on enabled surfaces fail startup/reload, while inactive surfaces are skipped with diagnostics.

‎docs/gateway/secrets.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,8 @@ Provider aliases are source-specific. A matching explicit provider entry wins; i
230230

231231
<Accordion title="Exec provider">
232232
- Runs the configured absolute binary path directly, no shell.
233-
- `command` must be a regular file, not a symlink. For package-manager shims, resolve the real binary path (for example with `realpath "$(command -v vault)"`) and configure that absolute path. Use `trustedDirs` to restrict executables to approved directories.
233+
- `command` must not be a symlink, must not be group- or world-writable, and on POSIX must be owned by the current user. For package-manager shims, resolve the real binary path (for example with `realpath "$(command -v vault)"`) and configure that absolute path. Use `trustedDirs` to restrict executables to approved directories.
234+
- [`config validate`](/cli/config#config-validate) checks every manual exec command path without executing providers. Config writes and dry runs check only changed or newly referenced providers, so an unrelated inactive provider does not block repairs. These are path trust checks, not proof that a provider can execute or return a secret.
234235
- Supports `timeoutMs` (default 5000), `noOutputTimeoutMs` (default equals `timeoutMs`), `maxOutputBytes` (default 1 MiB), `env`/`passEnv` allowlist, and `trustedDirs`.
235236
- `jsonOnly` defaults to `true`. With `jsonOnly: false` and a single requested id, plain non-JSON stdout is accepted as that id's value.
236237
- Windows fail-closed: if ACL verification is unavailable for the command path, resolution fails. Use a command path whose ACLs OpenClaw can verify; there is no provider-level bypass.

‎src/cli/config-cli-input.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -580,13 +580,7 @@ async function readConfigPatchInput(opts: ConfigPatchOptions): Promise<unknown>
580580
}
581581

582582
function buildDeleteOperation(path: PathSegment[]): ConfigSetOperation {
583-
return {
584-
inputMode: "json",
585-
requestedPath: path,
586-
setPath: path,
587-
value: undefined,
588-
mutation: "delete",
589-
};
583+
return { ...buildUnsetOperation(path), inputMode: "json" };
590584
}
591585

592586
export function buildUnsetOperation(

‎src/cli/config-cli-runner.ts‎

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import {
4848
collectDryRunResolvabilityErrors,
4949
collectDryRunSchemaErrors,
5050
collectDryRunStaticErrorsForSkippedExecRefs,
51-
collectPluginIntegrationProviderErrors,
51+
collectConfigSecretProviderErrors,
5252
dedupeDryRunErrors,
5353
formatDryRunFailureMessage,
5454
loadValidConfigForWrite,
@@ -328,11 +328,9 @@ export async function runConfigOperations(params: {
328328
const writePath = recordOperation(operation);
329329
const unsetResult = unsetAtPath(next, operation.setPath);
330330
if (!unsetResult.removed && operation.inputMode === "unset") {
331+
const requestedPath = formatConfigSetPath(operation.requestedPath, operation.pathTokens);
331332
const runtimeOnly = getAtPath(snapshot.runtimeConfig, operation.setPath).found;
332-
const message = formatConfigUnsetMissingPathMessage({
333-
path: formatConfigSetPath(operation.requestedPath, operation.pathTokens),
334-
runtimeOnly,
335-
});
333+
const message = formatConfigUnsetMissingPathMessage({ path: requestedPath, runtimeOnly });
336334
if (options.dryRun && options.json) {
337335
throw new ConfigSetDryRunValidationError({
338336
ok: false,
@@ -347,7 +345,7 @@ export async function runConfigOperations(params: {
347345
kind: "missing-path",
348346
message: runtimeOnly
349347
? message
350-
: `Config path not found: ${formatConfigSetPath(operation.requestedPath, operation.pathTokens)}. Nothing was changed.`,
348+
: `Config path not found: ${requestedPath}. Nothing was changed.`,
351349
},
352350
],
353351
});
@@ -414,10 +412,11 @@ export async function runConfigOperations(params: {
414412
"",
415413
{ normalizeRoot: true },
416414
).map((line) => line.trim());
417-
const pluginIntegrationErrors = collectPluginIntegrationProviderErrors({
418-
config: nextConfig,
419-
operations: appliedOperations,
420-
});
415+
const providerErrors = formatConfigIssueLines(
416+
await collectConfigSecretProviderErrors({ config: nextConfig, operations: appliedOperations }),
417+
"",
418+
).map((message): ConfigSetDryRunError => ({ kind: "schema", message }));
419+
421420
if (options.dryRun) {
422421
const hasJsonMode = operations.some(({ inputMode }) => inputMode === "json");
423422
const hasBuilderMode = operations.some(({ inputMode }) => inputMode === "builder");
@@ -446,7 +445,7 @@ export async function runConfigOperations(params: {
446445
if ((!hasJsonMode || !requiresFullSchemaValidation) && policyIssueLines.length > 0) {
447446
errors.push(...policyIssueLines.map((message) => ({ kind: "schema" as const, message })));
448447
}
449-
errors.push(...pluginIntegrationErrors);
448+
errors.push(...providerErrors);
450449
if (requiresFullSchemaValidation) {
451450
errors.push(
452451
...collectDryRunSchemaErrors(
@@ -475,9 +474,7 @@ export async function runConfigOperations(params: {
475474
inputModes: uniqueValues(operations.map(({ inputMode }) => inputMode)),
476475
checks: {
477476
schema:
478-
requiresFullSchemaValidation ||
479-
policyIssueLines.length > 0 ||
480-
pluginIntegrationErrors.length > 0,
477+
requiresFullSchemaValidation || policyIssueLines.length > 0 || providerErrors.length > 0,
481478
resolvability: checksRefs || modelRefCheck.refsTotal > 0,
482479
resolvabilityComplete:
483480
(checksRefs || modelRefCheck.refsTotal > 0) &&
@@ -528,11 +525,11 @@ export async function runConfigOperations(params: {
528525
if (policyIssueLines.length > 0) {
529526
throw new Error(formatPolicyFailure(policyIssueLines));
530527
}
531-
if (pluginIntegrationErrors.length > 0) {
528+
if (providerErrors.length > 0) {
532529
throw new Error(
533530
[
534-
"Config validation failed: plugin-managed SecretRef provider integration is invalid.",
535-
...pluginIntegrationErrors.map((error) => `- ${error.message}`),
531+
"Config validation failed: SecretRef provider configuration is invalid.",
532+
...providerErrors.map((error) => `- ${error.message}`),
536533
].join("\n"),
537534
);
538535
}

‎src/cli/config-cli-validation.ts‎

Lines changed: 52 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,15 @@ import { readConfigFileSnapshotForWrite } from "../config/config.js";
44
import { formatConfigIssueLines, normalizeConfigIssues } from "../config/issue-format.js";
55
import { renderConfigValidationIssueLines } from "../config/issue-location.js";
66
import { isPluginPackagingRuntimeOutputInvalidConfigSnapshot } from "../config/recovery-policy.js";
7+
import type { ConfigValidationIssue } from "../config/types.js";
78
import type { OpenClawConfig } from "../config/types.openclaw.js";
8-
import {
9-
coerceSecretRef,
10-
resolveSecretInputRef,
11-
type PluginIntegrationSecretProviderConfig,
12-
type SecretRef,
13-
} from "../config/types.secrets.js";
9+
import { coerceSecretRef, resolveSecretInputRef, type SecretRef } from "../config/types.secrets.js";
1410
import { validateConfigObjectRawWithPlugins } from "../config/validation.js";
1511
import { formatErrorMessage } from "../infra/errors.js";
1612
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1713
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1814
import { type RuntimeEnv, defaultRuntime, writeRuntimeJson } from "../runtime.js";
15+
import { assertSecureExecCommandPath } from "../secrets/exec-provider-path-validation.js";
1916
import {
2017
isPluginIntegrationSecretProviderConfig,
2118
resolveSecretProviderIntegrationConfig,
@@ -76,18 +73,21 @@ export async function loadValidConfigForWrite(runtime: RuntimeEnv = defaultRunti
7673

7774
export { formatInvalidConfigRepairHint };
7875

79-
export function strictlyValidateConfigSnapshotForCli(
76+
export async function strictlyValidateConfigSnapshotForCli(
8077
snapshot: ConfigFileSnapshot,
8178
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "manifestRegistry">,
82-
): ConfigFileSnapshot {
79+
): Promise<ConfigFileSnapshot> {
8380
if (!snapshot.valid) {
8481
return snapshot;
8582
}
8683
const validated = validateConfigObjectRawWithPlugins(snapshot.sourceConfig, {
8784
semanticValidation: "strict",
8885
pluginMetadataSnapshot,
8986
});
90-
return validated.ok ? snapshot : { ...snapshot, valid: false, issues: validated.issues };
87+
const issues = validated.ok
88+
? await collectConfigSecretProviderErrors({ config: snapshot.runtimeConfig })
89+
: validated.issues;
90+
return issues.length === 0 ? snapshot : { ...snapshot, valid: false, issues };
9191
}
9292

9393
function collectSecretRefsFromUnknown(value: unknown): SecretRef[] {
@@ -277,14 +277,16 @@ function touchesSecretProviderCollection(path: readonly string[]): boolean {
277277
);
278278
}
279279

280-
export function collectPluginIntegrationProviderErrors(params: {
280+
export async function collectConfigSecretProviderErrors(params: {
281281
config: OpenClawConfig;
282-
operations: ConfigSetOperation[];
283-
}): ConfigSetDryRunError[] {
282+
operations?: ConfigSetOperation[];
283+
}): Promise<ConfigValidationIssue[]> {
284284
const providers = params.config.secrets?.providers ?? {};
285-
let validateAllProviders = false;
286285
const touchedProviderAliases = new Set<string>();
287-
for (const operation of params.operations) {
286+
// Explicit validation checks all manual providers; writes must leave unrelated
287+
// dormant providers alone so operators can repair the rest of their config.
288+
let validateAllProviders = params.operations === undefined;
289+
for (const operation of params.operations ?? []) {
288290
if (operation.touchedProviderAlias) {
289291
touchedProviderAliases.add(operation.touchedProviderAlias);
290292
}
@@ -296,42 +298,46 @@ export function collectPluginIntegrationProviderErrors(params: {
296298
}
297299
validateAllProviders ||= touchesSecretProviderCollection(operation.setPath);
298300
}
299-
if (!validateAllProviders && touchedProviderAliases.size === 0) {
300-
return [];
301-
}
302-
const integrationProviders: Array<{
303-
alias: string;
304-
provider: PluginIntegrationSecretProviderConfig;
305-
}> = [];
301+
const issues: ConfigValidationIssue[] = [];
302+
let manifestRegistry: PluginMetadataSnapshot["manifestRegistry"] | undefined;
306303
for (const [alias, provider] of Object.entries(providers)) {
307-
if (
308-
(validateAllProviders || touchedProviderAliases.has(alias)) &&
309-
isPluginIntegrationSecretProviderConfig(provider)
310-
) {
311-
integrationProviders.push({ alias, provider });
304+
if (!validateAllProviders && !touchedProviderAliases.has(alias)) {
305+
continue;
312306
}
313-
}
314-
if (integrationProviders.length === 0) {
315-
return [];
316-
}
317-
const manifestRegistry = loadPluginMetadataSnapshot({
318-
config: params.config,
319-
env: process.env,
320-
}).manifestRegistry;
321-
const errors: ConfigSetDryRunError[] = [];
322-
for (const { alias, provider } of integrationProviders) {
323-
const resolved = resolveSecretProviderIntegrationConfig({
324-
manifestRegistry,
325-
providerAlias: alias,
326-
providerConfig: provider,
327-
config: params.config,
328-
env: process.env,
329-
});
330-
if (!resolved.ok) {
331-
errors.push({ kind: "schema", message: `secrets.providers.${alias}: ${resolved.reason}` });
307+
const providerPath = `secrets.providers.${alias}`;
308+
if (isPluginIntegrationSecretProviderConfig(provider)) {
309+
// Preserve write-time manifest validation without adding executable-path
310+
// policy to plugin integrations; activation owns their materialized command.
311+
if (!params.operations) {
312+
continue;
313+
}
314+
manifestRegistry ??= loadPluginMetadataSnapshot({
315+
config: params.config,
316+
env: process.env,
317+
}).manifestRegistry;
318+
const resolved = resolveSecretProviderIntegrationConfig({
319+
manifestRegistry,
320+
providerAlias: alias,
321+
providerConfig: provider,
322+
config: params.config,
323+
env: process.env,
324+
});
325+
if (!resolved.ok) {
326+
issues.push({ path: providerPath, message: resolved.reason });
327+
}
328+
} else if (isPlainRecord(provider) && "command" in provider) {
329+
try {
330+
await assertSecureExecCommandPath({
331+
command: provider.command,
332+
label: `${providerPath}.command`,
333+
trustedDirs: provider.trustedDirs,
334+
});
335+
} catch (err) {
336+
issues.push({ path: `${providerPath}.command`, message: formatErrorMessage(err) });
337+
}
332338
}
333339
}
334-
return errors;
340+
return issues;
335341
}
336342

337343
export function dedupeDryRunErrors(errors: ConfigSetDryRunError[]): ConfigSetDryRunError[] {

0 commit comments

Comments
 (0)