-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworkspace-policy.ts
More file actions
291 lines (256 loc) · 9.93 KB
/
Copy pathworkspace-policy.ts
File metadata and controls
291 lines (256 loc) · 9.93 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
import { createHash } from "node:crypto"
import { execFile } from "node:child_process"
import { lstat, readdir, realpath } from "node:fs/promises"
import { isAbsolute, resolve, sep } from "node:path"
import { promisify } from "node:util"
import { normalizeRelativePath, pathIsWithinRoot } from "./file-tree-policy.js"
const execFileAsync = promisify(execFile)
export type WorkspacePolicyViolationCode =
| "invalid-policy-path"
| "path-outside-workspace"
| "path-outside-writable-roots"
| "hidden-path"
| "symlink"
| "hardlink"
| "gitlink"
| "nested-git-metadata"
| "ignored-path"
| "special-file"
| "unmerged-index"
export interface WorkspacePolicyViolation {
code: WorkspacePolicyViolationCode
path: string
message: string
details?: Record<string, unknown>
}
export interface WorkspacePolicyCheckOptions {
workspaceRoot: string
writableRoots: string[]
hiddenPaths?: string[]
gitBacked?: boolean
}
export interface WorkspacePolicyResult {
schema: "wp-codebox/workspace-policy-result/v1"
passed: boolean
policy_sha256: string
violations: WorkspacePolicyViolation[]
}
interface NormalizedWorkspacePolicy {
workspaceRoot: string
writableRoots: string[]
hiddenPaths: string[]
gitBacked: boolean
}
interface GitStatusEntry {
status: string
path: string
}
export async function checkWorkspacePolicy(options: WorkspacePolicyCheckOptions): Promise<WorkspacePolicyResult> {
const workspaceRoot = resolve(options.workspaceRoot)
const policy: NormalizedWorkspacePolicy = {
workspaceRoot,
writableRoots: options.writableRoots.map(normalizePolicyPath),
hiddenPaths: (options.hiddenPaths ?? []).map(normalizePolicyPath),
gitBacked: options.gitBacked ?? false,
}
const violations: WorkspacePolicyViolation[] = []
for (const [kind, paths] of [
["writable root", policy.writableRoots],
["hidden path", policy.hiddenPaths],
] as const) {
for (const path of paths) {
if (!path || isAbsolute(path) || path === ".." || path.startsWith(`..${sep}`)) {
violations.push({
code: "invalid-policy-path",
path,
message: `Invalid ${kind}: ${path || "<empty>"}`,
})
}
}
}
const paths = new Set<string>()
for (const path of await listWorkspacePaths(workspaceRoot, { skipRootGitMetadata: policy.gitBacked })) {
paths.add(path)
}
if (policy.gitBacked) {
const gitEntries = await readGitStatusEntries(workspaceRoot)
for (const entry of gitEntries) {
paths.add(entry.path)
if (entry.status === "!!") {
violations.push({ code: "ignored-path", path: entry.path, message: `Ignored path is present in git-backed workspace: ${entry.path}` })
}
if (isUnmergedStatus(entry.status)) {
violations.push({ code: "unmerged-index", path: entry.path, message: `Unmerged index entry: ${entry.path}`, details: { status: entry.status } })
}
}
for (const path of await readGitlinkPaths(workspaceRoot)) {
paths.add(path)
violations.push({ code: "gitlink", path, message: `Gitlink/submodule entry is not allowed: ${path}` })
}
for (const path of await readUnmergedIndexPaths(workspaceRoot)) {
paths.add(path)
violations.push({ code: "unmerged-index", path, message: `Unmerged index entry: ${path}` })
}
}
for (const path of paths) {
violations.push(...(await checkWorkspacePath(policy, path)))
}
return {
schema: "wp-codebox/workspace-policy-result/v1",
passed: violations.length === 0,
policy_sha256: workspacePolicySha256(policy),
violations: sortViolations(dedupeViolations(violations)),
}
}
export function workspacePolicySha256(policy: WorkspacePolicyCheckOptions | NormalizedWorkspacePolicy): string {
const normalized = {
workspaceRoot: resolve(policy.workspaceRoot),
writableRoots: [...policy.writableRoots].map(normalizePolicyPath).sort(),
hiddenPaths: [...(policy.hiddenPaths ?? [])].map(normalizePolicyPath).sort(),
gitBacked: policy.gitBacked ?? false,
}
return createHash("sha256").update(JSON.stringify(normalized)).digest("hex")
}
async function checkWorkspacePath(policy: NormalizedWorkspacePolicy, path: string): Promise<WorkspacePolicyViolation[]> {
const violations: WorkspacePolicyViolation[] = []
const normalizedPath = normalizePolicyPath(path)
const absolutePath = resolve(policy.workspaceRoot, normalizedPath)
if (!pathIsWithinRoot(absolutePath, policy.workspaceRoot)) {
return [{ code: "path-outside-workspace", path, message: `Path escapes workspace root: ${path}` }]
}
if (!isPathUnderAny(normalizedPath, policy.writableRoots)) {
violations.push({ code: "path-outside-writable-roots", path: normalizedPath, message: `Path is outside writable roots: ${normalizedPath}` })
}
if (isPathUnderAny(normalizedPath, policy.hiddenPaths)) {
violations.push({ code: "hidden-path", path: normalizedPath, message: `Path is under a hidden policy path: ${normalizedPath}` })
}
if (hasNestedGitMetadata(normalizedPath)) {
violations.push({ code: "nested-git-metadata", path: normalizedPath, message: `Nested .git metadata is not allowed: ${normalizedPath}` })
}
let stat
try {
stat = await lstat(absolutePath)
} catch {
return violations
}
if (stat.isSymbolicLink()) {
violations.push({ code: "symlink", path: normalizedPath, message: `Symlink is not allowed: ${normalizedPath}` })
return violations
}
if (stat.isFile()) {
if (typeof stat.nlink !== "number" || !Number.isFinite(stat.nlink)) {
violations.push({ code: "hardlink", path: normalizedPath, message: `Unable to determine link count for regular file: ${normalizedPath}`, details: { linkCountAvailable: false } })
} else if (stat.nlink > 1) {
violations.push({ code: "hardlink", path: normalizedPath, message: `Hardlink is not allowed: ${normalizedPath}`, details: { links: stat.nlink } })
}
}
if (!stat.isFile() && !stat.isDirectory()) {
violations.push({ code: "special-file", path: normalizedPath, message: `Special file is not allowed: ${normalizedPath}` })
}
if (stat.isDirectory()) {
try {
const entryRealpath = await realpath(absolutePath)
const rootRealpath = await realpath(policy.workspaceRoot)
if (!pathIsWithinRoot(entryRealpath, rootRealpath)) {
violations.push({ code: "path-outside-workspace", path: normalizedPath, message: `Path resolves outside workspace root: ${normalizedPath}` })
}
} catch {
// lstat already proved the entry exists; realpath can fail on broken trees.
}
}
return violations
}
async function listWorkspacePaths(workspaceRoot: string, options: { skipRootGitMetadata?: boolean } = {}): Promise<string[]> {
const paths: string[] = []
const queue = [""]
while (queue.length > 0) {
const current = queue.shift() ?? ""
const absolute = current ? resolve(workspaceRoot, current) : workspaceRoot
const entries = await readdir(absolute, { withFileTypes: true })
for (const entry of entries) {
const relativePath = normalizePolicyPath(current ? `${current}/${entry.name}` : entry.name)
if (options.skipRootGitMetadata && (relativePath === ".git" || relativePath.startsWith(".git/"))) {
continue
}
paths.push(relativePath)
if (entry.isDirectory() && !entry.isSymbolicLink()) {
queue.push(relativePath)
}
}
}
return paths
}
async function readGitStatusEntries(workspaceRoot: string): Promise<GitStatusEntry[]> {
const { stdout } = await execFileAsync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored"], {
cwd: workspaceRoot,
encoding: "buffer",
maxBuffer: 1024 * 1024 * 20,
})
const tokens = stdout.toString("utf8").split("\0").filter(Boolean)
const entries: GitStatusEntry[] = []
for (let index = 0; index < tokens.length; index++) {
const token = tokens[index]
const status = token.slice(0, 2)
const path = normalizePolicyPath(token.slice(3))
entries.push({ status, path })
if (status.includes("R") || status.includes("C")) {
index++
if (tokens[index]) {
entries.push({ status, path: normalizePolicyPath(tokens[index]) })
}
}
}
return entries
}
async function readGitlinkPaths(workspaceRoot: string): Promise<string[]> {
const { stdout } = await execFileAsync("git", ["ls-files", "-s", "-z"], {
cwd: workspaceRoot,
encoding: "buffer",
maxBuffer: 1024 * 1024 * 20,
})
return stdout
.toString("utf8")
.split("\0")
.filter(Boolean)
.filter((entry) => entry.startsWith("160000 "))
.map((entry) => normalizePolicyPath(entry.slice(entry.indexOf("\t") + 1)))
}
async function readUnmergedIndexPaths(workspaceRoot: string): Promise<string[]> {
const { stdout } = await execFileAsync("git", ["ls-files", "-u", "-z"], {
cwd: workspaceRoot,
encoding: "buffer",
maxBuffer: 1024 * 1024 * 20,
})
return stdout
.toString("utf8")
.split("\0")
.filter(Boolean)
.map((entry) => normalizePolicyPath(entry.slice(entry.indexOf("\t") + 1)))
}
function normalizePolicyPath(path: string): string {
return normalizeRelativePath(path)
}
function isPathUnderAny(path: string, roots: string[]): boolean {
return roots.some((root) => root === "." || path === root || path.startsWith(`${root}/`))
}
function hasNestedGitMetadata(path: string): boolean {
const parts = path.split("/")
return parts.includes(".git")
}
function isUnmergedStatus(status: string): boolean {
return ["DD", "AU", "UD", "UA", "DU", "AA", "UU"].includes(status)
}
function dedupeViolations(violations: WorkspacePolicyViolation[]): WorkspacePolicyViolation[] {
const seen = new Set<string>()
return violations.filter((violation) => {
const key = `${violation.code}\0${violation.path}\0${violation.message}`
if (seen.has(key)) {
return false
}
seen.add(key)
return true
})
}
function sortViolations(violations: WorkspacePolicyViolation[]): WorkspacePolicyViolation[] {
return violations.sort((a, b) => a.path.localeCompare(b.path) || a.code.localeCompare(b.code))
}