-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.test.ts
More file actions
535 lines (465 loc) · 16.1 KB
/
Copy pathscanner.test.ts
File metadata and controls
535 lines (465 loc) · 16.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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { API_CONTRACT_MISMATCH_RULE_ID } from '../contract/contract-check.js'
import { err, ok } from '../model/result.js'
import { Severity } from '../model/finding.js'
import * as fileReader from '../parse/file-reader.js'
import { FileReaderError } from '../parse/file-reader.js'
import { missingErrorHandler } from '../rules/missing-error-handler.js'
import { DEFAULT_SCAN_CONFIG, resolveConfig, scan } from './scanner.js'
function createFixture(): string {
return mkdtempSync(join(tmpdir(), 'sentinel-scanner-'))
}
function writeScanFixture(root: string, files: Record<string, string>): void {
for (const [relativePath, content] of Object.entries(files)) {
const absolutePath = join(root, relativePath)
mkdirSync(dirname(absolutePath), { recursive: true })
writeFileSync(absolutePath, content, 'utf8')
}
}
function writeOpenApiSpec(root: string, fileName: string, spec: unknown): string {
const filePath = join(root, fileName)
writeFileSync(filePath, JSON.stringify(spec), 'utf8')
return filePath
}
const OFF_RULES = {
'missing-error-handler': 'off' as const,
'no-hardcoded-url': 'off' as const,
'api-contract-mismatch': Severity.Error,
}
function usersPostSpec(): unknown {
return {
openapi: '3.0.3',
info: { title: 'Test', version: '1.0.0' },
paths: {
'/users': {
post: {
operationId: 'createUser',
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string' },
age: { type: 'integer' },
},
},
},
},
},
responses: {
'201': {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
id: { type: 'string' },
},
},
},
},
},
},
},
},
},
}
}
function usersGetSpec(): unknown {
return {
openapi: '3.0.3',
info: { title: 'Test', version: '1.0.0' },
paths: {
'/users': {
get: {
operationId: 'listUsers',
responses: {
'200': {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
id: { type: 'string' },
},
},
},
},
},
},
},
},
},
}
}
describe('resolveConfig', () => {
it('uses default exclude when exclude is omitted', () => {
const config = resolveConfig({ rootDir: '/tmp' })
expect(config.exclude).toEqual(DEFAULT_SCAN_CONFIG.exclude)
expect(config.exclude).toHaveLength(15)
})
it('merges user exclude patterns onto defaults', () => {
const config = resolveConfig({
rootDir: '/tmp',
exclude: ['generated/**'],
})
expect(config.exclude).toContain('**/node_modules/**')
expect(config.exclude).toContain('**/*.min.js')
expect(config.exclude).toContain('**/*.d.ts')
expect(config.exclude).toContain('**/vendor/**')
expect(config.exclude).toContain('generated/**')
})
it('deduplicates exclude patterns when user repeats a default', () => {
const config = resolveConfig({
rootDir: '/tmp',
exclude: ['**/node_modules/**'],
})
const nodeModulesCount = config.exclude.filter((p) => p === '**/node_modules/**').length
expect(nodeModulesCount).toBe(1)
})
it('replaces include when user provides include (does not merge)', () => {
const config = resolveConfig({
rootDir: '/tmp',
include: ['src/**'],
})
expect(config.include).toEqual(['src/**'])
})
})
describe('scan', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('continues scanning when one file fails to read and emits parse-error', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'good.ts': "fetch('/ok')",
'bad.ts': "fetch('/bad')",
})
const badPath = resolve(root, 'bad.ts')
const readSpy = vi.spyOn(fileReader, 'readFileContent')
readSpy.mockImplementation(async (path) => {
if (resolve(path) === badPath) {
return err(new FileReaderError(`Could not read file: ${path}`, new Error('EACCES')))
}
try {
return ok(await readFile(path, 'utf-8'))
} catch (cause) {
return err(new FileReaderError(`Could not read file: ${path}`, cause))
}
})
const result = await scan(
resolveConfig({
rootDir: root,
rules: { 'missing-error-handler': Severity.Warning, 'no-hardcoded-url': 'off' },
}),
)
expect(readSpy).toHaveBeenCalled()
expect(result.stats.filesErrored).toBe(1)
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: 'parse-error',
file: badPath,
}),
]),
)
expect(result.apiCalls.some((call) => call.url === '/ok')).toBe(true)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('emits unsupported-syntax for malformed files and still extracts partial calls', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'broken.ts': "fetch('/partial')\nconst x = {{{\n",
'valid.ts': "fetch('/ok')",
})
const result = await scan(
resolveConfig({
rootDir: root,
rules: { 'missing-error-handler': 'off', 'no-hardcoded-url': 'off' },
}),
)
const brokenPath = join(root, 'broken.ts')
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: 'unsupported-syntax',
file: brokenPath,
message: expect.stringContaining('Results for this file may be incomplete.'),
}),
]),
)
expect(result.apiCalls.some((call) => call.url === '/partial')).toBe(true)
expect(result.apiCalls.some((call) => call.url === '/ok')).toBe(true)
expect(result.stats.filesErrored).toBe(0)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('emits rule-error (not parse-error) when a rule throws', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'api.ts': "fetch('/users')",
})
vi.spyOn(missingErrorHandler, 'check').mockImplementation(() => {
throw new Error('rule boom')
})
const result = await scan(
resolveConfig({
rootDir: root,
rules: { 'missing-error-handler': Severity.Warning, 'no-hardcoded-url': 'off' },
}),
)
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: 'rule-error',
message: expect.stringContaining('rule boom'),
}),
]),
)
expect(result.diagnostics.some((d) => d.kind === 'parse-error')).toBe(false)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('never throws for domain-level errors across combined failure modes', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'good.ts': "fetch('/ok')",
'bad.ts': "fetch('/bad')",
'broken.ts': "fetch('/partial')\nconst x = {{{\n",
'api.ts': "fetch('/users')",
})
const badPath = resolve(root, 'bad.ts')
const readSpy = vi.spyOn(fileReader, 'readFileContent')
readSpy.mockImplementation(async (path) => {
if (resolve(path) === badPath) {
return err(new FileReaderError(`Could not read file: ${path}`, new Error('ENOENT')))
}
try {
return ok(await readFile(path, 'utf-8'))
} catch (cause) {
return err(new FileReaderError(`Could not read file: ${path}`, cause))
}
})
vi.spyOn(missingErrorHandler, 'check').mockImplementation(() => {
throw new Error('rule boom')
})
const result = await scan(
resolveConfig({
rootDir: root,
rules: { 'missing-error-handler': Severity.Warning, 'no-hardcoded-url': 'off' },
}),
)
expect(result.diagnostics.length).toBeGreaterThan(0)
expect(result.diagnostics.some((d) => d.kind === 'parse-error')).toBe(true)
expect(result.diagnostics.some((d) => d.kind === 'unsupported-syntax')).toBe(true)
expect(result.diagnostics.some((d) => d.kind === 'rule-error')).toBe(true)
expect(result.apiCalls.some((call) => call.url === '/ok')).toBe(true)
expect(result.apiCalls.some((call) => call.url === '/partial')).toBe(true)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('respects include patterns and excludes files outside them', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'src/in-scope.ts': "fetch('/in')",
'lib/out-of-scope.ts': "fetch('/out')",
})
const result = await scan(
resolveConfig({
rootDir: root,
include: ['src/**'],
rules: { 'missing-error-handler': 'off', 'no-hardcoded-url': 'off' },
}),
)
expect(result.stats.filesScanned).toBe(1)
expect(result.apiCalls.some((call) => call.url === '/in')).toBe(true)
expect(result.apiCalls.some((call) => call.url === '/out')).toBe(false)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('excludes minified vendor lib files and vendor dirs by default', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'src/assets/js/lib/apexcharts.min.js': "fetch('https://cdn.example.com')",
'src/assets/js/lib/bootstrap.bundle.min.js': "fetch('/noise')",
'vendor/jquery/index.js': "fetch('/vendor')",
'src/lib/utils.ts': "fetch('/lib-utils')",
'src/app.ts': "fetch('/real')",
})
const result = await scan(
resolveConfig({
rootDir: root,
rules: { 'missing-error-handler': 'off', 'no-hardcoded-url': 'off' },
}),
)
expect(result.stats.filesScanned).toBe(2)
expect(result.apiCalls.some((call) => call.url === '/real')).toBe(true)
expect(result.apiCalls.some((call) => call.url === '/lib-utils')).toBe(true)
expect(result.apiCalls.some((call) => call.url === '/noise')).toBe(false)
expect(result.apiCalls.some((call) => call.url === '/vendor')).toBe(false)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('discovers and scans .mts files with default include config', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'api.mts': "fetch('/mts')",
})
const result = await scan(
resolveConfig({
rootDir: root,
rules: { 'missing-error-handler': 'off', 'no-hardcoded-url': 'off' },
}),
)
expect(result.apiCalls.some((call) => call.url === '/mts')).toBe(true)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
describe('contract checking', () => {
it('produces no contract findings when contractSource is unset', async () => {
const root = createFixture()
try {
writeOpenApiSpec(root, 'api.json', usersPostSpec())
writeScanFixture(root, {
'api.ts': "axios.post('/users', { name: 'Alice' })",
})
const result = await scan(
resolveConfig({
rootDir: root,
rules: OFF_RULES,
}),
)
expect(
result.findings.filter((f) => f.ruleId === API_CONTRACT_MISMATCH_RULE_ID),
).toHaveLength(0)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('produces api-contract-mismatch findings for body-shape discrepancies', async () => {
const root = createFixture()
try {
writeOpenApiSpec(root, 'api.json', usersPostSpec())
const apiPath = join(root, 'api.ts')
writeScanFixture(root, {
'api.ts': "axios.post('/users', { age: 1 })",
})
const result = await scan(
resolveConfig({
rootDir: root,
contractSource: 'api.json',
rules: OFF_RULES,
}),
)
const contractFindings = result.findings.filter(
(f) => f.ruleId === API_CONTRACT_MISMATCH_RULE_ID,
)
expect(contractFindings).toHaveLength(1)
expect(contractFindings[0]?.message).toContain("Missing required field 'name'")
expect(contractFindings[0]?.message).toContain('POST /users')
expect(resolve(contractFindings[0]?.location.file ?? '')).toBe(resolve(apiPath))
expect(contractFindings[0]?.location.line).toBeGreaterThan(0)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('emits config-warning and no contract findings when the spec file is missing', async () => {
const root = createFixture()
try {
writeScanFixture(root, {
'api.ts': "axios.post('/users', { name: 'Alice' })",
})
const result = await scan(
resolveConfig({
rootDir: root,
contractSource: 'missing.json',
rules: OFF_RULES,
}),
)
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: 'config-warning',
message: expect.stringContaining('Could not parse OpenAPI spec'),
}),
]),
)
expect(
result.findings.filter((f) => f.ruleId === API_CONTRACT_MISMATCH_RULE_ID),
).toHaveLength(0)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('produces no findings for unmatched calls', async () => {
const root = createFixture()
try {
writeOpenApiSpec(root, 'api.json', usersGetSpec())
writeScanFixture(root, {
'api.ts': "fetch('/nope')",
})
const result = await scan(
resolveConfig({
rootDir: root,
contractSource: 'api.json',
rules: OFF_RULES,
}),
)
expect(
result.findings.filter((f) => f.ruleId === API_CONTRACT_MISMATCH_RULE_ID),
).toHaveLength(0)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('produces one finding per discrepancy for a call with multiple issues', async () => {
const root = createFixture()
try {
writeOpenApiSpec(root, 'api.json', usersPostSpec())
writeScanFixture(root, {
'api.ts': "axios.post('/users', { extra: true, age: 'bad' })",
})
const result = await scan(
resolveConfig({
rootDir: root,
contractSource: 'api.json',
rules: OFF_RULES,
}),
)
const contractFindings = result.findings.filter(
(f) => f.ruleId === API_CONTRACT_MISMATCH_RULE_ID,
)
expect(contractFindings.length).toBeGreaterThanOrEqual(2)
const apiCallIds = new Set(contractFindings.map((f) => f.apiCallId))
expect(apiCallIds.size).toBe(1)
const messages = contractFindings.map((f) => f.message)
expect(messages.some((m) => m.includes("Missing required field 'name'"))).toBe(true)
expect(messages.some((m) => m.includes("Unexpected field 'extra'"))).toBe(true)
expect(messages.some((m) => m.includes("Field 'age'"))).toBe(true)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})
})