Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(oauth): migration clamps stored client token lifetimes and outstanding access tokens to 90 days (#5040)
time-attack5ef753783469
diff --git a/src/core/grants/model.ts b/src/core/grants/model.tsindex 14c10e4adb..3c34a2fb73 100644--- a/src/core/grants/model.ts+++ b/src/core/grants/model.ts@@ -7,6 +7,10 @@ export const GRANT_PROFILES = ['memory-reader', 'memory-writer', 'coding-agent',export type GrantProfileId = typeof GRANT_PROFILES[number];export type GrantSurface = 'verbs' | 'starter' | 'full';+/** Access-token lifetime bounds for every per-client override and the server default: 1 minute to 90 days. */+export const TOKEN_TTL_MIN_SECONDS = 60;+export const TOKEN_TTL_MAX_SECONDS = 7_776_000;+/** SQL NULL operation snapshots preserve legacy clients; [] grants no operations. */export interface ClientGrant {clientId: string;@@ -131,7 +135,7 @@ export function validateClientGrant(grant: ClientGrant, ctx: GrantValidationContif (grant.allowedOperations?.some(name => !ctx.operationNames.has(name))) reasons.push('operations_unavailable');if (grant.profile !== null && grant.allowedOperations === null) reasons.push('operations_snapshot_missing');if (grant.budgetUsdPerDay !== null && (!/^\d+(?:\.\d{1,2})?$/.test(grant.budgetUsdPerDay) || Number(grant.budgetUsdPerDay) > 99999999.99)) reasons.push('budget_invalid');- if (grant.tokenTtlSeconds !== null && (!Number.isSafeInteger(grant.tokenTtlSeconds) || grant.tokenTtlSeconds < 60 || grant.tokenTtlSeconds > 7776000)) reasons.push('token_ttl_invalid');+ if (grant.tokenTtlSeconds !== null && (!Number.isSafeInteger(grant.tokenTtlSeconds) || grant.tokenTtlSeconds < TOKEN_TTL_MIN_SECONDS || grant.tokenTtlSeconds > TOKEN_TTL_MAX_SECONDS)) reasons.push('token_ttl_invalid');if (grant.surface !== null && !['verbs', 'starter', 'full'].includes(grant.surface)) reasons.push('surface_invalid');if (grant.profile !== null && !(GRANT_PROFILES as readonly string[]).includes(grant.profile)) reasons.push('profile_invalid');if (!Number.isSafeInteger(grant.boundMaxConcurrent) || grant.boundMaxConcurrent < 1) reasons.push('concurrency_invalid');diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex aadccdd67a..d7c876f661 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -209,6 +209,7 @@ import { v205 } from './v205-minion-spend-authorization.ts';import { v206 } from './v206-entity-mention-index.ts';import { v207 } from './v207-retrieval-feedback.ts';import { v208 } from './v208-delta-per-arm-cursor.ts';+import { v209 } from './v209-w9-f-clamp-oauth-token-ttl.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -416,4 +417,5 @@ export const MIGRATIONS: Migration[] = [v206,v207,v208,+ v209,];diff --git a/src/core/schema-migrations/v209-w9-f-clamp-oauth-token-ttl.ts b/src/core/schema-migrations/v209-w9-f-clamp-oauth-token-ttl.tsnew file mode 100644index 0000000000..b119649f70--- /dev/null+++ b/src/core/schema-migrations/v209-w9-f-clamp-oauth-token-ttl.ts@@ -0,0 +1,59 @@+import type { BrainEngine } from '../engine.ts';+import { sqlQueryForEngine } from '../sql-query.ts';+import { TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromRow } from '../grants/model.ts';+import { migrationNotice } from './helpers.ts';+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Brings stored per-client access-token lifetimes and outstanding access+// tokens inside the issuance bounds (src/core/grants/model.ts). An override+// above the maximum becomes the maximum, a positive one below the minimum+// becomes the minimum, and a non-positive one (issued as the server default)+// becomes NULL. Outstanding access tokens expire no later than created_at plus+// the maximum; no expiry is ever extended. Refresh tokens and legacy bearer+// tokens are untouched. Every change writes an oauth_grant_audit row. All+// client rows are locked first so in-flight issuance commits before tokens+// are shortened. Re-running finds nothing left to change.+export async function clampOAuthTokenTtls(engine: BrainEngine): Promise<void> {+ await engine.transaction(async tx => {+ const sql = sqlQueryForEngine(tx);+ const clients = await sql`SELECT * FROM oauth_clients ORDER BY client_id FOR UPDATE`;+ const names = new Map(clients.map(row => [String(row.client_id), String(row.client_name ?? '')]));+ for (const row of clients) {+ const before = grantFromRow(row);+ const stored = before.tokenTtlSeconds;+ if (stored === null || (stored >= TOKEN_TTL_MIN_SECONDS && stored <= TOKEN_TTL_MAX_SECONDS)) continue;+ const tokenTtlSeconds = stored > TOKEN_TTL_MAX_SECONDS ? TOKEN_TTL_MAX_SECONDS : stored > 0 ? TOKEN_TTL_MIN_SECONDS : null;+ const after = { ...before, tokenTtlSeconds, revision: before.revision + 1 };+ await sql`UPDATE oauth_clients SET token_ttl = ${tokenTtlSeconds}, grant_revision = ${after.revision} WHERE client_id = ${before.clientId}`;+ await sql`INSERT INTO oauth_grant_audit (client_id, actor, action, revision, before_grant, after_grant)+ VALUES (${before.clientId}, 'migration', 'clamp_token_ttl', ${after.revision},+ ${JSON.stringify(before)}::text::jsonb, ${JSON.stringify(after)}::text::jsonb)`;+ migrationNotice(` OAuth client ${before.clientName || '<unnamed>'} (${before.clientId}): access-token lifetime ${stored}s -> ${tokenTtlSeconds ?? 'server default'}${tokenTtlSeconds === null ? '' : 's'}\n`);+ }+ const shortened = await sql`UPDATE oauth_tokens+ SET expires_at = FLOOR(EXTRACT(EPOCH FROM created_at))::bigint + ${TOKEN_TTL_MAX_SECONDS}+ WHERE token_type = 'access' AND expires_at > FLOOR(EXTRACT(EPOCH FROM created_at))::bigint + ${TOKEN_TTL_MAX_SECONDS}+ RETURNING client_id`;+ const perClient = new Map<string, number>();+ for (const row of shortened) perClient.set(String(row.client_id), (perClient.get(String(row.client_id)) ?? 0) + 1);+ for (const [clientId, count] of perClient) {+ const [current] = await sql`SELECT grant_revision FROM oauth_clients WHERE client_id = ${clientId}`;+ const revision = Number(current?.grant_revision ?? 0);+ await sql`INSERT INTO oauth_grant_audit (client_id, actor, action, revision, before_grant, after_grant)+ VALUES (${clientId}, 'migration', 'shorten_access_tokens', ${revision}, NULL,+ ${JSON.stringify({ clientId, shortenedAccessTokens: count, maxAccessTokenLifetimeSeconds: TOKEN_TTL_MAX_SECONDS })}::text::jsonb)`;+ migrationNotice(` OAuth client ${names.get(clientId) || '<unnamed>'} (${clientId}): ${count} access token(s) now expire 90 days after issue\n`);+ }+ });+}++export const v209: Migration = {+ version: 209,+ name: 'w9_f_clamp_oauth_token_ttl',+ idempotent: true,+ sql: '',+ handler: clampOAuthTokenTtls,+};diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex cfe9cbf0b3..9e298272c1 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 203,+ "count": 204,"gaps": [17,18,@@ -14,9 +14,13 @@"PERSISTENCE_DATABASE_PENDING_INDEX_SQL": "6e0f618be33d037454933ea4dea11438413d45aef35d3bd4f33e89624d6e199e","PERSISTENCE_EFFECT_PARKED_INDEX_SQL": "0107863883415378d7c0dce7a0cbd5311c2c5a59fc0f81917cc8b767fd235cf2","PERSISTENCE_SYNC_RUN_INDEXES": "e1b12613c5fd2facb850e6857b0bddcf49b2478ec258fa226fe15e71e55df9c1",+ "TOKEN_TTL_MAX_SECONDS": "f4a45bec6ec0bacc859dc57732ceb76cec7eb72f242b5a6c89d47190d0525ab4",+ "TOKEN_TTL_MIN_SECONDS": "441d8ce6bd21f753de90abd3013eaa9992a469ea60c590f1005533618199aa25","buildIndexOnline": "c3c076436d7a1d161b94862125cafb9d3ba14d06e296a6379d6149452610285c",+ "clampOAuthTokenTtls": "092945a432b8d1885068cce483cb959a62fd00ccd459fe97481414e8b5615bb6","dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c","getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db",+ "grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26","migrateConnectorCheckpoints": "e0403022a56559556c82a9fa1e90d928f36e1d09c7db570e1d788a87d2dc9521","migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c",@@ -27,9 +31,10 @@"repairLegacyTimelineSourceRows": "405d4ae158482c020b029b93aff1ae4ac6854e6948cafaf82dbef473e6e5552e","seedConnectorDispatchAttempts": "2395a3995a6bf78776d37e72ce79b0dd15f6c6fa7f81c40612a744cb74ab01a5","slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",+ "sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 208,+ "latest": 209,"records": [{"handler": {@@ -3081,6 +3086,31 @@"transaction": "absent","verify": "absent","version": 208+ },+ {+ "handler": {+ "form": "identifier",+ "helpers": [+ "TOKEN_TTL_MAX_SECONDS",+ "TOKEN_TTL_MIN_SECONDS",+ "clampOAuthTokenTtls",+ "grantFromRow",+ "migrationNotice",+ "quietMigrationNotices",+ "sqlQueryForEngine"+ ],+ "sha256": "76aab609fde72769fdac91a4ae5cca12d693bcc4eda22ce76ce253b7439926bb"+ },+ "idempotent": true,+ "name": "w9_f_clamp_oauth_token_ttl",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 209}],"versions": [@@ -3286,7 +3316,8 @@205,206,207,- 208+ 208,+ 209]},"normalizer": "migrations-record-v1"