diff --git a/cdk/src/constructs/concurrency-reconciler.ts b/cdk/src/constructs/concurrency-reconciler.ts index c0fed93dd..4e66bba6d 100644 --- a/cdk/src/constructs/concurrency-reconciler.ts +++ b/cdk/src/constructs/concurrency-reconciler.ts @@ -22,7 +22,7 @@ import { Duration } from 'aws-cdk-lib'; import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as events from 'aws-cdk-lib/aws-events'; import * as targets from 'aws-cdk-lib/aws-events-targets'; -import { Runtime, Architecture } from 'aws-cdk-lib/aws-lambda'; +import { Runtime, Architecture, type IFunction } from 'aws-cdk-lib/aws-lambda'; import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs'; import { NagSuppressions } from 'cdk-nag'; import { Construct } from 'constructs'; @@ -92,6 +92,7 @@ export class ConcurrencyReconciler extends Construct { props.userConcurrencyTable.grantReadWriteData(this.fn); const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES); + this.fn.addEnvironment('RECONCILER_TICK_MINUTES', String(schedule.toMinutes())); const rule = new events.Rule(this, 'ReconcilerSchedule', { schedule: events.Schedule.rate(schedule), }); @@ -108,4 +109,20 @@ export class ConcurrencyReconciler extends Construct { }, ], true); } + + /** + * Have this reconciler invoke the Linear webhook processor's grant health probe + * (#1004) on one tick every 12 h. + * + * Revocation detection (#812) only runs when a Linear event needs a token, so an + * idle workspace or a dead webhook never re-detects a dead grant, and an unused + * refresh token simply expires. The probe refreshes expiring tokens and sends a + * rejected grant down the existing latch-and-announce path. It rides this + * schedule by async invoke because the root stack has no resource budget for a + * rule of its own: this adds only an IAM statement and two env vars. + */ + public triggerLinearGrantProbe(processor: IFunction): void { + this.fn.addEnvironment('LINEAR_GRANT_PROBE_FUNCTION_ARN', processor.functionArn); + processor.grantInvoke(this.fn); + } } diff --git a/cdk/src/handlers/linear-webhook-processor.ts b/cdk/src/handlers/linear-webhook-processor.ts index d9a9f9962..09b6c3ab3 100644 --- a/cdk/src/handlers/linear-webhook-processor.ts +++ b/cdk/src/handlers/linear-webhook-processor.ts @@ -33,6 +33,7 @@ import { fetchRecentComments, type RenderedComment, } from './shared/linear-feedback'; +import { type GRANT_HEALTH_PROBE_EVENT, isGrantHealthProbe, probeLinearGrants } from './shared/linear-grant-health'; import { probeLinearIssueContext, renderIssueContextHint, @@ -687,8 +688,38 @@ type BuilderResolvedToken = { vaultUserId?: string; }; +/** + * Grant health probe (#1004), invoked twice a day by the concurrency reconciler. Runs + * in this Lambda because it already holds + * the token-refresh grants, the registry write for the revocation latch and the + * OperationalAlerts publish, so a dead grant reuses the #812 announce path. + */ +async function runGrantHealthProbe(): Promise { + if (!WORKSPACE_REGISTRY_TABLE) { + logger.error('Linear grant health probe skipped: LINEAR_WORKSPACE_REGISTRY_TABLE_NAME not set'); + return; + } + const table = WORKSPACE_REGISTRY_TABLE; + const report = await probeLinearGrants(ddb, table, id => resolveLinearOauthToken(id, table)); + const fields = { + checked: report.checked, + healthy: report.healthy, + unhealthy: report.unhealthy, + revoked: report.revoked, + }; + if (report.unhealthy.length > 0) { + logger.warn('Linear grant health probe: some workspaces have no usable token — run `bgagent linear setup `', fields); + } else { + logger.info('Linear grant health probe', fields); + } +} + // eslint-disable-next-line complexity -- predates the ceiling (120 when it landed); must not grow -export async function handler(event: ProcessorEvent): Promise { +export async function handler(event: ProcessorEvent | typeof GRANT_HEALTH_PROBE_EVENT): Promise { + if (isGrantHealthProbe(event)) { + await runGrantHealthProbe(); + return; + } if (!event.raw_body) { logger.error('Linear webhook processor invoked without raw_body'); return; diff --git a/cdk/src/handlers/reconcile-concurrency.ts b/cdk/src/handlers/reconcile-concurrency.ts index 008f0e8a2..55307f2d2 100644 --- a/cdk/src/handlers/reconcile-concurrency.ts +++ b/cdk/src/handlers/reconcile-concurrency.ts @@ -18,6 +18,8 @@ */ import { DynamoDBClient, ScanCommand, QueryCommand, UpdateItemCommand } from '@aws-sdk/client-dynamodb'; +import { InvocationType, InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda'; +import { GRANT_HEALTH_PROBE_EVENT, isProbeTick } from './shared/linear-grant-health'; import { logger } from './shared/logger'; import { makeClient } from './shared/ua'; @@ -60,8 +62,37 @@ async function countActiveTasks(userId: string): Promise { * Scheduled handler: scan the concurrency table and reconcile each user's * active_count against actual active tasks in the task table. */ +const LINEAR_GRANT_PROBE_FUNCTION_ARN = process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN; +const RECONCILER_TICK_MINUTES = Number(process.env.RECONCILER_TICK_MINUTES); +const lambdaClient = LINEAR_GRANT_PROBE_FUNCTION_ARN ? makeClient(LambdaClient) : undefined; + +/** + * Kick the Linear grant health probe (#1004) on one tick per 12 h. Fire-and-forget + * (async invoke) and best-effort: a probe problem must never affect reconciliation. + */ +export async function triggerLinearGrantProbe(nowMs: number = Date.now()): Promise { + if (!lambdaClient || !LINEAR_GRANT_PROBE_FUNCTION_ARN || !isProbeTick(nowMs, RECONCILER_TICK_MINUTES)) { + return false; + } + try { + await lambdaClient.send(new InvokeCommand({ + FunctionName: LINEAR_GRANT_PROBE_FUNCTION_ARN, + InvocationType: InvocationType.Event, + Payload: Buffer.from(JSON.stringify(GRANT_HEALTH_PROBE_EVENT)), + })); + logger.info('Triggered the Linear grant health probe'); + return true; + } catch (err) { + logger.warn('Could not trigger the Linear grant health probe', { + error: err instanceof Error ? err.message : String(err), + }); + return false; + } +} + export async function handler(): Promise { logger.info('Concurrency reconciler started'); + await triggerLinearGrantProbe(); let corrected = 0; let scanned = 0; let errors = 0; diff --git a/cdk/src/handlers/shared/linear-grant-health.ts b/cdk/src/handlers/shared/linear-grant-health.ts new file mode 100644 index 000000000..1d0c2da94 --- /dev/null +++ b/cdk/src/handlers/shared/linear-grant-health.ts @@ -0,0 +1,128 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Scheduled Linear grant health probe (#1004). + * + * Revocation detection (#812) runs only when something needs a Linear token, which + * means when a Linear event arrives. A workspace whose webhook stopped delivering, or + * that nobody used for a while, therefore never re-detects a dead grant: observed + * live, a workspace sat with an expired refresh token for months with one ERROR log + * line. Linear refresh tokens also expire when unused, so the outage was preventable. + * + * The probe resolves a token for every active workspace on a schedule. That does two + * jobs with the existing code path: + * - it refreshes expiring access tokens, which keeps an idle refresh token alive; + * - a grant Linear rejects goes through the resolver's revocation recorder, which + * latches the workspace and announces it on OperationalAlerts (once). + */ + +import { ScanCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; + +/** How often each workspace is probed. Linear access tokens last about a day. */ +const GRANT_HEALTH_PROBE_INTERVAL_HOURS = 12; + +const MS_PER_MINUTE = 60_000; +const MS_PER_HOUR = 3_600_000; + +/** Async invocation payload that selects probe mode in the webhook processor. */ +export const GRANT_HEALTH_PROBE_EVENT = { grant_health_probe: true } as const; + +export function isGrantHealthProbe(event: unknown): event is typeof GRANT_HEALTH_PROBE_EVENT { + return typeof event === 'object' && event !== null + && (event as Record).grant_health_probe === true; +} + +/** + * True on exactly one tick per interval for a job that runs every `tickMinutes`: + * the tick falling in the half-open window `[k * interval, k * interval + tick)`. + * Ticks are `tick` apart, so each window holds exactly one. A nonsensical cadence + * probes every tick rather than never, so a misconfiguration cannot silently + * disable detection. + */ +export function isProbeTick( + nowMs: number, + tickMinutes: number, + intervalHours: number = GRANT_HEALTH_PROBE_INTERVAL_HOURS, +): boolean { + const tickMs = tickMinutes * MS_PER_MINUTE; + const intervalMs = intervalHours * MS_PER_HOUR; + if (!(tickMs > 0) || !(intervalMs > 0) || tickMs >= intervalMs) return true; + return nowMs % intervalMs < tickMs; +} + +export interface GrantHealthReport { + readonly checked: number; + readonly healthy: number; + /** Slugs (or ids when a row has no slug) whose token could not be resolved. */ + readonly unhealthy: readonly string[]; + /** Rows already latched `revoked`; not re-probed, they were already announced. */ + readonly revoked: readonly string[]; +} + +interface RegistryRow { + readonly linear_workspace_id?: string; + readonly workspace_slug?: string; + readonly status?: string; +} + +/** + * Resolve a token for every active registry row, sequentially (a handful of + * workspaces; sequential keeps the probe gentle on Linear's token endpoint). + */ +export async function probeLinearGrants( + ddb: DynamoDBDocumentClient, + registryTableName: string, + resolve: (linearWorkspaceId: string) => Promise, +): Promise { + const rows: RegistryRow[] = []; + let startKey: Record | undefined; + do { + const page = await ddb.send(new ScanCommand({ + TableName: registryTableName, + ProjectionExpression: 'linear_workspace_id, workspace_slug, #status', + ExpressionAttributeNames: { '#status': 'status' }, + ExclusiveStartKey: startKey, + })); + rows.push(...(page.Items ?? []) as RegistryRow[]); + startKey = page.LastEvaluatedKey; + } while (startKey); + + let healthy = 0; + const unhealthy: string[] = []; + const revoked: string[] = []; + let checked = 0; + for (const row of rows) { + if (!row.linear_workspace_id) continue; + const label = row.workspace_slug ?? row.linear_workspace_id; + if (row.status !== 'active') { + revoked.push(label); + continue; + } + checked++; + try { + if (await resolve(row.linear_workspace_id)) healthy++; + else unhealthy.push(label); + } catch { + // One workspace's failure must not hide the others. + unhealthy.push(label); + } + } + return { checked, healthy, unhealthy, revoked }; +} diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index a8cfbef5c..0fec66e0f 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -1351,7 +1351,7 @@ export class AgentStack extends Stack { agentMemory.grantReadWrite(orchestrator.fn); // --- Concurrency counter reconciler (drift correction) --- - new ConcurrencyReconciler(this, 'ConcurrencyReconciler', { + const concurrencyReconciler = new ConcurrencyReconciler(this, 'ConcurrencyReconciler', { taskTable: taskTable.table, userConcurrencyTable: userConcurrencyTable.table, }); @@ -2024,6 +2024,9 @@ export class AgentStack extends Stack { // not exist yet at this point in the constructor. if (linearIntegration) { operationalAlerts.grantPublish(linearIntegration.webhookProcessorFn); + // #1004: the reconciler kicks the processor's grant health probe twice a day, so a + // grant that dies while nobody uses Linear is still detected and announced here. + concurrencyReconciler.triggerLinearGrantProbe(linearIntegration.webhookProcessorFn); linearIntegration.webhookProcessorFn.addEnvironment( 'OPERATIONAL_ALERT_TOPIC_ARN', operationalAlerts.topic.topicArn, diff --git a/cdk/test/constructs/concurrency-reconciler.test.ts b/cdk/test/constructs/concurrency-reconciler.test.ts index 34e1e88e4..e3d9f82ef 100644 --- a/cdk/test/constructs/concurrency-reconciler.test.ts +++ b/cdk/test/constructs/concurrency-reconciler.test.ts @@ -20,6 +20,7 @@ import { App, Stack } from 'aws-cdk-lib'; import { Template, Match } from 'aws-cdk-lib/assertions'; import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as lambda from 'aws-cdk-lib/aws-lambda'; import { ConcurrencyReconciler } from '../../src/constructs/concurrency-reconciler'; function createStack(): Template { @@ -70,3 +71,41 @@ describe('ConcurrencyReconciler construct', () => { }); }); }); + +describe('ConcurrencyReconciler Linear grant probe trigger (#1004)', () => { + function build(withProbe: boolean): Template { + const stack = new Stack(new App(), 'ProbeStack'); + const table = (id: string, pk: string) => new dynamodb.Table(stack, id, { + partitionKey: { name: pk, type: dynamodb.AttributeType.STRING }, + }); + const reconciler = new ConcurrencyReconciler(stack, 'ConcurrencyReconciler', { + taskTable: table('Tasks', 'task_id'), + userConcurrencyTable: table('Users', 'user_id'), + }); + const processor = new lambda.Function(stack, 'Processor', { + runtime: lambda.Runtime.NODEJS_22_X, handler: 'index.handler', code: lambda.Code.fromInline('exports.handler=async()=>{}'), + }); + if (withProbe) reconciler.triggerLinearGrantProbe(processor); + return Template.fromStack(stack); + } + + test('grants invoke and passes the target without adding any resource', () => { + const without = build(false); + const template = build(true); + const types = (t: Template) => Object.entries(t.toJSON().Resources as Record) + .map(([id, r]) => `${r.Type} ${id}`).sort(); + + expect(types(template)).toEqual(types(without)); + template.hasResourceProperties('AWS::Lambda::Function', { + Environment: { + Variables: Match.objectLike({ + RECONCILER_TICK_MINUTES: '15', + LINEAR_GRANT_PROBE_FUNCTION_ARN: { 'Fn::GetAtt': [Match.stringLikeRegexp('Processor'), 'Arn'] }, + }), + }, + }); + template.hasResourceProperties('AWS::IAM::Policy', { + PolicyDocument: { Statement: Match.arrayWith([Match.objectLike({ Action: 'lambda:InvokeFunction' })]) }, + }); + }); +}); diff --git a/cdk/test/handlers/linear-webhook-processor.test.ts b/cdk/test/handlers/linear-webhook-processor.test.ts index bde275d66..ff49f55f9 100644 --- a/cdk/test/handlers/linear-webhook-processor.test.ts +++ b/cdk/test/handlers/linear-webhook-processor.test.ts @@ -25,6 +25,7 @@ jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({} jest.mock('@aws-sdk/lib-dynamodb', () => ({ DynamoDBDocumentClient: { from: jest.fn(() => ({ send: ddbSend })) }, GetCommand: jest.fn((input: unknown) => ({ _type: 'Get', input })), + ScanCommand: jest.fn((input: unknown) => ({ _type: 'Scan', input })), })); const createTaskCoreMock = jest.fn(); @@ -117,6 +118,34 @@ function issue(overrides: Record = {}): Record }; } +describe('linear-webhook-processor scheduled grant health probe (#1004)', () => { + beforeEach(() => { + ddbSend.mockReset(); + createTaskCoreMock.mockReset(); + resolveLinearOauthTokenMock.mockReset(); + }); + + test('the probe event resolves every active workspace and never takes the webhook path', async () => { + ddbSend.mockResolvedValueOnce({ + Items: [ + { linear_workspace_id: 'ws-live', workspace_slug: 'live', status: 'active' }, + { linear_workspace_id: 'ws-dead', workspace_slug: 'dead', status: 'active' }, + { linear_workspace_id: 'ws-latched', workspace_slug: 'latched', status: 'revoked' }, + ], + }); + resolveLinearOauthTokenMock.mockImplementation(async (id: string) => (id === 'ws-live' ? { access_token: 't' } : null)); + + await handler({ grant_health_probe: true }); + + expect(ddbSend.mock.calls[0][0]).toMatchObject({ _type: 'Scan', input: { TableName: 'LinearWorkspaceRegistry' } }); + expect(resolveLinearOauthTokenMock.mock.calls).toEqual([ + ['ws-live', 'LinearWorkspaceRegistry'], + ['ws-dead', 'LinearWorkspaceRegistry'], + ]); + expect(createTaskCoreMock).not.toHaveBeenCalled(); + }); +}); + describe('linear-webhook-processor handler', () => { beforeEach(() => { ddbSend.mockReset(); diff --git a/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts b/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts new file mode 100644 index 000000000..4ecf30b57 --- /dev/null +++ b/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts @@ -0,0 +1,61 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +// The reconciler kicks the Linear grant health probe (#1004). +const mockLambdaSend = jest.fn(); +jest.mock('@aws-sdk/client-lambda', () => ({ + LambdaClient: jest.fn(() => ({ send: mockLambdaSend })), + InvokeCommand: jest.fn((input: unknown) => ({ _type: 'Invoke', input })), + InvocationType: { Event: 'Event' }, +})); +jest.mock('@aws-sdk/client-dynamodb', () => ({ + DynamoDBClient: jest.fn(() => ({ send: jest.fn() })), + ScanCommand: jest.fn(), + QueryCommand: jest.fn(), + UpdateItemCommand: jest.fn(), +})); + +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; +process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN = 'arn:aws:lambda:us-east-1:123456789012:function:processor'; +process.env.RECONCILER_TICK_MINUTES = '15'; + +import { triggerLinearGrantProbe } from '../../src/handlers/reconcile-concurrency'; + +const WINDOW = 12 * 3_600_000; + +beforeEach(() => mockLambdaSend.mockReset()); + +test('async-invokes the processor with the probe event on the window tick only', async () => { + mockLambdaSend.mockResolvedValue({}); + expect(await triggerLinearGrantProbe(WINDOW * 100 + 60_000)).toBe(true); + expect(mockLambdaSend).toHaveBeenCalledTimes(1); + const { input } = mockLambdaSend.mock.calls[0][0]; + expect(input.FunctionName).toBe(process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN); + expect(input.InvocationType).toBe('Event'); + expect(JSON.parse(Buffer.from(input.Payload).toString())).toEqual({ grant_health_probe: true }); + + expect(await triggerLinearGrantProbe(WINDOW * 100 + 20 * 60_000)).toBe(false); + expect(mockLambdaSend).toHaveBeenCalledTimes(1); +}); + +test('an invoke failure never breaks the reconciler', async () => { + mockLambdaSend.mockRejectedValue(new Error('throttled')); + await expect(triggerLinearGrantProbe(WINDOW * 7)).resolves.toBe(false); +}); diff --git a/cdk/test/handlers/shared/linear-grant-health.test.ts b/cdk/test/handlers/shared/linear-grant-health.test.ts new file mode 100644 index 000000000..d4f8eb193 --- /dev/null +++ b/cdk/test/handlers/shared/linear-grant-health.test.ts @@ -0,0 +1,98 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + GRANT_HEALTH_PROBE_EVENT, + isGrantHealthProbe, + isProbeTick, + probeLinearGrants, +} from '../../../src/handlers/shared/linear-grant-health'; + +function fakeDdb(pages: Array<{ Items: unknown[]; LastEvaluatedKey?: Record }>) { + const send = jest.fn(); + for (const page of pages) send.mockResolvedValueOnce(page); + return { client: { send } as unknown as DynamoDBDocumentClient, send }; +} + +describe('isGrantHealthProbe', () => { + test('recognises only the scheduled probe input', () => { + expect(isGrantHealthProbe(GRANT_HEALTH_PROBE_EVENT)).toBe(true); + expect(isGrantHealthProbe({ raw_body: '{}' })).toBe(false); + expect(isGrantHealthProbe({ grant_health_probe: 'true' })).toBe(false); + expect(isGrantHealthProbe(null)).toBe(false); + }); +}); + +describe('isProbeTick', () => { + const HOUR = 3_600_000; + test('fires on exactly one 15-minute tick per 12-hour window, wherever the ticks start', () => { + for (const offsetMs of [0, 7 * 60_000, 14 * 60_000 + 59_999]) { + const fired: number[] = []; + for (let t = offsetMs; t < 48 * HOUR; t += 15 * 60_000) if (isProbeTick(t, 15)) fired.push(t); + expect(fired).toHaveLength(4); + expect(fired.map(t => Math.floor(t / (12 * HOUR)))).toEqual([0, 1, 2, 3]); + } + }); + + test('a nonsensical cadence probes every tick instead of never', () => { + expect(isProbeTick(5 * HOUR, Number.NaN)).toBe(true); + expect(isProbeTick(5 * HOUR, 0)).toBe(true); + expect(isProbeTick(5 * HOUR, 15, Number.NaN)).toBe(true); + }); +}); + +describe('probeLinearGrants', () => { + test('pages the registry and resolves every active workspace, skipping latched ones', async () => { + const { client, send } = fakeDdb([ + { + Items: [ + { linear_workspace_id: 'ws-1', workspace_slug: 'alpha', status: 'active' }, + { linear_workspace_id: 'ws-2', workspace_slug: 'beta', status: 'revoked' }, + ], + LastEvaluatedKey: { linear_workspace_id: 'ws-2' }, + }, + { Items: [{ linear_workspace_id: 'ws-3', workspace_slug: 'gamma', status: 'active' }] }, + ]); + const resolve = jest.fn(async (id: string) => (id === 'ws-1' ? { access_token: 't' } : null)); + + const report = await probeLinearGrants(client, 'Registry', resolve); + + expect(resolve.mock.calls.map(([id]) => id)).toEqual(['ws-1', 'ws-3']); + expect(report).toEqual({ checked: 2, healthy: 1, unhealthy: ['gamma'], revoked: ['beta'] }); + expect(send).toHaveBeenCalledTimes(2); + expect(send.mock.calls[1][0].input.ExclusiveStartKey).toEqual({ linear_workspace_id: 'ws-2' }); + }); + + test('one workspace throwing does not hide the others', async () => { + const { client } = fakeDdb([{ + Items: [ + { linear_workspace_id: 'ws-1', workspace_slug: 'alpha', status: 'active' }, + { linear_workspace_id: 'ws-2', status: 'active' }, + ], + }]); + const resolve = jest.fn() + .mockRejectedValueOnce(new Error('throttled')) + .mockResolvedValueOnce({ access_token: 't' }); + + expect(await probeLinearGrants(client, 'Registry', resolve)).toEqual({ + checked: 2, healthy: 1, unhealthy: ['alpha'], revoked: [], + }); + }); +}); diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 28b78fb50..362f615a9 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -280,6 +280,18 @@ If the app has been edited repeatedly through failed saves, creating a fresh app - Is the label spelled as configured? Matching is case-insensitive but must be the same word. - Check CloudWatch for `WebhookFn` and `WebhookProcessorFn`. Common: `Invalid Linear webhook signature`, `Linear workspace is not onboarded`, `Linear project is not onboarded`, `Linear actor has no linked platform user`. +### Linear stops responding and an "authorization revoked" alert arrives + +ABCA probes every registered workspace's grant every 12 hours, as well as whenever an event needs a token. The probe refreshes tokens that are about to expire, which keeps a grant alive even when nobody uses Linear for a while. If Linear rejects a grant, the workspace is marked `revoked` and one alert goes to the **OperationalAlerts** SNS topic (stack output `OperationalAlertsTopicArn`). Subscribe an email or chat endpoint to it, or deploy with `-c alertEmail=…`, because it ships with no subscribers. + +To recover, re-authorize the workspace: + +```bash +bgagent linear setup +``` + +The probe's summary is in the `WebhookProcessorFn` logs ("Linear grant health probe"), listing any workspace without a usable token. + ### Webhook signature verification fails repeatedly The stored signing secret doesn't match the subscription Linear is sending from — usually because the webhook was configured in Linear without telling ABCA, or the secret was rotated: diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index 0750b2854..6a6b9d45f 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -282,6 +282,18 @@ If the app has been edited repeatedly through failed saves, creating a fresh app - Is the label spelled as configured? Matching is case-insensitive but must be the same word. - Check CloudWatch for `WebhookFn` and `WebhookProcessorFn`. Common: `Invalid Linear webhook signature`, `Linear workspace is not onboarded`, `Linear project is not onboarded`, `Linear actor has no linked platform user`. +### Linear stops responding and an "authorization revoked" alert arrives + +ABCA probes every registered workspace's grant every 12 hours, as well as whenever an event needs a token. The probe refreshes tokens that are about to expire, which keeps a grant alive even when nobody uses Linear for a while. If Linear rejects a grant, the workspace is marked `revoked` and one alert goes to the **OperationalAlerts** SNS topic (stack output `OperationalAlertsTopicArn`). Subscribe an email or chat endpoint to it, or deploy with `-c alertEmail=…`, because it ships with no subscribers. + +To recover, re-authorize the workspace: + +```bash +bgagent linear setup +``` + +The probe's summary is in the `WebhookProcessorFn` logs ("Linear grant health probe"), listing any workspace without a usable token. + ### Webhook signature verification fails repeatedly The stored signing secret doesn't match the subscription Linear is sending from — usually because the webhook was configured in Linear without telling ABCA, or the secret was rotated: