-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathtestCliUtils.ts
More file actions
317 lines (297 loc) · 9.5 KB
/
testCliUtils.ts
File metadata and controls
317 lines (297 loc) · 9.5 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
/**
* Copyright 2026 GitProxy Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'fs';
import util from 'util';
import { exec } from 'child_process';
import { expect } from 'vitest';
import { Request } from 'express';
import { Proxy } from '../../../src/proxy';
import { Action } from '../../../src/proxy/actions/Action';
import { Step } from '../../../src/proxy/actions/Step';
import { exec as execProcessor } from '../../../src/proxy/processors/post-processor/audit';
import * as db from '../../../src/db';
import { Repo } from '../../../src/db/types';
import { Service as service } from '../../../src/service';
import { CommitData } from '../../../src/proxy/processors/types';
const execAsync = util.promisify(exec);
// cookie file name
const GIT_PROXY_COOKIE_FILE = 'git-proxy-cookie';
/**
* Type guard to check if error is from child_process exec
*/
function isExecError(error: unknown): error is Error & {
code: number;
stdout: string;
stderr: string;
} {
return error instanceof Error && 'code' in error && 'stdout' in error && 'stderr' in error;
}
/**
* @async
* @param {string} cli - The CLI command to be executed.
* @param {number} expectedExitCode - The expected exit code after the command
* execution. Typically, `0` for successful execution.
* @param {string} expectedMessages - The array of expected messages included
* in the output after the command execution.
* @param {string} expectedErrorMessages - The array of expected messages
* included in the error output after the command execution.
* @param {boolean} debug - Flag to enable detailed logging for debugging.
* @throws {AssertionError} Throws an error if the actual exit code does not
* match the `expectedExitCode`.
*/
async function runCli(
cli: string,
expectedExitCode: number = 0,
expectedMessages: string[] | null = null,
expectedErrorMessages: string[] | null = null,
debug: boolean = true,
) {
try {
console.log(`cli: '${cli}'`);
const { stdout, stderr } = await execAsync(cli);
if (debug) {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
}
expect(0).toEqual(expectedExitCode);
if (expectedMessages) {
expectedMessages.forEach((expectedMessage) => {
expect(stdout).toContain(expectedMessage);
});
}
if (expectedErrorMessages) {
expectedErrorMessages.forEach((expectedErrorMessage) => {
expect(stderr).toContain(expectedErrorMessage);
});
}
} catch (error: unknown) {
if (isExecError(error)) {
const exitCode = error.code;
if (debug) {
console.log(`error.stdout: ${error.stdout}`);
console.log(`error.stderr: ${error.stderr}`);
}
expect(exitCode).toEqual(expectedExitCode);
if (expectedMessages) {
expectedMessages.forEach((expectedMessage) => {
expect(error.stdout).toContain(expectedMessage);
});
}
if (expectedErrorMessages) {
expectedErrorMessages.forEach((expectedErrorMessage) => {
expect(error.stderr).toContain(expectedErrorMessage);
});
}
} else {
// Assertion error, forward to Vitest to process
throw error;
}
} finally {
if (debug) {
console.log(`cli: '${cli}': done`);
}
}
}
/**
* Starts the server.
* @param {*} service - The GitProxy API service to be started.
* @return {Promise<void>} A promise that resolves when the service has
* successfully started. Does not return any value upon resolution.
*/
async function startServer() {
await service.start(new Proxy());
}
/**
* Closes the specified HTTP server gracefully. This function wraps the
* `close` method of the `http.Server` instance in a promise to facilitate
* async/await usage. It ensures the server stops accepting new connections
* and terminates existing ones before shutting down.
*
* @param {number} waitTime - The wait time after close.
* @return {Promise<void>} A promise that resolves when the server has been
* successfully closed, or rejects if an error occurs during closure. The
* promise does not return any value upon resolution.
*
* @throws {Error} If the server cannot be closed properly or if an error
* occurs during the close operation.
*/
async function closeServer(waitTime: number = 0) {
const server = service.httpServer;
if (!server) {
throw new Error('Server not started');
}
return new Promise<void>((resolve, reject) => {
server.closeAllConnections();
server.close((err) => {
if (err) {
console.error('Failed to close the server:', err);
reject(err); // Reject the promise if there's an error
} else {
setTimeout(() => {
console.log(`Server closed successfully (wait time ${waitTime}).`);
resolve(); // Resolve the promise when the server is closed
}, waitTime);
}
});
});
}
/**
* Create local cookies file with an expired connect cookie.
*/
async function createCookiesFileWithExpiredCookie() {
await removeCookiesFile();
const cookies = [
'connect.sid=s%3AuWjJK_VGFbX9-03UfvoSt_HFU3a0vFOd.jd986YQ17Bw4j1xGJn2l9yiF3QPYhayaYcDqGsNgQY4; Path=/; HttpOnly',
];
fs.writeFileSync(GIT_PROXY_COOKIE_FILE, JSON.stringify(cookies), 'utf8');
}
/**
* Remove local cookies file.
*/
async function removeCookiesFile() {
if (fs.existsSync(GIT_PROXY_COOKIE_FILE)) {
fs.unlinkSync(GIT_PROXY_COOKIE_FILE);
}
}
/**
* Add a new repo to the database.
* @param {object} newRepo The new repo attributes.
* @param {boolean} debug Print debug messages to console if true.
*/
async function addRepoToDb(newRepo: Repo, debug = false) {
const { data: repos } = await db.getRepos();
const found = repos.find((y) => y.project === newRepo.project && newRepo.name === y.name);
if (!found) {
await db.createRepo(newRepo);
const repo = await db.getRepoByUrl(newRepo.url);
await db.addUserCanPush(repo?._id || '', 'admin');
await db.addUserCanAuthorise(repo?._id || '', 'admin');
if (debug) {
console.log(`New repo added to database: ${newRepo}`);
}
} else {
if (debug) {
console.log(`New repo already found in database: ${newRepo}`);
}
}
}
/**
* Removes a repo from the DB.
* @param {string} repoUrl The url of the repo to remove.
*/
async function removeRepoFromDb(repoUrl: string) {
const repo = await db.getRepoByUrl(repoUrl);
await db.deleteRepo(repo?._id || '');
}
/**
* Add a new git push record to the database.
* @param {string} id The ID of the git push.
* @param {string} repoUrl The repository URL of the git push.
* @param {string} user The user who pushed the git push.
* @param {string} userEmail The email of the user who pushed the git push.
* @param {boolean} debug Flag to enable logging for debugging.
*/
async function addGitPushToDb(
id: string,
repoUrl: string,
user: string | null = null,
userEmail: string | null = null,
debug: boolean = false,
) {
const action = new Action(
id,
'push', // type
'get', // method
Date.now(), // timestamp
repoUrl,
);
action.user = user || '';
action.userEmail = userEmail || '';
const step = new Step(
'authBlock', // stepName
false, // error
null, // errorMessage
true, // blocked
`\n\n\nGitProxy has received your push:\n\nhttp://localhost:8080/requests/${id}\n\n\n`, // blockedMessage
null, // content
);
const commitData: CommitData[] = [];
commitData.push({
tree: 'tree test',
parent: 'parent',
author: 'author',
committer: 'committer',
message: 'message',
authorEmail: 'authorEmail',
committerEmail: 'committerEmail',
commitTimestamp: '1234567890',
});
action.commitData = commitData;
action.addStep(step);
const result = await execProcessor({} as Request, action);
if (debug) {
console.log(`New git push added to DB: ${util.inspect(result)}`);
}
}
/**
* Removes a push from the DB
* @param {string} id
*/
async function removeGitPushFromDb(id: string) {
await db.deletePush(id);
}
/**
* Add new user record to the database.
* @param {string} username The user name.
* @param {string} password The user password.
* @param {string} email The user email.
* @param {string} gitAccount The user git account.
* @param {boolean} admin Flag to make the user administrator.
* @param {boolean} debug Flag to enable logging for debugging.
*/
async function addUserToDb(
username: string,
password: string,
email: string,
gitAccount: string,
admin: boolean = false,
debug: boolean = false,
) {
const result = await db.createUser(username, password, email, gitAccount, admin);
if (debug) {
console.log(`New user added to DB: ${util.inspect(result)}`);
}
}
/**
* Remove a user record from the database if present.
* @param {string} username The user name.
*/
async function removeUserFromDb(username: string) {
await db.deleteUser(username);
}
export {
runCli,
startServer,
closeServer,
addRepoToDb,
removeRepoFromDb,
addGitPushToDb,
removeGitPushFromDb,
addUserToDb,
removeUserFromDb,
createCookiesFileWithExpiredCookie,
removeCookiesFile,
};