-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-api.test.js
More file actions
395 lines (358 loc) · 14.4 KB
/
Copy pathgithub-api.test.js
File metadata and controls
395 lines (358 loc) · 14.4 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
'use strict'
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
const test = require('node:test')
const assert = require('node:assert/strict')
const { apiBaseUrl, createClient, makeLatestField, repoPath, request, retryDelayMs } = require('./github-api.js')
const noSleep = () => Promise.resolve()
// fakeResponse mimics the subset of the fetch Response interface that github-api.js consumes.
function fakeResponse({ status = 200, body = '', json = true } = {}) {
const text = typeof body === 'string' ? body : JSON.stringify(body)
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (name) => (name.toLowerCase() === 'content-type' && json ? 'application/json' : null) },
text: () => Promise.resolve(text),
}
}
// withFetch installs a stub global.fetch that records calls and answers from handler(url, options).
function withFetch(handler, fn) {
const previous = global.fetch
const calls = []
global.fetch = (url, options = {}) => {
calls.push({ url, options })
return Promise.resolve(handler(url, options, calls.length - 1))
}
return Promise.resolve(fn(calls)).finally(() => {
global.fetch = previous
})
}
function withApiUrl(value, fn) {
const previous = process.env['GITHUB_API_URL']
if (value === undefined) delete process.env['GITHUB_API_URL']
else process.env['GITHUB_API_URL'] = value
try {
return fn()
} finally {
if (previous === undefined) delete process.env['GITHUB_API_URL']
else process.env['GITHUB_API_URL'] = previous
}
}
test('apiBaseUrl trims trailing slashes for the active host', () => {
withApiUrl('https://api.github.com', () => assert.equal(apiBaseUrl(), 'https://api.github.com'))
withApiUrl('https://ghe.example.com/api/v3/', () => assert.equal(apiBaseUrl(), 'https://ghe.example.com/api/v3'))
})
test('apiBaseUrl fails closed when GITHUB_API_URL is unset instead of leaking the token to a default host', () => {
withApiUrl(undefined, () => assert.throws(() => apiBaseUrl(), /GITHUB_API_URL is not set/))
})
test('an authenticated call refuses to run when GITHUB_API_URL is unset', async () => {
let fetched = false
const previous = global.fetch
global.fetch = () => {
fetched = true
return Promise.resolve(fakeResponse({ status: 200, body: {} }))
}
try {
await withApiUrl(undefined, () =>
assert.rejects(createClient('secret-token').checkAuth('owner/name'), /GITHUB_API_URL is not set/),
)
} finally {
global.fetch = previous
}
assert.equal(fetched, false, 'no request must be made without a known API host')
})
test('repoPath splits and encodes owner/name', () => {
assert.equal(repoPath('owner/name'), 'owner/name')
assert.equal(repoPath('o w/n a'), 'o%20w/n%20a')
})
test('repoPath rejects malformed repositories', () => {
assert.throws(() => repoPath('owner'), /invalid repository/)
assert.throws(() => repoPath('a/b/c'), /invalid repository/)
assert.throws(() => repoPath(''), /invalid repository/)
})
test('makeLatestField maps the make-latest policy to the REST enum', () => {
assert.equal(makeLatestField({ makeLatest: 'true' }), 'true')
assert.equal(makeLatestField({ makeLatest: 'false' }), 'false')
assert.equal(makeLatestField({ makeLatest: 'auto' }), 'legacy')
assert.equal(makeLatestField({}), 'legacy')
})
test('makeLatestField keeps non-default branch releases out of Latest under default-branch', () => {
const onDefault = { makeLatest: 'default-branch', releaseContext: { refName: 'main', defaultBranch: 'main' } }
const offDefault = { makeLatest: 'default-branch', releaseContext: { refName: 'feature', defaultBranch: 'main' } }
assert.equal(makeLatestField(onDefault), 'legacy')
assert.equal(makeLatestField(offDefault), 'false')
})
test('checkAuth GETs the repository with a bearer header and throws on failure', async () => {
await withApiUrl('https://api.github.com', () =>
withFetch(
() => fakeResponse({ status: 200, body: { full_name: 'owner/name' } }),
async (calls) => {
await createClient('secret').checkAuth('owner/name')
assert.equal(calls[0].url, 'https://api.github.com/repos/owner/name')
assert.equal(calls[0].options.method, 'GET')
assert.equal(calls[0].options.headers.Authorization, 'Bearer secret')
},
),
)
await withApiUrl('https://api.github.com', () =>
withFetch(
() => fakeResponse({ status: 401, body: { message: 'Must authenticate to access this API.' } }),
async () => {
await assert.rejects(createClient('super-secret-token').checkAuth('owner/name'), (err) => {
assert.match(err.message, /HTTP 401.*Must authenticate/)
// The raw token must never appear in an error surfaced to logs or the step summary.
assert.equal(err.message.includes('super-secret-token'), false, 'token leaked into the error message')
return true
})
},
),
)
})
test('getReleaseByTag returns the release on 200 and absence on 404', async () => {
await withApiUrl('https://api.github.com', () =>
withFetch(
() => fakeResponse({ status: 200, body: { html_url: 'https://x/releases/v1', draft: false } }),
async () => {
const res = await createClient('secret').getReleaseByTag('owner/name', 'v1.2.3')
assert.deepEqual(res, { exists: true, url: 'https://x/releases/v1', isDraft: false })
},
),
)
await withApiUrl('https://api.github.com', () =>
withFetch(
() => fakeResponse({ status: 404, body: { message: 'Not Found' } }),
async (calls) => {
const res = await createClient('secret').getReleaseByTag('owner/name', 'v1.2.3')
assert.deepEqual(res, { exists: false, url: '' })
assert.equal(calls[0].url, 'https://api.github.com/repos/owner/name/releases/tags/v1.2.3')
},
),
)
})
test('getReleaseByTag does not swallow non-404 failures', async () => {
await withApiUrl('https://api.github.com', () =>
withFetch(
() => fakeResponse({ status: 403, body: { message: 'Forbidden' } }),
async () => {
await assert.rejects(
createClient('secret', { sleep: noSleep }).getReleaseByTag('owner/name', 'v1.2.3'),
/HTTP 403/,
)
},
),
)
})
test('createRelease without assets publishes directly and returns the URL', async () => {
await withApiUrl('https://api.github.com', () =>
withFetch(
() => fakeResponse({ status: 201, body: { id: 7, html_url: 'https://x/releases/v1', upload_url: '' } }),
async (calls) => {
const url = await createClient('secret').createRelease('owner/name', 'v1.2.3', [], {
makeLatest: 'true',
})
assert.equal(url, 'https://x/releases/v1')
assert.equal(calls.length, 1)
assert.equal(calls[0].options.method, 'POST')
const payload = JSON.parse(calls[0].options.body)
assert.equal(payload.tag_name, 'v1.2.3')
assert.equal(payload.draft, false)
assert.equal(payload.generate_release_notes, true)
assert.equal(payload.make_latest, 'true')
},
),
)
})
test('getTagVerification returns the host verification for a tag object', async () => {
await withApiUrl('https://api.github.com', () =>
withFetch(
() =>
fakeResponse({ status: 200, body: { tag: 'v1.2.3', verification: { verified: false, reason: 'no_user' } } }),
async (calls) => {
const verification = await createClient('secret').getTagVerification('owner/name', 'deadbeef')
assert.deepEqual(verification, { verified: false, reason: 'no_user' })
assert.equal(calls[0].url, 'https://api.github.com/repos/owner/name/git/tags/deadbeef')
},
),
)
})
test('getTagVerification returns an empty object when the response has no verification', async () => {
await withApiUrl('https://api.github.com', () =>
withFetch(
() => fakeResponse({ status: 200, body: { tag: 'v1.2.3' } }),
async () => {
assert.deepEqual(await createClient('secret').getTagVerification('owner/name', 'deadbeef'), {})
},
),
)
})
test('createRelease with assets drafts, uploads, then publishes', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dispatch-api-'))
const assetPath = path.join(dir, 'artifact.bin')
fs.writeFileSync(assetPath, 'payload-bytes')
try {
await withApiUrl('https://api.github.com', () =>
withFetch(
(url, options) => {
if (options.method === 'POST' && url.endsWith('/releases')) {
return fakeResponse({
status: 201,
body: {
id: 9,
html_url: '',
upload_url: 'https://uploads.example/repos/o/n/releases/9/assets{?name,label}',
},
})
}
if (options.method === 'POST') {
return fakeResponse({ status: 201, body: { id: 1 } })
}
return fakeResponse({ status: 200, body: { html_url: 'https://x/releases/v1' } })
},
async (calls) => {
const url = await createClient('secret').createRelease('owner/name', 'v1.2.3', [assetPath], {})
assert.equal(url, 'https://x/releases/v1')
assert.equal(JSON.parse(calls[0].options.body).draft, true)
const upload = calls[1]
assert.equal(upload.url, 'https://uploads.example/repos/o/n/releases/9/assets?name=artifact.bin')
assert.equal(upload.options.headers['Content-Type'], 'application/octet-stream')
const publish = calls[2]
assert.equal(publish.options.method, 'PATCH')
assert.equal(publish.url, 'https://api.github.com/repos/owner/name/releases/9')
assert.equal(JSON.parse(publish.options.body).draft, false)
},
),
)
} finally {
fs.rmSync(dir, { recursive: true, force: true })
}
})
// Transient-failure hardening
test('request sends an identifying User-Agent, which GitHub requires', async () => {
await withFetch(
() => fakeResponse({ status: 200, body: {} }),
async (calls) => {
await request('tok', 'GET', 'https://api.example/x')
assert.equal(calls[0].options.headers['User-Agent'], 'goeselt-dispatch')
},
)
})
test('request retries a retryable status and then succeeds', async () => {
await withFetch(
(url, options, i) => (i < 2 ? fakeResponse({ status: 503 }) : fakeResponse({ status: 200, body: { ok: true } })),
async (calls) => {
const res = await request('tok', 'GET', 'https://api.example/x', { sleep: noSleep })
assert.deepEqual(res.body, { ok: true })
assert.equal(calls.length, 3)
},
)
})
test('request stops after maxAttempts and surfaces the last failure', async () => {
await withFetch(
() => fakeResponse({ status: 500, body: { message: 'boom' } }),
async (calls) => {
await assert.rejects(request('tok', 'GET', 'https://api.example/x', { sleep: noSleep }), /HTTP 500 boom/)
assert.equal(calls.length, 4)
},
)
})
test('request retries an idempotent method after a network error', async () => {
await withFetch(
(url, options, i) => {
if (i === 0) throw new Error('ECONNRESET')
return fakeResponse({ status: 200, body: { ok: true } })
},
async (calls) => {
const res = await request('tok', 'GET', 'https://api.example/x', { sleep: noSleep })
assert.deepEqual(res.body, { ok: true })
assert.equal(calls.length, 2)
},
)
})
test('request does not retry a POST after a network error, to avoid duplicate writes', async () => {
await withFetch(
() => {
throw new Error('ECONNRESET')
},
async (calls) => {
await assert.rejects(request('tok', 'POST', 'https://api.example/x', { sleep: noSleep }), /ECONNRESET/)
assert.equal(calls.length, 1)
},
)
})
test('request honors a Retry-After header as the minimum backoff and retries a 403 secondary-rate limit', async () => {
const delays = []
const recordingSleep = (ms) => {
delays.push(ms)
return Promise.resolve()
}
await withFetch(
(url, options, i) =>
i === 0
? {
ok: false,
status: 403,
headers: { get: (name) => (name.toLowerCase() === 'retry-after' ? '7' : null) },
text: () => Promise.resolve(''),
}
: fakeResponse({ status: 200, body: { ok: true } }),
async (calls) => {
const res = await request('tok', 'GET', 'https://api.example/x', { sleep: recordingSleep })
assert.deepEqual(res.body, { ok: true })
assert.equal(calls.length, 2)
assert.ok(delays[0] >= 7000, `expected the Retry-After floor of 7000ms, got ${delays[0]}`)
},
)
})
test('request does not retry a plain 403 without Retry-After', async () => {
await withFetch(
() => fakeResponse({ status: 403, body: { message: 'Forbidden' } }),
async (calls) => {
await assert.rejects(request('tok', 'GET', 'https://api.example/x', { sleep: noSleep }), /HTTP 403/)
assert.equal(calls.length, 1)
},
)
})
test('retryDelayMs grows with attempts and respects the Retry-After floor', () => {
assert.ok(retryDelayMs(1, null) >= 500)
assert.ok(retryDelayMs(3, null) >= retryDelayMs(1, null))
assert.ok(retryDelayMs(1, '30') >= 30000)
})
test('retryDelayMs caps a hostile Retry-After so it cannot stall the run', () => {
// "Retry-After: 999999" would otherwise mean ~11.5 days; it must be clamped to the 60s ceiling.
assert.equal(retryDelayMs(1, '999999'), 60000)
})
test('request reports each retry through onRetry with the status and attempt', async () => {
const events = []
await withFetch(
(url, options, i) => (i === 0 ? fakeResponse({ status: 503 }) : fakeResponse({ status: 200, body: { ok: true } })),
async () => {
await request('tok', 'GET', 'https://api.example/x', { sleep: noSleep, onRetry: (info) => events.push(info) })
},
)
assert.equal(events.length, 1)
assert.deepEqual(
{
method: events[0].method,
status: events[0].status,
attempt: events[0].attempt,
maxAttempts: events[0].maxAttempts,
},
{ method: 'GET', status: 503, attempt: 1, maxAttempts: 4 },
)
assert.ok(events[0].delayMs >= 500)
})
test('onRetry reports a null status for a network-level retry', async () => {
const events = []
await withFetch(
(url, options, i) => {
if (i === 0) throw new Error('ECONNRESET')
return fakeResponse({ status: 200, body: {} })
},
async () => {
await request('tok', 'GET', 'https://api.example/x', { sleep: noSleep, onRetry: (info) => events.push(info) })
},
)
assert.equal(events.length, 1)
assert.equal(events[0].status, null)
})