Skip to content

Commit 4470767

Browse files
committed
fix(git): integrate PR #874 across shared source paths and scoped credentials
2 parents 05fb8a7 + 5b67631 commit 4470767

9 files changed

Lines changed: 375 additions & 28 deletions

File tree

‎packages/adapters/src/runtime/build-pipeline.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,8 @@ describe("runBuildPipeline pinned clone failure boundaries", () => {
191191
expect(result.status).toBe("deploying");
192192
expect(commands.filter((command) => command.includes(" clone "))).toHaveLength(1);
193193
expect(commands.filter((command) => command.includes("--unshallow"))).toHaveLength(1);
194-
expect(commands.at(-1)).toContain(" checkout ");
194+
expect(commands.at(-2)).toContain(" checkout ");
195+
expect(commands.at(-1)).toContain(" submodule update ");
195196
// Both network operations must obtain the relay header before invoking Git.
196197
for (const command of commands.filter(
197198
(entry) => entry.includes(" clone ") || entry.includes("--unshallow"),
@@ -210,6 +211,7 @@ describe("runBuildPipeline pinned clone failure boundaries", () => {
210211

211212
expect(result.status).toBe("deploying");
212213
expect(commands.some((command) => command.includes("--unshallow"))).toBe(false);
213-
expect(commands.at(-1)).toContain(" checkout ");
214+
expect(commands.at(-2)).toContain(" checkout ");
215+
expect(commands.at(-1)).toContain(" submodule update ");
214216
});
215217
});

‎packages/adapters/src/runtime/build-pipeline.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@
1313

1414
import type { BuildConfig, BuildStep, LogEntry, LogCallback } from "../types";
1515
import { safeErrorMessage, packageManagerEnsureCommand, nodeBinPathExport } from "@repo/core";
16-
import { sq, injectGitToken, assembleGitClone, gitShellCommand } from "./git-clone";
16+
import {
17+
sq,
18+
injectGitToken,
19+
assembleGitClone,
20+
gitShellCommand,
21+
GIT_SUBMODULE_UPDATE_ARGS,
22+
} from "./git-clone";
1723
import { materializeGitSsh, shellGitSshWriter, type GitSshMaterial } from "./git-ssh-material";
1824

1925
// Re-exported for the docker adapters that import these from here.
@@ -351,6 +357,9 @@ export async function runBuildPipeline(
351357
),
352358
);
353359
}
360+
await exec(
361+
`cd ${sq(env.projectDir)} && ${gitShellCommand(gitInvocation, GIT_SUBMODULE_UPDATE_ARGS.join(" "))}`,
362+
);
354363
} finally {
355364
// Always remove the ephemeral SSH key material, success or fail.
356365
await sshMaterial?.cleanup();

‎packages/adapters/src/runtime/cloud.ts‎

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,8 @@ import type {
5353
RollbackInput,
5454
MakeActiveResult,
5555
} from "./types";
56-
import {
57-
BuildLogger,
58-
injectGitToken,
59-
runBuildPipeline,
60-
sq,
61-
type BuildEnvironment,
62-
} from "./build-pipeline";
56+
import { BuildLogger, runBuildPipeline, sq, type BuildEnvironment } from "./build-pipeline";
57+
import { assembleGitClone, gitShellCommand, GIT_SUBMODULE_UPDATE_ARGS } from "./git-clone";
6358
import {
6459
CloudComposeSupport,
6560
resolveCloudWorkloadCmd,
@@ -1220,7 +1215,8 @@ export class CloudRuntime implements MultiServiceRuntimeAdapter {
12201215
await this.ensureWorkspaceGit(provisioned.runtime, logger, "Dockerfile source workspace");
12211216

12221217
const executor = this.workspaceExecutor(provisioned.runtime);
1223-
const cloneUrl = injectGitToken(config.repoUrl, config.gitToken);
1218+
const gitInvocation = assembleGitClone({ repoUrl: config.repoUrl, gitToken: config.gitToken });
1219+
const cloneUrl = gitInvocation.cloneUrl;
12241220
const fetchCommand = [
12251221
"set -e",
12261222
`rm -rf ${sq(sourceDir)}`,
@@ -1234,6 +1230,7 @@ export class CloudRuntime implements MultiServiceRuntimeAdapter {
12341230
// progress lines to stderr so they reach the build log stream.
12351231
`GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=/bin/echo git -c credential.helper= fetch --progress --depth ${config.commitSha ? "50" : "1"} origin ${sq(config.branch)}`,
12361232
`git -c credential.helper= -c advice.detachedHead=false checkout -q ${sq(checkoutRef)}`,
1233+
gitShellCommand(gitInvocation, GIT_SUBMODULE_UPDATE_ARGS.join(" ")),
12371234
'echo "Dockerfile source fetch ready."',
12381235
].join("\n");
12391236
const fetchResult = await executor.streamExec(fetchCommand, logger.callback);
@@ -1488,7 +1485,8 @@ export class CloudRuntime implements MultiServiceRuntimeAdapter {
14881485
throw new Error("Dockerfile build context escapes the repository source.");
14891486
}
14901487

1491-
const cloneUrl = injectGitToken(config.repoUrl, config.gitToken);
1488+
const gitInvocation = assembleGitClone({ repoUrl: config.repoUrl, gitToken: config.gitToken });
1489+
const cloneUrl = gitInvocation.cloneUrl;
14921490
const depthArgs = config.commitSha ? "--depth 50 " : "--depth 1 ";
14931491
const cloneTarget = contextRelativePath ? repoRoot : contextRoot;
14941492
const contextSource = contextRelativePath
@@ -1527,18 +1525,26 @@ export class CloudRuntime implements MultiServiceRuntimeAdapter {
15271525
// See fetchCommand above for env-var rationale; --progress keeps
15281526
// the clone visible in the streamed log even though stdout/stderr
15291527
// are pipes, not a tty.
1530-
`GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=/bin/echo git -c credential.helper= clone --progress ${depthArgs}--branch ${sq(config.branch)} ${sq(cloneUrl)} ${sq(cloneTarget)}`,
1528+
gitShellCommand(
1529+
gitInvocation,
1530+
`clone --progress ${depthArgs}--branch ${sq(config.branch)} ${sq(cloneUrl)} ${sq(cloneTarget)}`,
1531+
),
1532+
].join("\n");
1533+
const checkoutCommand = [
1534+
"set -e",
1535+
`cd ${sq(cloneTarget)}`,
1536+
...(config.commitSha
1537+
? [`git -c credential.helper= -c advice.detachedHead=false checkout ${sq(config.commitSha)}`]
1538+
: []),
1539+
gitShellCommand(gitInvocation, GIT_SUBMODULE_UPDATE_ARGS.join(" ")),
15311540
].join("\n");
1532-
const checkoutCommand = config.commitSha
1533-
? `cd ${sq(cloneTarget)} && git -c credential.helper= -c advice.detachedHead=false checkout ${sq(config.commitSha)}`
1534-
: "";
15351541
// No name-based pruning: a fresh clone already contains only git-tracked
15361542
// files (gitignored output was never committed), so pruning by name here
15371543
// would only risk deleting tracked source (e.g. a top-level `data/` dir).
15381544
// A tracked `.dockerignore` still applies at `docker build` on the worker.
15391545
const prepareCommand = [
15401546
"set -e",
1541-
`rm -rf ${sq(joinWorkspacePath(cloneTarget, ".git"))}`,
1547+
`find ${sq(cloneTarget)} -name .git -prune -exec rm -rf {} +`,
15421548
...prepareContextCommands,
15431549
'echo "Dockerfile context prepared."',
15441550
].join("\n");
@@ -1549,9 +1555,7 @@ export class CloudRuntime implements MultiServiceRuntimeAdapter {
15491555
await this.ensureWorkspaceGit(targetRuntime, logger, "Dockerfile build workspace");
15501556
logger.log(`Cloning Dockerfile context in build workspace (branch: ${config.branch})...\n`);
15511557
await this.execAndStream(targetRuntime, ["sh", "-c", cloneCommand], logger.callback, 900);
1552-
if (checkoutCommand) {
1553-
await this.execAndStream(targetRuntime, ["sh", "-c", checkoutCommand], logger.callback, 300);
1554-
}
1558+
await this.execAndStream(targetRuntime, ["sh", "-c", checkoutCommand], logger.callback, 900);
15551559
await this.execAndStream(targetRuntime, ["sh", "-c", prepareCommand], logger.callback, 300);
15561560
logger.log("Dockerfile context ready.\n");
15571561
}

‎packages/adapters/src/runtime/docker-build-context.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type { BuildConfig, LogCallback } from "../types";
99

1010
import { getTarCreateEnv, prepareSourceTarArgs } from "../archive";
1111
import { assembleGitClone } from "./build-pipeline";
12+
import { GIT_SUBMODULE_UPDATE_ARGS } from "./git-clone";
1213
import { localGitSshWriter, materializeGitSsh, type GitSshMaterial } from "./git-ssh-material";
1314
import { generateDockerfile } from "./docker-build-plan";
1415
import { dockerfileNeedsBuildKit } from "./docker-buildkit-trace";
@@ -409,7 +410,22 @@ async function cloneGitSource(
409410
});
410411
}
411412

412-
await rm(join(targetPath, ".git"), { recursive: true, force: true });
413+
await spawnGit([...credArgs, "-C", targetPath, ...GIT_SUBMODULE_UPDATE_ARGS], {
414+
timeoutMs: GIT_CLONE_IDLE_TIMEOUT_MS,
415+
onLog,
416+
env: gitEnv,
417+
});
418+
419+
// A submodule's .git is usually a file pointing into the parent's metadata.
420+
// Strip both forms without following symlinks into a path outside the checkout.
421+
const removeGitMetadata = async (directory: string): Promise<void> => {
422+
for (const entry of await readdir(directory, { withFileTypes: true })) {
423+
const path = join(directory, entry.name);
424+
if (entry.name === ".git") await rm(path, { recursive: true, force: true });
425+
else if (entry.isDirectory()) await removeGitMetadata(path);
426+
}
427+
};
428+
await removeGitMetadata(targetPath);
413429
} finally {
414430
await sshMaterial?.cleanup();
415431
}

‎packages/adapters/src/runtime/docker-clone-on-server.test.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
import { describe, expect, it, vi } from "vitest";
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import * as tarball from "./source-tarball";
23
import type { BuildConfig, CommandExecutor } from "../types";
34
import { BuildLogger } from "./build-pipeline";
45
import { DockerRuntime } from "./docker";
56

67
const COMMIT = "30a396bda22eda34bcd2bc73d5b601683b146e7a";
78

9+
afterEach(() => vi.restoreAllMocks());
10+
811
function config(): BuildConfig {
912
return {
1013
sessionId: "bld-clone-test",
@@ -42,6 +45,32 @@ function harness(executor: CommandExecutor): CloneHarness {
4245
}
4346

4447
describe("DockerRuntime clone-on-server pinned commit", () => {
48+
it.each([false, true])(
49+
"uses Git only when the downloaded archive has submodules: %s",
50+
async (hasSubmodules) => {
51+
vi.spyOn(tarball, "downloadTarballOnRemote").mockResolvedValue(undefined);
52+
const streamExec = vi.fn(async (_command: string) => ({ code: 0, output: "" }));
53+
const executor = {
54+
exec: vi.fn(async (command: string) => {
55+
if (command.startsWith("test -f ") && !hasSubmodules) throw new Error("file absent");
56+
return "";
57+
}),
58+
streamExec,
59+
} as unknown as CommandExecutor;
60+
await harness(executor).cloneSourceOnRemote(
61+
{ ...config(), gitCredentialHelperPath: undefined },
62+
"/tmp/openship-build-test",
63+
new BuildLogger(),
64+
);
65+
expect(tarball.downloadTarballOnRemote).toHaveBeenCalledOnce();
66+
const commands = streamExec.mock.calls.map(([command]) => String(command));
67+
expect(commands.some((command) => command.includes(" submodule update "))).toBe(
68+
hasSubmodules,
69+
);
70+
expect(commands.some((command) => command.includes(" clone "))).toBe(hasSubmodules);
71+
},
72+
);
73+
4574
it("surfaces a clone failure without attempting fetch in a non-repository", async () => {
4675
const executor = {
4776
exec: vi.fn(async () => ""),
@@ -80,10 +109,11 @@ describe("DockerRuntime clone-on-server pinned commit", () => {
80109
const commands = (executor.streamExec as ReturnType<typeof vi.fn>).mock.calls.map(([command]) =>
81110
String(command),
82111
);
83-
expect(commands).toHaveLength(3);
112+
expect(commands).toHaveLength(4);
84113
expect(commands[0]).toContain(" clone ");
85114
expect(commands[1]).toContain("--unshallow");
86115
expect(commands[2]).toContain(" checkout ");
116+
expect(commands[3]).toContain(" submodule update ");
87117
for (const command of commands.slice(0, 2)) {
88118
expect(command.indexOf("auth-header")).toBeLessThan(command.indexOf("git "));
89119
}

‎packages/adapters/src/runtime/docker.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ import {
140140
import { materializeGitSsh, shellGitSshWriter, type GitSshMaterial } from "./git-ssh-material";
141141
import { isArtifactPathRef, removeManagedArtifact } from "./managed-artifact";
142142
import { githubTarballUrl, downloadTarballOnRemote } from "./source-tarball";
143+
import { GIT_SUBMODULE_UPDATE_ARGS } from "./git-clone";
143144
import { scopeVolumeBinds, isHostPathSource } from "./volume-namespace";
144145
import {
145146
createDockerBuildContext,
@@ -1743,6 +1744,16 @@ export class DockerRuntime implements RuntimeAdapter {
17431744
destDir: remoteContextDir,
17441745
onLog: (entry) => log.log(entry.message, parseLogLevel(entry.message)),
17451746
});
1747+
// Check for submodules. If present, the tarball is missing submodule contents.
1748+
const hasSubmodules = await executor
1749+
.exec(`test -f ${sq(`${remoteContextDir}/.gitmodules`)}`)
1750+
.then(
1751+
() => true,
1752+
() => false,
1753+
);
1754+
if (hasSubmodules) {
1755+
throw new Error("Repository contains submodules; tarball download is insufficient");
1756+
}
17461757
// A tarball has no .git, but strip defensively in case a repo tracks one.
17471758
await executor.exec(`rm -rf ${sq(`${remoteContextDir}/.git`)}`).catch(() => {});
17481759
return;
@@ -1791,7 +1802,7 @@ export class DockerRuntime implements RuntimeAdapter {
17911802
log.log(`Cloning ${config.repoUrl} on the server → ${remoteContextDir} (${authLabel})...\n`);
17921803
await executor.exec(`rm -rf ${dir} && mkdir -p ${dir}`);
17931804

1794-
const run = async (operation: "clone" | "fetch" | "checkout", cmd: string) => {
1805+
const run = async (operation: "clone" | "fetch" | "checkout" | "submodule", cmd: string) => {
17951806
const { code } = await executor.streamExec(cmd, (entry) =>
17961807
log.log(entry.message, parseLogLevel(entry.message)),
17971808
);
@@ -1843,8 +1854,12 @@ export class DockerRuntime implements RuntimeAdapter {
18431854
),
18441855
);
18451856
}
1846-
// Never ship .git into the build image.
1847-
await executor.exec(`rm -rf ${sq(`${remoteContextDir}/.git`)}`).catch(() => {});
1857+
await run(
1858+
"submodule",
1859+
`cd ${dir} && ${gitShellCommand(gitInvocation, GIT_SUBMODULE_UPDATE_ARGS.join(" "))}`,
1860+
);
1861+
// Never ship .git into the build image. Submodules may create .git files/dirs within the tree.
1862+
await executor.exec(`find ${sq(remoteContextDir)} -name .git -prune -exec rm -rf {} +`);
18481863
} finally {
18491864
await sshMaterial?.cleanup();
18501865
}

‎packages/adapters/src/runtime/git-clone.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { describe, it, expect } from "vitest";
2+
import { execFileSync } from "node:child_process";
23
import {
34
sq,
45
injectGitToken,
@@ -171,10 +172,40 @@ describe("assembleGitClone — relay (desktop credential helper) mode", () => {
171172
it("authenticates the first request instead of waiting for a GitHub challenge", () => {
172173
const command = gitShellCommand(inv, "clone 'https://github.com/owner/repo.git' '/tmp/repo'");
173174
expect(command).toContain("'/tmp/helper.sh' auth-header 'https' 'github.com' 'owner/repo.git'");
174-
expect(command).toContain("GIT_CONFIG_KEY_3=http.extraHeader");
175+
expect(command).toContain(
176+
"GIT_CONFIG_KEY_3='http.https://github.com/owner/repo.git.extraHeader'",
177+
);
175178
expect(command).toContain('GIT_CONFIG_VALUE_3="$OPENSHIP_GIT_AUTH_HEADER"');
176179
expect(command.indexOf("auth-header")).toBeLessThan(command.indexOf("git clone"));
177180
});
181+
it("Git scopes the relay header to the parent repo and excludes foreign submodules", () => {
182+
// Replace only the out-of-process relay lookup, then let real Git parse the
183+
// exact environment that a networked clone/submodule command would inherit.
184+
const scoped = {
185+
...inv,
186+
shellPrelude: "OPENSHIP_GIT_AUTH_HEADER='Authorization: Basic test-only'",
187+
};
188+
const lookup = (url: string) =>
189+
execFileSync(
190+
"sh",
191+
[
192+
"-c",
193+
gitShellCommand(
194+
scoped,
195+
`config --get-urlmatch http.extraHeader ${sq(url)} || test $? -eq 1`,
196+
),
197+
],
198+
{ encoding: "utf8" },
199+
).trim();
200+
expect(lookup("https://github.com/owner/repo.git")).toBe("Authorization: Basic test-only");
201+
expect(lookup("https://github.com/owner/repo.git/info/refs")).toBe(
202+
"Authorization: Basic test-only",
203+
);
204+
expect(lookup("https://github.com/owner/other.git")).toBe("");
205+
expect(lookup("https://github.com/owner/repo.git-evil")).toBe("");
206+
expect(lookup("https://elsewhere.example/owner/repo.git")).toBe("");
207+
expect(lookup("http://github.com/owner/repo.git")).toBe("");
208+
});
178209
it("does not put a credential or Authorization value in the assembled command", () => {
179210
const command = gitShellCommand(inv, "clone 'repo' 'target'");
180211
expect(command).not.toContain("password=");

‎packages/adapters/src/runtime/git-clone.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,19 @@ import { shellQuote } from "@repo/core";
1818

1919
export type { AmbientGitVia };
2020

21+
// Initialize only after selecting the parent commit. --checkout honors the
22+
// recorded gitlink instead of following a submodule branch or merge strategy.
23+
export const GIT_SUBMODULE_UPDATE_ARGS = [
24+
"submodule",
25+
"update",
26+
"--init",
27+
"--recursive",
28+
"--checkout",
29+
"--depth",
30+
"1",
31+
"--progress",
32+
] as const;
33+
2134
/** Alias of `@repo/core`'s {@link shellQuote}. Kept as a name because ~300 call sites in
2235
* this package read `sq(...)`; there is one implementation, in core. */
2336
export const sq = shellQuote;
@@ -219,6 +232,11 @@ export function assembleGitClone(auth: GitCloneAuth): GitCloneInvocation {
219232
}
220233
const protocol = url.protocol.slice(0, -1);
221234
const path = url.pathname.replace(/^\/+/, "");
235+
const headerUrl = new URL(url);
236+
headerUrl.username = "";
237+
headerUrl.password = "";
238+
headerUrl.search = "";
239+
headerUrl.hash = "";
222240
const headerVar = "OPENSHIP_GIT_AUTH_HEADER";
223241
const headerCommand =
224242
`${sq(auth.gitCredentialHelperPath)} auth-header ` +
@@ -235,7 +253,9 @@ export function assembleGitClone(auth: GitCloneAuth): GitCloneInvocation {
235253
// gitShellCommand(), which adds the preemptive header as config slot 3.
236254
gitEnv:
237255
`${base.gitEnv.replace("GIT_CONFIG_COUNT=3", "GIT_CONFIG_COUNT=4")} ` +
238-
`GIT_CONFIG_KEY_3=http.extraHeader GIT_CONFIG_VALUE_3="$${headerVar}"`,
256+
// A submodule may name another host/repository. Its authentication must
257+
// go through the scoped relay helper, never inherit the parent's header.
258+
`GIT_CONFIG_KEY_3=${sq(`http.${headerUrl.href}.extraHeader`)} GIT_CONFIG_VALUE_3="$${headerVar}"`,
239259
};
240260
}
241261

0 commit comments

Comments
 (0)