Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Legacy-token writes still replay on a schema behind the build (GST-2314)

garrytane612eca1ae23
diff --git a/src/core/grants/model.ts b/src/core/grants/model.ts
index bdacf4c220..6697882b9e 100644
--- a/src/core/grants/model.ts
+++ b/src/core/grants/model.ts
@@ -397,5 +397,14 @@ export const TOKEN_GRANT_COLUMNS = ['source_grant', 'source_id', 'federated_read
* fails there with 0A000 ("cached plan must not change result type") until the connection re-prepares it.
*/
export const TOKEN_GRANT_ROW_COLUMNS = ['id', 'scopes', 'permissions', 'private_pages', 'grant_revision', ...TOKEN_GRANT_COLUMNS] as const;
-export const TOKEN_GRANT_ROW_SELECT = TOKEN_GRANT_ROW_COLUMNS.join(',');
+/**
+ * The select list of `TOKEN_GRANT_ROW_COLUMNS` that this brain's access_tokens has. Admission authorizes before it
+ * replays an accepted request or refuses a schema behind this build, and membership has no schema admission, so a
+ * column a pending migration adds reads as absent, as it did under SELECT *.
+ */
+export async function tokenGrantRowSelect(engine: { executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> }): Promise<string> {
+ const present = new Set((await engine.executeRaw<{ attname: string }>(
+ "SELECT attname FROM pg_attribute WHERE attrelid=to_regclass('access_tokens') AND attnum>0 AND NOT attisdropped")).map(c => c.attname));
+ return TOKEN_GRANT_ROW_COLUMNS.filter(c => present.has(c)).join(',');
+}
export type TokenGrantRow = Partial<Record<(typeof TOKEN_GRANT_ROW_COLUMNS)[number], unknown>>;
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index 47b5da3758..6150221e0c 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -6,7 +6,7 @@ import { slugUnderBoundPrefixes, matchesSlugAllowList, noSourceGrantError } from
import { NO_SOURCES } from '../source-id.ts';
import { hasScope } from '../scope.ts';
import { normalizeTokenScopes } from '../legacy-token-scope.ts';
-import { authSourcesFromGrant, grantFromTokenRow, TOKEN_GRANT_ROW_SELECT, type TokenGrantRow } from '../grants/model.ts';
+import { authSourcesFromGrant, grantFromTokenRow, tokenGrantRowSelect, type TokenGrantRow } from '../grants/model.ts';
import { readLocalWriter, currentVerifiedLocalWriter, takeRegisteredWriterRow, verifyLocalWriter, type LocalGrant } from './identity.ts';
import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';
import { authorizePageVisibility, excludesPrivateWritesAtAdmission } from './page-visibility.ts';
@@ -181,7 +181,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
}
if (a.principal.kind === 'legacy_token') {
// GST-2314: named columns, not SELECT *: inside this transaction a plan cached before a migration added a column fails 0A000.
- const [row] = await engine.executeRaw<TokenGrantRow & { revoked_at: unknown }>(`SELECT ${TOKEN_GRANT_ROW_SELECT},revoked_at FROM access_tokens WHERE id=$1${suffix}`, [a.principal.id]);
+ const [row] = await engine.executeRaw<TokenGrantRow & { revoked_at: unknown }>(`SELECT ${await tokenGrantRowSelect(engine)},revoked_at FROM access_tokens WHERE id=$1${suffix}`, [a.principal.id]);
if (!row || row.revoked_at != null) deny('The owning token is revoked.');
const grant = grantFromTokenRow(row);
if (grant.permissionsMalformed) deny('The current legacy grant is malformed.');
diff --git a/src/core/shared-skills/membership-authority.ts b/src/core/shared-skills/membership-authority.ts
index bdd6d8db02..a946edc467 100644
--- a/src/core/shared-skills/membership-authority.ts
+++ b/src/core/shared-skills/membership-authority.ts
@@ -4,7 +4,7 @@ import { sourceScopeOpts } from '../ops/context.ts';
import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, type LocalGrant } from '../persistence/identity.ts';
import type { Principal } from '../persistence/model.ts';
import { normalizeTokenScopes } from '../legacy-token-scope.ts';
-import { authSourcesFromGrant, grantFromTokenRow, TOKEN_GRANT_ROW_COLUMNS, type TokenGrantRow } from '../grants/model.ts';
+import { authSourcesFromGrant, grantFromTokenRow, tokenGrantRowSelect, type TokenGrantRow } from '../grants/model.ts';
import { hasScope } from '../scope.ts';
const deny = (): never => {
@@ -31,11 +31,7 @@ export async function memberAuthority(ctx: OperationContext, operation: string):
grant = row;
} else {
// GST-2314: named columns, not SELECT *: inside this transaction a plan cached before a migration added a column fails 0A000.
- // No schema admission guards membership, so a schema behind this build reads the columns it has, as SELECT * did.
- const present = new Set((await ctx.engine.executeRaw<{ attname: string }>(
- "SELECT attname FROM pg_attribute WHERE attrelid=to_regclass('access_tokens') AND attnum>0 AND NOT attisdropped")).map(c => c.attname));
- const columns = TOKEN_GRANT_ROW_COLUMNS.filter(c => present.has(c)).join(',');
- const [row] = await ctx.engine.executeRaw<TokenGrantRow>(`SELECT ${columns} FROM access_tokens WHERE id=$1 AND revoked_at IS NULL FOR SHARE`, [principal.id]);
+ const [row] = await ctx.engine.executeRaw<TokenGrantRow>(`SELECT ${await tokenGrantRowSelect(ctx.engine)} FROM access_tokens WHERE id=$1 AND revoked_at IS NULL FOR SHARE`, [principal.id]);
if (!row) deny();
const scopes = normalizeTokenScopes(row.scopes) ?? [];
const tokenGrant = grantFromTokenRow(row);
diff --git a/test/access-token-grant-columns.test.ts b/test/access-token-grant-columns.test.ts
index 2199eec196..57a612f90a 100644
--- a/test/access-token-grant-columns.test.ts
+++ b/test/access-token-grant-columns.test.ts
@@ -8,7 +8,8 @@
* pooled connection before and after `ALTER TABLE access_tokens ADD COLUMN`, succeed; so does a
* legacy-token put_page after the column is added.
* 2. Fails when: either read selects every column of access_tokens inside its transaction, or the membership read
- * (which no schema admission guards) names a column a schema behind this build does not have.
+ * (which no schema admission guards) or the publication read (which admission runs before it replays an accepted
+ * request or refuses a schema behind this build) names a column that schema does not have.
* 3. Real seams: the token service, the serve --http token verifier, MCP dispatch and the durable write path.
* Each read runs in POOL concurrent transactions held open together, so every pooled connection prepares it
* first and every one reuses its cached plan after the column is added.
@@ -88,6 +89,43 @@ for (const kind of testBackends()) {
expect(principal).toEqual({ kind: 'legacy_token', id: minted.id });
}, 240_000);
+ test('the publication authority read works on a schema that predates an access_tokens column it names', async () => {
+ const minted = await mintLegacyToken(engine, { name: 'behind-writer', scopes: ['read', 'write'], takesHolders: ['world'] });
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const authority: WriteAuthority = { version: 1, principal: { kind: 'legacy_token', id: minted.id }, remote: true, sourceId: 'default',
+ sourceIncarnation: source.incarnation, scopes: ['read', 'write'], operations: null, slugPrefixes: null, takesHolders: ['world'] };
+ const rollback = new Error('roll back the simulated older schema');
+ await engine.transaction(async tx => {
+ await tx.executeRaw('ALTER TABLE access_tokens DROP COLUMN private_pages');
+ await authorizeWrite(tx, authority, 'put_page', 'notes/behind-schema', true);
+ throw rollback;
+ }).catch(error => { if (error !== rollback) throw error; });
+ }, 240_000);
+
+ test('on a schema behind the build, an accepted legacy-token write replays and a new one is refused migrations_pending', async () => {
+ const minted = await mintLegacyToken(engine, { name: 'replayer', scopes: ['read', 'write'], takesHolders: ['world'] });
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const put = async (slug: string, requestId: string) => {
+ const auth = await provider.verifyAccessToken(minted.token) as unknown as AuthInfo;
+ const out = await dispatchToolCall(engine, 'put_page', { slug, content: note(slug), request_id: requestId },
+ { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] });
+ const text = out.content.map(c => c.text).join('\n');
+ return out.isError === true ? String(JSON.parse(text).code) : String(JSON.parse(text).state ?? 'ok');
+ };
+ const accepted = randomUUID();
+ expect(await put('notes/replayed', accepted)).not.toMatch(/error|denied|pending_/);
+ const [version] = await engine.executeRaw<{ value: string }>("SELECT value FROM config WHERE key='version'");
+ await engine.executeRaw('ALTER TABLE access_tokens DROP COLUMN private_pages');
+ await engine.executeRaw("UPDATE config SET value='279' WHERE key='version'");
+ try {
+ expect(await put('notes/replayed', accepted)).toBe('committed');
+ expect(await put('notes/not-admitted', randomUUID())).toBe('migrations_pending');
+ } finally {
+ await engine.executeRaw("ALTER TABLE access_tokens ADD COLUMN private_pages TEXT NOT NULL DEFAULT 'none' CHECK (private_pages IN ('none', 'granted_sources'))");
+ await engine.executeRaw("UPDATE config SET value=$1 WHERE key='version'", [version.value]);
+ }
+ }, 240_000);
+
test('a legacy-token put_page after the column is added publishes', async () => {
const minted = await mintLegacyToken(engine, { name: 'writer', scopes: ['read', 'write'], takesHolders: ['world'] });
const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });