Repository navigation
Expand file tree
/
Copy pathpath_validation.ts
More file actions
56 lines (50 loc) · 2.01 KB
/
Copy pathpath_validation.ts
File metadata and controls
56 lines (50 loc) · 2.01 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
/**
* Path validation for AI-returned finding.file to prevent path traversal and misuse.
* Rejects paths containing '..', null bytes, or absolute paths.
*/
const NULL_BYTE = '\0';
const PARENT_SEGMENT = '..';
const SLASH = '/';
const BACKSLASH = '\\';
/**
* Returns true if the path is safe to use: no '..', no null bytes, not absolute.
* Does not check against a list of allowed files; use isAllowedPathForPr for that.
*/
export function isSafeFindingFilePath(path: string | undefined): boolean {
if (path == null || typeof path !== 'string') return false;
const trimmed = path.trim();
if (trimmed.length === 0) return false;
return !containsUnsafePathContent(trimmed) && !isAbsolutePath(trimmed);
}
function containsUnsafePathContent(path: string): boolean {
return path.includes(NULL_BYTE) || path.includes(PARENT_SEGMENT);
}
function isAbsolutePath(path: string): boolean {
return path.startsWith(SLASH) || /^[a-zA-Z]:[/\\]/.test(path) || path.startsWith(BACKSLASH);
}
/**
* Returns true if path is safe (isSafeFindingFilePath) and is in the list of PR changed files.
* Used to validate finding.file before using it for PR review comments.
*/
export function isAllowedPathForPr(
path: string | undefined,
prFiles: Array<{ filename: string }>
): boolean {
if (!isSafeFindingFilePath(path)) return false;
if (prFiles.length === 0) return false;
const normalized = path!.trim();
return prFiles.some((f) => f.filename === normalized);
}
/**
* Resolves the file path to use for a PR review comment: finding.file if valid and in prFiles.
* Returns undefined when the finding's file is not in the PR so we do not attach the comment
* to the wrong file (e.g. the first file in the list).
*/
export function resolveFindingPathForPr(
findingFile: string | undefined,
prFiles: Array<{ filename: string; status: string }>
): string | undefined {
if (prFiles.length === 0) return undefined;
if (isAllowedPathForPr(findingFile, prFiles)) return findingFile!.trim();
return undefined;
}