Skip to content

config: ${VAR_NAME} env-variable substitution inside config.json (openclaw-compat) - #247

Merged
FMXExpress merged 1 commit into
mainfrom
claude/config-env-substitution
Jun 13, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/config-env-substitution

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Adds openclaw-style ${VAR_NAME} environment-variable substitution inside config.json string values. Any uppercase env var name wrapped in ${...} resolves at LoadConfig time to the env value (JSON-escaped on the fly). Lets operators keep API keys, bearer tokens, and webhook URLs in the environment and reference them by name from config.json the same way openclaw does.

{
  "providers": [
    { "name": "anthropic",
      "kind": "anthropic",
      "api_key": "${ANTHROPIC_API_KEY}",
      "model":   "claude-opus-4-7" }
  ],
  "gateway": { "token": "${PASCLAW_GATEWAY_TOKEN}" },
  "channels": [
    { "name":   "ops",
      "kind":   "discord",
      "target": "${OPS_DISCORD_WEBHOOK}" }
  ]
}

Pattern

${[A-Z_][A-Z0-9_]*} — matches openclaw exactly:

  • Uppercase only. ${api_key} does NOT match.
  • First character must be A-Z or _. ${1FOO} does NOT match.
  • Subsequent allow digits. ${FOO_42} does match if FOO_42 is set.
  • No dashes. ${WITH-DASH} does NOT match.

Behaviour

  • Set env var → spliced in, JSON-escaping any ", \, or control byte so the body stays valid JSON regardless of what the operator put in the env.
  • Unset (or set-but-empty) env var → literal ${VAR_NAME} left in place in the parsed string field. Deliberate diagnostic — pasclaw config show then prints the unresolved marker so the operator can see exactly which variable didn't resolve. No abort, no error.
  • Round-trip caveat — substitution is NOT preserved through SaveConfig. A config-mutating command (pasclaw auth login, pasclaw model set, pasclaw skills install, ...) writes the resolved value back. For env-only secrets that should never end up in config.json, prefer the dedicated env-var paths (PASCLAW_GATEWAY_TOKEN, OPENCLAW_GATEWAY_TOKEN) which don't go through string substitution at all. Documented in docs/configuration.md.

Test plan

  • make smoke — green
  • make test — full aggregate green (25 PASS markers, was 23)
  • make test-config-env-subst — 6 cases across two passes:
    • Clean env pass: unset env preserves literal; no-marker / malformed-marker input passes through; lowercase / mixed-case / digit-first / dash-containing names rejected; TConfig.FromJSON round-trips unresolved markers as plain string values without crashing.
    • --env-mode pass (fixture vars set by Makefile): simple ${VAR} substitution; mid-string prefix-${VAR}-suffix; multiple occurrences in same body; nested-object substitution; JSON-special bytes (" and \) in env values get escaped to \" and \\ so the body stays parseable.

Docs

  • docs/configuration.md — new ## ${VAR_NAME} environment-variable substitution section: pattern, examples, behaviour-on-unset, JSON safety, round-trip caveat, the no-escape workaround.
  • docs/gateway.md — adds a paragraph to the Authentication section pointing operators at the ${...} path for the gateway token, with the persist-through-SaveConfig caveat.

Scope

~400 LOC. ~130 in PasClaw.Config (helper functions + LoadConfig integration), ~190 in tests, ~60 in docs. The implementation deliberately doesn't touch PasClaw.JSON — substitution runs as raw text on the JSON body before parsing, keeping the JSON unit a leaf.


Generated by Claude Code

Match openclaw's template-substitution feature: any uppercase env
var name wrapped in ${...} inside a config string value resolves
at LoadConfig time to the env value (JSON-escaped). Lets operators
keep API keys, bearer tokens, webhook URLs in the environment and
reference them by name from config.json the same way openclaw
does:

  {
    "providers": [
      { "name": "anthropic",
        "kind": "anthropic",
        "api_key": "${ANTHROPIC_API_KEY}",
        "model":   "claude-opus-4-7" }
    ],
    "gateway": { "token": "${PASCLAW_GATEWAY_TOKEN}" },
    "channels": [
      { "name": "ops",
        "kind": "discord",
        "target": "${OPS_DISCORD_WEBHOOK}" }
    ]
  }

Pattern: ${[A-Z_][A-Z0-9_]*} (uppercase only, case-sensitive,
matches openclaw exactly). Implementation is raw-text substitution
applied to the JSON body BEFORE TConfig.FromJSON parses it. JSON-
escapes the substituted value on the fly so " / \ / control bytes
don't break the surrounding JSON regardless of what the operator
put in the env.

On unset (or set-but-empty) env var, the literal ${VAR_NAME} is
LEFT IN PLACE in the parsed string field. Deliberate: an operator
running `pasclaw config show` then sees exactly which marker
didn't resolve, instead of a silently-empty value. No abort, no
error, just visible-in-output diagnostics.

Tests (now 6 cases across two binary runs):

  Clean env (first pass):
    - unset env: literal ${VAR_NAME} preserved
    - no-marker / malformed-marker input passes through verbatim
    - lowercase / mixed-case / digit-first / dash-containing
      names do NOT match (charset rules enforced)
    - TConfig.FromJSON round-trips an unresolved marker as a
      plain string value (no crash; the literal lives in the
      parsed field so config-back-from-disk diagnostics work)

  --env-mode (second pass, fixture vars set by Makefile so FPC's
  startup-snapshotted envp picks them up):
    - simple ${VAR} substitution
    - mid-string substitution: prefix-${VAR}-suffix
    - multiple occurrences in same body each expand independently
    - works inside nested objects (raw-text substitution doesn't
      care about JSON depth)
    - JSON-special bytes (" and \) in env values get escaped to
      \" and \\ so the body stays parseable

Round-trip caveat documented in docs/configuration.md: SaveConfig
does NOT preserve markers -- a config-mutating command writes the
resolved value back. For env-only secrets that should never end
up in config.json, prefer the dedicated env-var paths
(PASCLAW_GATEWAY_TOKEN, OPENCLAW_GATEWAY_TOKEN), which don't go
through string substitution at all.

Docs:
  docs/configuration.md  new "## ${VAR_NAME} environment-variable
                         substitution" section with pattern,
                         examples, behaviour-on-unset, JSON
                         safety, round-trip caveat, the no-escape
                         workaround.
  docs/gateway.md        adds a paragraph to the Authentication
                         section pointing operators at the
                         ${...} path for the gateway token, with
                         the caveat that the resolved value
                         persists through SaveConfig.
@FMXExpress
FMXExpress merged commit ff01246 into main Jun 13, 2026
FMXExpress pushed a commit that referenced this pull request Jun 14, 2026
…itution

The template hardcoded `/data/pasclaw/workspace` and the app.yaml set
`PASCLAW_HOME=/data/pasclaw` so the two aligned by hand. When operators
skip the persistent volume (or DO drops the env var for whatever
reason) and PASCLAW_HOME falls back to the Dockerfile default
`/home/pasclaw/.pasclaw`, the sandbox stays pinned to `/data/pasclaw/
workspace` -- a path that no longer exists on disk. Result: every
/v1/fs call returns 403 with "outside workspace" regardless of path,
because the configured workspace is a phantom directory.

Switch the template to `\${PASCLAW_HOME}/workspace` so the
substitution path from PR #247 keeps the two in lockstep automatically.
Verified: PASCLAW_HOME=/tmp/scratch resolves to sandbox.workspace=
/tmp/scratch/workspace at runtime via ExpandEnvVarsInJSON.

Tradeoffs noted:
- \${VAR_NAME} substitution was designed for secrets; using it for an
  infrastructure path is a slight design smell but acceptable since
  the feature is general-purpose.
- If PASCLAW_HOME is ever unset (it's pinned by the Dockerfile ENV so
  this won't happen in practice), the literal `\${PASCLAW_HOME}/
  workspace` would persist as a broken path. Real-world risk: ~zero.
- Auditing the sandbox boundary now needs `cat config.json` + `printenv
  PASCLAW_HOME` instead of just `cat config.json`. Acceptable for the
  robustness gain.

Followup (separate PR worth filing): make TSandboxPolicy.Workspace
default to \$PASCLAW_HOME/workspace in code when the field is blank
in gateway/serve mode. Drops the template field entirely and removes
the env-substitution dance for new deployments.

Also separate: /v1/fs with no `?path=` param defaults to GetHome
(PASCLAW_HOME root), which is still outside the workspace under this
config -- the operator just needs to pass `?path=\$PASCLAW_HOME/
workspace` explicitly. Defaulting /v1/fs to the workspace when
restrict_to_workspace=true would be a more intuitive UX; out of
scope for this commit.
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
Single-service "just basic" deployment of `pasclaw gateway` on DO
App Platform. Modelled on openclaw-appplatform but trimmed:
  - no ngrok / Tailscale / Spaces backup / CHEATSHEET / AI-SETUP /
    CLAUDE.md
  - no s6-overlay process supervisor -- pasclaw gateway runs as PID
    1 under tini for zombie reaping
  - no GHCR variant -- single App Spec building from this repo
  - no persistent volume by default -- documented opt-in for
    operators who want sessions / memory / KB to survive restarts

Files added under digitalocean/:

  Dockerfile               Two-stage FPC build. Stage 1 (debian:bookworm)
                           clones Indy at build time + compiles. Stage 2
                           (bookworm-slim) has just libssl3 / libsqlite3
                           / ca-certificates / tini + the binary. Final
                           image ~80 MB.

  entrypoint.sh            mkdir $PASCLAW_HOME, stamp
                           config.template.json into config.json on
                           first boot (only when absent -- never
                           clobbers a mounted-in custom config), exec
                           `pasclaw gateway --addr 0.0.0.0 --port $PORT`.

  config.template.json     Defaults wired with ${VAR_NAME} markers --
                           PR FMXExpress#247's expansion resolves them from env at
                           LoadConfig time. Anthropic primary, OpenAI
                           fallback, optional Brave web_search, optional
                           OTel, sandbox + denylist on.

  .do/app.yaml             App Spec: github source -> dockerfile_path,
                           basic-xxs (~$5/mo), health_check on
                           /v1/health, SECRET-marked env vars for the
                           gateway token + provider keys.

  .env.example             Documented env vars for local Makefile use.
                           Never commit a populated copy.

  Makefile                 docker build / run / health / smoke targets
                           rooted at the repo root so the build context
                           picks up src/ and Makefile.

  README.md                Five-step deploy via dashboard OR doctl,
                           cost breakdown (~$5/mo basic + ~$1/mo for
                           the optional 1GB volume), persistent-state
                           caveat, security notes (gateway-token as
                           the only thing between the public internet
                           and an agent that can shell + fs_*), and
                           the deliberate-omissions list.

.dockerignore extended (existing file was minimal; PR FMXExpress#121 shape) to
exclude wholesale: docs/, cog/, browser/, all *.md, Delphi project
files (*.dproj/*.dpk), local env files. The vendor/Indy/ exclusion
was already there from PR FMXExpress#121. All scaffolds-other-than-Dockerfile
metadata excluded so a future `docker build .` over the repo doesn't
silently leak ~3,800 LOC of docs + sample binaries + 600 MB of Indy
into a container image. The user's exact concern from the
pre-PR conversation: "won't this unrelated stuff go in there?"

The .dockerignore is belt-and-suspenders -- the new Dockerfile uses
selective COPY for every file it needs (Makefile, src/, two files
from digitalocean/) so wholesale exclusion of unrelated trees is
just a build-context-upload speedup AND a guard against future
Dockerfiles that do `COPY .`. cog/ benefits too -- its existing
build now skips digitalocean/ and docs/ for free.

No PasClaw core changes. `make smoke` green. Local Docker build
not exercised here (no docker in this environment); a `make
-f digitalocean/Makefile build` on any host with docker installed
walks the build end-to-end and is the canonical pre-deploy smoke
test.
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
…itution

The template hardcoded `/data/pasclaw/workspace` and the app.yaml set
`PASCLAW_HOME=/data/pasclaw` so the two aligned by hand. When operators
skip the persistent volume (or DO drops the env var for whatever
reason) and PASCLAW_HOME falls back to the Dockerfile default
`/home/pasclaw/.pasclaw`, the sandbox stays pinned to `/data/pasclaw/
workspace` -- a path that no longer exists on disk. Result: every
/v1/fs call returns 403 with "outside workspace" regardless of path,
because the configured workspace is a phantom directory.

Switch the template to `\${PASCLAW_HOME}/workspace` so the
substitution path from PR FMXExpress#247 keeps the two in lockstep automatically.
Verified: PASCLAW_HOME=/tmp/scratch resolves to sandbox.workspace=
/tmp/scratch/workspace at runtime via ExpandEnvVarsInJSON.

Tradeoffs noted:
- \${VAR_NAME} substitution was designed for secrets; using it for an
  infrastructure path is a slight design smell but acceptable since
  the feature is general-purpose.
- If PASCLAW_HOME is ever unset (it's pinned by the Dockerfile ENV so
  this won't happen in practice), the literal `\${PASCLAW_HOME}/
  workspace` would persist as a broken path. Real-world risk: ~zero.
- Auditing the sandbox boundary now needs `cat config.json` + `printenv
  PASCLAW_HOME` instead of just `cat config.json`. Acceptable for the
  robustness gain.

Followup (separate PR worth filing): make TSandboxPolicy.Workspace
default to \$PASCLAW_HOME/workspace in code when the field is blank
in gateway/serve mode. Drops the template field entirely and removes
the env-substitution dance for new deployments.

Also separate: /v1/fs with no `?path=` param defaults to GetHome
(PASCLAW_HOME root), which is still outside the workspace under this
config -- the operator just needs to pass `?path=\$PASCLAW_HOME/
workspace` explicitly. Defaulting /v1/fs to the workspace when
restrict_to_workspace=true would be a more intuitive UX; out of
scope for this commit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants