Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(security): /cso wave: /ingest writer check, search_by_image local-path ban, push webhook verifies first

garrytana26a95d98a81
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac3394f160..78f5ab9115 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [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.
+
+### 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`.
+
## [0.60.599.0] - 2026-11-07
**A page write refused `source_changed` now says why in its receipt, and a source can opt in to having a `remember`, `capture` or `add_timeline_entry` adopt an uncommitted local edit instead of being refused.** Before, only `pending_import`, `sync_held` and `canonical_file_missing` refusals carried a cause, so a write lost to a hand edit, an occupied path or a file that moved mid-write looked the same in `gbrain write-request` and doctor. Every `source_changed` refusal now records `error_detail.origin`. With `persistence.adopt_local_edits.source.<id>` on (off by default), a one-sided local edit (Git `HEAD` still holds the database's copy, or any edit on a repo-less brain) is committed as its own write first, then the caller's write lands on top. Keep the flag off until the follow-ups in #8755 are done.
diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.ts
index bfffe68c7a..d26fed4c2f 100644
--- a/src/commands/serve-http-webhooks.ts
+++ b/src/commands/serve-http-webhooks.ts
@@ -27,6 +27,7 @@ import type { ServeHttpContext } from './serve-http.ts';
import { NO_SOURCES } from '../core/source-id.ts';
import { noSourceGrantError } from '../core/ops/context.ts';
import { renderAction } from '../core/agent-output.ts';
+import { assertWebhookWriterMayReplace } from '../core/minions/handlers/ingest-capture.ts';
/**
* v0.46: normalize the per-event GitHub webhook payload shape into
@@ -468,14 +469,28 @@ async function handleIngest(
return;
}
+ // The job re-checks this writer at write time; refusing here answers the caller before anything is queued.
+ const writeSourceId = authInfo.sourceId ?? 'default';
+ const writer = authInfo.principal ? { principal: { kind: authInfo.principal.kind, id: authInfo.principal.id } } : undefined;
+ if (callerSlug) {
+ try {
+ await assertWebhookWriterMayReplace(engine, writer, writeSourceId, callerSlug);
+ } catch (err) {
+ if (err instanceof OperationError) {
+ res.status(err.code === 'page_not_found' ? 404 : 403).json({ error: err.code, message: err.message });
+ return;
+ }
+ }
+ }
+
try {
- const writeSourceId = authInfo.sourceId ?? 'default';
const job = await ingestQueue.add(
'ingest_capture',
{
event,
...(callerSlug ? { slug: callerSlug } : {}),
sourceId: writeSourceId,
+ ...(writer ? { writer } : {}),
},
{
// Idempotency: same content from the same client within the
@@ -662,16 +677,24 @@ function mountGitHubWebhook(app: Express, ctx: ServeHttpContext): void {
res.status(500).json({ error: 'lookup_failed' });
return;
}
- if (!source) {
- res.status(404).json({ error: 'unknown_repo', repo: fullName });
- return;
- }
-
- const cfg = (typeof source.config === 'string' ? JSON.parse(source.config) : source.config) as {
+ const cfg = (source ? (typeof source.config === 'string' ? JSON.parse(source.config) : source.config) : {}) as {
webhook_secret?: string;
tracked_branch?: string;
};
+ // HMAC verify before anything about the repository is answered: an unknown repo, a source with no secret and a
+ // bad signature all get the same 401, so an unsigned request cannot tell which repositories this brain syncs.
+ // GitHub sends "sha256=<hex>" — strip the prefix BEFORE safeHexEqual because Buffer.from('sha256=...', 'hex')
+ // silently truncates at the first non-hex char (the 's'), leaving both operands as 0-byte buffers and making
+ // every signature "match". Strict hex shape first: a malformed 64-char signature would make safeHexEqual throw.
+ const secret = cfg.webhook_secret;
+ const computedHex = typeof secret === 'string' && secret ? createHmac('sha256', secret).update(payload).digest('hex') : null;
+ if (!source || !computedHex || !/^sha256=[0-9a-f]{64}$/.test(sigHeader) || !safeHexEqual(sigHeader.slice('sha256='.length), computedHex)) {
+ if (source && !computedHex) console.error(`webhook: push for source ${source.id} refused: no webhook secret is set (run: gbrain sources webhook set ${source.id})`);
+ res.status(401).json({ error: 'signature_mismatch' });
+ return;
+ }
+
// D5: ref must match the configured tracked branch (default 'main').
const trackedBranch = cfg.tracked_branch ?? 'main';
const expectedRef = `refs/heads/${trackedBranch}`;
@@ -685,30 +708,6 @@ function mountGitHubWebhook(app: Express, ctx: ServeHttpContext): void {
return;
}
- const secret = cfg.webhook_secret;
- if (!secret || typeof secret !== 'string') {
- res.status(401).json({ error: 'webhook_not_configured', message: 'Run: gbrain sources webhook set ' + source.id });
- return;
- }
-
- // HMAC verify. GitHub sends "sha256=<hex>" — strip the prefix BEFORE
- // safeHexEqual because Buffer.from('sha256=...', 'hex') silently
- // truncates at the first non-hex char (the 's'), leaving both
- // operands as 0-byte buffers and making every signature "match".
- // Strict hex shape first: a malformed 64-char signature would make
- // safeHexEqual throw (500 instead of 401), codex LOW.
- const { createHmac } = await import('node:crypto');
- const computedHex = createHmac('sha256', secret).update(payload).digest('hex');
- const prefix = 'sha256=';
- if (!/^sha256=[0-9a-f]{64}$/.test(sigHeader)) {
- res.status(401).json({ error: 'signature_mismatch', message: 'expected sha256=<64 hex> signature' });
- return;
- }
- if (!safeHexEqual(sigHeader.slice(prefix.length), computedHex)) {
- res.status(401).json({ error: 'signature_mismatch' });
- return;
- }
-
try {
await submitGitHubPush(engine, source.id, (parsed as { after?: unknown }).after, res);
} catch (err) {
diff --git a/src/core/minions/handlers/ingest-capture.ts b/src/core/minions/handlers/ingest-capture.ts
index aadc9b1b73..7d071168d2 100644
--- a/src/core/minions/handlers/ingest-capture.ts
+++ b/src/core/minions/handlers/ingest-capture.ts
@@ -43,6 +43,10 @@ import { privateRequestRefusal } from '../../persistence/visibility-request.ts';
import { parseMarkdown } from '../../markdown.ts';
import { OperationError, type OperationContext } from '../../ops/contract.ts';
import { submitPageMutation } from '../../persistence/page-mutations.ts';
+import { authorizePageVisibility, excludesPrivateWrites } from '../../persistence/page-visibility.ts';
+import type { Principal, WriteAuthority } from '../../persistence/model.ts';
+import { assertMemberPageWriter, assertScopePageWriter } from '../../access/member-facts.ts';
+import { validateSlug } from '../../utils.ts';
export interface IngestCaptureResult {
slug: string;
@@ -67,9 +71,29 @@ export function defaultSlugForEvent(event: IngestionEvent, now: Date = new Date(
return `inbox/${y}-${m}-${d}-${hashPrefix}`;
}
+/** The token or OAuth client the POST /ingest route stored on the job, or undefined (checked as a guest). */
+function webhookPrincipal(writer: unknown): Principal | undefined {
+ const principal = (writer as { principal?: { kind?: unknown; id?: unknown } } | null | undefined)?.principal;
+ if (!principal || typeof principal.id !== 'string' || (principal.kind !== 'legacy_token' && principal.kind !== 'oauth_client')) return undefined;
+ return { kind: principal.kind, id: principal.id } as Principal;
+}
+
+/**
+ * A webhook capture replaces a page only where its writer's own remote write could: never a member fact page or the
+ * scope page, and never a page the writer cannot read (another member's readable_by page, a private page). A job with
+ * no stored writer is checked as a guest, which reads no restricted page.
+ */
+export async function assertWebhookWriterMayReplace(engine: BrainEngine, writer: unknown, sourceId: string, slug: string): Promise<void> {
+ const target = validateSlug(slug);
+ assertMemberPageWriter({ remote: true }, target, 'ingest_capture');
+ assertScopePageWriter({ remote: true }, target, 'ingest_capture');
+ await authorizePageVisibility(engine, { version: 1, principal: webhookPrincipal(writer), remote: true, sourceId, sourceIncarnation: '',
+ scopes: [], operations: null, slugPrefixes: null, excludePrivate: await excludesPrivateWrites(engine, true) } as WriteAuthority, target);
+}
+
export function makeIngestCaptureHandler(engine: BrainEngine) {
return async function ingestCaptureHandler(job: MinionJobContext): Promise<IngestCaptureResult> {
- const data = job.data as { event?: unknown; slug?: unknown; sourceId?: unknown };
+ const data = job.data as { event?: unknown; slug?: unknown; sourceId?: unknown; writer?: unknown };
const event = data.event as IngestionEvent | undefined;
if (!event) {
throw new Error('ingest_capture: job.data.event is required');
@@ -205,6 +229,10 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
if (rows.length > 0) sourceId = event.source_id;
}
+ const webhookWrite = untrustedPayload && event.source_kind === 'webhook' && !isTombstone;
+ const checkWriter = (sid: string) => webhookWrite ? assertWebhookWriterMayReplace(engine, data.writer, sid, slug) : Promise.resolve();
+ await checkWriter(sourceId ?? 'default');
+
// G6: a managed brain refuses direct writes, so its captures and tombstones go through the door (put_page /
// delete_page), which publishes the file before the row.
const managed = await managedPersistenceEnabled(engine);
@@ -277,6 +305,7 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
? await engine.executeRaw<{ archived: boolean | null }>('SELECT archived FROM sources WHERE id = $1', [sourceId]) : null;
if (!vanished || (vanished.length > 0 && vanished[0]?.archived !== true)) throw err;
sourceFallback = { requested: sourceId!, effective: 'default', reason: vanished.length ? 'archived' : 'fk_violation' };
+ await checkWriter('default');
response = await put('default');
}
if (sourceFallback) {
@@ -327,6 +356,7 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
const isSourceFk = fkErr?.code === '23503' && namesPagesSourceFk;
if (sourceId !== undefined && isSourceFk) {
sourceFallback = { requested: sourceId, effective: 'default', reason: 'fk_violation' };
+ await checkWriter('default');
result = await importFromContent(engine, slug, event.content, { ...importOpts, sourceId: undefined });
} else {
throw err;
diff --git a/src/core/ops/image.ts b/src/core/ops/image.ts
index 62c0a9f78f..d9b8cfc39f 100644
--- a/src/core/ops/image.ts
+++ b/src/core/ops/image.ts
@@ -50,12 +50,18 @@ const search_by_image: Operation = {
// D18 P0 — remote callers cannot pass image_path. Rejecting at handler
// entry, before any file I/O fires. validateParams catches it too at the
// dispatch layer; this is defense-in-depth.
- if (ctx.remote === true && imagePath) {
+ if (ctx.remote !== false && imagePath) {
throw opError('permission_denied',
'permission_denied: image_path is not permitted for remote callers (D18). Use image_url or image_data instead.',
'Pass the image as `image_data` (base64 PNG/JPEG/WebP) or `image_url` (http(s)) instead of `image_path`.');
}
+ if (ctx.remote !== false && imageUrl && !/^https?:\/\//.test(imageUrl)) {
+ throw opError('permission_denied',
+ 'permission_denied: image_url must be an http(s):// URL for remote callers; local files are never read for them.',
+ 'Pass the image as `image_data` (base64 PNG/JPEG/WebP) or an http(s) `image_url`.');
+ }
+
if (!imagePath && !imageUrl && !imageData) {
throw opError('invalid_params', 'search_by_image requires one of: image_path, image_url, image_data',
ctx.remote === false
@@ -70,17 +76,17 @@ const search_by_image: Operation = {
// D23-#6 — remote OAuth clients are charged through the durable
// reserve-then-settle ledger below. Local CLI callers bypass the cap
// (clientId="") because they use their own provider credentials.
- const clientId = (ctx.remote === true ? (ctx.auth?.clientId ?? '') : '');
+ const clientId = (ctx.remote !== false ? (ctx.auth?.clientId ?? '') : '');
// Resolve image bytes via the SSRF-defended loader. For remote callers,
// tighter byte cap.
const remoteCap = await getRemoteMaxBytes(ctx.engine);
const localCap = await getLocalMaxBytes(ctx.engine);
- const cap = ctx.remote === true ? remoteCap : localCap;
+ const cap = ctx.remote === false ? localCap : remoteCap;
const { loadImageInput } = await import('../search/image-loader.ts');
const loaded = await loadImageInput(
(imagePath ?? imageUrl ?? `data:${imageMime ?? 'image/png'};base64,${imageData}`)!,
- { maxBytes: cap },
+ { maxBytes: cap, allowLocalPath: ctx.remote === false },
);
// Resolve source-scope through the single trust+grant resolver. Pre-fix
diff --git a/src/core/search/image-loader.ts b/src/core/search/image-loader.ts
index 533b3d44ee..6164f732b4 100644
--- a/src/core/search/image-loader.ts
+++ b/src/core/search/image-loader.ts
@@ -27,7 +27,7 @@
* conservative for v1.
*/
-import { readFile } from 'node:fs/promises';
+import { readFile, stat } from 'node:fs/promises';
import { isAbsolute } from 'node:path';
import { SSRFError, HttpBodyError, HttpProxyError, fetchWithSSRFGuard, type GuardedHttpResponse } from '../ssrf-validate.ts';
@@ -71,6 +71,8 @@ export interface ImageLoadOpts {
timeoutMs?: number;
/** Max redirect hops (URLs only). Defaults to 3. */
maxRedirects?: number;
+ /** Accept file:// URIs and absolute paths. Only trusted local callers set it; defaults to false. */
+ allowLocalPath?: boolean;
}
/**
@@ -96,6 +98,9 @@ export async function loadImageInput(
return loadHttpUrl(input, { maxBytes, timeoutMs: opts.timeoutMs ?? 5000, maxRedirects: opts.maxRedirects ?? 3 });
}
if (input.startsWith('file://') || isAbsolute(input)) {
+ if (!opts.allowLocalPath) {
+ throw new ImageLoadError('INVALID_URL', 'Local file paths are not accepted here: pass an http(s):// URL or a data: URI.');
+ }
const path = input.startsWith('file://') ? input.slice(7) : input;
return loadLocalPath(path, maxBytes);
}
@@ -108,8 +113,12 @@ export async function loadImageInput(
async function loadLocalPath(path: string, maxBytes: number): Promise<LoadedImage> {
let bytes: Buffer;
try {
+ const info = await stat(path);
+ if (!info.isFile()) throw new ImageLoadError('FETCH_FAILED', `${path} is not a regular file`);
+ if (info.size > maxBytes) throw new ImageLoadError('OVERSIZED', `Image at ${path} is ${info.size} bytes; cap is ${maxBytes}`);
bytes = await readFile(path);
} catch (err) {
+ if (err instanceof ImageLoadError) throw err;
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes('ENOENT')) {
throw new ImageLoadError('NOT_FOUND', `File not found: ${path}`);
diff --git a/test/cross-modal-phase2.test.ts b/test/cross-modal-phase2.test.ts
index 13d46933aa..d14aa0ced9 100644
--- a/test/cross-modal-phase2.test.ts
+++ b/test/cross-modal-phase2.test.ts
@@ -56,7 +56,7 @@ describe('loadImageInput — local path', () => {
test('loads a PNG file and sniffs MIME', async () => {
const path = join(tmpRoot, 'test.png');
writeFileSync(path, PNG_BYTES);
- const result = await loadImageInput(path);
+ const result = await loadImageInput(path, { allowLocalPath: true });
expect(result.contentType).toBe('image/png');
expect(result.bytes.length).toBe(PNG_BYTES.length);
expect(result.base64).toBe(PNG_BYTES.toString('base64'));
@@ -65,21 +65,21 @@ describe('loadImageInput — local path', () => {
test('loads a JPEG file and sniffs MIME', async () => {
const path = join(tmpRoot, 'test.jpg');
writeFileSync(path, JPEG_BYTES);
- const result = await loadImageInput(path);
+ const result = await loadImageInput(path, { allowLocalPath: true });
expect(result.contentType).toBe('image/jpeg');
});
test('loads a WebP file and sniffs MIME', async () => {
const path = join(tmpRoot, 'test.webp');
writeFileSync(path, WEBP_BYTES);
- const result = await loadImageInput(path);
+ const result = await loadImageInput(path, { allowLocalPath: true });
expect(result.contentType).toBe('image/webp');
});
test('rejects unsupported format (GIF)', async () => {
const path = join(tmpRoot, 'test.gif');
writeFileSync(path, Buffer.from('GIF89a' + 'x'.repeat(100)));
- const err = await loadImageInput(path).catch(e => e);
+ const err = await loadImageInput(path, { allowLocalPath: true }).catch(e => e);
expect(err).toBeInstanceOf(ImageLoadError);
expect(err.code).toBe('INVALID_FORMAT');
});
@@ -88,7 +88,7 @@ describe('loadImageInput — local path', () => {
const path = join(tmpRoot, 'huge.png');
// 11MB file with PNG magic bytes
writeFileSync(path, Buffer.concat([PNG_BYTES, Buffer.alloc(11 * 1024 * 1024)]));
- const err = await loadImageInput(path).catch(e => e);
+ const err = await loadImageInput(path, { allowLocalPath: true }).catch(e => e);
expect(err).toBeInstanceOf(ImageLoadError);
expect(err.code).toBe('OVERSIZED');
});
@@ -96,16 +96,27 @@ describe('loadImageInput — local path', () => {
test('rejects file via custom (tighter) maxBytes', async () => {
const path = join(tmpRoot, 'medium.png');
writeFileSync(path, Buffer.concat([PNG_BYTES, Buffer.alloc(1024 * 1024)])); // 1MB
- const err = await loadImageInput(path, { maxBytes: 500 * 1024 }).catch(e => e);
+ const err = await loadImageInput(path, { maxBytes: 500 * 1024, allowLocalPath: true }).catch(e => e);
expect(err).toBeInstanceOf(ImageLoadError);
expect(err.code).toBe('OVERSIZED');
});
test('NOT_FOUND on nonexistent path', async () => {
- const err = await loadImageInput(join(tmpRoot, 'missing.png')).catch(e => e);
+ const err = await loadImageInput(join(tmpRoot, 'missing.png'), { allowLocalPath: true }).catch(e => e);
expect(err).toBeInstanceOf(ImageLoadError);
expect(err.code).toBe('NOT_FOUND');
});
+
+ test('refuses file:// URIs and absolute paths unless the caller opts in', async () => {
+ const path = join(tmpRoot, 'default-off.png');
+ writeFileSync(path, PNG_BYTES);
+ for (const input of [path, `file://${path}`]) {
+ const err = await loadImageInput(input).catch(e => e);
+ expect(err).toBeInstanceOf(ImageLoadError);
+ expect(err.code).toBe('INVALID_URL');
+ expect(err.message).not.toContain(path);
+ }
+ });
});
describe('loadImageInput — data: URI', () => {
diff --git a/test/search-by-image-op.test.ts b/test/search-by-image-op.test.ts
index 21df0eecf8..6134d8ff57 100644
--- a/test/search-by-image-op.test.ts
+++ b/test/search-by-image-op.test.ts
@@ -199,3 +199,60 @@ describe('search_by_image op — D23-#6 spend cap', () => {
expect(Array.isArray(results)).toBe(true);
});
});
+
+describe('search_by_image op — image_url never reads server files for remote callers (CSO A-1)', () => {
+ const remoteCtx = () => ({ engine, remote: true, auth: { token: 't', clientId: 'c-files', scopes: ['read'] } }) as any;
+ let providerCalls = 0;
+ beforeEach(() => {
+ providerCalls = 0;
+ const answer = fetchHandler!;
+ fetchHandler = async (url, init) => { providerCalls++; return answer(url, init); };
+ });
+
+ for (const shape of ['file:// URI', 'bare absolute path'] as const) {
+ test(`image_url as a ${shape} naming a server file is refused before any read, and its bytes never reach the caller`, async () => {
+ const path = join(tmpRoot, 'note.txt');
+ writeFileSync(path, 'sk-example-not-a-real-key');
+ const err = await op().handler(remoteCtx(), { image_url: shape === 'file:// URI' ? `file://${path}` : path })
+ .catch((e: unknown) => e as { code?: string; message?: string });
+ expect((err as { code?: string }).code).toBe('permission_denied');
+ expect(String((err as { message?: string }).message)).not.toContain(Buffer.from('sk-example-n').toString('hex'));
+ expect(String((err as { message?: string }).message)).not.toContain(path);
+ });
+
+ test(`image_url as a ${shape} naming a server image is refused and never sent to the provider`, async () => {
+ const path = join(tmpRoot, 'server-only.png');
+ writeFileSync(path, PNG_BYTES);
+ const err = await op().handler(remoteCtx(), { image_url: shape === 'file:// URI' ? `file://${path}` : path })
+ .catch((e: unknown) => e as { code?: string });
+ expect((err as { code?: string }).code).toBe('permission_denied');
+ expect(providerCalls).toBe(0);
+ });
+ }
+
+ test('image_path is refused when the context does not say it is local (fail closed)', async () => {
+ const path = join(tmpRoot, 'unset.png');
+ writeFileSync(path, PNG_BYTES);
+ const err = await op().handler({ engine } as any, { image_path: path }).catch((e: unknown) => e as { code?: string });
+ expect((err as { code?: string }).code).toBe('permission_denied');
+ expect(providerCalls).toBe(0);
+ });
+
+ test('a local image_path that is not a regular file is refused without reading it', async () => {
+ const err = await op().handler({ engine, remote: false } as any, { image_path: tmpRoot }).catch((e: unknown) => e as Error);
+ expect(err).toBeInstanceOf(Error);
+ expect((err as Error).message).toContain('regular file');
+ expect(providerCalls).toBe(0);
+ });
+
+ test('a local image_path over the size cap is refused before it is read', async () => {
+ await engine.setConfig('search.image_query.max_bytes', '64');
+ const path = join(tmpRoot, 'big.png');
+ writeFileSync(path, Buffer.concat([PNG_BYTES, Buffer.alloc(4096)]));
+ const err = await op().handler({ engine, remote: false } as any, { image_path: path }).catch((e: unknown) => e as Error);
+ expect(err).toBeInstanceOf(Error);
+ expect((err as Error).message).toMatch(/cap is 64/);
+ expect(providerCalls).toBe(0);
+ });
+});
+
diff --git a/test/serve-http-github-push-webhook.test.ts b/test/serve-http-github-push-webhook.test.ts
new file mode 100644
index 0000000000..14c4fac8b8
--- /dev/null
+++ b/test/serve-http-github-push-webhook.test.ts
@@ -0,0 +1,86 @@
+/**
+ * /webhooks/github push events answer an unsigned or badly signed request the same way whatever the repository
+ * (security wave, CSO A-2). Before this fix the push path looked the repository up and answered unknown_repo,
+ * ref_mismatch (naming the tracked branch) and webhook_not_configured (naming the source id) before it checked the
+ * HMAC, so an unauthenticated peer could tell which repositories a brain syncs. Protects: every unverified push gets
+ * one 401 signature_mismatch body; a verified push for another branch still gets 202 ref_mismatch.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import express from 'express';
+import { createHmac } from 'node:crypto';
+import type { Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { mountWebhooks } from '../src/commands/serve-http-webhooks.ts';
+import type { ServeHttpContext } from '../src/commands/serve-http.ts';
+
+const SECRET = 'example-webhook-secret';
+let engine: PGLiteEngine;
+let server: Server;
+let base: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw('INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::jsonb)',
+ ['source-signed', JSON.stringify({ github_repo: 'acme-example/signed', tracked_branch: 'main', webhook_secret: SECRET })]);
+ await engine.executeRaw('INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::jsonb)',
+ ['source-unset', JSON.stringify({ github_repo: 'acme-example/unset', tracked_branch: 'main' })]);
+ const app = express();
+ const pass: express.RequestHandler = (_req, _res, next) => next();
+ mountWebhooks(app, {
+ engine,
+ resourceVerifier: { verifyAccessToken: async () => { throw new Error('unused'); } },
+ resourceMetadataUrl: 'http://127.0.0.1/.well-known/oauth-protected-resource',
+ ingestRateLimiter: pass,
+ githubWebhookLimiter: pass,
+ broadcastEvent: () => {},
+ } as unknown as ServeHttpContext);
+ server = await new Promise<Server>(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}, 60_000);
+
+afterAll(async () => {
+ await new Promise<void>(resolve => server?.close(() => resolve()));
+ await engine?.disconnect();
+}, 60_000);
+
+async function push(repo: string, ref: string, signature?: string) {
+ const payload = JSON.stringify({ repository: { full_name: repo }, ref });
+ const res = await fetch(`${base}/webhooks/github`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-github-event': 'push',
+ 'x-hub-signature-256': signature ?? `sha256=${createHmac('sha256', 'not-the-secret').update(payload).digest('hex')}` },
+ body: payload,
+ });
+ return { status: res.status, text: await res.text() };
+}
+const signed = (repo: string, ref: string) => {
+ const payload = JSON.stringify({ repository: { full_name: repo }, ref });
+ return `sha256=${createHmac('sha256', SECRET).update(payload).digest('hex')}`;
+};
+
+describe('unverified GitHub push webhooks', () => {
+ test('a registered repo, an unregistered repo and a repo with no secret get the same 401', async () => {
+ const answers = [
+ await push('acme-example/signed', 'refs/heads/feature'),
+ await push('acme-example/unknown', 'refs/heads/feature'),
+ await push('acme-example/unset', 'refs/heads/main'),
+ await push('acme-example/signed', 'refs/heads/main'),
+ ];
+ for (const answer of answers) {
+ expect(answer.status).toBe(401);
+ expect(answer.text).toBe(answers[0]!.text);
+ expect(answer.text).not.toContain('main');
+ expect(answer.text).not.toContain('source-');
+ expect(answer.text).not.toContain('acme-example');
+ }
+ });
+
+ test('a verified push for another branch is still acknowledged as ref_mismatch', async () => {
+ const answer = await push('acme-example/signed', 'refs/heads/feature', signed('acme-example/signed', 'refs/heads/feature'));
+ expect(answer.status).toBe(202);
+ expect(JSON.parse(answer.text)).toMatchObject({ status: 'ignored', reason: 'ref_mismatch' });
+ });
+});
diff --git a/test/serve-http-ingest-member-access.test.ts b/test/serve-http-ingest-member-access.test.ts
new file mode 100644
index 0000000000..402cb901ba
--- /dev/null
+++ b/test/serve-http-ingest-member-access.test.ts
@@ -0,0 +1,155 @@
+/**
+ * POST /ingest replaces pages only where the caller's own remote write could (security wave, CSO AUTHZ-1).
+ *
+ * The webhook route hands its body to the ingest_capture job, which writes outside the MCP op layer. Before this
+ * fix the job carried no caller identity, so a write-scoped token replaced pages that every MCP write op refuses it:
+ * another member's readable_by page, an owner visibility: private page, another member's fact page. Protects:
+ * - the route refuses those slugs (404 page_not_found, 403 for member pages) and queues nothing;
+ * - the job re-checks the stored writer at write time, so a page restricted after the 202 is still refused;
+ * - a queued webhook job without a stored writer is checked as a guest (fail closed);
+ * - a page the caller can read, and a fresh slug, still import.
+ * Real token verifier, real Express route, repo-less PGLite brain with members.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import express from 'express';
+import type { Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { mountWebhooks } from '../src/commands/serve-http-webhooks.ts';
+import type { ServeHttpContext } from '../src/commands/serve-http.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { makeIngestCaptureHandler } from '../src/core/minions/handlers/ingest-capture.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { computeContentHash, type IngestionEvent } from '../src/core/ingestion/types.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+
+const SRC = 'source-a';
+const MEMBER_ONLY = 'notes/alice-plan';
+const PRIVATE = 'notes/owner-private';
+const OPEN = 'notes/team-open';
+const ALICE_MEMBER_PAGE = 'memory/members/alice-example';
+
+let engine: PGLiteEngine;
+let server: Server;
+let base: string;
+let bobToken: string;
+let bobTokenId: string;
+
+const page = (title: string, extra = '') => `---\ntype: note\ntitle: ${title}\n${extra}---\n# ${title}\n\nOriginal body.\n`;
+const takeover = '---\ntype: note\ntitle: Replaced\nreadable_by: [bob-example]\n---\n# Replaced\n\nReplaced by another member.\n';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ await importFromContent(engine, MEMBER_ONLY, page('Alice plan', 'readable_by: [alice-example]\n'), { sourceId: SRC, noEmbed: true } as never);
+ await importFromContent(engine, PRIVATE, page('Owner private', 'visibility: private\n'), { sourceId: SRC, noEmbed: true } as never);
+ await importFromContent(engine, OPEN, page('Team open'), { sourceId: SRC, noEmbed: true } as never);
+ for (const id of ['alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ const bob = await mintLegacyToken(engine, { name: 'bob', scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC] });
+ await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [bob.id, 'bob-example']);
+ bobToken = bob.token;
+ bobTokenId = String(bob.id);
+
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const app = express();
+ const pass: express.RequestHandler = (_req, _res, next) => next();
+ mountWebhooks(app, {
+ engine,
+ resourceVerifier: provider,
+ resourceMetadataUrl: 'http://127.0.0.1/.well-known/oauth-protected-resource',
+ ingestRateLimiter: pass,
+ githubWebhookLimiter: pass,
+ broadcastEvent: () => {},
+ } as unknown as ServeHttpContext);
+ server = await new Promise<Server>(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}, 60_000);
+
+afterAll(async () => {
+ await new Promise<void>(resolve => server?.close(() => resolve()));
+ await engine?.disconnect();
+}, 60_000);
+
+const ingest = (slug: string, body = takeover) => fetch(`${base}/ingest`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${bobToken}`, 'content-type': 'text/markdown', 'x-gbrain-slug': slug },
+ body,
+});
+const jobCtx = (data: Record<string, unknown>): MinionJobContext => ({ id: 1, name: 'ingest_capture', data, attempts_made: 0,
+ signal: new AbortController().signal, deadlineAtMs: null, shutdownSignal: new AbortController().signal, updateProgress: async () => {},
+ updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] });
+const webhookEvent = (content: string): IngestionEvent => ({ source_id: 'webhook-client-example', source_kind: 'webhook',
+ source_uri: 'mcp-webhook:client-example:1', received_at: new Date().toISOString(), content_type: 'text/markdown', content,
+ content_hash: computeContentHash(content), untrusted_payload: true });
+const body = async (slug: string) => (await engine.readPageSnapshot(slug, { sourceId: SRC }))?.page.compiled_truth ?? null;
+const queuedJobs = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'ingest_capture'"))[0]!.n;
+
+describe('POST /ingest refuses pages the caller cannot write over MCP', () => {
+ test('another member\'s readable_by page: 404 page_not_found, nothing queued, page unchanged', async () => {
+ const before = await queuedJobs();
+ const res = await ingest(MEMBER_ONLY);
+ expect(res.status).toBe(404);
+ expect((await res.json() as { error: string }).error).toBe('page_not_found');
+ expect(await queuedJobs()).toBe(before);
+ expect(await body(MEMBER_ONLY)).toContain('Original body.');
+ });
+
+ test('a differently cased slug for the same page is refused the same way', async () => {
+ const res = await ingest('Notes/Alice-Plan');
+ expect(res.status).toBe(404);
+ expect(await body(MEMBER_ONLY)).toContain('Original body.');
+ });
+
+ test('an owner visibility: private page: 404 page_not_found, page unchanged', async () => {
+ const res = await ingest(PRIVATE);
+ expect(res.status).toBe(404);
+ expect((await res.json() as { error: string }).error).toBe('page_not_found');
+ expect(await body(PRIVATE)).toContain('Original body.');
+ });
+
+ test('another member\'s fact page: 403 permission_denied', async () => {
+ const res = await ingest(ALICE_MEMBER_PAGE, page('Alice facts'));
+ expect(res.status).toBe(403);
+ expect((await res.json() as { error: string }).error).toBe('permission_denied');
+ expect(await engine.readPageSnapshot(ALICE_MEMBER_PAGE, { sourceId: SRC })).toBeNull();
+ });
+
+ test('a page the caller can read still imports through the job', async () => {
+ const res = await ingest(OPEN, page('Team open', '') + '\nUpdated by bob.\n');
+ expect(res.status).toBe(202);
+ const { job_id } = await res.json() as { job_id: number };
+ const [row] = await engine.executeRaw<{ data: unknown }>('SELECT data FROM minion_jobs WHERE id = $1', [job_id]);
+ const data = (typeof row!.data === 'string' ? JSON.parse(row!.data) : row!.data) as Record<string, unknown>;
+ expect((await makeIngestCaptureHandler(engine)(jobCtx(data))).status).toBe('imported');
+ expect(await body(OPEN)).toContain('Updated by bob.');
+ });
+});
+
+describe('ingest_capture re-checks the webhook writer at write time', () => {
+ test('a stored writer who cannot read the target is refused page_not_found, page unchanged', async () => {
+ const outcome = await makeIngestCaptureHandler(engine)(jobCtx({ event: webhookEvent(takeover), slug: MEMBER_ONLY, sourceId: SRC,
+ writer: { principal: { kind: 'legacy_token', id: bobTokenId } } })).catch((err: { code?: string }) => err);
+ expect((outcome as { code?: string }).code).toBe('page_not_found');
+ expect(await body(MEMBER_ONLY)).toContain('Original body.');
+ });
+
+ test('a queued webhook job with no stored writer is checked as a guest', async () => {
+ const outcome = await makeIngestCaptureHandler(engine)(jobCtx({ event: webhookEvent(takeover), slug: PRIVATE, sourceId: SRC }))
+ .catch((err: { code?: string }) => err);
+ expect((outcome as { code?: string }).code).toBe('page_not_found');
+ expect(await body(PRIVATE)).toContain('Original body.');
+ });
+
+ test('a member fact page is refused for a webhook writer', async () => {
+ const outcome = await makeIngestCaptureHandler(engine)(jobCtx({ event: webhookEvent(page('Alice facts')), slug: ALICE_MEMBER_PAGE, sourceId: SRC,
+ writer: { principal: { kind: 'legacy_token', id: bobTokenId } } })).catch((err: { code?: string }) => err);
+ expect((outcome as { code?: string }).code).toBe('permission_denied');
+ expect(await engine.readPageSnapshot(ALICE_MEMBER_PAGE, { sourceId: SRC })).toBeNull();
+ });
+});