Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

security: remote-added URL sources clone and pull without git-lfs downloads

garrytan1626b05f56ba
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 78f5ab9115..b943410417 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,14 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
-**Security wave from a /cso audit: three remote-surface holes closed on `gbrain serve --http` and `gbrain mcp expose`.** A write-scoped token could replace, through `POST /ingest`, pages that every MCP write refuses it: another member's `readable_by` page, an owner `visibility: private` page, another member's fact page. A read-scoped caller could make `search_by_image` read a file on the brain host by passing a `file://` URI or an absolute path as `image_url`, which echoed the file's first bytes, sent server images to the embedding provider, or hung or exhausted the server. And an unsigned GitHub push webhook answered whether a repository was wired to the brain, its tracked branch and its source id before checking the signature. A default keyless install (stdio MCP, no HTTP surface) was not exposed to any of them.
+**Security wave from a /cso audit: four remote-surface holes closed on `gbrain serve --http` and `gbrain mcp expose`.** A write-scoped token could replace, through `POST /ingest`, pages that every MCP write refuses it: another member's `readable_by` page, an owner `visibility: private` page, another member's fact page. A read-scoped caller could make `search_by_image` read a file on the brain host by passing a `file://` URI or an absolute path as `image_url`, which echoed the file's first bytes, sent server images to the embedding provider, or hung or exhausted the server. And an unsigned GitHub push webhook answered whether a repository was wired to the brain, its tracked branch and its source id before checking the signature. A remote caller adding a source by URL could also make the brain host contact an address the cloned repository names for itself, which the URL check never sees. A default keyless install (stdio MCP, no HTTP surface) was not exposed to any of them.
### Itemized changes
- `src/commands/serve-http-webhooks.ts`, `src/core/minions/handlers/ingest-capture.ts`: `POST /ingest` stores the caller's token or OAuth client on the job. The route answers `404 page_not_found` for an `X-Gbrain-Slug` the caller cannot read and `403 permission_denied` for a member fact page or the scope page, and queues nothing. The job checks the same writer again right before it writes, so a page restricted after the 202 is still refused, and a queued webhook job with no stored writer is checked as a guest. Fresh slugs and pages the caller can read import as before.
- `src/core/ops/image.ts`, `src/core/search/image-loader.ts`: `search_by_image` accepts only an http(s) `image_url` from any caller that is not the trusted local CLI, and refuses `image_path` unless the context says the caller is local. The loader reads local paths only when its caller opts in, and checks for a regular file and the size cap before it reads.
- `src/commands/serve-http-webhooks.ts`: a push event is verified against the source's secret before anything about the repository is answered. An unknown repository, a source with no secret and a bad signature all get the same `401 signature_mismatch`; the missing-secret case is logged on the server with the command that sets it.
-- Tests: `test/serve-http-ingest-member-access.test.ts` (real token verifier and Express route, two members), `test/search-by-image-op.test.ts`, `test/cross-modal-phase2.test.ts` and `test/serve-http-github-push-webhook.test.ts`.
+- `src/core/git-remote.ts`, `src/core/sources-ops.ts`, `src/core/ops/sources.ts`, `src/commands/sync/preflight.ts`: a URL source a remote caller adds is cloned, re-cloned and pulled with git-lfs downloads off (large files stay pointer files), and the source records `added_by_remote_caller: true` so every later pull keeps it off. A remote caller whose clone fails gets a fixed message; git's own error goes to the brain host's log. Sources added from the local CLI keep git-lfs.
+- Tests: `test/serve-http-ingest-member-access.test.ts` (real token verifier and Express route, two members), `test/search-by-image-op.test.ts`, `test/cross-modal-phase2.test.ts`, `test/serve-http-github-push-webhook.test.ts` and `test/sources-remote-lfs.test.ts` (real git-lfs against a local LFS endpoint).
## [0.60.599.0] - 2026-11-07
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 2010214c00..87fc6d079c 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -630,6 +630,9 @@ async function pullAndResolveHead(
// stop). Both stop the pull: a `git pull` still running after this
// process exits could fast-forward the tree behind a released lock.
const { pullRepo, isStoppedGitPull } = await import('../../core/git-remote.ts');
+ const { lfsDownloadsOff } = await import('../../core/sources-ops.ts');
+ const skipLfs = opts.sourceId ? lfsDownloadsOff((await engine.executeRaw<{ config: unknown }>(
+ 'SELECT config FROM sources WHERE id = $1', [opts.sourceId]))[0]?.config) : false;
const shutdown = abortOnCleanupPass('sync-git-pull');
if (opts.sourceId) await recordUpstreamBeforeFetch(engine, opts.sourceId, gitContextRoot);
try {
@@ -637,7 +640,7 @@ async function pullAndResolveHead(
// --timeout through opts.signal, and by pullRepo's own 300s default
// when no --timeout is set. Pull applies to the whole git repo
// (gitContextRoot), not just the sync scope — git has no per-subdir pull.
- await pullRepo(gitContextRoot, { signal: composeAbortSignals(opts.signal, shutdown.signal) });
+ await pullRepo(gitContextRoot, { signal: composeAbortSignals(opts.signal, shutdown.signal), skipLfs });
serr(`[gbrain phase] sync.git_pull done ${Date.now() - _t0}ms`);
if (opts.sourceId) await settleUpstreamAfterPull(engine, opts.sourceId, gitContextRoot, true);
} catch (e: unknown) {
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index 0328ca8b6b..42a5323dfa 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -97,8 +97,13 @@ export interface CloneOpts {
depth?: number; // default 1; 0 means full clone
branch?: string;
timeoutMs?: number; // default 600_000 (10 min)
+ /** Keep git-lfs from downloading: the repository's own .lfsconfig picks the LFS endpoint, outside the URL gate. */
+ skipLfs?: boolean;
}
+/** git-lfs leaves pointer files in place and contacts no LFS endpoint. */
+const LFS_DOWNLOADS_OFF = { GIT_LFS_SKIP_SMUDGE: '1' } as const;
+
export class GitOperationError extends Error {
constructor(
public op: 'clone' | 'pull' | 'fetch' | 'remote_get_url',
@@ -169,7 +174,7 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
execFileSync('git', args, {
stdio: ['ignore', 'pipe', 'pipe'],
timeout: opts.timeoutMs ?? 600_000,
- env: gitChildEnv({ ...GIT_ENV }),
+ env: gitChildEnv({ ...GIT_ENV, ...(opts.skipLfs ? LFS_DOWNLOADS_OFF : {}) }),
});
} catch (e) {
throw new GitOperationError(
@@ -193,7 +198,7 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
* `opts.timeoutMs` (default 5 min); `isStoppedGitPull` recognizes the error
* that produces, so callers can tell "we stopped it" from "git failed".
*/
-export async function pullRepo(repoPath: string, opts: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<void> {
+export async function pullRepo(repoPath: string, opts: { timeoutMs?: number; signal?: AbortSignal; skipLfs?: boolean } = {}): Promise<void> {
assertManagedFilesystemWrite(repoPath);
const fail = (reason: string, error: unknown): never => {
throw new GitOperationError('pull', `git pull failed in ${repoPath}: ${reason}`, error);
@@ -217,7 +222,7 @@ export async function pullRepo(repoPath: string, opts: { timeoutMs?: number; sig
try {
const merge = await execFileBounded('git', ['-C', repoPath, '-c', 'core.hooksPath=/dev/null', '-c', 'merge.autoStash=false', 'merge', '--ff-only', '--quiet', '@{upstream}'], {
timeout: opts.timeoutMs ?? 300_000,
- env: gitChildEnv({ ...GIT_ENV }),
+ env: gitChildEnv({ ...GIT_ENV, ...(opts.skipLfs ? LFS_DOWNLOADS_OFF : {}) }),
signal: opts.signal,
});
if (merge.error) fail(merge.stderr.trim() || merge.error.message, merge.error);
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index 3e6f2c9b79..a64a04d676 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -141,7 +141,7 @@ const sources_add: Operation = {
mutating: true,
scope: 'sources_admin',
handler: async (ctx, p) => {
- const { addSource } = await import('../sources-ops.ts');
+ const { addSource, SourceOpError } = await import('../sources-ops.ts');
if(ctx.remote!==false&&await (await import('../persistence/ownership.ts')).managedPersistenceEnabled(ctx.engine))
throw managedLifecycleRefusal(ctx, ['sources', 'add', ...sourceIdArg(p.id), ...(typeof p.url === 'string' && /^https:\/\/\S+$/.test(p.url) ? ['--url', p.url] : [])]);
@@ -180,9 +180,15 @@ const sources_add: Operation = {
name: p.name as string | undefined,
localPath: remotePath,
remoteUrl: p.url as string | undefined,
+ addedByRemoteCaller: !isLocal,
federated:
p.federated === undefined ? null : (p.federated as boolean),
cloneDir: remoteCloneDir,
+ }).catch((err: unknown) => {
+ // git's own error names the far end and how it answered; a remote caller gets a fixed message, the host log keeps it.
+ if (isLocal || !(err instanceof SourceOpError) || err.code !== 'clone_failed') throw err;
+ console.error(`[gbrain] sources_add ${String(p.id)}: ${err.message}`);
+ throw new SourceOpError('clone_failed', 'git clone failed for this URL. The brain host\'s log has the reason.', err);
});
const { redactSourceConfig } = await import('../source-config-redact.ts');
const { parseSourceConfig } = await import('../sources-load.ts');
diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.ts
index 31eacb10ba..f721eea66a 100644
--- a/src/core/sources-ops.ts
+++ b/src/core/sources-ops.ts
@@ -155,6 +155,8 @@ export interface AddSourceOpts {
expectedIncarnation?: string;
localPath?: string | null;
remoteUrl?: string;
+ /** The URL came from a remote caller: its clone and every later pull run without git-lfs downloads. */
+ addedByRemoteCaller?: boolean;
federated?: boolean | null;
/**
* Override clone destination. Defaults to $GBRAIN_HOME/clones/<id>/.
@@ -559,7 +561,7 @@ export async function addSource(
mkdirSync(dirname(tempDir), { recursive: true });
try {
- cloneRepo(parsedUrl.url, tempDir);
+ cloneRepo(parsedUrl.url, tempDir, { skipLfs: opts.addedByRemoteCaller === true });
} catch (e) {
// Clone failed before we've touched the DB. tempDir may or may not
// exist; nuke it just in case.
@@ -574,10 +576,8 @@ export async function addSource(
// recloneIfMissing to rm+replace this clone — gbrain created it, here or at
// a --clone-dir path. A user-tree row (created by an external INSERT, no
// --url) never carries this, so it can never be deleted by reclone.
- const config: Record<string, unknown> = {
- remote_url: parsedUrl.url,
- managed_clone: true,
- };
+ const config: Record<string, unknown> = { remote_url: parsedUrl.url, managed_clone: true };
+ if (opts.addedByRemoteCaller) config.added_by_remote_caller = true;
if (opts.federated !== null && opts.federated !== undefined) {
config.federated = opts.federated;
}
@@ -1093,6 +1093,12 @@ export async function getSourceStatus(
// ── recloneIfNeeded (used by sources.ts restore path) ──────────────────────
+/** A source a remote caller added by URL never downloads git-lfs objects: its repository names the LFS endpoint. */
+export function lfsDownloadsOff(config: unknown): boolean {
+ const parsed = typeof config === 'string' ? (() => { try { return JSON.parse(config) as unknown; } catch { return null; } })() : config;
+ return (parsed as Record<string, unknown> | null)?.added_by_remote_caller === true;
+}
+
/**
* Re-clone a source's remote_url into its local_path if the clone is
* missing on disk. Used by `gbrain sources restore` after an operator
@@ -1148,7 +1154,7 @@ export async function recloneIfMissing(
const rand = randomBytes(6).toString('hex');
const tempDir = join(parent, `.gbrain-reclone-${basename(src.local_path)}-${rand}`);
try {
- cloneRepo(remoteUrl, tempDir);
+ cloneRepo(remoteUrl, tempDir, { skipLfs: lfsDownloadsOff(src.config) });
} catch (e) {
rmSync(tempDir, { recursive: true, force: true });
if (e instanceof GitOperationError) {
diff --git a/test/sources-remote-lfs.test.ts b/test/sources-remote-lfs.test.ts
new file mode 100644
index 0000000000..66247a2971
--- /dev/null
+++ b/test/sources-remote-lfs.test.ts
@@ -0,0 +1,183 @@
+/**
+ * Sources a remote caller adds by URL never download git-lfs objects (security wave, CSO SINK-1, option B).
+ *
+ * A repository's committed .lfsconfig names the LFS endpoint, and git-lfs contacts it outside the remote-URL gate.
+ * On a host with git-lfs installed globally, a remote caller's sources_add could make the brain host send requests to
+ * any HTTP endpoint the repository named, on the clone and on every later pull. Protects:
+ * - cloneRepo / pullRepo with skipLfs leave pointer files and contact no LFS endpoint (real git and git-lfs);
+ * - sources_add from a remote caller clones that way, records it on the source, and a re-clone follows the record;
+ * - sources_add from the trusted local CLI keeps LFS downloads;
+ * - a remote caller's failed clone gets a fixed message instead of git's own error.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { cloneRepo, pullRepo } from '../src/core/git-remote.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { recloneIfMissing } from '../src/core/sources-ops.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const hasLfs = spawnSync('git', ['lfs', 'version']).status === 0 && process.platform !== 'win32';
+const ROOT = mkdtempSync(join(tmpdir(), 'gbrain-remote-lfs-'));
+const OID = '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824';
+const pointer = `version https://git-lfs.github.com/spec/v1\noid sha256:${OID}\nsize 5\n`;
+
+afterAll(() => rmSync(ROOT, { recursive: true, force: true }));
+
+describe.skipIf(!hasLfs)('real git-lfs: skipLfs contacts no LFS endpoint', () => {
+ const globalConfig = join(ROOT, 'gitconfig');
+ const work = join(ROOT, 'work');
+ const bare = join(ROOT, 'repo.git');
+ const hitsLog = join(ROOT, 'lfs-hits.log');
+ const hits = () => readFileSync(hitsLog, 'utf8').split('\n').filter(Boolean);
+ let servers: { kill(): void } | undefined;
+ let url: string;
+ let lfsPort: number;
+ const env = () => ({ GIT_CONFIG_GLOBAL: globalConfig, GIT_CONFIG_NOSYSTEM: '1' });
+ const authorConfig = join(ROOT, 'author-gitconfig');
+ // The fixture repository is written without git-lfs, so only the code under test ever runs the LFS filter.
+ const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, env: { ...process.env, GIT_CONFIG_GLOBAL: authorConfig, GIT_CONFIG_NOSYSTEM: '1' }, stdio: 'pipe' });
+
+ beforeAll(async () => {
+ // cloneRepo blocks this process while git runs, so both servers live in a child process.
+ const script = join(ROOT, 'servers.ts');
+ writeFileSync(hitsLog, '');
+ writeFileSync(script, `
+import { appendFileSync } from 'node:fs';
+const lfs = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch(req) { appendFileSync(${JSON.stringify(hitsLog)}, req.method + ' ' + new URL(req.url).pathname + '\\n'); return new Response('{}', { status: 404 }); } });
+const git = Bun.serve({ port: 0, hostname: '127.0.0.1', async fetch(req) {
+ const u = new URL(req.url);
+ const body = new Uint8Array(await req.arrayBuffer());
+ const proc = Bun.spawn(['git', 'http-backend'], { stdin: body, stdout: 'pipe', stderr: 'pipe', env: {
+ PATH: process.env.PATH, GIT_PROJECT_ROOT: ${JSON.stringify(ROOT)}, GIT_HTTP_EXPORT_ALL: '1', PATH_INFO: u.pathname, QUERY_STRING: u.search.slice(1),
+ REQUEST_METHOD: req.method, CONTENT_TYPE: req.headers.get('content-type') ?? '', CONTENT_LENGTH: String(body.length), GIT_PROTOCOL: req.headers.get('git-protocol') ?? '' } });
+ const out = Buffer.from(await new Response(proc.stdout).arrayBuffer());
+ const sep = out.indexOf('\\r\\n\\r\\n');
+ const headers = new Headers();
+ let status = 200;
+ for (const line of out.subarray(0, sep).toString().split('\\r\\n')) {
+ const i = line.indexOf(':');
+ const key = line.slice(0, i).trim();
+ if (key.toLowerCase() === 'status') status = parseInt(line.slice(i + 1), 10); else headers.set(key, line.slice(i + 1).trim());
+ }
+ return new Response(out.subarray(sep + 4), { status, headers });
+} });
+console.log(git.port + ' ' + lfs.port);
+`);
+ const proc = Bun.spawn([process.execPath, '--no-env-file', script], { stdout: 'pipe', stderr: 'inherit' });
+ servers = proc;
+ const reader = proc.stdout.getReader();
+ let first = '';
+ while (!first.includes('\n')) { const { value, done } = await reader.read(); if (done) break; first += new TextDecoder().decode(value); }
+ reader.releaseLock();
+ const [gitPort, lfsPortText] = first.trim().split(' ');
+ lfsPort = Number(lfsPortText);
+ url = `http://127.0.0.1:${gitPort}/repo.git`;
+ writeFileSync(globalConfig, '[filter "lfs"]\n\tclean = git-lfs clean -- %f\n\tsmudge = git-lfs smudge -- %f\n\tprocess = git-lfs filter-process\n\trequired = true\n');
+ writeFileSync(authorConfig, '[user]\n\tname = example\n\temail = [email protected]\n');
+ mkdirSync(work);
+ git(work, 'init', '-q', '-b', 'main', '.');
+ writeFileSync(join(work, '.lfsconfig'), `[lfs]\n\turl = http://127.0.0.1:${lfsPort}/internal-lfs\n`);
+ writeFileSync(join(work, 'x.bin'), pointer);
+ writeFileSync(join(work, 'note.md'), '# note\n');
+ git(work, 'add', '-A');
+ git(work, 'commit', '-q', '-m', 'pointer');
+ writeFileSync(join(work, '.gitattributes'), '*.bin filter=lfs diff=lfs merge=lfs -text\n');
+ git(work, 'add', '.gitattributes');
+ git(work, 'commit', '-q', '-m', 'attributes');
+ git(ROOT, 'clone', '-q', '--bare', work, bare);
+ git(bare, 'update-server-info');
+ });
+ afterAll(() => { servers?.kill(); });
+ beforeEach(() => { writeFileSync(hitsLog, ''); });
+
+ test('control: a clone without skipLfs asks the repository-named LFS endpoint', async () => {
+ await withEnv(env(), async () => {
+ try { cloneRepo(url, join(ROOT, 'control'), { timeoutMs: 60_000 }); } catch { /* the endpoint answers 404 */ }
+ });
+ expect(hits().length).toBeGreaterThan(0);
+ }, 90_000);
+
+ test('a skipLfs clone and a skipLfs pull leave pointers and contact no LFS endpoint', async () => {
+ const dest = join(ROOT, 'skipped');
+ await withEnv(env(), async () => { cloneRepo(url, dest, { timeoutMs: 60_000, depth: 0, skipLfs: true }); });
+ expect(readFileSync(join(dest, 'x.bin'), 'utf8')).toBe(pointer);
+ writeFileSync(join(work, 'y.bin'), pointer.replace('size 5', 'size 6'));
+ git(work, 'add', 'y.bin');
+ git(work, 'commit', '-q', '-m', 'second pointer');
+ git(work, 'push', '-q', bare, 'main');
+ git(bare, 'update-server-info');
+ await withEnv(env(), async () => { await pullRepo(dest, { timeoutMs: 60_000, skipLfs: true }); });
+ expect(readFileSync(join(dest, 'y.bin'), 'utf8')).toContain('size 6');
+ expect(hits()).toEqual([]);
+ }, 90_000);
+});
+
+describe('sources_add: a remote caller\'s URL source clones without LFS downloads', () => {
+ const fakeDir = join(ROOT, 'fake-git');
+ const log = join(fakeDir, 'calls.log');
+ const mode = join(fakeDir, 'mode');
+ const home = join(ROOT, 'home');
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ mkdirSync(fakeDir, { recursive: true });
+ const recorder = join(fakeDir, 'record.ts');
+ writeFileSync(recorder, `
+import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
+const args = process.argv.slice(2);
+appendFileSync(${JSON.stringify(log)}, JSON.stringify({ args, skip: process.env.GIT_LFS_SKIP_SMUDGE ?? null }) + '\\n');
+if (readFileSync(${JSON.stringify(mode)}, 'utf8') === 'fail') { console.error('fatal: unable to access internal-detail-example: 502'); process.exit(128); }
+if (args.includes('clone')) mkdirSync(args[args.length - 1]!, { recursive: true });
+`);
+ writeFileSync(join(fakeDir, 'git'), `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${recorder}' "$@"\n`);
+ chmodSync(join(fakeDir, 'git'), 0o755);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1').catch(() => {});
+ });
+ afterAll(async () => { await engine?.disconnect(); });
+ beforeEach(() => { writeFileSync(log, ''); writeFileSync(mode, 'ok'); });
+
+ const clones = () => readFileSync(log, 'utf8').trim().split('\n').filter(Boolean)
+ .map(line => JSON.parse(line) as { args: string[]; skip: string | null }).filter(call => call.args.includes('clone'));
+ const add = (remote: boolean, id: string) => withEnv({ PATH: `${fakeDir}:${process.env.PATH}`, GBRAIN_HOME: home }, () =>
+ operationsByName.sources_add!.handler({ engine, remote, auth: remote ? { token: 't', clientId: 'c-admin', scopes: ['sources_admin'] } : undefined } as never,
+ { id, url: `https://example.com/acme-example/${id}.git` }));
+ const config = async (id: string) => {
+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1', [id]);
+ return (typeof row?.config === 'string' ? JSON.parse(row.config) : row?.config) as Record<string, unknown>;
+ };
+
+ test('a remote caller\'s clone runs with LFS downloads off, and the source records it', async () => {
+ await add(true, 'remote-added');
+ expect(clones().map(call => call.skip)).toEqual(['1']);
+ expect((await config('remote-added')).added_by_remote_caller).toBe(true);
+ });
+
+ test('a re-clone of that source keeps LFS downloads off', async () => {
+ const [row] = await engine.executeRaw<{ local_path: string }>("SELECT local_path FROM sources WHERE id = 'remote-added'");
+ rmSync(row!.local_path, { recursive: true, force: true });
+ await withEnv({ PATH: `${fakeDir}:${process.env.PATH}`, GBRAIN_HOME: home }, () => recloneIfMissing(engine, 'remote-added'));
+ expect(clones().map(call => call.skip)).toEqual(['1']);
+ });
+
+ test('the trusted local CLI keeps LFS downloads', async () => {
+ await add(false, 'local-added');
+ expect(clones().map(call => call.skip)).toEqual([null]);
+ expect((await config('local-added')).added_by_remote_caller).toBeUndefined();
+ });
+
+ test('a remote caller\'s failed clone gets a fixed message; the local CLI keeps git\'s error', async () => {
+ writeFileSync(mode, 'fail');
+ const remote = await add(true, 'remote-fails').catch((err: Error) => err);
+ expect((remote as Error).message).not.toContain('internal-detail-example');
+ expect((remote as Error).message).toContain('git clone failed');
+ const local = await add(false, 'local-fails').catch((err: Error) => err);
+ expect((local as Error).message).toContain('internal-detail-example');
+ });
+});