mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-14 08:53:22 +00:00
* fix(auth): honor permissions.takes_holders for legacy bearer tokens over serve --http (#2529) The OAuth provider's legacy access_tokens branch parsed permissions.source_id but never read permissions.takes_holders, so the /mcp dispatch site's fail-closed default pinned every remote caller to world-only takes visibility — set-takes-holders was a silent no-op over serve --http, in both directions (grants above world never applied; restrictions below world didn't either). - src/core/legacy-token-scope.ts: new parseTakesHoldersAllowList shared by BOTH transports (the drift between the legacy HTTP transport's correct inline parse and the OAuth provider is how this bug shipped). [] preserved as explicit deny-all; non-array → undefined → consumer defaults ['world']. - src/core/operations.ts: AuthInfo.takesHoldersAllowList typed field (same ride-along as sourceId/allowedSources). - src/core/oauth-provider.ts: legacy branch threads the stored grant. OAuth-client tokens unchanged (no per-client storage — TODO filed). - src/mcp/http-transport.ts: converged on the shared helper (behavior no-op). - src/commands/serve-http.ts: sidecar cast replaced by the typed field. - src/core/facts/meta-hook.ts: hashAllowList gives [] its own cache key (cache identity only — payload filtering stays visibility-based). Tests: 7 verifyAccessToken cases (grant/absent/garbage/deny-all/mixed/ oauth-client/column-default), pure-helper describe, meta-hook cache-key pin, and a Postgres e2e (test/e2e/serve-http-takes-holders.test.ts) pinning the issue repro end-to-end over POST /mcp — the seam that had no coverage. Reported by @Derek95king. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(agent-voice): default-deny CORS + origin gate + loopback bind in reference server (#2477) The recipe reference server reflected any Origin into Access-Control-Allow-Origin on every route, including the unauthenticated side-effectful POSTs. Recipe is install_kind: copy-into-host-repo, so the reference is the source of truth for every future install. - Default-deny CORS: headers emitted only for exact matches against the new AGENT_VOICE_CORS_ORIGIN allowlist (comma-separated), with Vary: Origin; Allow-Credentials never set. Same-origin /call needs no configuration. - Origin gate on /session and /tool: CORS headers gate response reads, not request sends — a no-preflight "simple" cross-origin POST still executes. Disallowed Origins now 403 before any body read / upstream fetch / tool dispatch. No-Origin callers (curl, Twilio, native) and same-origin pages (Origin host == Host, tunnels included) pass. DNS rebinding stays a documented production-checklist item (TODO filed). - Loopback-default bind: HOST env, default 127.0.0.1 (mirrors gbrain serve --http --bind default); HOST=0.0.0.0 for containers/LAN. - Startup log prints the bind + CORS posture; recipe md + install manifest bumped to 0.1.1 with the production checklist rewritten to match. Tests: test/agent-voice-cors.serial.test.ts spawns the real server twice and pins default-deny, allowlist echo + trimming, preflight behavior, and the gate's ordering (evil-origin 403 vs no-origin reaching the handler). Reported by @sebastiondev. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: agent-voice origin gate fails closed on malformed Origin (#2477) Coverage-audit follow-up: a cross-origin POST with an unparseable Origin header must 403 (new URL() throws → originAllowed returns false), never fall through to the handler. A bypass here would defeat the gate. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: pin loopback-bind default + wire-level fail-closed takes default (#2529 #2477) Pre-landing review (testing specialist) flagged two revert-catching gaps: - #2477 HOST default (127.0.0.1) had no assertion — a regression to all-interfaces would pass every test. Capture the server's startup log and assert the loopback bind; add a HOST=0.0.0.0 override case. - #2529 serve-http `?? ['world']` default branch was only unit-covered. Add a 4th e2e case: a legacy token with no takes_holders key sees world-held takes but NOT brain-held ones over POST /mcp, pinning the fail-closed default end-to-end. Also assert the deny-all case returns a successful (non-error) tool result so the negatives can't pass vacuously. Verified: agent-voice 4/4, serve-http-takes-holders e2e 4/4 (real Postgres). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(auth): shared permissions decode + collision-free hot-memory cache key (#2529) Adversarial-review hardening on the #2529 fix: - The two transports shared parseTakesHoldersAllowList but still decoded the permissions column differently: the OAuth provider JSON.parse'd a string-typed value, the legacy HTTP transport didn't. On a double-encoded jsonb string scalar (#2339 class) a deny-all token would fail open to ['world'] on the HTTP transport while the provider honored it. Extract coerceLegacyPermissions into the shared module and route both through it, so "the two transports cannot drift" is literally true (shared decode + shared parse). Arrays/scalars/malformed strings → undefined (no grant). - hashAllowList used bare sentinels ('_' for undefined, '(empty)' for []), which collided with real holder values ['_'] and ['(empty)']. Encode collision-free (undefined → 'none', else JSON.stringify(sorted)) so the []-vs-undefined cache separation the #2529 change relies on holds for every holder value. Tests: coerceLegacyPermissions unit cases (object/JSON-string/malformed/ array/scalar), all existing takes-holders + meta-hook + e2e suites green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.42.74.0 fix(security): honor takes_holders over serve --http + agent-voice default-deny CORS (#2529 #2477) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: document agent-voice HOST + AGENT_VOICE_CORS_ORIGIN env vars in install hint (v0.42.74.0) The post-install hint's env-var quick-start predated the #2477 hardening and listed neither the loopback-default HOST bind nor the default-deny AGENT_VOICE_CORS_ORIGIN allowlist. Add both as optional entries (safe by default) and refresh the stale startup-log line to match the server's actual loopback-bind output. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: correct CHANGELOG command guidance + TODOS filing version (#2529 #2477) Ship-stage document-release caught two wrong CLI invocations in the v0.42.74.0 CHANGELOG "To take advantage" block: `gbrain auth permissions <token>` has no read-only view form (that shape errors + exits 1 — set the scope directly with `set-takes-holders <values>`), and `integrations install agent-voice --refresh` requires `--target <host-repo>`. Also correct the follow-ups TODO header from the plan's stale v0.42.56.0 guess to the actual ship version v0.42.74.0. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(deps): bump js-yaml to 3.15.1 — osv GHSA-5p4m-2wfm-xmqj (#2529 #2477) osv-scan flagged js-yaml@3.15.0 (High, CVSS 7.5), fixed in 3.15.1. The transitive copy (gray-matter → js-yaml) was pinned to ^3.15.0 by the package.json `overrides` block; bump both the direct dependency and the override to ^3.15.1 so the vulnerable version is gone from bun.lock entirely (gray-matter/js-yaml now resolves to 3.15.1). Patch bump, in-range, frontmatter parsing verified (markdown + frontmatter + import + oauth suites green). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(deps): bump admin nanoid to 3.3.18 — osv GHSA-2v37-7h3g-55p8 (#2529 #2477) osv-scan flagged nanoid@3.3.16 (High, CVSS 8.2) in admin/bun.lock, fixed in 3.3.17. nanoid is transitive (postcss → nanoid), so pin it in the admin overrides block; refresh resolves to 3.3.18 (latest patched 3.x). Admin SPA build verified green; both root and admin lockfiles now scan clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
187 lines
8.2 KiB
TypeScript
187 lines
8.2 KiB
TypeScript
/**
|
|
* v0.31 Phase 6 follow-up — meta-hook cache key + invalidation contract.
|
|
*
|
|
* Pins:
|
|
* - 30s TTL: cache hit on second call within window (different rows
|
|
* don't show up).
|
|
* - bumpHotMemoryCache(source_id, session_id) drops only the matching
|
|
* entries; other (source_id, session_id) tuples stay cached.
|
|
* - cache key isolates across distinct allow-lists (already covered by
|
|
* facts-context-injection.serial.test.ts; pinned here from a different
|
|
* angle — the in-process cache directly).
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
|
import {
|
|
getBrainHotMemoryMeta,
|
|
bumpHotMemoryCache,
|
|
__resetHotMemoryCacheForTests,
|
|
} from '../src/core/facts/meta-hook.ts';
|
|
import type { OperationContext } from '../src/core/operations.ts';
|
|
import type { GBrainConfig } from '../src/core/config.ts';
|
|
|
|
let engine: PGLiteEngine;
|
|
|
|
beforeAll(async () => {
|
|
engine = new PGLiteEngine();
|
|
await engine.connect({});
|
|
await engine.initSchema();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await engine.disconnect();
|
|
});
|
|
|
|
beforeEach(() => {
|
|
__resetHotMemoryCacheForTests();
|
|
});
|
|
|
|
function ctx(overrides: Partial<OperationContext> = {}): OperationContext {
|
|
return {
|
|
engine,
|
|
config: {} as GBrainConfig,
|
|
logger: { info: () => {}, warn: () => {}, error: () => {} },
|
|
dryRun: false,
|
|
remote: false,
|
|
sourceId: 'default',
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
describe('meta-hook cache', () => {
|
|
test('cache hit returns the same payload without re-querying', async () => {
|
|
await engine.insertFact(
|
|
{ fact: 'cache test fact', kind: 'fact', entity_slug: 'cache-test', visibility: 'world', source: 'test' },
|
|
{ source_id: 'default' },
|
|
);
|
|
|
|
const first = await getBrainHotMemoryMeta('get_stats', ctx());
|
|
expect(first?.brain_hot_memory).toBeDefined();
|
|
const firstFacts = (first!.brain_hot_memory as { facts: { id: number }[] }).facts;
|
|
const firstCount = firstFacts.length;
|
|
|
|
// Insert another fact — but cache hit short-circuits so the new one
|
|
// doesn't surface until we bump.
|
|
await engine.insertFact(
|
|
{ fact: 'second fact (post-cache)', kind: 'fact', entity_slug: 'cache-test', visibility: 'world', source: 'test' },
|
|
{ source_id: 'default' },
|
|
);
|
|
const second = await getBrainHotMemoryMeta('get_stats', ctx());
|
|
const secondFacts = (second!.brain_hot_memory as { facts: { id: number }[] }).facts;
|
|
expect(secondFacts.length).toBe(firstCount);
|
|
});
|
|
|
|
test('bumpHotMemoryCache forces a fresh query on next call', async () => {
|
|
await engine.insertFact(
|
|
{ fact: 'bump-test seed', kind: 'fact', entity_slug: 'bump', visibility: 'world', source: 'test' },
|
|
{ source_id: 'default' },
|
|
);
|
|
const first = await getBrainHotMemoryMeta('get_stats', ctx());
|
|
const firstCount = (first!.brain_hot_memory as { facts: unknown[] }).facts.length;
|
|
await engine.insertFact(
|
|
{ fact: 'bump-test post-bump', kind: 'fact', entity_slug: 'bump', visibility: 'world', source: 'test' },
|
|
{ source_id: 'default' },
|
|
);
|
|
bumpHotMemoryCache('default', null);
|
|
const second = await getBrainHotMemoryMeta('get_stats', ctx());
|
|
const secondCount = (second!.brain_hot_memory as { facts: unknown[] }).facts.length;
|
|
expect(secondCount).toBeGreaterThan(firstCount);
|
|
});
|
|
|
|
test('bumpHotMemoryCache for one (source, session) does not affect another', async () => {
|
|
// Seed and warm caches for two sessions of the same source.
|
|
await engine.insertFact(
|
|
{ fact: 'sess-A fact', kind: 'fact', entity_slug: 'multi-sess', visibility: 'world', source: 'test', source_session: 'sess-A' },
|
|
{ source_id: 'default' },
|
|
);
|
|
await engine.insertFact(
|
|
{ fact: 'sess-B fact', kind: 'fact', entity_slug: 'multi-sess', visibility: 'world', source: 'test', source_session: 'sess-B' },
|
|
{ source_id: 'default' },
|
|
);
|
|
// Note: the helper uses ctx.source_session via the exotic accessor;
|
|
// since OperationContext doesn't formally carry it, call with a forged
|
|
// shape via overrides.
|
|
const ctxA = ctx({}) as OperationContext & { source_session?: string };
|
|
ctxA.source_session = 'sess-A';
|
|
const ctxB = ctx({}) as OperationContext & { source_session?: string };
|
|
ctxB.source_session = 'sess-B';
|
|
const a1 = await getBrainHotMemoryMeta('get_stats', ctxA);
|
|
const b1 = await getBrainHotMemoryMeta('get_stats', ctxB);
|
|
const a1Count = (a1?.brain_hot_memory as { facts: unknown[] } | undefined)?.facts.length ?? 0;
|
|
const b1Count = (b1?.brain_hot_memory as { facts: unknown[] } | undefined)?.facts.length ?? 0;
|
|
|
|
// Bump only sess-A; sess-B's cache stays warm.
|
|
bumpHotMemoryCache('default', 'sess-A');
|
|
|
|
// Add a fact to each session; only sess-A's next call should reflect it.
|
|
await engine.insertFact(
|
|
{ fact: 'sess-A fact 2', kind: 'fact', entity_slug: 'multi-sess', visibility: 'world', source: 'test', source_session: 'sess-A' },
|
|
{ source_id: 'default' },
|
|
);
|
|
await engine.insertFact(
|
|
{ fact: 'sess-B fact 2', kind: 'fact', entity_slug: 'multi-sess', visibility: 'world', source: 'test', source_session: 'sess-B' },
|
|
{ source_id: 'default' },
|
|
);
|
|
const a2 = await getBrainHotMemoryMeta('get_stats', ctxA);
|
|
const b2 = await getBrainHotMemoryMeta('get_stats', ctxB);
|
|
const a2Count = (a2?.brain_hot_memory as { facts: unknown[] } | undefined)?.facts.length ?? 0;
|
|
const b2Count = (b2?.brain_hot_memory as { facts: unknown[] } | undefined)?.facts.length ?? 0;
|
|
|
|
expect(a2Count).toBeGreaterThanOrEqual(a1Count);
|
|
// sess-B's cache wasn't bumped → returns cached count, NOT the new
|
|
// fact-2 row.
|
|
expect(b2Count).toBe(b1Count);
|
|
});
|
|
|
|
test('skipped on facts-self ops (recall, extract_facts, forget_fact)', async () => {
|
|
expect(await getBrainHotMemoryMeta('recall', ctx())).toBeUndefined();
|
|
expect(await getBrainHotMemoryMeta('extract_facts', ctx())).toBeUndefined();
|
|
expect(await getBrainHotMemoryMeta('forget_fact', ctx())).toBeUndefined();
|
|
});
|
|
|
|
test('different allow-lists produce distinct cache entries', async () => {
|
|
await engine.insertFact(
|
|
{ fact: 'alpha fact for cache', kind: 'fact', entity_slug: 'allow-cache', visibility: 'world', source: 'test' },
|
|
{ source_id: 'default' },
|
|
);
|
|
const ctxNoList = ctx();
|
|
const ctxWithList = ctx({ takesHoldersAllowList: ['world', 'self'] });
|
|
const r1 = await getBrainHotMemoryMeta('get_stats', ctxNoList);
|
|
const r2 = await getBrainHotMemoryMeta('get_stats', ctxWithList);
|
|
// Both compute their own entries — neither should error, both have
|
|
// the same world-visible fact in this hermetic case.
|
|
expect(r1?.brain_hot_memory).toBeDefined();
|
|
expect(r2?.brain_hot_memory).toBeDefined();
|
|
});
|
|
|
|
test('[] (explicit deny-all) and undefined allow-lists do NOT share a cache entry (#2529)', async () => {
|
|
// Isolated source so topK saturation from other tests can't mask the
|
|
// count difference this test keys on.
|
|
const src = 'deny-key-src';
|
|
await engine.executeRaw(
|
|
`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{}'::jsonb) ON CONFLICT (id) DO NOTHING`,
|
|
[src],
|
|
);
|
|
await engine.insertFact(
|
|
{ fact: 'deny-key seed fact', kind: 'fact', entity_slug: 'deny-key', visibility: 'world', source: 'test' },
|
|
{ source_id: src },
|
|
);
|
|
// Warm the cache under the UNSET allow-list key.
|
|
const unset = await getBrainHotMemoryMeta('get_stats', ctx({ sourceId: src }));
|
|
const unsetCount = (unset?.brain_hot_memory as { facts: unknown[] } | undefined)?.facts.length ?? 0;
|
|
expect(unsetCount).toBeGreaterThan(0);
|
|
|
|
// New fact lands AFTER the warm — a shared cache key would serve the
|
|
// stale (pre-insert) payload to the [] caller. Pre-fix, hashAllowList
|
|
// collapsed both to '_' and this returned unsetCount.
|
|
await engine.insertFact(
|
|
{ fact: 'deny-key post-warm fact', kind: 'fact', entity_slug: 'deny-key', visibility: 'world', source: 'test' },
|
|
{ source_id: src },
|
|
);
|
|
const emptyList = await getBrainHotMemoryMeta('get_stats', ctx({ sourceId: src, takesHoldersAllowList: [] }));
|
|
const emptyCount = (emptyList?.brain_hot_memory as { facts: unknown[] } | undefined)?.facts.length ?? 0;
|
|
expect(emptyCount).toBeGreaterThan(unsetCount);
|
|
});
|
|
});
|