-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathgitGateway.js
More file actions
339 lines (296 loc) · 9.48 KB
/
gitGateway.js
File metadata and controls
339 lines (296 loc) · 9.48 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
const fetch = require('node-fetch');
const {
transformRecordedData: transformGitHub,
setupGitHub,
teardownGitHub,
setupGitHubTest,
teardownGitHubTest,
} = require('./github');
const {
transformRecordedData: transformGitLab,
setupGitLab,
teardownGitLab,
setupGitLabTest,
teardownGitLabTest,
} = require('./gitlab');
const { getGitClient } = require('./common');
function getEnvs() {
const {
NETLIFY_API_TOKEN: netlifyApiToken,
GITHUB_REPO_TOKEN: githubToken,
GITLAB_REPO_TOKEN: gitlabToken,
NETLIFY_INSTALLATION_ID: installationId,
} = process.env;
if (!netlifyApiToken) {
throw new Error(
'Please set NETLIFY_API_TOKEN, GITHUB_REPO_TOKEN, GITLAB_REPO_TOKEN, NETLIFY_INSTALLATION_ID environment variables',
);
}
return { netlifyApiToken, githubToken, gitlabToken, installationId };
}
const apiRoot = 'https://api.netlify.com/api/v1/';
async function fetchWithTimeout(netlifyApiToken, path, method = 'GET', payload = null, parseAs = 'json') {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000); // 10 second timeout
try {
const options = {
signal: controller.signal,
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${netlifyApiToken}`,
},
};
if (payload) {
options.body = JSON.stringify(payload);
}
const response = await fetch(`${apiRoot}${path}`, options);
clearTimeout(timeout);
return parseAs === 'json' ? response.json() : response.text();
} catch (error) {
clearTimeout(timeout);
if (error.name === 'AbortError') {
console.error(`Netlify API ${method} timeout after 10s: ${path}`);
throw new Error(`Netlify API ${method} request timeout: ${path}`);
}
throw error;
}
}
async function createSite(netlifyApiToken, payload) {
return fetchWithTimeout(netlifyApiToken, 'sites', 'POST', payload);
}
async function enableIdentity(netlifyApiToken, siteId) {
return fetchWithTimeout(netlifyApiToken, `sites/${siteId}/identity`, 'POST', {});
}
async function enableGitGateway(netlifyApiToken, siteId, provider, token, repo) {
return fetchWithTimeout(netlifyApiToken, `sites/${siteId}/services/git/instances`, 'POST', {
[provider]: {
repo,
access_token: token,
},
});
}
async function enableLargeMedia(netlifyApiToken, siteId) {
return fetchWithTimeout(netlifyApiToken, `sites/${siteId}/services/large-media/instances`, 'POST', {});
}
async function waitForDeploys(netlifyApiToken, siteId) {
const maxRetries = 5;
const retryDelayMs = 15 * 1000; // 15 seconds between retries
for (let i = 0; i < maxRetries; i++) {
try {
const deploys = await fetchWithTimeout(netlifyApiToken, `sites/${siteId}/deploys`);
if (deploys && deploys.some(deploy => deploy.state === 'ready')) {
return;
}
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
}
} catch (error) {
console.error(`Error checking deploy status: ${error.message}`);
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
}
}
}
throw new Error(`Timed out waiting for deploy of site ${siteId} after ${maxRetries * retryDelayMs / 1000}s`);
}
async function createUser(netlifyApiToken, siteUrl, email, password) {
const response = await fetch(`${siteUrl}/.netlify/functions/create-user`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${netlifyApiToken}`,
},
body: JSON.stringify({ email, password }),
});
if (response.ok) {
console.log('User created successfully');
} else {
throw new Error('Failed to create user');
}
}
const netlifySiteURL = 'https://fake-site-url.netlify.com/';
const email = 'decap@p-m.si';
const password = '12345678';
const backendName = 'git-gateway';
const methods = {
github: {
setup: setupGitHub,
teardown: teardownGitHub,
setupTest: setupGitHubTest,
teardownTest: teardownGitHubTest,
transformData: transformGitHub,
createSite: (netlifyApiToken, result) => {
const { installationId } = getEnvs();
return createSite(netlifyApiToken, {
repo: {
provider: 'github',
installation_id: installationId,
repo: `${result.owner}/${result.repo}`,
},
});
},
token: () => getEnvs().githubToken,
},
gitlab: {
setup: setupGitLab,
teardown: teardownGitLab,
setupTest: setupGitLabTest,
teardownTest: teardownGitLabTest,
transformData: transformGitLab,
createSite: async (netlifyApiToken, result) => {
const { id, public_key } = await fetchWithTimeout(netlifyApiToken, 'deploy_keys', 'POST');
const { gitlabToken } = getEnvs();
const project = `${result.owner}/${result.repo}`;
await fetch(`https://gitlab.com/api/v4/projects/${encodeURIComponent(project)}/deploy_keys`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${gitlabToken}`,
},
body: JSON.stringify({ title: 'Netlify Deploy Key', key: public_key, can_push: false }),
}).then(res => res.json());
const site = await createSite(netlifyApiToken, {
account_slug: result.owner,
repo: {
provider: 'gitlab',
repo: `${result.owner}/${result.repo}`,
deploy_key_id: id,
},
});
await fetch(`https://gitlab.com/api/v4/projects/${encodeURIComponent(project)}/hooks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${gitlabToken}`,
},
body: JSON.stringify({
url: 'https://api.netlify.com/hooks/gitlab',
push_events: true,
merge_requests_events: true,
enable_ssl_verification: true,
}),
}).then(res => res.json());
return site;
},
token: () => getEnvs().gitlabToken,
},
};
async function setupGitGateway(options) {
const { provider, ...rest } = options;
const result = await methods[provider].setup(rest);
if (process.env.RECORD_FIXTURES) {
const { netlifyApiToken } = getEnvs();
console.log(`Creating Netlify Site for provider: ${provider}`);
let site_id, ssl_url;
try {
({ site_id, ssl_url } = await methods[provider].createSite(netlifyApiToken, result));
} catch (e) {
console.log(e);
throw e;
}
console.log('Enabling identity for site:', site_id);
await enableIdentity(netlifyApiToken, site_id);
console.log('Enabling git gateway for site:', site_id);
const token = methods[provider].token();
await enableGitGateway(
netlifyApiToken,
site_id,
provider,
token,
`${result.owner}/${result.repo}`,
);
console.log('Enabling large media for site:', site_id);
await enableLargeMedia(netlifyApiToken, site_id);
const git = getGitClient(result.tempDir);
await git.raw([
'config',
'-f',
'.lfsconfig',
'lfs.url',
`https://${site_id}.netlify.com/.netlify/large-media`,
]);
await git.addConfig('commit.gpgsign', 'false');
await git.add('.lfsconfig');
await git.commit('add .lfsconfig');
await git.push('origin', 'master');
await waitForDeploys(netlifyApiToken, site_id);
console.log('Creating user for site:', site_id, 'with email:', email);
try {
await createUser(netlifyApiToken, ssl_url, email, password);
} catch (e) {
console.log(e);
}
return {
...result,
user: {
...result.user,
backendName,
netlifySiteURL: ssl_url,
email,
password,
},
site_id,
ssl_url,
provider,
};
} else {
console.log('Running tests in "playback" mode - local data will be used');
return {
...result,
user: {
...result.user,
backendName,
netlifySiteURL,
email,
password,
},
provider,
mockResponses: true,
};
}
}
async function teardownGitGateway(taskData) {
if (process.env.RECORD_FIXTURES) {
const { netlifyApiToken } = getEnvs();
const { site_id } = taskData;
console.log('Deleting Netlify site:', site_id);
await fetchWithTimeout(netlifyApiToken, `sites/${site_id}`, 'DELETE', null, 'text');
const result = await methods[taskData.provider].teardown(taskData);
return result;
}
return null;
}
async function setupGitGatewayTest(taskData) {
if (process.env.RECORD_FIXTURES) {
const result = await methods[taskData.provider].setupTest(taskData);
return result;
}
return null;
}
async function teardownGitGatewayTest(taskData) {
if (process.env.RECORD_FIXTURES) {
const options = {
transformRecordedData: (expectation, toSanitize) => {
const result = methods[taskData.provider].transformData(expectation, toSanitize);
if (result.response && result.url === '/.netlify/identity/token') {
const parsed = JSON.parse(result.response);
parsed.access_token = 'access_token';
parsed.refresh_token = 'refresh_token';
return { ...result, response: JSON.stringify(parsed) };
} else {
return result;
}
},
};
const result = await methods[taskData.provider].teardownTest(taskData, options);
return result;
}
return null;
}
module.exports = {
setupGitGateway,
teardownGitGateway,
setupGitGatewayTest,
teardownGitGatewayTest,
};