-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathlinear-oauth.test.ts
More file actions
367 lines (323 loc) · 15.1 KB
/
Copy pathlinear-oauth.test.ts
File metadata and controls
367 lines (323 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/**
* 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 { CliError } from '../src/errors';
import {
buildAuthorizationUrl,
computeExpiresAt,
exchangeAuthorizationCode,
generatePkce,
isAccessTokenExpiring,
LINEAR_AUTHORIZE_ENDPOINT,
LINEAR_OAUTH_SCOPES,
LINEAR_TOKEN_ENDPOINT,
linearOauthSecretName,
readExistingWebhookSecret,
refreshAccessToken,
resolveWebhookSecretAction,
} from '../src/linear-oauth';
describe('linearOauthSecretName', () => {
test('prefixes with bgagent-linear-oauth-', () => {
expect(linearOauthSecretName('acme')).toBe('bgagent-linear-oauth-acme');
expect(linearOauthSecretName('acme-corp')).toBe('bgagent-linear-oauth-acme-corp');
});
});
describe('LINEAR_OAUTH_SCOPES', () => {
test('matches the actor=app-compatible scope set verified in the spike', () => {
// Locked: removing app:assignable / app:mentionable breaks the Agent install
// (verified 2026-05-18); adding `admin` breaks actor=app entirely.
expect(LINEAR_OAUTH_SCOPES).toEqual(['read', 'write', 'app:assignable', 'app:mentionable']);
});
});
describe('generatePkce', () => {
test('produces base64url-encoded verifier and SHA-256 challenge', () => {
const { codeVerifier, codeChallenge } = generatePkce();
expect(codeVerifier).toMatch(/^[A-Za-z0-9_-]+$/);
expect(codeChallenge).toMatch(/^[A-Za-z0-9_-]+$/);
// base64url-encoded SHA-256 = 43 chars (256 bits / 6 bits per char, no padding)
expect(codeChallenge.length).toBe(43);
});
test('generates fresh values on each call', () => {
const a = generatePkce();
const b = generatePkce();
expect(a.codeVerifier).not.toBe(b.codeVerifier);
expect(a.codeChallenge).not.toBe(b.codeChallenge);
});
test('challenge is deterministic from the verifier', async () => {
const { codeVerifier, codeChallenge } = generatePkce();
// Replay the verifier through SHA-256 and base64url-encode — must match.
const { createHash } = await import('crypto');
const expected = createHash('sha256').update(codeVerifier).digest().toString('base64url');
expect(codeChallenge).toBe(expected);
});
});
describe('buildAuthorizationUrl', () => {
test('includes all required OAuth + PKCE params and actor=app by default', () => {
const url = buildAuthorizationUrl({
clientId: 'cid',
redirectUri: 'https://localhost:8443/oauth/callback',
state: 'state-uuid',
codeChallenge: 'challenge-base64url',
});
expect(url.startsWith(LINEAR_AUTHORIZE_ENDPOINT)).toBe(true);
const parsed = new URL(url);
expect(parsed.searchParams.get('client_id')).toBe('cid');
expect(parsed.searchParams.get('redirect_uri')).toBe('https://localhost:8443/oauth/callback');
expect(parsed.searchParams.get('response_type')).toBe('code');
expect(parsed.searchParams.get('state')).toBe('state-uuid');
expect(parsed.searchParams.get('code_challenge')).toBe('challenge-base64url');
expect(parsed.searchParams.get('code_challenge_method')).toBe('S256');
expect(parsed.searchParams.get('actor')).toBe('app');
// Space-separated per RFC 6749 §3.3. Comma-separated triggers Linear's
// misleading "Invalid redirect_uri" — caught during smoke test 2026-05-19.
expect(parsed.searchParams.get('scope')).toBe('read write app:assignable app:mentionable');
});
test('actorApp:false drops the actor param entirely (regression OAuth fallback)', () => {
const url = buildAuthorizationUrl({
clientId: 'cid',
redirectUri: 'https://localhost:8443/oauth/callback',
state: 'state-uuid',
codeChallenge: 'challenge',
actorApp: false,
});
const parsed = new URL(url);
expect(parsed.searchParams.has('actor')).toBe(false);
});
});
describe('isAccessTokenExpiring', () => {
test('returns false for a token expiring well in the future', () => {
const future = new Date(Date.now() + 3600 * 1000).toISOString();
expect(isAccessTokenExpiring(future)).toBe(false);
});
test('returns true within the 60s threshold', () => {
const soon = new Date(Date.now() + 30 * 1000).toISOString();
expect(isAccessTokenExpiring(soon)).toBe(true);
});
test('returns true for a past expiry', () => {
const past = new Date(Date.now() - 60 * 1000).toISOString();
expect(isAccessTokenExpiring(past)).toBe(true);
});
test('returns true for a malformed expires_at (defensive: prefer over-refresh)', () => {
expect(isAccessTokenExpiring('not a date')).toBe(true);
});
test('respects custom threshold', () => {
const fiveMinutesOut = new Date(Date.now() + 5 * 60 * 1000).toISOString();
expect(isAccessTokenExpiring(fiveMinutesOut, 10)).toBe(false);
expect(isAccessTokenExpiring(fiveMinutesOut, 600)).toBe(true);
});
});
describe('computeExpiresAt', () => {
test('adds expires_in seconds to the given now', () => {
const now = new Date('2026-05-19T12:00:00.000Z');
expect(computeExpiresAt(86400, now)).toBe('2026-05-20T12:00:00.000Z');
});
});
// ─── Token endpoint round-trip tests ────────────────────────────────────────
function mockResponse(status: number, body: unknown): Response {
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
} as unknown as Response;
}
describe('exchangeAuthorizationCode', () => {
test('happy path: parses Linear`s RFC-shaped response', async () => {
const fetchImpl = jest.fn().mockResolvedValueOnce(mockResponse(200, {
access_token: 'lin_oauth_aaaaaa',
token_type: 'Bearer',
expires_in: 86399,
refresh_token: 'lin_refresh_bbbbbb',
scope: 'read write app:assignable app:mentionable',
}));
const result = await exchangeAuthorizationCode({
code: 'authcode',
codeVerifier: 'verifier',
redirectUri: 'https://localhost:8443/oauth/callback',
clientId: 'cid',
clientSecret: 'csec',
fetchImpl: fetchImpl as unknown as typeof fetch,
});
expect(result.access_token).toBe('lin_oauth_aaaaaa');
expect(result.refresh_token).toBe('lin_refresh_bbbbbb');
expect(result.expires_in).toBe(86399);
expect(result.scope).toBe('read write app:assignable app:mentionable');
// Verify the wire body is exactly what Linear expects (RFC 6749 §4.1.3).
expect(fetchImpl).toHaveBeenCalledTimes(1);
const [url, init] = fetchImpl.mock.calls[0];
expect(url).toBe(LINEAR_TOKEN_ENDPOINT);
expect(init.method).toBe('POST');
expect(init.headers).toEqual({ 'Content-Type': 'application/x-www-form-urlencoded' });
const sent = new URLSearchParams(init.body);
expect(sent.get('grant_type')).toBe('authorization_code');
expect(sent.get('code')).toBe('authcode');
expect(sent.get('code_verifier')).toBe('verifier');
expect(sent.get('redirect_uri')).toBe('https://localhost:8443/oauth/callback');
expect(sent.get('client_id')).toBe('cid');
expect(sent.get('client_secret')).toBe('csec');
});
test('translates Linear OAuth error responses to CliError with description', async () => {
const fetchImpl = jest.fn().mockResolvedValueOnce(mockResponse(400, {
error: 'invalid_grant',
error_description: 'authorization code has already been used',
}));
await expect(exchangeAuthorizationCode({
code: 'authcode',
codeVerifier: 'verifier',
redirectUri: 'https://localhost:8443/oauth/callback',
clientId: 'cid',
clientSecret: 'csec',
fetchImpl: fetchImpl as unknown as typeof fetch,
})).rejects.toThrow(/invalid_grant.*authorization code has already been used/);
});
test('rejects responses missing access_token (unexpected Linear shape)', async () => {
const fetchImpl = jest.fn().mockResolvedValueOnce(mockResponse(200, {
not_a_token: 'oops',
}));
await expect(exchangeAuthorizationCode({
code: 'authcode',
codeVerifier: 'verifier',
redirectUri: 'https://localhost:8443/oauth/callback',
clientId: 'cid',
clientSecret: 'csec',
fetchImpl: fetchImpl as unknown as typeof fetch,
})).rejects.toThrow(/unexpected shape/);
});
test('rejects non-JSON responses (Linear maintenance / proxy intercepts)', async () => {
const fetchImpl = jest.fn().mockResolvedValueOnce({
ok: false,
status: 502,
json: async () => { throw new Error('not json'); },
} as unknown as Response);
await expect(exchangeAuthorizationCode({
code: 'authcode',
codeVerifier: 'verifier',
redirectUri: 'https://localhost:8443/oauth/callback',
clientId: 'cid',
clientSecret: 'csec',
fetchImpl: fetchImpl as unknown as typeof fetch,
})).rejects.toThrow(/non-JSON.*HTTP 502/);
});
});
describe('refreshAccessToken', () => {
test('happy path: posts refresh_token grant and returns new tokens', async () => {
const fetchImpl = jest.fn().mockResolvedValueOnce(mockResponse(200, {
access_token: 'lin_oauth_new',
token_type: 'Bearer',
expires_in: 86399,
refresh_token: 'lin_refresh_rotated',
scope: 'read write app:assignable app:mentionable',
}));
const result = await refreshAccessToken({
refreshToken: 'lin_refresh_old',
clientId: 'cid',
clientSecret: 'csec',
fetchImpl: fetchImpl as unknown as typeof fetch,
});
expect(result.access_token).toBe('lin_oauth_new');
expect(result.refresh_token).toBe('lin_refresh_rotated');
const [, init] = fetchImpl.mock.calls[0];
const sent = new URLSearchParams(init.body);
expect(sent.get('grant_type')).toBe('refresh_token');
expect(sent.get('refresh_token')).toBe('lin_refresh_old');
// refresh grant does NOT send code/code_verifier/redirect_uri
expect(sent.get('code')).toBeNull();
expect(sent.get('redirect_uri')).toBeNull();
});
test('translates revoked-refresh-token error to CliError', async () => {
const fetchImpl = jest.fn().mockResolvedValueOnce(mockResponse(400, {
error: 'invalid_grant',
error_description: 'refresh token was revoked',
}));
await expect(refreshAccessToken({
refreshToken: 'lin_refresh_revoked',
clientId: 'cid',
clientSecret: 'csec',
fetchImpl: fetchImpl as unknown as typeof fetch,
})).rejects.toThrow(CliError);
});
});
describe('resolveWebhookSecretAction', () => {
it('PRESERVES an existing per-workspace secret over the stack-wide one (multi-workspace re-run — the bug)', () => {
// The regression: re-running `setup` on an already-installed workspace must
// NOT overwrite its working signing secret with the stack-wide fallback
// (which belongs to a different workspace once >1 is installed) — that
// silently breaks signature verification (webhook 401 "Invalid signature").
const action = resolveWebhookSecretAction('lin_wh_thisWorkspace', true);
expect(action).toEqual({ kind: 'preserve', secret: 'lin_wh_thisWorkspace' });
});
it('preserves the existing secret even when no stack-wide secret is set', () => {
expect(resolveWebhookSecretAction('lin_wh_existing', false)).toEqual({
kind: 'preserve',
secret: 'lin_wh_existing',
});
});
it('mirrors the stack-wide secret when there is no per-workspace one yet (first workspace)', () => {
expect(resolveWebhookSecretAction(undefined, true)).toEqual({ kind: 'mirror-stackwide' });
});
it('prompts when neither a per-workspace nor a stack-wide secret exists (first install)', () => {
expect(resolveWebhookSecretAction(undefined, false)).toEqual({ kind: 'prompt' });
});
it('ignores a malformed existing secret (not lin_wh_) and falls through', () => {
// A corrupt/empty value must not be "preserved" as if valid.
expect(resolveWebhookSecretAction('garbage', true)).toEqual({ kind: 'mirror-stackwide' });
expect(resolveWebhookSecretAction('', false)).toEqual({ kind: 'prompt' });
});
});
describe('readExistingWebhookSecret — fail-closed pre-read (#612 review B1/B2)', () => {
const notFound = (err: unknown) => (err as { name?: string }).name === 'ResourceNotFoundException';
const bundle = (secret?: string) =>
JSON.stringify({ access_token: 'a', webhook_signing_secret: secret });
it('returns the existing lin_wh_ secret when the bundle has one (→ preserve, not clobber)', async () => {
const got = await readExistingWebhookSecret(async () => bundle('lin_wh_thisWorkspace'), notFound);
// This is the value that makes resolveWebhookSecretAction PRESERVE — the fix.
expect(got).toBe('lin_wh_thisWorkspace');
expect(resolveWebhookSecretAction(got, true)).toEqual({ kind: 'preserve', secret: 'lin_wh_thisWorkspace' });
});
it('returns undefined on ResourceNotFoundException (genuine first install)', async () => {
const got = await readExistingWebhookSecret(async () => {
throw Object.assign(new Error('no'), { name: 'ResourceNotFoundException' });
}, notFound);
expect(got).toBeUndefined();
});
it('returns undefined when the bundle exists but has no/malformed secret', async () => {
expect(await readExistingWebhookSecret(async () => bundle(undefined), notFound)).toBeUndefined();
expect(await readExistingWebhookSecret(async () => bundle('not-a-wh'), notFound)).toBeUndefined();
expect(await readExistingWebhookSecret(async () => undefined, notFound)).toBeUndefined();
});
it('THROWS (fails closed) on AccessDenied — must NOT default to undefined and clobber', async () => {
// The B1 bug: a bare catch here would return undefined → mirror-stackwide →
// the #611 clobber, silently. The pre-read must surface the error instead.
const accessDenied = Object.assign(new Error('denied'), { name: 'AccessDeniedException' });
await expect(
readExistingWebhookSecret(async () => { throw accessDenied; }, notFound),
).rejects.toBe(accessDenied);
});
it('THROWS on KMSAccessDeniedException / Throttling / network (any non-not-found)', async () => {
for (const name of ['KMSAccessDeniedException', 'ThrottlingException', 'InternalServiceError']) {
const err = Object.assign(new Error(name), { name });
await expect(
readExistingWebhookSecret(async () => { throw err; }, notFound),
).rejects.toBe(err);
}
});
it('THROWS on a corrupt-but-present bundle (JSON.parse) — not silently "nothing to preserve"', async () => {
await expect(
readExistingWebhookSecret(async () => '{not valid json', notFound),
).rejects.toThrow();
});
});