Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andluke 8cd4cf96e9 Name the bare Git fixture explicitly
Co-authored-by: luke <luopeihuan@gmail.com>
2026-12-04 05:12:09 +00:00
paseo-bot[bot] b78548a87a Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-clone 2026-12-04 04:42:55 +00:00
lukeandRoundRedDot 5dee36e9ae refactor(server): use named Git checkout arguments
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:40:04 +08:00
lukeandRoundRedDot 8af3380124 Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-auth-review
# Conflicts:
#	packages/server/src/server/plugins/managed-source.posix.test.ts

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:23:54 +08:00
lukeandRoundRedDot a14826c8fd fix(server): preserve credentials during filtered plugin checkout
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:20:52 +08:00
lukeandRoundRedDot f00b32dbe6 perf(server): clone Git plugin sources without history blobs
- Use blobless clone filter when fetching Git plugin sources to improve install performance
- Add POSIX test verification for blobless git operations

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 09:22:00 +08:00
2 changed files with 198 additions and 30 deletions
@@ -1,6 +1,8 @@
import { mkdir, rename, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { existsSync, readFileSync } from "node:fs";
import { createServer } from "node:http";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -36,6 +38,66 @@ async function commitAll(repository: string, message: string): Promise<string> {
return stdout.trim();
}
async function serveGitHttp({
request,
response,
root,
}: {
request: IncomingMessage;
response: ServerResponse;
root: string;
}) {
const url = new URL(request.url!, "http://localhost");
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);
const child = spawn("git", ["http-backend"], {
env: {
...process.env,
GIT_PROJECT_ROOT: root,
GIT_HTTP_EXPORT_ALL: "1",
PATH_INFO: url.pathname,
QUERY_STRING: url.search.slice(1),
REQUEST_METHOD: request.method,
CONTENT_TYPE: request.headers["content-type"],
CONTENT_LENGTH: String(body.length),
HTTP_GIT_PROTOCOL: request.headers["git-protocol"] as string | undefined,
},
});
const closed = once(child, "close");
child.stdin.end(body);
const output: Buffer[] = [];
for await (const chunk of child.stdout) output.push(chunk as Buffer);
const [code] = await closed;
const data = Buffer.concat(output);
const end = data.indexOf("\r\n\r\n");
if (code !== 0 || end < 0) throw new Error("git http-backend failed");
for (const line of data.subarray(0, end).toString().split("\r\n")) {
const colon = line.indexOf(":");
if (colon < 0) continue;
const name = line.slice(0, colon);
const value = line.slice(colon + 1).trim();
if (name.toLowerCase() === "status") response.statusCode = Number(value.slice(0, 3));
else response.setHeader(name, value);
}
response.end(data.subarray(end + 4));
}
function createGitFixtureServer({ root, posts }: { root: string; posts: string[] }) {
return createServer((request, response) => {
if (
request.headers.authorization !==
`Basic ${Buffer.from("fixture:fake-secret").toString("base64")}`
) {
response.writeHead(401, { "WWW-Authenticate": 'Basic realm="fixture"' }).end();
return;
}
const url = new URL(request.url!, "http://localhost");
if (request.method === "POST") posts.push(url.pathname);
void serveGitHttp({ request, response, root }).catch(() => response.writeHead(500).end());
});
}
/** Points https://github.com/fixture/repository.git at a local repository for the callback. */
async function withGitHubFixture(repository: string, run: () => Promise<void>): Promise<void> {
const overlay = {
@@ -120,6 +182,98 @@ describe("managed Git plugin sources", () => {
});
}, 30_000);
it("downloads only the files of the installed commit, not every blob in history", async () => {
const repository = await createRepository();
// A file that exists only in history, like screenshots a plugin repository later dropped.
await writeFile(path.join(repository, "history-only.bin"), "x".repeat(256 * 1024));
await commitAll(repository, "add a large asset");
const { stdout: historyBlob } = await runGitCommand(["rev-parse", "HEAD:history-only.bin"], {
cwd: repository,
});
await rm(path.join(repository, "history-only.bin"));
await commitAll(repository, "drop the asset");
await runGitCommand(["config", "uploadpack.allowFilter", "true"], { cwd: repository });
await runGitCommand(["config", "uploadpack.allowAnySHA1InWant", "true"], { cwd: repository });
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
roots.push(home);
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({
source: `git:${pathToFileURL(repository).href}`,
});
candidate = await sources.place("managed-example", candidate);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
const { stdout: checkoutRoot } = await runGitCommand(["rev-parse", "--show-toplevel"], {
cwd: candidate.directory,
});
const { stdout: missing } = await runGitCommand(
["rev-list", "--objects", "--all", "--missing=print"],
{ cwd: checkoutRoot.trim() },
);
expect(missing.split("\n")).toContain(`?${historyBlob.trim()}`);
}, 30_000);
it("fetches filtered checkout blobs for credentialed Git installs and updates", async () => {
const repository = await createRepository();
const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-smart-http-"));
roots.push(root);
await runGitCommand(["clone", "--bare", repository, "plugin.git"], { cwd: root });
const bare = path.join(root, "plugin.git");
await runGitCommand(["--git-dir", bare, "config", "uploadpack.allowFilter", "true"], {
cwd: root,
});
const posts: string[] = [];
const server = createGitFixtureServer({ root, posts });
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected HTTP port");
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-credential-filter-"));
roots.push(home);
const previous = process.env.GIT_CONFIG_PARAMETERS;
process.env.GIT_CONFIG_PARAMETERS = [previous, "'credential.helper='"]
.filter(Boolean)
.join(" ");
try {
const remote = `http://fixture:fake-secret@127.0.0.1:${address.port}/plugin.git`;
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({ source: remote });
candidate = await sources.place("managed-example", candidate);
sources.commit("managed-example", candidate.record);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
expect(posts.length).toBeGreaterThanOrEqual(2);
expect(new Set(posts)).toEqual(new Set(["/plugin.git/git-upload-pack"]));
const installFetches = posts.length;
const config = await readFile(path.join(candidate.directory, ".git", "config"), "utf8");
expect(config).not.toMatch(/fixture:fake-secret/);
expect(config).toContain("https://paseo.invalid/plugin.git");
expect(config).toContain("partialclonefilter = blob:none");
await writeFile(
path.join(repository, "index.server.ts"),
"export default () => 'updated';\n",
);
const revision = await commitAll(repository, "update");
await runGitCommand(["push", bare, "main"], { cwd: repository });
const preview = await sources.preview("managed-example", candidate.directory);
expect(preview.target).toEqual({ kind: "git", commit: revision });
const updated = await sources.prepareUpdate(preview.proposal!, candidate.directory);
expect(await readFile(path.join(updated.directory, "index.server.ts"), "utf8")).toContain(
"updated",
);
expect(posts.length - installFetches).toBeGreaterThanOrEqual(2);
} finally {
if (previous === undefined) delete process.env.GIT_CONFIG_PARAMETERS;
else process.env.GIT_CONFIG_PARAMETERS = previous;
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}, 30_000);
it("offers current default HEAD after installing a tag", async () => {
const repository = await createRepository();
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
@@ -194,7 +194,7 @@ export class ManagedPluginSources {
const commit = await resolveRequestedRef(sourceRoot, input.ref);
if (target?.kind === "git" && commit !== target.commit)
throw new Error("Git target changed since review");
await checkout(sourceRoot, commit);
await checkout({ checkoutRoot: sourceRoot, commit, remote });
record = { kind: "git", remote };
}
const directory = path.resolve(sourceRoot, pluginPath);
@@ -502,7 +502,7 @@ function assertPluginPath(checkoutRoot: string, directory: string): void {
}
}
async function clone(remote: string, checkoutRoot: string): Promise<void> {
function gitRemote(remote: string) {
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
@@ -514,12 +514,23 @@ async function clone(remote: string, checkoutRoot: string): Promise<void> {
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
return { cloneRemote, envOverlay };
}
async function clone(remote: string, checkoutRoot: string): Promise<void> {
const { cloneRemote, envOverlay } = gitRemote(remote);
try {
await runGitCommand(["clone", "--no-checkout", "--", cloneRemote, checkoutRoot], {
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
// A blobless clone keeps every commit and ref for revision lookups, and checkout fetches
// only the files of the chosen commit. A full clone of a plugin repository with large
// assets in its history can outlast GIT_TIMEOUT_MS on an ordinary connection.
await runGitCommand(
["clone", "--no-checkout", "--filter=blob:none", "--", cloneRemote, checkoutRoot],
{
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
},
);
} catch (error) {
throw redactRemoteError(error, remote);
}
@@ -545,17 +556,30 @@ function redactRemoteError(error: unknown, remote: string): Error {
return new Error(message);
}
async function checkout(checkoutRoot: string, commit: string): Promise<void> {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
async function checkout({
checkoutRoot,
commit,
remote,
}: {
checkoutRoot: string;
commit: string;
remote: string;
}): Promise<void> {
const { envOverlay } = gitRemote(remote);
try {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
} catch (error) {
throw redactRemoteError(error, remote);
}
}
async function resolveRequestedRef(
@@ -576,17 +600,7 @@ async function resolveRequestedRef(
async function resolveRemoteCommit(remote: string, cwd: string, ref?: string): Promise<string> {
if (ref?.startsWith("-")) throw new Error("Plugin Git ref cannot start with '-'");
if (ref && /^[0-9a-f]{40,64}$/.test(ref)) return ref;
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
cloneRemote === remote
? GIT_ENV
: {
...GIT_ENV,
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
const { cloneRemote, envOverlay } = gitRemote(remote);
try {
const names = ref
? [`refs/heads/${ref}`, `refs/tags/${ref}^{}`, `refs/tags/${ref}`, ref]