Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Refuse a re-created links section before its rows can name a page the writer can't see (GST-2228)

garrytanb366c9720d11
diff --git a/src/core/persistence/manual-links.ts b/src/core/persistence/manual-links.ts
index 42964b6d61..360d0a0086 100644
--- a/src/core/persistence/manual-links.ts
+++ b/src/core/persistence/manual-links.ts
@@ -13,7 +13,7 @@ import { linksFenceProjectionRows, projectLinksFence } from '../links-fence-proj
import { removeManualTransitions } from '../link-temporal-apply.ts';
import { refreshRelationships, type RelationshipKey } from '../link-relationships.ts';
import { executeRawJsonb } from '../sql-query.ts';
-import { authorizePageVisibility } from './page-visibility.ts';
+import { authorizePageVisibility, pageNotVisibleError } from './page-visibility.ts';
const optional = (value: unknown) => typeof value === 'string' && value ? value : undefined;
@@ -97,8 +97,9 @@ async function assertRemovalAttributable(engine: BrainEngine, pageId: number, re
* The publication projects the fence (canonical-projections.ts) and the apply projects it once more, so a fence
* the write left unchanged (an idempotent add) still has its edges. `add_link` drops the database-only twin of
* the edge it fences (same endpoints, type and provenance, no origin); on a page with no links fence, the section it
- * creates lists the edges a dropped section left first, each with its own dates (`keptLinksFenceRows`), and a remote
- * writer that cannot read one of their targets gets the same page_not_found as for a missing page. `remove_link`
+ * creates lists the edges a dropped section left first, each with its own dates (`keptLinksFenceRows`). Before any of
+ * that is read, a remote writer is checked against every target those edges name: one it cannot read, or a deleted
+ * one, refuses with the same slug-free page_not_found as for a missing page. `remove_link`
* deletes the removed rows' own dated statements, whatever their source, and also the matching database-only edges
* written before the fence existed, with their manual dated statements, so a removal only moves the database toward
* git; edges a reconciliation producer derives from the page text stay, and the result names them
@@ -115,8 +116,15 @@ export async function prepareManualLinkMutation(engine: BrainEngine, row: WriteR
const validFrom = optional(p.valid_from), validUntil = optional(p.valid_until);
const pageId = Number(stored.page.id);
const absent = readPageLinksFence(snapshot.page).state === 'absent';
+ if (row.operation === 'add_link' && absent && row.authority.remote) {
+ const targets = await engine.executeRaw<{ slug: string; deleted: boolean }>(`SELECT DISTINCT t.slug, t.deleted_at IS NOT NULL AS deleted
+ FROM links l JOIN pages t ON t.id=l.to_page_id WHERE l.from_page_id=$1 AND l.origin_page_id=$1 AND l.origin_field=$2`, [pageId, LINKS_FENCE_ORIGIN_FIELD]);
+ for (const target of targets) {
+ if (target.deleted) throw pageNotVisibleError();
+ await authorizePageVisibility(engine, row.authority, target.slug);
+ }
+ }
const kept = row.operation === 'add_link' && absent ? await keptLinksFenceRows(engine, pageId) : [];
- for (const keptRow of kept) await authorizePageVisibility(engine, row.authority, keptRow.to);
if (row.operation === 'remove_link' && absent) await assertRemovalAttributable(engine, pageId, { to, linkType, linkSource });
const current = kept.length ? replaceOrInsertLinksFence(snapshot.page[section] ?? '', renderLinksFence(kept)) : snapshot.page[section] ?? '';
let body: string;
diff --git a/test/link-dates-per-row-gst2228.test.ts b/test/link-dates-per-row-gst2228.test.ts
index cccc536802..23eb0c1c5a 100644
--- a/test/link-dates-per-row-gst2228.test.ts
+++ b/test/link-dates-per-row-gst2228.test.ts
@@ -164,6 +164,41 @@ for (const backend of testBackends()) {
expect(await pageRows(engine)).toEqual(sortRows([hidden, BETA]));
}, opts), 180_000);
+ test('a remote writer refused for a kept row\'s target learns nothing: the refusal names no slug or row count and matches the one for a deleted target', async () => {
+ const target = 'companies/hidden-example';
+ const rows: LinksFenceRow[] = [
+ { to: target, type: 'works_at', source: 'manual', validFrom: '2020-01-01', context: 'first stint' },
+ { to: target, type: 'works_at', source: 'crm-import', validFrom: '2022-01-01', context: 'second stint' },
+ ];
+ const requestId = randomUUID();
+ const refusal = async (kind: 'private' | 'deleted') => {
+ let seen: Record<string, unknown> | undefined;
+ await managedBrain(async ({ engine, ctx }) => {
+ await seed(ctx);
+ await put(ctx, target, `---\ntype: company\ntitle: Hidden Example\n${kind === 'private' ? 'visibility: private\n' : ''}---\n\n# Hidden Example\n\nA company.\n`);
+ await put(ctx, ALICE, PERSON(`Alice v1.\n\n${SECTION(rows)}`));
+ await put(ctx, ALICE, PERSON(DROPPED));
+ await forgetSources(engine);
+ if (kind === 'deleted') await op(ctx, 'delete_page', { slug: target, expected_revision: (await engine.readPageSnapshot(target, { sourceId: 'default' }))!.revision });
+ const before = { revision: await revision(engine), statements: await statements(engine), edges: await edges(engine) };
+ expect(before.edges).toEqual([`${target} crm-import`, `${target} manual`]);
+ const clientId = 'client-fixture';
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id) VALUES($1,'fixture-hash','example-client','read write','default')`, [clientId]);
+ const remote = { ...ctx, remote: true, transport: 'http', auth: { token: 'fixture', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'write'], sourceId: 'default' } } as OperationContext;
+ const error = await op(remote, 'add_link', { request_id: requestId, from: ALICE, to: BETA.to, link_type: BETA.type, context: BETA.context })
+ .then(() => null, (thrown: unknown) => thrown as Record<string, unknown>);
+ expect(error).not.toBeNull();
+ seen = Object.fromEntries(Object.getOwnPropertyNames(error).filter(key => key !== 'stack').sort().map(key => [key, error![key]]));
+ expect({ revision: await revision(engine), statements: await statements(engine), edges: await edges(engine) }).toEqual(before);
+ }, opts);
+ return JSON.stringify(seen).replace(/"(created_at|updated_at)":"[^"]*"/g, '"$1":"<time>"');
+ };
+ const hidden = await refusal('private');
+ expect({ code: JSON.parse(hidden).code, slug: hidden.includes(target) || hidden.includes('hidden-example'), rowCount: /\d+ rows?\b/.test(hidden) })
+ .toEqual({ code: 'page_not_found', slug: false, rowCount: false });
+ expect(hidden).toBe(await refusal('deleted'));
+ }, 360_000);
+
test('statements from before the source column, one kept row: add_link puts them on that row and labels them with its source', () => managedBrain(async ({ engine, ctx, root }) => {
await seed(ctx);
await put(ctx, ALICE, PERSON(`Alice v1.\n\n${SECTION([FIRST_STINT])}`));