Skip to content

Commit b8c6baf

Browse files
committed
1 parent 01a23bc commit b8c6baf

4 files changed

Lines changed: 190 additions & 70 deletions

File tree

‎scripts/lib/plain-gh.mjs‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,51 @@ function pathEntries(env) {
4444
return (env.PATH ?? "").split(path.delimiter).filter(Boolean);
4545
}
4646

47+
/**
48+
* Credential-injecting PATH wrappers may be the only authenticated gh entry
49+
* point even though writes need the unwrapped CLI. Forward its token only to
50+
* the selected plain CLI process; never persist it in process.env.
51+
*
52+
* @param {NodeJS.ProcessEnv} env
53+
* @returns {NodeJS.ProcessEnv}
54+
*/
55+
function plainGhAuthenticatedEnv(env) {
56+
const next = plainGhEnv(env);
57+
if (
58+
next.GH_TOKEN ||
59+
next.GITHUB_TOKEN ||
60+
next.GH_ENTERPRISE_TOKEN ||
61+
next.GITHUB_ENTERPRISE_TOKEN
62+
) {
63+
return next;
64+
}
65+
66+
const tokenEnv = { ...next };
67+
delete tokenEnv.OPENCLAW_GH_BIN;
68+
const args = ["auth", "token"];
69+
if (tokenEnv.GH_HOST) {
70+
args.push("--hostname", tokenEnv.GH_HOST);
71+
}
72+
try {
73+
const token = execFileSync("gh", args, {
74+
encoding: "utf8",
75+
env: tokenEnv,
76+
stdio: ["ignore", "pipe", "ignore"],
77+
timeout: 10_000,
78+
}).trim();
79+
if (token) {
80+
if (tokenEnv.GH_HOST && tokenEnv.GH_HOST !== "github.com") {
81+
next.GH_ENTERPRISE_TOKEN = token;
82+
} else {
83+
next.GH_TOKEN = token;
84+
}
85+
}
86+
} catch {
87+
// The selected CLI may have usable credentials in its own config.
88+
}
89+
return next;
90+
}
91+
4792
/**
4893
* @param {NodeJS.ProcessEnv} [env]
4994
* @returns {NodeJS.ProcessEnv}
@@ -128,7 +173,7 @@ export function resolvePlainGhBin(
128173
* @returns {string | Uint8Array<ArrayBuffer>}
129174
*/
130175
export function execPlainGh(args, options = {}) {
131-
const env = plainGhEnv(options.env ?? process.env);
176+
const env = plainGhAuthenticatedEnv(options.env ?? process.env);
132177
const ghBin = resolvePlainGhBin(env);
133178
return execFileSync(ghBin, args, {
134179
...options,

‎scripts/lib/plain-gh.sh‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,22 +73,34 @@ plain_gh_search_path() {
7373
printf '%s\n' "$output"
7474
}
7575

76-
bridge_plain_gh_auth() {
77-
if [ -n "${GH_TOKEN:-}" ] || [ -n "${GITHUB_TOKEN:-}" ]; then
78-
return 0
76+
plain_gh_auth_token() {
77+
if [ -n "${GH_TOKEN:-}" ] ||
78+
[ -n "${GITHUB_TOKEN:-}" ] ||
79+
[ -n "${GH_ENTERPRISE_TOKEN:-}" ] ||
80+
[ -n "${GITHUB_ENTERPRISE_TOKEN:-}" ]; then
81+
return 1
7982
fi
8083

81-
local gh_path
82-
local token
83-
gh_path=$(type -P gh 2>/dev/null) || return 0
84-
if token=$(plain_gh_env "$gh_path" auth token 2>/dev/null) && [ -n "$token" ]; then
85-
export GH_TOKEN="$token"
84+
local path_gh
85+
path_gh=$(type -P gh 2>/dev/null) || return 1
86+
local args=(auth token)
87+
if [ -n "${GH_HOST:-}" ]; then
88+
args+=(--hostname "$GH_HOST")
8689
fi
90+
OPENCLAW_GH_BIN= plain_gh_env "$path_gh" "${args[@]}"
8791
}
8892

8993
gh_plain() {
9094
local gh_bin
9195
gh_bin=$(resolve_plain_gh_bin) || return 1
92-
bridge_plain_gh_auth
96+
local token
97+
if token=$(plain_gh_auth_token 2>/dev/null) && [ -n "$token" ]; then
98+
local token_name=GH_TOKEN
99+
if [ -n "${GH_HOST:-}" ] && [ "$GH_HOST" != "github.com" ]; then
100+
token_name=GH_ENTERPRISE_TOKEN
101+
fi
102+
plain_gh_env "$token_name=$token" "$gh_bin" "$@"
103+
return
104+
fi
93105
plain_gh_env "$gh_bin" "$@"
94106
}

‎test/scripts/plain-gh.test.ts‎

Lines changed: 93 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// Plain GitHub CLI helper tests cover wrapper-safe gh execution for maintainer scripts.
22
import { spawnSync } from "node:child_process";
3-
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4-
import { tmpdir } from "node:os";
3+
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
54
import path from "node:path";
65
import { afterEach, describe, expect, it } from "vitest";
76
import {
@@ -13,18 +12,12 @@ import {
1312
PLAIN_GH_SYSTEM_CANDIDATES,
1413
resolvePlainGhBin,
1514
} from "../../scripts/lib/plain-gh.mjs";
15+
import { useAutoCleanupTempDirTracker } from "../helpers/temp-dir.js";
1616

17-
const tempDirs: string[] = [];
18-
19-
afterEach(() => {
20-
for (const dir of tempDirs.splice(0)) {
21-
rmSync(dir, { recursive: true, force: true });
22-
}
23-
});
17+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
2418

2519
function makeFakeGh(): string {
26-
const dir = mkdtempSync(path.join(tmpdir(), "plain-gh-"));
27-
tempDirs.push(dir);
20+
const dir = tempDirs.make("plain-gh-");
2821
const binDir = path.join(dir, "bin");
2922
mkdirSync(binDir);
3023
const ghPath = path.join(binDir, "gh");
@@ -47,8 +40,7 @@ printf 'GH_TOKEN_SET=%s\\n' "\${GH_TOKEN:+1}"
4740
}
4841

4942
function makeLargeFakeGh(): string {
50-
const dir = mkdtempSync(path.join(tmpdir(), "plain-gh-large-"));
51-
tempDirs.push(dir);
43+
const dir = tempDirs.make("plain-gh-large-");
5244
const ghPath = path.join(dir, "gh");
5345
writeFileSync(
5446
ghPath,
@@ -61,6 +53,44 @@ process.stdout.write("x".repeat(bytes));
6153
return ghPath;
6254
}
6355

56+
function makeCredentialForwardingGh() {
57+
const dir = tempDirs.make("plain-gh-auth-forward-");
58+
const binDir = path.join(dir, "bin");
59+
const calls = path.join(dir, "calls.log");
60+
const realGh = path.join(dir, "real-gh");
61+
mkdirSync(binDir);
62+
writeFileSync(
63+
path.join(binDir, "gh"),
64+
`#!/bin/sh
65+
printf 'path:%s\\n' "$*" >> "$PLAIN_GH_FAKE_CALLS"
66+
if [ "$1 $2" = "auth token" ]; then
67+
printf 'forwarded-test-token\\n'
68+
exit 0
69+
fi
70+
exit 9
71+
`,
72+
);
73+
writeFileSync(
74+
realGh,
75+
`#!/bin/sh
76+
printf 'plain:%s\\n' "$*" >> "$PLAIN_GH_FAKE_CALLS"
77+
case "$PLAIN_GH_EXPECTED_TOKEN_ENV" in
78+
GH_TOKEN) token="\${GH_TOKEN-}"; other_token="\${GH_ENTERPRISE_TOKEN-}" ;;
79+
GH_ENTERPRISE_TOKEN) token="\${GH_ENTERPRISE_TOKEN-}"; other_token="\${GH_TOKEN-}" ;;
80+
*) echo 'unexpected token environment' >&2; exit 7 ;;
81+
esac
82+
if [ "$token" != "forwarded-test-token" ] || [ -n "$other_token" ]; then
83+
echo 'missing forwarded credentials' >&2
84+
exit 8
85+
fi
86+
printf 'authenticated plain gh\\n'
87+
`,
88+
);
89+
chmodSync(path.join(binDir, "gh"), 0o755);
90+
chmodSync(realGh, 0o755);
91+
return { binDir, calls, realGh };
92+
}
93+
6494
describe("plain gh helpers", () => {
6595
it("prefers OPENCLAW_GH_BIN over PATH shims", () => {
6696
const ghPath = makeFakeGh();
@@ -203,44 +233,59 @@ describe("plain gh helpers", () => {
203233
expect(readFileSync(outputPath, "utf8")).toContain("COLORTERM_SET=");
204234
});
205235

206-
it("bridges PATH-shim credentials to the selected plain gh", () => {
207-
const ghPath = makeFakeGh();
208-
const shimDir = mkdtempSync(path.join(tmpdir(), "plain-gh-auth-shim-"));
209-
tempDirs.push(shimDir);
210-
const shimPath = path.join(shimDir, "gh");
211-
writeFileSync(
212-
shimPath,
213-
`#!/usr/bin/env bash
214-
if [ "$*" = "auth token" ]; then
215-
printf 'bridged-test-token\\n'
216-
exit 0
217-
fi
218-
exit 2
219-
`,
220-
);
221-
chmodSync(shimPath, 0o755);
222-
const script = [
223-
"set -euo pipefail",
224-
"source scripts/lib/plain-gh.sh",
225-
`OPENCLAW_GH_BIN=${JSON.stringify(ghPath)}`,
226-
"export OPENCLAW_GH_BIN",
227-
"gh_plain api rate_limit",
228-
].join("\n");
236+
it.each([
237+
{
238+
host: undefined,
239+
name: "github.com",
240+
tokenArgs: "auth token",
241+
tokenEnv: "GH_TOKEN",
242+
},
243+
{
244+
host: "github.example.com",
245+
name: "an Enterprise host",
246+
tokenArgs: "auth token --hostname github.example.com",
247+
tokenEnv: "GH_ENTERPRISE_TOKEN",
248+
},
249+
])("forwards $name credentials from a PATH wrapper to the plain CLI", (testCase) => {
250+
const fixture = makeCredentialForwardingGh();
251+
const env: NodeJS.ProcessEnv = {
252+
...process.env,
253+
OPENCLAW_GH_BIN: fixture.realGh,
254+
PATH: `${fixture.binDir}${path.delimiter}${process.env.PATH ?? ""}`,
255+
PLAIN_GH_EXPECTED_TOKEN_ENV: testCase.tokenEnv,
256+
PLAIN_GH_FAKE_CALLS: fixture.calls,
257+
};
258+
if (testCase.host) {
259+
env.GH_HOST = testCase.host;
260+
} else {
261+
delete env.GH_HOST;
262+
}
263+
for (const name of [
264+
"GH_TOKEN",
265+
"GITHUB_TOKEN",
266+
"GH_ENTERPRISE_TOKEN",
267+
"GITHUB_ENTERPRISE_TOKEN",
268+
]) {
269+
delete env[name];
270+
}
229271

230-
const result = spawnSync("bash", ["-c", script], {
272+
expect(execPlainGh(["api", "user"], { encoding: "utf8", env })).toBe(
273+
"authenticated plain gh\n",
274+
);
275+
const shell = spawnSync("bash", ["-c", "source scripts/lib/plain-gh.sh; gh_plain api user"], {
276+
cwd: process.cwd(),
231277
encoding: "utf8",
232-
env: {
233-
...process.env,
234-
GH_TOKEN: "",
235-
GITHUB_TOKEN: "",
236-
PATH: `${shimDir}${path.delimiter}/usr/bin:/bin`,
237-
},
278+
env,
238279
});
239280

240-
expect(result.status, result.stderr).toBe(0);
241-
expect(result.stdout).toContain("argv=api rate_limit");
242-
expect(result.stdout).toContain("GH_TOKEN_SET=1");
243-
expect(result.stdout).not.toContain("bridged-test-token");
281+
expect(shell.status, shell.stderr).toBe(0);
282+
expect(shell.stdout).toBe("authenticated plain gh\n");
283+
expect(readFileSync(fixture.calls, "utf8").trim().split("\n")).toEqual([
284+
`path:${testCase.tokenArgs}`,
285+
"plain:api user",
286+
`path:${testCase.tokenArgs}`,
287+
"plain:api user",
288+
]);
244289
});
245290

246291
it("captures large gh payloads by default", () => {
@@ -251,6 +296,7 @@ exit 2
251296
encoding: "utf8",
252297
env: {
253298
...process.env,
299+
GH_TOKEN: "large-payload-test-token",
254300
OPENCLAW_GH_BIN: ghPath,
255301
PLAIN_GH_FAKE_BYTES: String(bytes),
256302
},

‎test/scripts/pr-ci-dispatch.test.ts‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ function createFakeGh() {
2323
set -euo pipefail
2424
printf '%s\\t%s\\n' "$(basename "$0")" "$*" >> "$OPENCLAW_TEST_GH_CALLS"
2525
case "$1 $2" in
26+
"auth token") printf 'forwarded-test-token\\n' ;;
2627
"api --method")
2728
if [ "\${OPENCLAW_TEST_GH_MODE:-}" = "pending-head-change" ]; then
2829
printf '{"workflow_runs":[]}\\n'
@@ -40,7 +41,13 @@ case "$1 $2" in
4041
printf '%s\\n' "$OPENCLAW_TEST_HEAD_SHA"
4142
fi
4243
;;
43-
"workflow run") : > "$OPENCLAW_TEST_GH_DISPATCHED" ;;
44+
"workflow run")
45+
if [ "\${GH_TOKEN-}" != "forwarded-test-token" ]; then
46+
echo "missing forwarded credentials" >&2
47+
exit 3
48+
fi
49+
: > "$OPENCLAW_TEST_GH_DISPATCHED"
50+
;;
4451
*) echo "unexpected gh invocation: $*" >&2; exit 2 ;;
4552
esac
4653
`;
@@ -65,24 +72,33 @@ function runDispatch(
6572
writeFileSync(preload, "global.setTimeout = (callback) => { callback(); return 0; };\n");
6673
nodeOptions = `${nodeOptions} --require ${preload}`.trim();
6774
}
75+
const env: NodeJS.ProcessEnv = {
76+
...process.env,
77+
NODE_OPTIONS: nodeOptions,
78+
OPENCLAW_GH_BIN: fakeGh.realGh,
79+
OPENCLAW_TEST_CHANGED_HEAD_SHA: changedSha,
80+
OPENCLAW_TEST_GH_CALLS: fakeGh.calls,
81+
OPENCLAW_TEST_GH_DISPATCHED: fakeGh.dispatched,
82+
OPENCLAW_TEST_GH_MODE: options.mode ?? "",
83+
OPENCLAW_TEST_GH_SEEN_RUN_LIST: fakeGh.seenRunList,
84+
OPENCLAW_TEST_HEAD_SHA: sha,
85+
PATH: `${fakeGh.binDir}:${process.env.PATH ?? ""}`,
86+
};
87+
for (const name of [
88+
"GH_TOKEN",
89+
"GITHUB_TOKEN",
90+
"GH_ENTERPRISE_TOKEN",
91+
"GITHUB_ENTERPRISE_TOKEN",
92+
]) {
93+
delete env[name];
94+
}
6895
return spawnSync(
6996
process.execPath,
7097
[dispatchScript, "12345", "contributor/fix-hosted-gates", sha, "false"],
7198
{
7299
cwd: options.cwd,
73100
encoding: "utf8",
74-
env: {
75-
...process.env,
76-
NODE_OPTIONS: nodeOptions,
77-
OPENCLAW_GH_BIN: fakeGh.realGh,
78-
OPENCLAW_TEST_CHANGED_HEAD_SHA: changedSha,
79-
OPENCLAW_TEST_GH_CALLS: fakeGh.calls,
80-
OPENCLAW_TEST_GH_DISPATCHED: fakeGh.dispatched,
81-
OPENCLAW_TEST_GH_MODE: options.mode ?? "",
82-
OPENCLAW_TEST_GH_SEEN_RUN_LIST: fakeGh.seenRunList,
83-
OPENCLAW_TEST_HEAD_SHA: sha,
84-
PATH: `${fakeGh.binDir}:${process.env.PATH ?? ""}`,
85-
},
101+
env,
86102
},
87103
);
88104
}
@@ -128,6 +144,7 @@ describePosix("scripts/pr ci-dispatch", () => {
128144
expect(callLines).toContain(
129145
`real-gh\tworkflow run ci.yml --ref contributor/fix-hosted-gates -f target_ref=${sha} -f release_gate=true -f pull_request_number=12345`,
130146
);
147+
expect(callLines).toContain("gh\tauth token");
131148
expect(callLines).toContain(
132149
`gh\tapi --method GET repos/openclaw/openclaw/actions/workflows/ci.yml/runs -f event=workflow_dispatch -f head_sha=${sha} -f per_page=20`,
133150
);

0 commit comments

Comments
 (0)