Skip to content

Commit fa71a6f

Browse files
authored
fix(qa): isolate packaged mock auth bootstrap (#126247)
* fix(qa): isolate packaged mock auth config Punchcard-Session: frost-orchard-lantern-ze (cherry picked from commit 648bd40) * fix(qa): scrub inherited shell startup env * fix(qa): block exported Bash functions
1 parent 40e3ab8 commit fa71a6f

6 files changed

Lines changed: 193 additions & 41 deletions

File tree

‎.github/workflows/openclaw-release-telegram-qa.yml‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1530,17 +1530,27 @@ jobs:
15301530
"$RUNTIME_ROOT"/tmp/openclaw-"$RUNNER_UID"/openclaw-qa-suite-*) ;;
15311531
*) echo "SUT temp root escaped the workflow runtime root." >&2; exit 1 ;;
15321532
esac
1533+
requested_config_path="${OPENCLAW_CONFIG_PATH:?}"
15331534
config_path="${temp_root}/openclaw.json"
15341535
[[ -f "$config_path" && ! -L "$config_path" ]]
15351536
[[ "$(realpath -e "$config_path")" == "$config_path" ]]
1537+
case "$requested_config_path" in
1538+
"$config_path") ;;
1539+
"${temp_root}/state/qa-auth-bootstrap/openclaw.json")
1540+
[[ "${1:-}" == "models" && "${2:-}" == "auth" ]]
1541+
[[ -f "$requested_config_path" && ! -L "$requested_config_path" ]]
1542+
[[ "$(realpath -e "$requested_config_path")" == "$requested_config_path" ]]
1543+
;;
1544+
*) echo "SUT config path escaped the canonical or auth-bootstrap roots." >&2; exit 1 ;;
1545+
esac
15361546
capture_live_model_config "$config_path"
15371547
15381548
export OPENCLAW_QA_TEMP_ROOT="$temp_root"
15391549
export HOME="${temp_root}/home"
15401550
export OPENCLAW_HOME="$HOME"
15411551
export OPENCLAW_STATE_DIR="${temp_root}/state"
15421552
export OPENCLAW_OAUTH_DIR="${OPENCLAW_STATE_DIR}/credentials"
1543-
export OPENCLAW_CONFIG_PATH="$config_path"
1553+
export OPENCLAW_CONFIG_PATH="$requested_config_path"
15441554
export XDG_CACHE_HOME="${temp_root}/xdg-cache"
15451555
export XDG_CONFIG_HOME="${temp_root}/xdg-config"
15461556
export XDG_DATA_HOME="${temp_root}/xdg-data"
@@ -1575,6 +1585,9 @@ jobs:
15751585
chown -R "$SUT_UID:$SUT_GID" "$path"
15761586
chmod -R u=rwX,go= "$path"
15771587
done
1588+
if [[ "$requested_config_path" != "$config_path" ]]; then
1589+
[[ "$(stat -c '%F:%a:%u:%g' "$requested_config_path")" == "regular file:600:${SUT_UID}:${SUT_GID}" ]]
1590+
fi
15781591
if [[ -n "${OPENCLAW_BUNDLED_PLUGINS_DIR:-}" ]]; then
15791592
chown -R root:root "$OPENCLAW_BUNDLED_PLUGINS_DIR"
15801593
chmod -R a+rX,go-w "$OPENCLAW_BUNDLED_PLUGINS_DIR"
@@ -1640,6 +1653,7 @@ jobs:
16401653
export SUT_UID SUT_GID RUNNER_UID RUNNER_GID RUNNER_HOME RUNNER_TEMP_DIR
16411654
export CANDIDATE_ROOT CANDIDATE_ARTIFACTS_DIR RUNTIME_ROOT NODE_BIN
16421655
export PRELOAD_PATH RUNNER_SENTINEL TRUSTED_WORKSPACE EVIDENCE_ROOT
1656+
export CANONICAL_CONFIG_PATH="$config_path"
16431657
export boundary_mode generation command_file identity_file sandbox_file
16441658
export command_sha256 expected_env_keys_b64 sandbox_payload_b64
16451659
@@ -1801,8 +1815,12 @@ jobs:
18011815
runtime_stage=verify-runtime-files
18021816
[[ -r "$CANDIDATE_ROOT/dist/index.js" &&
18031817
! -w "$CANDIDATE_ROOT/dist/index.js" &&
1804-
-r "${OPENCLAW_CONFIG_PATH:?}" &&
1805-
! -w "$OPENCLAW_CONFIG_PATH" ]]
1818+
-r "${CANONICAL_CONFIG_PATH:?}" &&
1819+
! -w "$CANONICAL_CONFIG_PATH" ]]
1820+
if [[ "$OPENCLAW_CONFIG_PATH" != "$CANONICAL_CONFIG_PATH" ]]; then
1821+
[[ "${1:-}" == "models" && "${2:-}" == "auth" &&
1822+
-r "$OPENCLAW_CONFIG_PATH" && -w "$OPENCLAW_CONFIG_PATH" ]]
1823+
fi
18061824
[[ -d "${CANDIDATE_ARTIFACTS_DIR:?}" && -r "$CANDIDATE_ARTIFACTS_DIR" && -x "$CANDIDATE_ARTIFACTS_DIR" && ! -w "$CANDIDATE_ARTIFACTS_DIR" ]]
18071825
for writable_path in \
18081826
"${OPENCLAW_QA_TEMP_ROOT:?}/workspace" \
@@ -1839,6 +1857,7 @@ jobs:
18391857
unset \
18401858
CANDIDATE_ROOT \
18411859
CANDIDATE_ARTIFACTS_DIR \
1860+
CANONICAL_CONFIG_PATH \
18421861
EVIDENCE_ROOT \
18431862
NODE_BIN \
18441863
PRELOAD_PATH \
@@ -1880,9 +1899,6 @@ jobs:
18801899
else
18811900
runtime_node_args=("$runtime_candidate_root/dist/index.js" "$@")
18821901
fi
1883-
# Login Bash reads /etc/bash.bashrc with inherited nounset.
1884-
# Add PS1 only after the attested inbound env-key comparison.
1885-
export PS1=
18861902
runtime_stage=exec-runtime
18871903
exec "$runtime_node_bin" "${runtime_node_args[@]}"
18881904
'\'' openclaw-sut "$@"

‎extensions/qa-lab/src/gateway-child-env.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,29 @@ import {
1717
import { listMockCodexModelInfos } from "./providers/shared/mock-model-config.js";
1818
import type { RuntimeId } from "./runtime-parity.js";
1919

20-
const QA_GATEWAY_CHILD_BLOCKED_SECRET_ENV_VARS = Object.freeze([
20+
const QA_GATEWAY_CHILD_BLOCKED_ENV_VARS = Object.freeze([
21+
"BASH_ENV",
22+
"BASHOPTS",
23+
"ENV",
2124
"OPENCLAW_QA_CONVEX_SECRET_CI",
2225
"OPENCLAW_QA_CONVEX_SECRET_MAINTAINER",
2326
"OPENCLAW_QA_SUT_FORBIDDEN_SENTINEL",
2427
"OPENCLAW_QA_TELEGRAM_GROUP_ID",
2528
"OPENCLAW_QA_TELEGRAM_DRIVER_BOT_TOKEN",
2629
"OPENCLAW_QA_TELEGRAM_SUT_BOT_TOKEN",
30+
"SHELLOPTS",
2731
]);
2832

29-
function scrubQaGatewayChildSecretEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
30-
for (const envKey of QA_GATEWAY_CHILD_BLOCKED_SECRET_ENV_VARS) {
33+
function scrubQaGatewayChildEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
34+
for (const envKey of QA_GATEWAY_CHILD_BLOCKED_ENV_VARS) {
3135
delete env[envKey];
3236
}
37+
// Bash imports exported functions before the launcher can apply its allowlist.
38+
for (const envKey of Object.keys(env)) {
39+
if (envKey.startsWith("BASH_FUNC_")) {
40+
delete env[envKey];
41+
}
42+
}
3343
return env;
3444
}
3545

@@ -112,10 +122,12 @@ export function buildQaRuntimeEnv(params: {
112122
delete normalizedEnv.OPENCLAW_SKIP_CHANNELS;
113123
delete normalizedEnv.OPENCLAW_SKIP_PROVIDERS;
114124
Object.assign(normalizedEnv, params.runtimeEnvPatch);
125+
// Parent shell startup controls must be removed after caller patches so no
126+
// launcher or runtime child can import them before its own allowlist runs.
115127
normalizedEnv.OPENCLAW_BUILD_PRIVATE_QA = "1";
116128
delete normalizedEnv[QA_LIVE_ANTHROPIC_SETUP_TOKEN_ENV];
117129
delete normalizedEnv[QA_LIVE_SETUP_TOKEN_VALUE_ENV];
118-
return scrubQaGatewayChildSecretEnv(scrubQaGatewayChildTestRunnerEnv(normalizedEnv));
130+
return scrubQaGatewayChildEnv(scrubQaGatewayChildTestRunnerEnv(normalizedEnv));
119131
}
120132

121133
export async function stageQaCodexMockModelCatalog(params: {

‎extensions/qa-lab/src/gateway-child.test.ts‎

Lines changed: 100 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { spawn } from "node:child_process";
1+
import { spawn, spawnSync } from "node:child_process";
22
// Qa Lab tests cover gateway child plugin behavior.
33
import { EventEmitter, once } from "node:events";
44
import { lstat, mkdir, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises";
@@ -160,22 +160,32 @@ if (!recordPath || !configPath || !stateDir) {
160160
throw new Error("missing fixture environment");
161161
}
162162
const record = (value) => fs.appendFileSync(recordPath, JSON.stringify(value) + "\\n");
163+
const authDbPath = path.join(stateDir, "agents", "qa", "agent", "openclaw-agent.sqlite");
163164
if (args[0] === "models") {
164165
let stdin = "";
165166
process.stdin.setEncoding("utf8");
166167
for await (const chunk of process.stdin) stdin += chunk;
167168
const provider = args[args.indexOf("--provider") + 1];
169+
const configStat = fs.lstatSync(configPath);
168170
record({
169171
kind: "auth",
170172
args,
171173
stdin,
172-
dbExists: fs.existsSync(path.join(stateDir, "agents", "qa", "agent", "openclaw-agent.sqlite")),
174+
authDbPath,
175+
dbExists: fs.existsSync(authDbPath),
176+
configPath,
177+
configMode: configStat.mode & 0o777,
178+
configRegular: configStat.isFile(),
179+
configSymlink: configStat.isSymbolicLink(),
180+
stateDir,
173181
env: {
174182
OPENCLAW_CLI: process.env.OPENCLAW_CLI,
175183
OPENCLAW_CONFIG_PATH: configPath,
176184
OPENCLAW_STATE_DIR: stateDir,
177185
},
178186
});
187+
fs.mkdirSync(path.dirname(authDbPath), { recursive: true });
188+
fs.writeFileSync(authDbPath, "fixture auth");
179189
if (process.env.QA_FAIL_PROVIDER === provider) {
180190
process.stderr.write("Authorization: Bearer " + stdin.trim());
181191
process.exit(9);
@@ -186,7 +196,16 @@ if (args[0] === "models") {
186196
process.exit(0);
187197
}
188198
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
189-
record({ kind: "gateway", args, fixtureProfiles: config.fixtureProfiles });
199+
record({
200+
kind: "gateway",
201+
args,
202+
authDbPath,
203+
dbExists: fs.existsSync(authDbPath),
204+
configPath,
205+
authProfileIds: Object.keys(config.auth?.profiles ?? {}),
206+
fixtureProfiles: config.fixtureProfiles,
207+
stateDir,
208+
});
190209
process.stderr.write("fixture gateway exit");
191210
process.exit(17);
192211
`,
@@ -793,6 +812,7 @@ describe("buildQaRuntimeEnv", () => {
793812
OPENCLAW_QA_TELEGRAM_GROUP_ID: "-1001234567890",
794813
OPENCLAW_QA_TELEGRAM_DRIVER_BOT_TOKEN: "driver-token",
795814
OPENCLAW_QA_TELEGRAM_SUT_BOT_TOKEN: "sut-token",
815+
"BASH_FUNC_sudo%%": "() { printf imported; }",
796816
},
797817
});
798818

@@ -804,8 +824,64 @@ describe("buildQaRuntimeEnv", () => {
804824
expect(env.OPENCLAW_QA_TELEGRAM_GROUP_ID).toBeUndefined();
805825
expect(env.OPENCLAW_QA_TELEGRAM_DRIVER_BOT_TOKEN).toBeUndefined();
806826
expect(env.OPENCLAW_QA_TELEGRAM_SUT_BOT_TOKEN).toBeUndefined();
827+
expect(env["BASH_FUNC_sudo%%"]).toBeUndefined();
807828
});
808829

830+
it.runIf(process.platform === "linux")(
831+
"scrubs inherited shell startup env before the workflow allowlist runs",
832+
async () => {
833+
const tempRoot = await tempDirs.makeTempDir("qa-shell-startup-env-");
834+
const markerPath = path.join(tempRoot, "bash-env-ran");
835+
const functionMarkerPath = path.join(tempRoot, "bash-function-ran");
836+
const bashEnvPath = path.join(tempRoot, "malicious-bash-env");
837+
const allowlistProbePath = path.join(tempRoot, "allowlist-probe.sh");
838+
await writeFile(bashEnvPath, `printf 'ran' > ${JSON.stringify(markerPath)}\n`, "utf8");
839+
await writeFile(
840+
allowlistProbePath,
841+
`
842+
set -Eeuo pipefail
843+
for key in BASH_ENV BASHOPTS ENV SHELLOPTS; do
844+
! compgen -e | grep -Fxq "$key"
845+
done
846+
declare -A keep_env=([SAFE_VALUE]=1)
847+
while IFS= read -r key; do
848+
if [[ -z "\${keep_env[$key]+x}" ]]; then
849+
unset "$key"
850+
fi
851+
done < <(compgen -e)
852+
printf '%s' "\${SAFE_VALUE:?}"
853+
`,
854+
"utf8",
855+
);
856+
const env = buildQaRuntimeEnv({
857+
...createParams({ SAFE_VALUE: "base" }),
858+
runtimeEnvPatch: {
859+
SAFE_VALUE: "allowlist-survived",
860+
BASH_ENV: bashEnvPath,
861+
BASHOPTS: "checkwinsize",
862+
ENV: bashEnvPath,
863+
SHELLOPTS: "braceexpand",
864+
"BASH_FUNC_compgen%%": `() { printf 'ran' > ${JSON.stringify(functionMarkerPath)}; builtin compgen "$@"; }`,
865+
},
866+
});
867+
868+
for (const key of ["BASH_ENV", "BASHOPTS", "ENV", "SHELLOPTS"]) {
869+
expect(env[key]).toBeUndefined();
870+
}
871+
expect(env["BASH_FUNC_compgen%%"]).toBeUndefined();
872+
873+
const result = spawnSync("/bin/bash", ["--noprofile", "--norc", allowlistProbePath], {
874+
encoding: "utf8",
875+
env,
876+
});
877+
878+
expect(result.status, result.stderr).toBe(0);
879+
expect(result.stdout).toBe("allowlist-survived");
880+
await expect(readFile(markerPath, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
881+
await expect(readFile(functionMarkerPath, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
882+
},
883+
);
884+
809885
it("re-scrubs blocked credentials in the spawned gateway child env", async () => {
810886
const tempParent = await tempDirs.makeTempDir("qa-gateway-env-scrub-");
811887
qaTempPathState.preferredTmpDir = tempParent;
@@ -1442,16 +1518,28 @@ describe("buildQaRuntimeEnv", () => {
14421518
],
14431519
]);
14441520
for (const record of authRecords) {
1445-
expect(record.dbExists).toBe(false);
14461521
expect(record.stdin).toMatch(/^sk-qa-mock-[a-f0-9]{32}\n$/u);
14471522
expect(record.env).toMatchObject({
14481523
OPENCLAW_CLI: "1",
14491524
});
1525+
expect(record.configMode).toBe(0o600);
1526+
expect(record.configRegular).toBe(true);
1527+
expect(record.configSymlink).toBe(false);
14501528
}
1529+
expect(authRecords.map((record) => record.dbExists)).toEqual([false, true]);
1530+
const authConfigPaths = authRecords.map((record) => String(record.configPath));
1531+
expect(new Set(authConfigPaths).size).toBe(1);
1532+
expect(authConfigPaths[0]).toBe(
1533+
path.join(String(authRecords[0]?.stateDir), "qa-auth-bootstrap", "openclaw.json"),
1534+
);
14511535
expect(records.at(-1)).toMatchObject({
14521536
kind: "gateway",
1453-
fixtureProfiles: ["openai", "anthropic"],
1537+
authProfileIds: ["qa-mock-openai", "qa-mock-anthropic"],
1538+
dbExists: true,
14541539
});
1540+
expect(records.at(-1)?.configPath).not.toBe(authConfigPaths[0]);
1541+
expect(records.at(-1)?.fixtureProfiles).toBeUndefined();
1542+
expect(new Set(records.map((record) => record.authDbPath)).size).toBe(1);
14551543
});
14561544

14571545
it("blocks packaged gateway spawn when candidate auth bootstrap fails", async () => {
@@ -1487,7 +1575,13 @@ describe("buildQaRuntimeEnv", () => {
14871575
);
14881576
const records = await readJsonLines(recordPath);
14891577
expect(records).toHaveLength(1);
1490-
expect(records[0]).toMatchObject({ kind: "auth", dbExists: false });
1578+
expect(records[0]).toMatchObject({
1579+
kind: "auth",
1580+
dbExists: false,
1581+
configMode: 0o600,
1582+
configRegular: true,
1583+
configSymlink: false,
1584+
});
14911585
const submittedKey = String(records[0]?.stdin).trim();
14921586
expect(submittedKey).toMatch(/^sk-qa-mock-[a-f0-9]{32}$/u);
14931587
expect(error.message).not.toContain(submittedKey);

‎extensions/qa-lab/src/gateway-child.ts‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,11 @@ import {
6868
stageQaLiveApiKeyProfiles,
6969
stageQaLiveAnthropicSetupToken,
7070
} from "./providers/live-frontier/auth.js";
71-
import { buildQaMockProfileId, stageQaMockAuthProfiles } from "./providers/shared/mock-auth.js";
71+
import {
72+
applyQaMockAuthProfileConfig,
73+
buildQaMockProfileId,
74+
stageQaMockAuthProfiles,
75+
} from "./providers/shared/mock-auth.js";
7276
import { seedQaAgentWorkspace } from "./qa-agent-workspace.js";
7377
import { buildQaGatewayConfig, type QaThinkingLevel } from "./qa-gateway-config.js";
7478
import type { QaTransportAdapter } from "./qa-transport.js";
@@ -175,6 +179,7 @@ function createQaPackagedMockApiKey(): string {
175179

176180
async function stageQaPackagedMockAuthProfiles(params: {
177181
command: QaGatewayChildCommand;
182+
configPath: string;
178183
cwd: string;
179184
env: NodeJS.ProcessEnv;
180185
providers: readonly string[];
@@ -196,7 +201,7 @@ async function stageQaPackagedMockAuthProfiles(params: {
196201
buildQaMockProfileId(provider),
197202
],
198203
cwd: params.command.cwd ?? params.cwd,
199-
env: params.env,
204+
env: { ...params.env, OPENCLAW_CONFIG_PATH: params.configPath },
200205
stdin: `${createQaPackagedMockApiKey()}\n`,
201206
});
202207
} catch (error) {
@@ -270,6 +275,7 @@ export async function startQaGatewayChild(params: {
270275
const xdgDataHome = path.join(tempRoot, "xdg-data");
271276
const xdgCacheHome = path.join(tempRoot, "xdg-cache");
272277
const configPath = path.join(tempRoot, "openclaw.json");
278+
const packagedAuthConfigPath = path.join(stateDir, "qa-auth-bootstrap", "openclaw.json");
273279
const gatewayToken = `qa-suite-${randomUUID()}`;
274280
const transport = params.transport ?? createQaGatewayEmptyTransport();
275281
await seedQaAgentWorkspace({
@@ -352,7 +358,9 @@ export async function startQaGatewayChild(params: {
352358
});
353359
const mockAuthProviders = getQaProvider(providerMode).mockAuthProviders;
354360
if (mockAuthProviders && mockAuthProviders.length > 0) {
355-
if (!usesPackagedCandidate) {
361+
if (usesPackagedCandidate) {
362+
cfg = applyQaMockAuthProfileConfig({ cfg, providers: mockAuthProviders });
363+
} else {
356364
cfg = await stageQaMockAuthProfiles({
357365
cfg,
358366
stateDir,
@@ -378,6 +386,7 @@ export async function startQaGatewayChild(params: {
378386
let cfg!: OpenClawConfig;
379387
let getChildFailure: (() => QaChildFailure | null) | null = null;
380388
let env: NodeJS.ProcessEnv | null = null;
389+
let packagedMockAuthStaged = false;
381390
let migrationConvergenceRestartUsed = false;
382391
let reuseStartupLaunchState = false;
383392

@@ -576,13 +585,29 @@ export async function startQaGatewayChild(params: {
576585
mode: 0o600,
577586
});
578587
const mockAuthProviders = getQaProvider(providerMode).mockAuthProviders;
579-
if (usesPackagedCandidate && gatewayCommand && mockAuthProviders?.length) {
588+
if (
589+
usesPackagedCandidate &&
590+
gatewayCommand &&
591+
mockAuthProviders?.length &&
592+
!packagedMockAuthStaged
593+
) {
594+
const canonicalConfig = await fs.readFile(configPath);
595+
await fs.mkdir(path.dirname(packagedAuthConfigPath), { recursive: true, mode: 0o700 });
596+
await fs.writeFile(packagedAuthConfigPath, canonicalConfig, {
597+
flag: "wx",
598+
mode: 0o600,
599+
});
580600
await stageQaPackagedMockAuthProfiles({
581601
command: gatewayCommand,
602+
configPath: packagedAuthConfigPath,
582603
cwd: gatewayCwd,
583604
env,
584605
providers: mockAuthProviders,
585606
});
607+
if (!canonicalConfig.equals(await fs.readFile(configPath))) {
608+
throw new Error("installed package mock auth bootstrap mutated canonical config");
609+
}
610+
packagedMockAuthStaged = true;
586611
}
587612
}
588613
if (!env) {

0 commit comments

Comments
 (0)