Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔒 fix: require authentication configuration for memory webhooks (#21254)

Bryan1762a07a9005
diff --git a/apps/server/src/router-hono/devtools/__tests__/routes.test.ts b/apps/server/src/router-hono/devtools/__tests__/routes.test.ts
index 7b0bb3d9128..e87aa38899f 100644
--- a/apps/server/src/router-hono/devtools/__tests__/routes.test.ts
+++ b/apps/server/src/router-hono/devtools/__tests__/routes.test.ts
@@ -1,14 +1,31 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { memoryUserMemoryBenchmarkLocomo } from '../handlers/memoryUserMemoryBenchmarkLocomo';
import app from '../index';
vi.mock('../handlers/agentTracing', () => ({ agentTracing: vi.fn() }));
vi.mock('../handlers/testPush', () => ({ testPush: vi.fn() }));
vi.mock('../handlers/memoryUserMemoryBenchmarkLocomo', () => ({
- memoryUserMemoryBenchmarkLocomo: vi.fn(),
+ memoryUserMemoryBenchmarkLocomo: vi.fn(() => new Response('benchmark executed')),
}));
describe('devtools hono routes', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('rejects the memory benchmark probe when authentication is unconfigured', async () => {
+ vi.stubEnv('MEMORY_USER_MEMORY_WEBHOOK_HEADERS', undefined);
+ vi.stubEnv('MEMORY_USER_MEMORY_FEATURE_FLAG_BENCHMARK_LOCOMO', 'true');
+
+ const response = await app.request('/api/dev/memory-user-memory/benchmark-locomo', {
+ method: 'POST',
+ });
+
+ expect(response.status).toBe(503);
+ expect(memoryUserMemoryBenchmarkLocomo).not.toHaveBeenCalled();
+ });
+
it('keeps the /api/dev URLs the Next.js segments used to serve', () => {
const paths = app.routes
.filter((route) => route.method !== 'ALL')
diff --git a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts b/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
index 3f60ba9a079..655e4d374df 100644
--- a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
+++ b/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
@@ -1,7 +1,15 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import app from '../index';
+const memoryHandler = vi.hoisted(() => vi.fn());
+const memoryPaths = [
+ '/api/webhooks/memory-extraction',
+ '/api/webhooks/memory-extraction/benchmark-locomo',
+ '/api/webhooks/memory-user-memory/persona/update-writing',
+ '/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel',
+];
+
/**
* These endpoints used to be Next.js route segments, where the directory layout
* *was* the URL. Now the paths are hand-written strings in the app index and a
@@ -18,19 +26,76 @@ vi.mock('../handlers/githubSetup', () => ({ githubSetup: vi.fn() }));
vi.mock('../handlers/linearCallback', () => ({ linearCallback: vi.fn() }));
vi.mock('../handlers/linearInstall', () => ({ linearInstall: vi.fn() }));
vi.mock('../handlers/logto', () => ({ logtoWebhook: vi.fn() }));
-vi.mock('../handlers/memoryExtraction', () => ({ memoryExtractionWebhook: vi.fn() }));
+vi.mock('../handlers/memoryExtraction', () => ({ memoryExtractionWebhook: memoryHandler }));
vi.mock('../handlers/memoryExtractionBenchmarkLocomo', () => ({
- memoryExtractionBenchmarkLocomo: vi.fn(),
+ memoryExtractionBenchmarkLocomo: memoryHandler,
}));
vi.mock('../handlers/memoryUserMemoryChatTopicCancel', () => ({
- memoryUserMemoryChatTopicCancel: vi.fn(),
+ memoryUserMemoryChatTopicCancel: memoryHandler,
}));
vi.mock('../handlers/memoryUserMemoryPersonaUpdateWriting', () => ({
- memoryUserMemoryPersonaUpdateWriting: vi.fn(),
+ memoryUserMemoryPersonaUpdateWriting: memoryHandler,
}));
vi.mock('../handlers/video', () => ({ videoWebhook: vi.fn() }));
describe('webhooks hono routes', () => {
+ beforeEach(() => {
+ memoryHandler.mockReset();
+ memoryHandler.mockImplementation((c) => c.json({ executed: true }));
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('rejects memory requests before execution when authentication is unconfigured', async () => {
+ for (const value of [undefined, '', ' ,invalid,x-empty=']) {
+ vi.stubEnv('MEMORY_USER_MEMORY_WEBHOOK_HEADERS', value);
+
+ for (const path of memoryPaths) {
+ const response = await app.request(path, { method: 'POST' });
+
+ expect(response.status).toBe(503);
+ await expect(response.json()).resolves.toEqual({
+ error:
+ 'Memory webhook authentication is not configured. Set MEMORY_USER_MEMORY_WEBHOOK_HEADERS.',
+ });
+ }
+ }
+
+ expect(memoryHandler).not.toHaveBeenCalled();
+ });
+
+ it('requires every configured memory authentication header before execution', async () => {
+ vi.stubEnv('MEMORY_USER_MEMORY_WEBHOOK_HEADERS', 'x-memory-secret=secret,x-scheduler=trusted');
+
+ for (const headers of [{}, { 'x-memory-secret': 'wrong' }, { 'x-memory-secret': 'secret' }]) {
+ for (const path of memoryPaths) {
+ const response = await app.request(path, { headers, method: 'POST' });
+
+ expect(response.status).toBe(403);
+ }
+ }
+
+ expect(memoryHandler).not.toHaveBeenCalled();
+ });
+
+ it('executes memory requests with all configured authentication headers', async () => {
+ vi.stubEnv('MEMORY_USER_MEMORY_WEBHOOK_HEADERS', 'x-memory-secret=secret,x-scheduler=trusted');
+
+ for (const path of memoryPaths) {
+ const response = await app.request(path, {
+ headers: { 'X-Memory-Secret': 'secret', 'x-scheduler': 'trusted' },
+ method: 'POST',
+ });
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ executed: true });
+ }
+
+ expect(memoryHandler).toHaveBeenCalledTimes(memoryPaths.length);
+ });
+
it('serves every migrated webhook at its original URL', () => {
const paths = app.routes.filter((route) => route.method === 'POST').map((route) => route.path);
diff --git a/apps/server/src/router-hono/webhooks/handlers/__tests__/memoryExtractionBenchmarkLocomo.test.ts b/apps/server/src/router-hono/webhooks/handlers/__tests__/memoryExtractionBenchmarkLocomo.test.ts
index a0db721ce77..7f7a517ed97 100644
--- a/apps/server/src/router-hono/webhooks/handlers/__tests__/memoryExtractionBenchmarkLocomo.test.ts
+++ b/apps/server/src/router-hono/webhooks/handlers/__tests__/memoryExtractionBenchmarkLocomo.test.ts
@@ -6,7 +6,7 @@ const upsertSource = vi.fn();
const extractBenchmarkSource = vi.fn();
vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({
- parseMemoryExtractionConfig: () => ({ webhook: { headers: {} } }),
+ parseMemoryExtractionConfig: () => ({ webhook: { headers: { 'x-memory-secret': 'secret' } } }),
}));
vi.mock('@/database/models/userMemory/sources/benchmarkLoCoMo', () => ({
@@ -105,7 +105,7 @@ describe('benchmark LoCoMo memory extraction webhook', () => {
],
userId: 'locomo-user-conv-26',
}),
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', 'x-memory-secret': 'secret' },
method: 'POST',
}),
);
diff --git a/apps/server/src/router-hono/webhooks/middlewares/memoryWebhookAuth.ts b/apps/server/src/router-hono/webhooks/middlewares/memoryWebhookAuth.ts
index d302e8ab567..130fa410d7d 100644
--- a/apps/server/src/router-hono/webhooks/middlewares/memoryWebhookAuth.ts
+++ b/apps/server/src/router-hono/webhooks/middlewares/memoryWebhookAuth.ts
@@ -6,17 +6,25 @@ import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryEx
* Shared header guard for the memory webhook receivers.
*
* `MEMORY_USER_MEMORY_WEBHOOK_HEADERS` configures a set of static
- * `header: value` pairs that every caller must present. When no headers are
- * configured the guard is a no-op, matching the previous per-route behavior.
+ * `header: value` pairs that every caller must present. Reject requests when
+ * authentication is not configured rather than exposing the memory pipeline.
*/
export const memoryWebhookAuth = (): MiddlewareHandler => async (c, next) => {
const { webhook } = parseMemoryExtractionConfig();
- if (webhook.headers && Object.keys(webhook.headers).length > 0) {
- for (const [key, value] of Object.entries(webhook.headers)) {
- if (c.req.header(key) !== value) {
- return c.json({ error: `Unauthorized: Missing or invalid header '${key}'` }, 403);
- }
+ if (!webhook.headers || Object.keys(webhook.headers).length === 0) {
+ return c.json(
+ {
+ error:
+ 'Memory webhook authentication is not configured. Set MEMORY_USER_MEMORY_WEBHOOK_HEADERS.',
+ },
+ 503,
+ );
+ }
+
+ for (const [key, value] of Object.entries(webhook.headers)) {
+ if (c.req.header(key) !== value) {
+ return c.json({ error: `Unauthorized: Missing or invalid header '${key}'` }, 403);
}
}
diff --git a/packages/memory-user-memory/benchmarks/locomo/README.md b/packages/memory-user-memory/benchmarks/locomo/README.md
index 49951d3cbba..74b4c1e6d90 100644
--- a/packages/memory-user-memory/benchmarks/locomo/README.md
+++ b/packages/memory-user-memory/benchmarks/locomo/README.md
@@ -108,12 +108,26 @@ DELETE FROM user_memories USING target_users u WHERE user_memories.user_id = u.u
## 3. Run the ingest
-Set the required envs and execute:
+The memory webhooks are privileged server-to-server endpoints for trusted operators and benchmark tooling. They require configured authentication headers; a browser login session does not authenticate these requests.
+
+Before starting the LobeHub server, set the following in its environment. Replace `YOUR_RANDOM_SHARED_SECRET` with a randomly generated secret (for example, the output of `openssl rand -hex 32`):
+
+```bash
+export MEMORY_USER_MEMORY_WEBHOOK_HEADERS="x-memory-secret=YOUR_RANDOM_SHARED_SECRET"
+```
+
+Restart the server after changing its environment. Then set the same header value for the ingestor, together with the service URL and dataset path:
```bash
MEMORY_USER_MEMORY_LOBEHUB_BASE_URL="http://localhost:3000" \
MEMORY_USER_MEMORY_BENCHMARKS_LOCOMO_DATASETS="path/to/locomo/dataset/data/locomo10.json" \
+MEMORY_USER_MEMORY_WEBHOOK_HEADERS="x-memory-secret=YOUR_RANDOM_SHARED_SECRET" \
bun run tsx lobehub/packages/memory-user-memory/benchmarks/locomo/run.ts
```
+`MEMORY_USER_MEMORY_WEBHOOK_HEADERS` accepts comma-separated `header=value` pairs. The ingestor sends these headers with each request, and every header configured on the server must match. Setting this variable only on the ingestor does not configure the server.
+
+- **HTTP 503:** server-side authentication headers are unset, empty, or parse to no valid pairs. Configure them on the LobeHub server.
+- **HTTP 403:** a required request header is missing or incorrect. Check that the ingestor and server use matching values.
+
Only samples whose IDs pass the filter in `run.ts` (currently `conv-26`) will ingest; adjust the filter if you need more samples.