Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(grants): rotation names the uncarried private-pages grant; get_versions hides marked versions from a granted token (#8104)

garrytanc9c920c1a6ed
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 574b81c14f..54e34db1b4 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -74,7 +74,7 @@ import {
redactToken,
validateToken,
} from '../mcp-registration.ts';
-import { carryLegacyGrant, mintLegacyToken, readActiveTokenPermissions, revokeLegacyTokenById, type MintedLegacyToken } from '../token-mint.ts';
+import { carryLegacyGrant, mintLegacyToken, readActiveTokenPermissions, readActiveTokenPrivatePages, revokeLegacyTokenById, uncarriedPrivatePagesNote, type MintedLegacyToken } from '../token-mint.ts';
import { generateToken } from '../utils.ts';
import { readCredentials, writeCredentials, type HarnessCredentials } from '../harness/credentials.ts';
import { installSharedSkillsConnection, type SharedSkillsConnectionOptions } from '../harness/shared-skills.ts';
@@ -492,19 +492,20 @@ export async function mintHarnessToken(opts: Parameters<NonNullable<HarnessDeps[
}
}
const prior = opts.carry && await readActiveTokenPermissions(engine, opts.carry.fromId);
+ const uncarried = opts.carry && prior !== undefined && await readActiveTokenPrivatePages(engine, opts.carry.fromId) === 'granted_sources' ? { uncarriedPrivatePages: 'granted_sources' as const } : {};
if (prior !== undefined && opts.carry && opts.allowedOperations) {
const carried = carryLegacyGrant(prior, { ...opts.carry, allowedOperations: opts.allowedOperations,
...(sourceGrant && sourceGrant.length > 0 ? { sourceGrant } : {}) });
const minted = await mintLegacyToken(engine, { name: opts.name, scopes: opts.scopes, ...carried });
- return { ...minted, withheldOperations: carried.withheldOperations };
+ return { ...minted, withheldOperations: carried.withheldOperations, ...uncarried };
}
- return await mintLegacyToken(engine, {
+ return { ...await mintLegacyToken(engine, {
name: opts.name,
takesHolders: ['world'],
scopes: opts.scopes,
...(opts.allowedOperations !== undefined ? { allowedOperations: opts.allowedOperations } : {}),
...(sourceGrant && sourceGrant.length > 0 ? { sourceGrant } : {}),
- });
+ }), ...uncarried };
} finally {
await engine.disconnect();
}
@@ -1295,6 +1296,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
}
tokens.set(host, minted.token);
if (minted.withheldOperations?.length) d.log(withheldOperationsNote(minted.name, minted.withheldOperations.length));
+ if (minted.uncarriedPrivatePages) d.log(uncarriedPrivatePagesNote(minted.name, minted.uncarriedPrivatePages));
receipt.harness_tokens![host] = { id: minted.id, name: minted.name, minted: true };
if (host === hosts[0]) {
receipt.token.id = minted.id;
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 5d63fbe41f..a2b6126ffa 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -22,7 +22,7 @@ import { moveSlugBindings, recordRenameAlias } from '../page-state/rename-alias.
import { segmentedRevertRefusal } from '../page-state/versions.ts';
import { sanitizeText } from '../batch-rows.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';
-import { privatePagesFilterFragment, privateSnapshotFilterFragment, privatePagesFilterForCaller, privacyForCaller, callerReadersAllowedSql } from '../search/private-visibility.ts';
+import { privatePagesFilterFragment, privateSnapshotFilterFragment, privatePagesFilterForCaller, privacyForCaller, callerReadersAllowedSql, currentCallerAccess } from '../search/private-visibility.ts';
import { validDateSql } from '../valid-time.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
import { rederiveHiddenSql } from '../eligibility/sql.ts';
@@ -1030,7 +1030,7 @@ export async function getVersions<B extends boolean = true>(
opts?: GetVersionsOpts<B>,
): Promise<PageVersionRows<B>> {
const privacy = opts?.excludePrivate
- ? trustedSql(`AND ${privatePagesFilterForCaller('p')} AND ${callerReadersAllowedSql('pv', 'snapshot')} AND ${privacyForCaller('p', privateSnapshotFilterFragment('pv'))}`) : sqlFragment``;
+ ? trustedSql(`AND ${privatePagesFilterForCaller('p')} AND ${callerReadersAllowedSql('pv', 'snapshot')} AND ${privacyForCaller('p', privateSnapshotFilterFragment('pv'))}${currentCallerAccess().hidePrivate ? " AND NOT COALESCE(pv.frontmatter ? 'pinned_question', false)" : ''}`) : sqlFragment``;
const scope = opts?.sourceIds && opts.sourceIds.length > 0
? sqlFragment`AND p.source_id = ANY(${opts.sourceIds}::text[])`
: opts?.sourceId ? sqlFragment`AND p.source_id = ${opts.sourceId}` : sqlFragment``;
diff --git a/src/core/token-mint.ts b/src/core/token-mint.ts
index 7d3723c64d..d8e6f7206f 100644
--- a/src/core/token-mint.ts
+++ b/src/core/token-mint.ts
@@ -21,7 +21,7 @@ import { ALLOWED_SCOPES_LIST, assertAllowedScopes } from './scope.ts';
import type { SqlQuery } from './sql-query.ts';
import { opError } from './ops/contract.ts';
import { generateToken, hashToken, isUndefinedColumnError } from './utils.ts';
-import { permissionsMirror, tokenGrantColumnValues, tokenGrantFromPermissions, TOKEN_GRANT_COLUMNS, type GrantSources, type PrincipalGrant } from './grants/model.ts';
+import { permissionsMirror, privatePagesFromColumn, tokenGrantColumnValues, tokenGrantFromPermissions, TOKEN_GRANT_COLUMNS, type GrantSources, type PrincipalGrant, type PrivatePagesGrant } from './grants/model.ts';
/** Canonical token-id shape — shared with the `auth revoke --id` CLI gate. */
export const TOKEN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -50,6 +50,8 @@ export interface MintedLegacyToken {
scopes: string[];
/** Rotation only: operations this run would grant that the carried snapshot withheld. */
withheldOperations?: string[];
+ /** Rotation only (#8104): the replaced token's private-pages grant, which a rotation never carries. */
+ uncarriedPrivatePages?: Exclude<PrivatePagesGrant, 'none'>;
}
/**
@@ -185,6 +187,27 @@ export function carryLegacyGrant(priorRaw: unknown, fresh: {
withheldOperations: fresh.allowedOperations.filter(op => !allowedOperations.includes(op)) };
}
+/**
+ * #8104: an active token's private-pages grant. Rotation does not carry it (the replacement starts at `none`), so the
+ * harness names the rescope that grants it again. `none` when the token is gone or the brain predates the column.
+ */
+export async function readActiveTokenPrivatePages(engine: BrainEngine, id: string): Promise<PrivatePagesGrant> {
+ if (!TOKEN_ID_RE.test(id)) return 'none';
+ try {
+ const [row] = await engine.executeRaw<{ private_pages: unknown }>(
+ 'SELECT private_pages FROM access_tokens WHERE id = $1::uuid AND revoked_at IS NULL', [id]);
+ return privatePagesFromColumn(row?.private_pages);
+ } catch (e) {
+ if (isUndefinedColumnError(e, 'private_pages')) return 'none';
+ throw e;
+ }
+}
+
+/** #8104: the note a rotation prints beside the withheld-operations note when the replaced token had a private-pages grant. */
+export function uncarriedPrivatePagesNote(name: string, mode: Exclude<PrivatePagesGrant, 'none'>): string {
+ return `token ${name}: private-pages grant not carried; run \`gbrain auth rescope --token ${name} --private-pages ${mode.replace('_', '-')}\` to grant it again.`;
+}
+
/** The stored grant of an active token, or undefined when it is gone or revoked. */
export async function readActiveTokenPermissions(engine: BrainEngine, id: string): Promise<unknown> {
if (!TOKEN_ID_RE.test(id)) return undefined;
diff --git a/test/harness-rotation-grants.test.ts b/test/harness-rotation-grants.test.ts
index a0e0b582ad..2c5f8bca6a 100644
--- a/test/harness-rotation-grants.test.ts
+++ b/test/harness-rotation-grants.test.ts
@@ -17,7 +17,7 @@ import { join } from 'node:path';
import { createEngine } from '../src/core/engine-factory.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { mintHarnessToken } from '../src/core/bootstrap/harness.ts';
-import { carryLegacyGrant, mintLegacyToken } from '../src/core/token-mint.ts';
+import { carryLegacyGrant, mintLegacyToken, readActiveTokenPrivatePages, uncarriedPrivatePagesNote } from '../src/core/token-mint.ts';
import { executeRawJsonb } from '../src/core/sql-query.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -81,3 +81,34 @@ test('carry rules: an explicit --source wins; policy changes add only their own
.toEqual({ takesHolders: ['world'], sourceGrant: ['team-a'], allowedOperations: ['get_page', 'join_brain'], withheldOperations: [] });
expect(carryLegacyGrant({ allowed_operations: [] }, { ...fresh, explicitSource: false }).allowedOperations).toEqual([]);
});
+
+// Value: protects=#8104: a rotated harness token never inherits the replaced token's private-pages grant (it starts at none), and the
+// rotation reports the rescope that grants it again; a prior token without the grant reports nothing; fails_when=rotation drops the
+// grant silently (no uncarriedPrivatePages) or carries it onto the new row; why_new=carryLegacyGrant reads only the permissions mirror,
+// which has no private_pages; seam=none (the production mint on a sandboxed PGLite brain); no_claim=the harness log line's placement
+test('rotation does not carry a private-pages grant and names the rescope that grants it again', async () => {
+ const privatePagesOf = (id: string) => withBrain(async engine => (await engine.executeRaw<{ private_pages: string }>(
+ 'SELECT private_pages FROM access_tokens WHERE id = $1::uuid', [id]))[0]!.private_pages);
+ const rotate = async (grant: 'granted_sources' | 'none') => {
+ const prior = await withBrain(async engine => {
+ const minted = await mintLegacyToken(engine, { name: 'bootstrap-harness', takesHolders: ['world'], scopes: ['read', 'write'], allowedOperations: ['get_page'] });
+ await engine.executeRaw('UPDATE access_tokens SET private_pages = $2 WHERE id = $1::uuid', [minted.id, grant]);
+ return minted;
+ });
+ return withEnv(env(), () => mintHarnessToken({ name: 'bootstrap-harness', scopes: ['read', 'write'],
+ allowedOperations: ['get_page'], carry: { fromId: prior.id, explicitSource: false, policyAdded: [] } }));
+ };
+ const granted = await rotate('granted_sources');
+ expect(granted.uncarriedPrivatePages).toBe('granted_sources');
+ expect(await privatePagesOf(granted.id)).toBe('none');
+ expect(uncarriedPrivatePagesNote(granted.name, granted.uncarriedPrivatePages!))
+ .toBe('token bootstrap-harness: private-pages grant not carried; run `gbrain auth rescope --token bootstrap-harness --private-pages granted-sources` to grant it again.');
+ const plain = await rotate('none');
+ expect(plain.uncarriedPrivatePages).toBeUndefined();
+ expect(await privatePagesOf(plain.id)).toBe('none');
+ // Last in the file: a brain whose schema predates the column reads every token as none.
+ expect(await withBrain(async engine => {
+ await engine.executeRaw('ALTER TABLE access_tokens DROP COLUMN private_pages');
+ return readActiveTokenPrivatePages(engine, granted.id);
+ })).toBe('none');
+}, 120_000);