Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(access): who-can-read accounts for folder rules
garrytandc2a2f661be6
diff --git a/src/commands/access.ts b/src/commands/access.tsindex 12db4eeeae..fb949871d2 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -19,8 +19,9 @@ import { sqlQueryForEngine } from '../core/sql-query.ts';import { grantFromClient, type PrincipalGrant } from '../core/grants/model.ts';import { readClientGrant } from '../core/grants/service.ts';import { resolveTokenGrant } from '../core/grants/legacy-token.ts';-import { isPrivacyPrivatePage } from '../core/search/private-visibility.ts';-import { identityFor, normalizePrincipal, normalizeReaders, readersAllow } from '../core/access/principals.ts';+import { accessAllowedSql, isPrivacyPrivatePage, withCallerAccess } from '../core/search/private-visibility.ts';+import { folderAccessFor } from '../core/access/caller.ts';+import { identityFor, normalizePrincipal, normalizeReaders } from '../core/access/principals.ts';import { mayActForCovers, singleMemberAudience, type AudiencePrincipal } from '../core/access/audience.ts';import { linkMember, listMemberLinks, unlinkMember } from '../core/access/actor.ts';import {@@ -105,27 +106,40 @@ export interface WhoCanReadEntry {/** Who may read `slug` remotely: its normalized readers, privacy and the enabled members those readers admit. */export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: string): Promise<WhoCanReadEntry[]> {- const rows = await engine.executeRaw<{ slug: string; source_id: string; type: string | null; frontmatter: unknown }>(- `SELECT slug, source_id, type, frontmatter FROM pages WHERE slug = $1${sourceId ? ' AND source_id = $2' : ''} ORDER BY source_id`,+ const rows = await engine.executeRaw<{ slug: string; source_id: string; type: string | null; frontmatter: unknown; folder_rule_ids: string[] | null }>(+ `SELECT slug, source_id, type, frontmatter, folder_rule_ids FROM pages WHERE slug = $1${sourceId ? ' AND source_id = $2' : ''} ORDER BY source_id`,sourceId ? [slug, sourceId] : [slug]);if (!rows.length) {throw opError('not_found', `No page "${slug}"${sourceId ? ` in source ${sourceId}` : ''}.`, 'Check the slug with gbrain list or gbrain search.');}const members = (await listMembers(engine)).filter(m => m.status === 'enabled');- return rows.map(row => {+ const entries: WhoCanReadEntry[] = [];+ for (const row of rows) {const fm = typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter;const readers = normalizeReaders(fm);const priv = isPrivacyPrivatePage({ type: row.type, frontmatter: fm });- const allowed = readers === null ? 'every_source_reader' as const : members.filter(m => readersAllow(fm, identityFor(m.id, m.groups))).map(m => m.id);+ const ruled = (row.folder_rule_ids?.length ?? 0) > 0;+ const allowed: string[] = [];+ if (readers !== null || ruled) {+ for (const m of members) {+ const identity = identityFor(m.id, m.groups);+ const folder = await folderAccessFor(engine, identity);+ const admitted = await withCallerAccess({ identity, ...folder, restricted: true }, () => engine.executeRaw(+ `SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND ${accessAllowedSql('p', identity)}`, [row.source_id, row.slug]));+ if (admitted.length) allowed.push(m.id);+ }+ }const notes = [- readers === null ? 'No readable_by: every caller entitled to the source reads it.'+ readers === null ? (ruled ? 'No readable_by, but folder rules cover it: only members who meet every rule read it remotely.' : 'No readable_by: every caller entitled to the source reads it.'): readers.includes('!nobody') ? 'readable_by is malformed, so no remote caller reads it; fix the frontmatter.': 'Only credentials bound to these members (directly or through a group) read it remotely; unbound credentials and stdio do not.',+ ...(readers !== null && ruled ? ['Folder rules cover it too: a member must meet readable_by and every rule.'] : []),...(priv ? ['visibility: private also applies: a member still needs private_pages: granted_sources on this source.'] : []),'Derived pages (atoms, facts, chronicle events) of a page that names readers are hidden from every remote caller.',];- return { slug: row.slug, source_id: row.source_id, readers, private: priv, members: allowed, note: notes.join(' ') };- });+ entries.push({ slug: row.slug, source_id: row.source_id, readers, private: priv, members: readers === null && !ruled ? 'every_source_reader' : allowed, note: notes.join(' ') });+ }+ return entries;}export interface AccessCheckResult {@@ -299,7 +313,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<voconst pages = await whoCanRead(engine, slug, flagValue(rest, '--source'));return print(json, { pages }, () => pages.flatMap(p => [`${p.source_id}:${p.slug}`,- ` Readers: ${p.readers === null ? 'not restricted' : p.readers.join(', ')}${p.private ? ' (visibility: private)' : ''}`,+ ` Readers: ${p.readers === null ? 'no readable_by' : p.readers.join(', ')}${p.private ? ' (visibility: private)' : ''}`,` Members who may read it: ${p.members === 'every_source_reader' ? 'every caller entitled to the source' : p.members.join(', ') || 'none'}`,` ${p.note}`]));}diff --git a/test/access-who-can-read-folder-rules.test.ts b/test/access-who-can-read-folder-rules.test.tsnew file mode 100644index 0000000000..c930a4e43a--- /dev/null+++ b/test/access-who-can-read-folder-rules.test.ts@@ -0,0 +1,51 @@+/**+ * #8740: gbrain access who-can-read accounts for folder rules.+ *+ * 1. Protects: who-can-read names the members the remote read path admits for a page a folder rule covers, instead+ * of reporting it readable by every caller entitled to the source.+ * 2. Fails when: who-can-read derives its answer from readable_by alone, so a page restricted only by a folder rule+ * prints "not restricted" while remote reads enforce the rule.+ * 3. Existing coverage: access-members pins readable_by pages; access-folder-rules pins the read path.+ * 4. Real seams: PGLite, real members, groups and an applied folder rule; repo-less brain.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { whoCanRead } from '../src/commands/access.ts';+import { addGroup, addMember } from '../src/core/access/members.ts';+import { proposeRevision } from '../src/core/access/policy.ts';++const SRC = 'source-a';+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [SRC]);+ for (const id of ['alice-example', 'bob-example', 'carol-example']) await addMember(engine, id);+ await addGroup(engine, 'team-b', ['bob-example']);+ const result = await proposeRevision(engine, SRC, [{ id: 'team-b-only', prefix: 'team-b/', readable_by: ['group:team-b', 'member:carol-example'] }], { origin: 'cli' });+ expect(result.state).toBe('applied');+ await engine.putPage('team-b/profile', { type: 'note', title: 'Team B profile', compiled_truth: 'Team notes.' }, { sourceId: SRC });+ await engine.putPage('team-b/alice-note', { type: 'note', title: 'Alice note', compiled_truth: 'Notes.', frontmatter: { readable_by: ['alice-example', 'bob-example'] } }, { sourceId: SRC });+ await engine.putPage('open/profile', { type: 'note', title: 'Open profile', compiled_truth: 'Open notes.' }, { sourceId: SRC });+}, 60_000);++afterAll(async () => { await engine.disconnect(); });++describe('#8740 who-can-read and folder rules', () => {+ test('a page covered only by a folder rule lists the members the rule admits', async () => {+ const [entry] = await whoCanRead(engine, 'team-b/profile', SRC);+ expect(entry.members).toEqual(['bob-example', 'carol-example']);+ });++ test('readable_by and a folder rule must both pass', async () => {+ const [entry] = await whoCanRead(engine, 'team-b/alice-note', SRC);+ expect(entry.members).toEqual(['bob-example']);+ });++ test('a page under no rule and no readers stays open to every source reader', async () => {+ const [entry] = await whoCanRead(engine, 'open/profile', SRC);+ expect(entry.members).toBe('every_source_reader');+ });+});