-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcontainer-cleanup-branches.test.ts
More file actions
363 lines (300 loc) · 12.6 KB
/
container-cleanup-branches.test.ts
File metadata and controls
363 lines (300 loc) · 12.6 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
/**
* Targeted branch-coverage tests for container-cleanup.ts.
*
* These tests cover paths that were not exercised by the existing
* docker-manager-cleanup.test.ts suite, focusing on:
* - sanitizeDockerComposeYaml edge cases
* - cleanup() branches for cli-proxy logs, audit dir, session state, and SSL
*/
import { cleanup, collectDiagnosticLogs } from './container-cleanup';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as yaml from 'js-yaml';
// Mock execa
import { mockExecaFn, mockExecaSync } from './test-helpers/mock-execa.test-utils';
// eslint-disable-next-line @typescript-eslint/no-require-imports
jest.mock('execa', () => require('./test-helpers/mock-execa.test-utils').execaMockFactory());
// Mock ssl-bump so cleanup() doesn't attempt real mount operations
jest.mock('./ssl-bump', () => ({
cleanupSslKeyMaterial: jest.fn(),
unmountSslTmpfs: jest.fn().mockResolvedValue(undefined),
}));
jest.mock('./host-env', () => {
const actual = jest.requireActual('./host-env');
return {
...actual,
getSafeHostUid: () => String(process.getuid?.() ?? 1000),
getSafeHostGid: () => String(process.getgid?.() ?? 1000),
};
});
// ─── helpers ─────────────────────────────────────────────────────────────────
function makeTmpDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'awf-'));
}
// ─── sanitizeDockerComposeYaml edge cases (via collectDiagnosticLogs) ────────
describe('sanitizeDockerComposeYaml edge cases', () => {
let testDir: string;
beforeEach(() => {
testDir = makeTmpDir();
jest.clearAllMocks();
mockExecaFn.mockResolvedValue({ stdout: '', stderr: '', exitCode: 0 });
});
afterEach(() => {
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('returns raw string when YAML parses to a non-object (null)', async () => {
// "null" is valid YAML that parses to null — the sanitizer should return the raw content
fs.writeFileSync(path.join(testDir, 'docker-compose.yml'), 'null');
await collectDiagnosticLogs(testDir);
const diagnosticsDir = path.join(testDir, 'diagnostics');
const sanitized = fs.readFileSync(path.join(diagnosticsDir, 'docker-compose.yml'), 'utf8');
expect(sanitized).toBe('null');
});
it('sanitizes when compose has no services key', async () => {
// Parsed object but without a "services" key — should dump the yaml without error
fs.writeFileSync(path.join(testDir, 'docker-compose.yml'), 'version: "3"\n');
await collectDiagnosticLogs(testDir);
const diagnosticsDir = path.join(testDir, 'diagnostics');
const sanitized = fs.readFileSync(path.join(diagnosticsDir, 'docker-compose.yml'), 'utf8');
expect(yaml.load(sanitized)).toEqual({ version: '3' });
});
it('sanitizes when services is an array instead of an object', async () => {
// services is an array — should be treated as "no services to sanitize"
fs.writeFileSync(
path.join(testDir, 'docker-compose.yml'),
['version: "3"', 'services:', ' - name: agent'].join('\n')
);
await collectDiagnosticLogs(testDir);
const diagnosticsDir = path.join(testDir, 'diagnostics');
const sanitized = fs.readFileSync(path.join(diagnosticsDir, 'docker-compose.yml'), 'utf8');
expect(yaml.load(sanitized)).toEqual({ version: '3', services: [{ name: 'agent' }] });
});
it('skips service entries that are not plain objects', async () => {
// A service entry whose value is a primitive (null/string) — should not throw
const raw = ['services:', ' broken_service: null', ' valid_service:', ' image: nginx'].join('\n');
fs.writeFileSync(path.join(testDir, 'docker-compose.yml'), raw);
await collectDiagnosticLogs(testDir);
const diagnosticsDir = path.join(testDir, 'diagnostics');
const sanitized = fs.readFileSync(path.join(diagnosticsDir, 'docker-compose.yml'), 'utf8');
expect(yaml.load(sanitized)).toEqual({
services: {
broken_service: null,
valid_service: {
image: 'nginx',
},
},
});
});
it('preserves all env vars when service has no environment key', async () => {
// Service without an "environment" field — no redaction needed
const raw = ['services:', ' agent:', ' image: ubuntu:22.04'].join('\n');
fs.writeFileSync(path.join(testDir, 'docker-compose.yml'), raw);
await collectDiagnosticLogs(testDir);
const sanitized = fs.readFileSync(
path.join(testDir, 'diagnostics', 'docker-compose.yml'),
'utf8'
);
expect(sanitized).not.toContain('[REDACTED]');
expect(yaml.load(sanitized)).toEqual({
services: {
agent: {
image: 'ubuntu:22.04',
},
},
});
});
it('redacts secrets in array-form environment entries', async () => {
// Array-style environment (list of KEY=VALUE strings)
const raw = [
'services:',
' agent:',
' environment:',
' - GITHUB_TOKEN=ghp_array',
' - NORMAL_VAR=keep_me',
' - NO_EQUALS_HERE',
].join('\n');
fs.writeFileSync(path.join(testDir, 'docker-compose.yml'), raw);
await collectDiagnosticLogs(testDir);
const sanitized = fs.readFileSync(
path.join(testDir, 'diagnostics', 'docker-compose.yml'),
'utf8'
);
expect(sanitized).not.toContain('ghp_array');
expect(sanitized).toContain('keep_me');
// Entry without "=" should be preserved unchanged
expect(sanitized).toContain('NO_EQUALS_HERE');
});
});
// ─── cleanup() missing branch coverage ───────────────────────────────────────
describe('cleanup - cli-proxy logs', () => {
let testDir: string;
beforeEach(() => {
testDir = makeTmpDir();
jest.clearAllMocks();
mockExecaSync.mockReturnValue(undefined);
});
afterEach(() => {
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('chmods cli-proxy-logs inside proxyLogsDir when it exists', async () => {
const proxyLogsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-proxy-'));
try {
const cliProxyLogsDir = path.join(proxyLogsDir, 'cli-proxy-logs');
fs.mkdirSync(cliProxyLogsDir, { recursive: true });
fs.writeFileSync(path.join(cliProxyLogsDir, 'difc-proxy.log'), 'audit entry\n');
await cleanup(testDir, false, proxyLogsDir);
expect(mockExecaSync).toHaveBeenCalledWith('chmod', ['-R', 'a+rX', cliProxyLogsDir]);
} finally {
if (fs.existsSync(proxyLogsDir)) {
fs.rmSync(proxyLogsDir, { recursive: true, force: true });
}
}
});
it('moves non-empty cli-proxy-logs to /tmp when proxyLogsDir is not specified', async () => {
const cliProxyLogsDir = path.join(testDir, 'cli-proxy-logs');
fs.mkdirSync(cliProxyLogsDir, { recursive: true });
fs.writeFileSync(path.join(cliProxyLogsDir, 'difc-proxy.log'), 'audit entry\n');
await cleanup(testDir, false);
const timestamp = path.basename(testDir).replace('awf-', '');
const destination = path.join(os.tmpdir(), `cli-proxy-logs-${timestamp}`);
expect(fs.existsSync(destination)).toBe(true);
const movedLogPath = path.join(destination, 'difc-proxy.log');
expect(fs.existsSync(movedLogPath)).toBe(true);
expect(fs.readFileSync(movedLogPath, 'utf8')).toBe('audit entry\n');
// testDir is deleted by cleanup; clean up the destination
if (fs.existsSync(destination)) {
fs.rmSync(destination, { recursive: true, force: true });
}
});
it('does not move empty cli-proxy-logs directory', async () => {
const cliProxyLogsDir = path.join(testDir, 'cli-proxy-logs');
fs.mkdirSync(cliProxyLogsDir, { recursive: true });
// leave it empty
await cleanup(testDir, false);
const timestamp = path.basename(testDir).replace('awf-', '');
const destination = path.join(os.tmpdir(), `cli-proxy-logs-${timestamp}`);
expect(fs.existsSync(destination)).toBe(false);
});
});
describe('cleanup - api-proxy logs via proxyLogsDir', () => {
let testDir: string;
beforeEach(() => {
testDir = makeTmpDir();
jest.clearAllMocks();
mockExecaSync.mockReturnValue(undefined);
});
afterEach(() => {
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('chmods api-proxy-logs inside proxyLogsDir when it exists and is non-empty', async () => {
const proxyLogsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-proxy-'));
try {
const apiProxyLogsDir = path.join(proxyLogsDir, 'api-proxy-logs');
fs.mkdirSync(apiProxyLogsDir, { recursive: true });
fs.writeFileSync(path.join(apiProxyLogsDir, 'proxy.log'), 'request\n');
await cleanup(testDir, false, proxyLogsDir);
expect(mockExecaSync).toHaveBeenCalledWith('chmod', ['-R', 'a+rX', apiProxyLogsDir]);
} finally {
if (fs.existsSync(proxyLogsDir)) {
fs.rmSync(proxyLogsDir, { recursive: true, force: true });
}
}
});
});
describe('cleanup - audit dir', () => {
let testDir: string;
beforeEach(() => {
testDir = makeTmpDir();
jest.clearAllMocks();
mockExecaSync.mockReturnValue(undefined);
});
afterEach(() => {
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('skips chmod when auditDir is specified but does not exist', async () => {
const nonExistentAuditDir = path.join(os.tmpdir(), `awf-nonexistent-audit-${Date.now()}`);
await cleanup(testDir, false, undefined, nonExistentAuditDir);
expect(mockExecaSync).not.toHaveBeenCalledWith('chmod', ['-R', 'a+rX', nonExistentAuditDir]);
});
it('does not move empty default audit directory', async () => {
const defaultAuditDir = path.join(testDir, 'audit');
fs.mkdirSync(defaultAuditDir, { recursive: true });
// leave it empty
await cleanup(testDir, false);
const timestamp = path.basename(testDir).replace('awf-', '');
const destination = path.join(os.tmpdir(), `awf-audit-${timestamp}`);
expect(fs.existsSync(destination)).toBe(false);
});
});
describe('cleanup - sessionStateDir', () => {
let testDir: string;
beforeEach(() => {
testDir = makeTmpDir();
jest.clearAllMocks();
mockExecaSync.mockReturnValue(undefined);
});
afterEach(() => {
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('skips chmod when sessionStateDir is specified but does not exist', async () => {
const nonExistentStateDir = path.join(os.tmpdir(), `awf-nonexistent-state-${Date.now()}`);
await cleanup(testDir, false, undefined, undefined, nonExistentStateDir);
expect(mockExecaSync).not.toHaveBeenCalledWith('chmod', ['-R', 'a+rX', nonExistentStateDir]);
});
it('chmods sessionStateDir in-place when it exists', async () => {
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-state-'));
try {
fs.writeFileSync(path.join(stateDir, 'events.jsonl'), '{"type":"start"}\n');
await cleanup(testDir, false, undefined, undefined, stateDir);
expect(mockExecaSync).toHaveBeenCalledWith('chmod', ['-R', 'a+rX', stateDir]);
} finally {
if (fs.existsSync(stateDir)) {
fs.rmSync(stateDir, { recursive: true, force: true });
}
}
});
});
describe('cleanup - SSL directory', () => {
let testDir: string;
beforeEach(() => {
testDir = makeTmpDir();
jest.clearAllMocks();
mockExecaSync.mockReturnValue(undefined);
});
afterEach(() => {
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('calls unmountSslTmpfs when ssl directory exists in workDir', async () => {
const { cleanupSslKeyMaterial, unmountSslTmpfs } = jest.requireMock('./ssl-bump') as {
cleanupSslKeyMaterial: jest.Mock;
unmountSslTmpfs: jest.Mock;
};
unmountSslTmpfs.mockResolvedValue(undefined);
const sslDir = path.join(testDir, 'ssl');
fs.mkdirSync(sslDir, { recursive: true });
fs.writeFileSync(path.join(sslDir, 'ca.pem'), 'fake-cert');
await cleanup(testDir, false);
expect(cleanupSslKeyMaterial).toHaveBeenCalledWith(testDir);
expect(unmountSslTmpfs).toHaveBeenCalledWith(sslDir);
});
it('does not call unmountSslTmpfs when ssl directory does not exist', async () => {
const { unmountSslTmpfs } = jest.requireMock('./ssl-bump') as {
unmountSslTmpfs: jest.Mock;
};
await cleanup(testDir, false);
expect(unmountSslTmpfs).not.toHaveBeenCalled();
});
});