@agent-corpus/policy-manager 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -29
- package/dist/adapters.d.ts +3 -1
- package/dist/adapters.js +37 -18
- package/dist/classifier.d.ts +98 -0
- package/dist/classifier.js +343 -0
- package/dist/cli.js +66 -7
- package/dist/config.d.ts +2 -0
- package/dist/config.js +6 -2
- package/dist/evidence.d.ts +1 -0
- package/dist/evidence.js +60 -0
- package/dist/flow.d.ts +4 -0
- package/dist/flow.js +91 -18
- package/dist/gitalias.d.ts +13 -0
- package/dist/gitalias.js +33 -0
- package/dist/grants.d.ts +9 -9
- package/dist/grants.js +46 -30
- package/dist/hard.d.ts +63 -0
- package/dist/hard.js +1637 -0
- package/dist/helpers.d.ts +59 -0
- package/dist/helpers.js +304 -0
- package/dist/merged.d.ts +6 -0
- package/dist/merged.js +23 -0
- package/dist/nativerules.d.ts +44 -0
- package/dist/nativerules.js +653 -0
- package/dist/permissive.js +179 -7
- package/dist/policy.d.ts +12 -0
- package/dist/policy.js +228 -45
- package/dist/profile.d.ts +7 -0
- package/dist/profile.js +32 -1
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +334 -0
- package/dist/reads.d.ts +46 -0
- package/dist/reads.js +812 -0
- package/dist/replay.d.ts +42 -0
- package/dist/replay.js +174 -1
- package/dist/service.d.ts +12 -1
- package/dist/service.js +23 -6
- package/dist/session.d.ts +76 -13
- package/dist/session.js +373 -116
- package/dist/shell.d.ts +2 -0
- package/dist/shell.js +1 -1
- package/dist/shellscan.d.ts +58 -0
- package/dist/shellscan.js +395 -0
- package/dist/statepaths.d.ts +41 -0
- package/dist/statepaths.js +706 -0
- package/dist/types.d.ts +11 -1
- package/package.json +1 -1
package/dist/hard.js
ADDED
|
@@ -0,0 +1,1637 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { canonical, git, inside, resolveWord, sensitive, tempRoots, withEvidence, } from "./evidence.js";
|
|
5
|
+
import { aliasDirectory, gitAlias, KNOWN_GIT, shellArgs } from "./gitalias.js";
|
|
6
|
+
import { defaultProfilePath } from "./profile.js";
|
|
7
|
+
import { readOnly } from "./reads.js";
|
|
8
|
+
import { command, innerScript, scan } from "./shellscan.js";
|
|
9
|
+
import { codeTouchesState, findReachesState, namesState, stateText } from "./statepaths.js";
|
|
10
|
+
/**
|
|
11
|
+
* Hard human items: requests that always go to a person, are never sent to the AI classifier, and
|
|
12
|
+
* that no classification can approve. Credentials, protected configuration, unrecoverable loss and
|
|
13
|
+
* the profile's humanPatterns, plus two built-in guards on the policy manager's own approvals.
|
|
14
|
+
*/
|
|
15
|
+
export const HARD_RULES = [
|
|
16
|
+
/** Credential or secret retrieval, and reads of credential paths. */
|
|
17
|
+
"credential-read",
|
|
18
|
+
/** Writes to harness permission and hook settings. */
|
|
19
|
+
"harness-settings",
|
|
20
|
+
/** Writes to the policy profile itself. */
|
|
21
|
+
"policy-profile",
|
|
22
|
+
/**
|
|
23
|
+
* Writing, moving, deleting or changing the policy service's own state (`acp-<uid>-*` in the
|
|
24
|
+
* temp directory: audit logs, token, socket, grants, cache). Reading the audit logs is allowed.
|
|
25
|
+
*/
|
|
26
|
+
"policy-state",
|
|
27
|
+
/**
|
|
28
|
+
* A shell or interpreter that reads its script from standard input, a here-string or a file the
|
|
29
|
+
* policy cannot read (`cat x.sh | sh`, `sh < x.sh`, `. <(curl ...)`, `| pwsh`). A literal
|
|
30
|
+
* `echo`, `printf` or quoted here-document piped in is unwrapped and judged instead.
|
|
31
|
+
*/
|
|
32
|
+
"opaque-script",
|
|
33
|
+
/** `git push --force`/`--mirror`, and `+` refspecs: they overwrite remote history. */
|
|
34
|
+
"force-push",
|
|
35
|
+
/** Deleting a local or remote branch whose commits are not verified merged. */
|
|
36
|
+
"delete-unmerged-branch",
|
|
37
|
+
/** `git worktree remove --force`/`prune`: discards a worktree's uncommitted and untracked work. */
|
|
38
|
+
"remove-worktree-force",
|
|
39
|
+
/** `git clean`: deletes untracked files. */
|
|
40
|
+
"git-clean",
|
|
41
|
+
/** A command matching the profile's `humanPatterns`. */
|
|
42
|
+
"human-patterns",
|
|
43
|
+
/**
|
|
44
|
+
* The deterministic floor under the classifier: cloud and infrastructure writes and deletes
|
|
45
|
+
* (az, aws, gcloud, kubectl, helm, terraform, pulumi...), GitHub repository, release and secret
|
|
46
|
+
* deletion, package publishing, and a recursive `rm` outside a linked feature worktree, the
|
|
47
|
+
* temp directory and the profile's scratch roots. None of these is provably recoverable.
|
|
48
|
+
*/
|
|
49
|
+
"cloud-write",
|
|
50
|
+
"repo-delete",
|
|
51
|
+
"publish",
|
|
52
|
+
"rm-outside",
|
|
53
|
+
/** Any other decision the engine filed as sensitive: protected paths and configuration. */
|
|
54
|
+
"protected",
|
|
55
|
+
/** An agent running `approve` itself. */
|
|
56
|
+
"self-approve",
|
|
57
|
+
/** A classification record for another session or CLI, or with anything added. */
|
|
58
|
+
"foreign-classification-record",
|
|
59
|
+
];
|
|
60
|
+
/** The reason of session's approve guard (an agent running `approve`). */
|
|
61
|
+
export const APPROVE_GUARD = "Only the user may approve a request, by running approve in their own terminal";
|
|
62
|
+
const FOREIGN_RECORD_REASON = /^A classification record/;
|
|
63
|
+
/** The engine's own reasons for hard cases it parsed. */
|
|
64
|
+
const REASON_RULES = [
|
|
65
|
+
[/^Force or mirror pushes overwrite remote history$/, "force-push"],
|
|
66
|
+
[/^Forced refspecs overwrite remote history$/, "force-push"],
|
|
67
|
+
[/^Local branch deletion requires human approval/, "delete-unmerged-branch"],
|
|
68
|
+
[/^Remote branch deletion may lose work/, "delete-unmerged-branch"],
|
|
69
|
+
[/^Remote branch has commits that are not fetched/, "delete-unmerged-branch"],
|
|
70
|
+
[/^Remote branch deletion is only verified for origin/, "delete-unmerged-branch"],
|
|
71
|
+
[/^Only branch deletions with verified merge state/, "delete-unmerged-branch"],
|
|
72
|
+
[/^Forced worktree removal requires human approval$/, "remove-worktree-force"],
|
|
73
|
+
[/^git clean deletes untracked files$/, "git-clean"],
|
|
74
|
+
[/^Matches an organization human-approval pattern$/, "human-patterns"],
|
|
75
|
+
[/credential|secret|Printing the environment/i, "credential-read"],
|
|
76
|
+
];
|
|
77
|
+
const SHELL_TOOLS = new Set(["Bash", "bash", "exec_command", "shell", "powershell"]);
|
|
78
|
+
const WRITE_TOOLS = new Set([
|
|
79
|
+
"Write",
|
|
80
|
+
"Edit",
|
|
81
|
+
"MultiEdit",
|
|
82
|
+
"NotebookEdit",
|
|
83
|
+
"create",
|
|
84
|
+
"edit",
|
|
85
|
+
"write_file",
|
|
86
|
+
]);
|
|
87
|
+
/**
|
|
88
|
+
* Harness permission, hook and MCP settings, matched on a path with `/` separators. Each names
|
|
89
|
+
* files that change what the harness lets run, or that run with the user's rights.
|
|
90
|
+
*/
|
|
91
|
+
const HARNESS_SETTINGS = [
|
|
92
|
+
// Claude Code: settings (permissions, hooks), hook scripts, and user MCP servers.
|
|
93
|
+
/(?<![\w-])\.claude\/settings(?:\.local)?\.json$/i,
|
|
94
|
+
/(?<![\w-])\.claude\/hooks(?:\/|$)/i,
|
|
95
|
+
/(?<![\w-])\.claude\.json$/i,
|
|
96
|
+
// Codex: hooks, hook scripts, configuration (approval policy, sandbox, MCP) and command rules.
|
|
97
|
+
/(?<![\w-])\.codex\/(?:hooks\.json|config\.toml)$/i,
|
|
98
|
+
/(?<![\w-])\.codex\/(?:hooks|rules)(?:\/|$)/i,
|
|
99
|
+
// Copilot: user hooks, configuration and saved permissions, and repository hooks.
|
|
100
|
+
/(?<![\w-])\.copilot\/(?:config\.json|settings\.json|permissions-config\.json|hooks(?:\/|$))/i,
|
|
101
|
+
/(?<![\w-])\.github\/hooks(?:\/[^/]*\.json)?$/i,
|
|
102
|
+
];
|
|
103
|
+
/** File names a write in an unknown directory could be a harness setting through. */
|
|
104
|
+
const SETTINGS_NAMES = /^(?:settings(?:\.local)?\.json|\.claude\.json|hooks\.json|config\.toml|config\.json|policy\.json|permissions-config\.json|hooks|rules)$/i;
|
|
105
|
+
const PROFILE_NAME = /(?<![\w-])policy-manager\/policy\.json$/i;
|
|
106
|
+
const slashes = (path) => path.replace(/\\/g, "/");
|
|
107
|
+
/**
|
|
108
|
+
* `path` with `/` separators, runs of separators collapsed and no trailing one. Done by splitting,
|
|
109
|
+
* not a regular expression, so a long run of slashes in hook input costs linear time.
|
|
110
|
+
*/
|
|
111
|
+
function normalize(path) {
|
|
112
|
+
return slashes(path)
|
|
113
|
+
.split("/")
|
|
114
|
+
.filter((part, index) => part !== "" || index === 0)
|
|
115
|
+
.join("/");
|
|
116
|
+
}
|
|
117
|
+
/** Settings in a harness directory moved by an environment variable. */
|
|
118
|
+
function configuredSettings(path) {
|
|
119
|
+
const dirs = [
|
|
120
|
+
[
|
|
121
|
+
process.env.CLAUDE_CONFIG_DIR,
|
|
122
|
+
/^(?:settings(?:\.local)?\.json|\.claude\.json|hooks(?:\/|$))/i,
|
|
123
|
+
],
|
|
124
|
+
[process.env.CODEX_HOME, /^(?:hooks\.json|config\.toml|(?:hooks|rules)(?:\/|$))/i],
|
|
125
|
+
[
|
|
126
|
+
process.env.COPILOT_HOME,
|
|
127
|
+
/^(?:config\.json|settings\.json|permissions-config\.json|hooks(?:\/|$))/i,
|
|
128
|
+
],
|
|
129
|
+
];
|
|
130
|
+
const target = slashes(path);
|
|
131
|
+
return dirs.some(([dir, name]) => {
|
|
132
|
+
if (!dir)
|
|
133
|
+
return false;
|
|
134
|
+
const root = resolvedRoot(dir);
|
|
135
|
+
return target.startsWith(root) && name.test(target.slice(root.length));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
const roots = new Map();
|
|
139
|
+
/** `dir` resolved with `/` separators and a trailing `/` (memoized: asked once per word). */
|
|
140
|
+
function resolvedRoot(dir) {
|
|
141
|
+
let root = roots.get(dir);
|
|
142
|
+
if (root === undefined) {
|
|
143
|
+
root = `${slashes(resolve(dir))}/`;
|
|
144
|
+
if (roots.size > 64)
|
|
145
|
+
roots.clear();
|
|
146
|
+
roots.set(dir, root);
|
|
147
|
+
}
|
|
148
|
+
return root;
|
|
149
|
+
}
|
|
150
|
+
/** A policy service state directory (`acp-<uid>-...`, any user's) or a path inside one. */
|
|
151
|
+
const POLICY_STATE = /(?:^|\/)acp-(?:\d+|user)-[^/]*(?:\/|$)/i;
|
|
152
|
+
export const policyStatePath = (path) => POLICY_STATE.test(normalize(path));
|
|
153
|
+
/** The hard rules a path names. */
|
|
154
|
+
function pathRules(path, rules, credentials) {
|
|
155
|
+
// Pure for a given environment, and asked for the same words many times: memoized.
|
|
156
|
+
const key = `${credentials ? 1 : 0}${process.env.CLAUDE_CONFIG_DIR}|${process.env.CODEX_HOME}|${process.env.COPILOT_HOME}|${path}`;
|
|
157
|
+
let found = pathMemo.get(key);
|
|
158
|
+
if (!found) {
|
|
159
|
+
found = [];
|
|
160
|
+
const target = normalize(path);
|
|
161
|
+
if (target === slashes(defaultProfilePath()) || PROFILE_NAME.test(target))
|
|
162
|
+
found.push("policy-profile");
|
|
163
|
+
if (HARNESS_SETTINGS.some((pattern) => pattern.test(target)) || configuredSettings(target))
|
|
164
|
+
found.push("harness-settings");
|
|
165
|
+
if (credentials && sensitive(target))
|
|
166
|
+
found.push("credential-read");
|
|
167
|
+
if (pathMemo.size > 8192)
|
|
168
|
+
pathMemo.clear();
|
|
169
|
+
pathMemo.set(key, found);
|
|
170
|
+
}
|
|
171
|
+
for (const rule of found)
|
|
172
|
+
rules.add(rule);
|
|
173
|
+
}
|
|
174
|
+
const pathMemo = new Map();
|
|
175
|
+
/** Absolute forms of a shell word in each directory it could be resolved in. */
|
|
176
|
+
function resolutions(word, cwds) {
|
|
177
|
+
const found = [];
|
|
178
|
+
for (const cwd of cwds)
|
|
179
|
+
try {
|
|
180
|
+
found.push(resolveWord(cwd, word));
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
/* `~user` and the like: matched as written */
|
|
184
|
+
}
|
|
185
|
+
return found;
|
|
186
|
+
}
|
|
187
|
+
/** Global options that take the next word as their value. */
|
|
188
|
+
const GIT_VALUED = new Set([
|
|
189
|
+
"-C",
|
|
190
|
+
"-c",
|
|
191
|
+
"--git-dir",
|
|
192
|
+
"--work-tree",
|
|
193
|
+
"--namespace",
|
|
194
|
+
"--config-env",
|
|
195
|
+
"--super-prefix",
|
|
196
|
+
]);
|
|
197
|
+
/** Whether `flag` is a long option `name` or an abbreviation Git accepts (at least `min` long). */
|
|
198
|
+
function long(flag, name, min = 4) {
|
|
199
|
+
const given = flag.split("=")[0];
|
|
200
|
+
return given.length >= min && name.startsWith(given);
|
|
201
|
+
}
|
|
202
|
+
const short = (flag, letters) => /^-[a-zA-Z]+$/.test(flag) && letters.test(flag.slice(1));
|
|
203
|
+
const FORCE_PUSH = ["--force", "--force-with-lease", "--force-if-includes", "--mirror", "--prune"];
|
|
204
|
+
const forcing = (flag) => FORCE_PUSH.some((name) => long(flag, name, 3)) || short(flag, /f/);
|
|
205
|
+
/** The rules a Git invocation with a literal, known subcommand falls under. */
|
|
206
|
+
function gitRules(sub, rest, rules) {
|
|
207
|
+
const flags = rest.filter((word) => word.startsWith("-"));
|
|
208
|
+
const positional = rest.filter((word) => !word.startsWith("-"));
|
|
209
|
+
const has = (test) => flags.some(test);
|
|
210
|
+
if (sub === "push") {
|
|
211
|
+
if (has(forcing) || positional.some((word) => word.startsWith("+")))
|
|
212
|
+
rules.add("force-push");
|
|
213
|
+
if (has((f) => long(f, "--delete") || short(f, /d/)) ||
|
|
214
|
+
positional.slice(1).some((w) => w.startsWith(":")))
|
|
215
|
+
rules.add("delete-unmerged-branch");
|
|
216
|
+
}
|
|
217
|
+
else if (sub === "branch") {
|
|
218
|
+
if (has((f) => long(f, "--delete") || short(f, /[dD]/)))
|
|
219
|
+
rules.add("delete-unmerged-branch");
|
|
220
|
+
}
|
|
221
|
+
else if (sub === "update-ref") {
|
|
222
|
+
if (has((f) => f === "-d" || long(f, "--stdin")))
|
|
223
|
+
rules.add("delete-unmerged-branch");
|
|
224
|
+
}
|
|
225
|
+
else if (sub === "worktree") {
|
|
226
|
+
if (positional[0] === "prune" ||
|
|
227
|
+
(positional[0] === "remove" && has((f) => long(f, "--force") || short(f, /f/))))
|
|
228
|
+
rules.add("remove-worktree-force");
|
|
229
|
+
}
|
|
230
|
+
else if (sub === "clean") {
|
|
231
|
+
if (!has((f) => long(f, "--dry-run") || short(f, /n/)))
|
|
232
|
+
rules.add("git-clean");
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* The rules an opaque Git invocation could reach, judged on every word of the script: its program
|
|
237
|
+
* or subcommand is not a literal known word, or an alias or environment could change what runs.
|
|
238
|
+
*/
|
|
239
|
+
function opaqueGitRules(words, keywords, rules) {
|
|
240
|
+
const has = (word) => words.includes(word);
|
|
241
|
+
const flags = words.filter((word) => word.startsWith("-") || word.startsWith("+"));
|
|
242
|
+
if (has("clean") && !flags.some((f) => long(f, "--dry-run") || short(f, /n/)))
|
|
243
|
+
rules.add("git-clean");
|
|
244
|
+
if (flags.some((f) => forcing(f) || f.startsWith("+")) && (!keywords || has("push")))
|
|
245
|
+
rules.add("force-push");
|
|
246
|
+
if (has("worktree") && (has("prune") || (has("remove") && flags.some(forcing))))
|
|
247
|
+
rules.add("remove-worktree-force");
|
|
248
|
+
if (flags.some((f) => f === "--delete" || short(f, /[dD]/)) &&
|
|
249
|
+
(!keywords || has("branch") || has("push") || has("update-ref")))
|
|
250
|
+
rules.add("delete-unmerged-branch");
|
|
251
|
+
}
|
|
252
|
+
const CLOUD = new Set(["az", "aws", "gcloud"]);
|
|
253
|
+
/** A cloud CLI word that marks a read: anything without one is treated as a write. */
|
|
254
|
+
const CLOUD_READ_VERB = /^(?:list(?:-.*)?|show(?:-.*)?|get(?:-.*)?|describe(?:-.*)?|query|search|wait|exists|version|ls|tail|help|whoami|login|logout|status)$/;
|
|
255
|
+
const INFRA_WRITE = {
|
|
256
|
+
kubectl: /^(?:apply|create|delete|replace|patch|edit|scale|autoscale|rollout|set|label|annotate|drain|cordon|uncordon|taint|expose|run|exec|cp|attach)$/,
|
|
257
|
+
oc: /^(?:apply|create|delete|replace|patch|edit|scale|rollout|set|label|annotate|expose|run|exec|new-app|start-build)$/,
|
|
258
|
+
helm: /^(?:install|upgrade|uninstall|delete|rollback|push)$/,
|
|
259
|
+
terraform: /^(?:apply|destroy|import|taint|untaint|state|force-unlock|workspace)$/,
|
|
260
|
+
tofu: /^(?:apply|destroy|import|taint|untaint|state|force-unlock|workspace)$/,
|
|
261
|
+
terragrunt: /^(?:apply|destroy|import|taint|untaint|state|force-unlock|run-all)$/,
|
|
262
|
+
pulumi: /^(?:up|update|destroy|refresh|import|state|cancel|stack)$/,
|
|
263
|
+
eksctl: /^(?:create|delete|upgrade|scale|set|unset|drain)$/,
|
|
264
|
+
};
|
|
265
|
+
const PUBLISHERS = {
|
|
266
|
+
npm: /^(?:publish|unpublish|deprecate|dist-tag)$/,
|
|
267
|
+
pnpm: /^publish$/,
|
|
268
|
+
yarn: /^(?:publish|npm)$/,
|
|
269
|
+
cargo: /^(?:publish|yank|owner)$/,
|
|
270
|
+
twine: /^upload$/,
|
|
271
|
+
gem: /^(?:push|yank)$/,
|
|
272
|
+
poetry: /^publish$/,
|
|
273
|
+
docker: /^push$/,
|
|
274
|
+
podman: /^push$/,
|
|
275
|
+
};
|
|
276
|
+
const GH_DELETE = {
|
|
277
|
+
repo: /^(?:create|fork|delete|archive|unarchive|rename|edit|sync)$/,
|
|
278
|
+
release: /^(?:create|edit|upload|delete|delete-asset)$/,
|
|
279
|
+
secret: /^(?:delete|remove|set)$/,
|
|
280
|
+
variable: /^(?:delete|set)$/,
|
|
281
|
+
gist: /^(?:create|new|edit|rename|delete)$/,
|
|
282
|
+
// What gh itself runs and with which credentials: extensions, aliases, settings and auth.
|
|
283
|
+
extension: /^(?:install|upgrade|exec|remove)$/,
|
|
284
|
+
extensions: /^(?:install|upgrade|exec|remove)$/,
|
|
285
|
+
ext: /^(?:install|upgrade|exec|remove)$/,
|
|
286
|
+
alias: /^(?:set|import|delete)$/,
|
|
287
|
+
config: /^set$/,
|
|
288
|
+
auth: /^(?:refresh|login|logout|setup-git|token|switch)$/,
|
|
289
|
+
cache: /^delete$/,
|
|
290
|
+
label: /^delete$/,
|
|
291
|
+
issue: /^(?:delete|transfer)$/,
|
|
292
|
+
"ssh-key": /^(?:add|delete)$/,
|
|
293
|
+
"gpg-key": /^(?:add|delete)$/,
|
|
294
|
+
codespace: /^(?:create|delete|edit|stop|rebuild|cp|ssh|ports)$/,
|
|
295
|
+
cs: /^(?:create|delete|edit|stop|rebuild|cp|ssh|ports)$/,
|
|
296
|
+
// Merging and workflow or deploy triggers cannot be taken back. (`gh ruleset` only reads.)
|
|
297
|
+
pr: /^merge$/,
|
|
298
|
+
workflow: /^(?:run|enable|disable)$/,
|
|
299
|
+
run: /^(?:rerun|delete|cancel)$/,
|
|
300
|
+
};
|
|
301
|
+
/**
|
|
302
|
+
* The only REST writes through `gh api` that reach the classifier: recoverable PR and issue
|
|
303
|
+
* conversation. Each entry is a method set and an endpoint under `repos/<owner>/<repo>/`. Every
|
|
304
|
+
* other write is a floor item (merging, dispatching workflows, deployments, rulesets, transfers,
|
|
305
|
+
* memberships, secrets, variables, settings, refs, releases, ...).
|
|
306
|
+
*/
|
|
307
|
+
const GH_API_WRITES = [
|
|
308
|
+
// Issue and PR comments: create, edit.
|
|
309
|
+
[/^POST$/, /^issues\/\d+\/comments$/],
|
|
310
|
+
[/^PATCH$/, /^issues\/comments\/\d+$/],
|
|
311
|
+
// Review comments and replies: create, edit.
|
|
312
|
+
[/^POST$/, /^pulls\/\d+\/comments(?:\/\d+\/replies)?$/],
|
|
313
|
+
[/^PATCH$/, /^pulls\/comments\/\d+$/],
|
|
314
|
+
// Reviews: create, update the body, submit.
|
|
315
|
+
[/^POST$/, /^pulls\/\d+\/reviews$/],
|
|
316
|
+
[/^PUT$/, /^pulls\/\d+\/reviews\/\d+$/],
|
|
317
|
+
[/^POST$/, /^pulls\/\d+\/reviews\/\d+\/events$/],
|
|
318
|
+
// Labels and assignees.
|
|
319
|
+
[/^(?:POST|PUT)$/, /^issues\/\d+\/labels$/],
|
|
320
|
+
[/^DELETE$/, /^issues\/\d+\/labels(?:\/[^/]+)?$/],
|
|
321
|
+
[/^(?:POST|DELETE)$/, /^issues\/\d+\/assignees$/],
|
|
322
|
+
// PR create, and edit of title, body, base or draft (not its state).
|
|
323
|
+
[/^POST$/, /^pulls$/],
|
|
324
|
+
[/^PATCH$/, /^pulls\/\d+$/],
|
|
325
|
+
];
|
|
326
|
+
/** GraphQL mutations that reach the classifier: the same recoverable conversation edits. */
|
|
327
|
+
const GH_MUTATIONS = new Set([
|
|
328
|
+
"addComment",
|
|
329
|
+
"updateIssueComment",
|
|
330
|
+
"addPullRequestReview",
|
|
331
|
+
"addPullRequestReviewComment",
|
|
332
|
+
"addPullRequestReviewThreadReply",
|
|
333
|
+
"updatePullRequestReviewComment",
|
|
334
|
+
"submitPullRequestReview",
|
|
335
|
+
"resolveReviewThread",
|
|
336
|
+
"unresolveReviewThread",
|
|
337
|
+
"createPullRequest",
|
|
338
|
+
"updatePullRequest",
|
|
339
|
+
"addLabelsToLabelable",
|
|
340
|
+
"removeLabelsFromLabelable",
|
|
341
|
+
"addAssigneesToAssignable",
|
|
342
|
+
"removeAssigneesFromAssignable",
|
|
343
|
+
]);
|
|
344
|
+
/**
|
|
345
|
+
* The top-level field names of every mutation in a GraphQL document, or undefined if it has no
|
|
346
|
+
* mutation. Strings are skipped; an alias (`a: addComment(...)`) counts as its field. A document
|
|
347
|
+
* it cannot follow (block strings, unbalanced brackets) yields no fields, which fails closed.
|
|
348
|
+
*/
|
|
349
|
+
function mutationFields(text) {
|
|
350
|
+
if (!/\bmutation\b/.test(text))
|
|
351
|
+
return undefined;
|
|
352
|
+
if (text.includes('"""'))
|
|
353
|
+
return [];
|
|
354
|
+
const fields = [];
|
|
355
|
+
let depth = 0;
|
|
356
|
+
let parens = 0;
|
|
357
|
+
let inMutation = false;
|
|
358
|
+
let found = false;
|
|
359
|
+
for (let i = 0; i < text.length; i++) {
|
|
360
|
+
const c = text[i];
|
|
361
|
+
if (c === '"') {
|
|
362
|
+
for (i++; i < text.length && text[i] !== '"'; i++)
|
|
363
|
+
if (text[i] === "\\")
|
|
364
|
+
i++;
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (c === "(")
|
|
368
|
+
parens++;
|
|
369
|
+
else if (c === ")")
|
|
370
|
+
parens--;
|
|
371
|
+
else if (c === "{")
|
|
372
|
+
depth++;
|
|
373
|
+
else if (c === "}") {
|
|
374
|
+
depth--;
|
|
375
|
+
if (depth === 0)
|
|
376
|
+
inMutation = false;
|
|
377
|
+
}
|
|
378
|
+
else if (depth === 0 && parens === 0 && /[A-Za-z_]/.test(c)) {
|
|
379
|
+
const word = /^[A-Za-z_]\w*/.exec(text.slice(i))?.[0] ?? "";
|
|
380
|
+
if (word === "mutation")
|
|
381
|
+
inMutation = found = true;
|
|
382
|
+
i += word.length - 1;
|
|
383
|
+
}
|
|
384
|
+
else if (inMutation && depth === 1 && parens === 0 && /[A-Za-z_]/.test(c)) {
|
|
385
|
+
const word = /^[A-Za-z_]\w*/.exec(text.slice(i))?.[0] ?? "";
|
|
386
|
+
i += word.length - 1;
|
|
387
|
+
if (!/^\s*:/.test(text.slice(i + 1)))
|
|
388
|
+
fields.push(word);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (depth !== 0 || parens !== 0)
|
|
392
|
+
return [];
|
|
393
|
+
return found ? fields : undefined;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Whether a `gh api` call is a floor item: any write (a non-GET method, or fields, which make it a
|
|
397
|
+
* POST) outside GH_API_WRITES, any GraphQL mutation outside GH_MUTATIONS (or a pull request state
|
|
398
|
+
* change), and any call whose endpoint or query cannot be read. Options are read anywhere after
|
|
399
|
+
* `api`. A header that overrides the method (`X-HTTP-Method-Override`) or is not literal, and an
|
|
400
|
+
* unquoted expansion other than the endpoint (`$EXTRA`, which can split into `-X DELETE`), fail
|
|
401
|
+
* closed.
|
|
402
|
+
*/
|
|
403
|
+
function ghApiFloor(words) {
|
|
404
|
+
const texts = words.map((word) => word.text);
|
|
405
|
+
let endpoint;
|
|
406
|
+
let endpointAt = -1;
|
|
407
|
+
let method;
|
|
408
|
+
let fields = false;
|
|
409
|
+
const values = [];
|
|
410
|
+
const start = texts.indexOf("api") + 1;
|
|
411
|
+
for (let k = start; k < texts.length; k++) {
|
|
412
|
+
const text = texts[k];
|
|
413
|
+
const header = /^(?:-H|--header)$/.test(text)
|
|
414
|
+
? words[k + 1]
|
|
415
|
+
: /^(?:--header=|-H.)/.test(text)
|
|
416
|
+
? { ...words[k], text: text.replace(/^(?:--header=|-H)/, "") }
|
|
417
|
+
: undefined;
|
|
418
|
+
if (header && (!header.literal || /x-http-method-override/i.test(header.text)))
|
|
419
|
+
return true;
|
|
420
|
+
const attached = /^(?:-X|--method=)(.+)$/.exec(text);
|
|
421
|
+
if (text === "-X" || text === "--method")
|
|
422
|
+
method = texts[++k];
|
|
423
|
+
else if (attached)
|
|
424
|
+
method = attached[1];
|
|
425
|
+
else if (/^(?:-[fF]|--field|--raw-field)$/.test(text)) {
|
|
426
|
+
fields = true;
|
|
427
|
+
values.push(texts[++k] ?? "");
|
|
428
|
+
}
|
|
429
|
+
else if (/^(?:--field|--raw-field)=|^-[fF]./.test(text)) {
|
|
430
|
+
fields = true;
|
|
431
|
+
values.push(text.replace(/^(?:--field=|--raw-field=|-[fF])/, ""));
|
|
432
|
+
}
|
|
433
|
+
else if (text === "--input" || text.startsWith("--input=")) {
|
|
434
|
+
fields = true;
|
|
435
|
+
if (text === "--input")
|
|
436
|
+
k++;
|
|
437
|
+
values.push("@");
|
|
438
|
+
}
|
|
439
|
+
else if (/^-[Htqp]$|^--(?:header|jq|template|hostname|cache|preview)$/.test(text))
|
|
440
|
+
k++;
|
|
441
|
+
else if (!text.startsWith("-") && endpoint === undefined) {
|
|
442
|
+
endpoint = text;
|
|
443
|
+
endpointAt = k;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (words.some((word, k) => k >= start && k !== endpointAt && word.bare))
|
|
447
|
+
return true;
|
|
448
|
+
const effective = (method ?? (fields ? "POST" : "GET")).toUpperCase();
|
|
449
|
+
// A call with no method and no fields is a GET, whatever the endpoint; a write to an endpoint
|
|
450
|
+
// that cannot be read is a floor item.
|
|
451
|
+
if (endpoint === undefined)
|
|
452
|
+
return true;
|
|
453
|
+
if (/\$/.test(endpoint))
|
|
454
|
+
return (!["GET", "HEAD"].includes(effective) &&
|
|
455
|
+
!(effective === "POST" && fields && variableReply(endpoint)));
|
|
456
|
+
if (endpoint === "graphql") {
|
|
457
|
+
// A query read from a file cannot be judged; one without a mutation reads.
|
|
458
|
+
if (values.some((value) => value === "@" || /^query=@/.test(value)))
|
|
459
|
+
return true;
|
|
460
|
+
for (const value of values) {
|
|
461
|
+
const mutations = mutationFields(value);
|
|
462
|
+
if (mutations === undefined)
|
|
463
|
+
continue;
|
|
464
|
+
if (!mutations.length || mutations.some((field) => !GH_MUTATIONS.has(field)))
|
|
465
|
+
return true;
|
|
466
|
+
if (mutations.includes("updatePullRequest") && /\bstate\s*:/.test(value))
|
|
467
|
+
return true;
|
|
468
|
+
}
|
|
469
|
+
return false;
|
|
470
|
+
}
|
|
471
|
+
if (["GET", "HEAD"].includes(effective))
|
|
472
|
+
return false;
|
|
473
|
+
const path = /^\/?repos\/[^/]+\/[^/]+\/([^?#]*)$/.exec(endpoint)?.[1]?.replace(/\/$/, "");
|
|
474
|
+
if (path === undefined)
|
|
475
|
+
return true;
|
|
476
|
+
if (!GH_API_WRITES.some(([methods, shape]) => methods.test(effective) && shape.test(path)))
|
|
477
|
+
return true;
|
|
478
|
+
// Editing a pull request is recoverable; closing, reopening or merging state is not its job here.
|
|
479
|
+
if (/^pulls\/\d+$/.test(path) && values.some((value) => /^state=/.test(value)))
|
|
480
|
+
return true;
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
/** A comment POST shape whose only numeric ids may come from a variable. */
|
|
484
|
+
const GH_VARIABLE_REPLY = /^(?:issues\/#\/comments|pulls\/#\/comments(?:\/#\/replies)?|pulls\/comments\/#\/replies)$/;
|
|
485
|
+
/**
|
|
486
|
+
* Whether a POST to an endpoint with a variable is a comment or reply whose only variable parts
|
|
487
|
+
* are numeric-id segments (`$id`, `${id}`, `$1`): `reply(){ gh api repos/o/r/pulls/7/comments/$1/
|
|
488
|
+
* replies -f body="$2"; }`. Owner and repository must be literal. The caller has made sure it is a
|
|
489
|
+
* POST, a write that goes to the classifier rather than the floor.
|
|
490
|
+
*/
|
|
491
|
+
function variableReply(endpoint) {
|
|
492
|
+
const match = /^\/?repos\/([^/$]+)\/([^/$]+)\/([^?#]*?)\/?$/.exec(endpoint);
|
|
493
|
+
if (!match)
|
|
494
|
+
return false;
|
|
495
|
+
const segments = match[3].split("/").map((segment) => {
|
|
496
|
+
if (/^\d+$/.test(segment) || /^\$(?:\w+|\{\w+\})$/.test(segment))
|
|
497
|
+
return "#";
|
|
498
|
+
return segment;
|
|
499
|
+
});
|
|
500
|
+
return (!segments.some((segment) => segment.includes("$")) && GH_VARIABLE_REPLY.test(segments.join("/")));
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Options a CLI accepts before its command words: `valued` take the next word as their value,
|
|
504
|
+
* `flags` take none. `--name=value` and a short option with its value attached are read as one.
|
|
505
|
+
*/
|
|
506
|
+
const KUBE_VALUED = /^(?:-n|--namespace|--context|--cluster|--user|-s|--server|--kubeconfig|--token|--as|--as-group|--as-uid|--request-timeout|--certificate-authority|--client-certificate|--client-key|--tls-server-name|--cache-dir|-v|--v|--log-file|--profile|--profile-output|--username|--password)$/;
|
|
507
|
+
const KUBE_FLAGS = /^(?:--insecure-skip-tls-verify|--match-server-version|--warnings-as-errors|-h|--help)$/;
|
|
508
|
+
const GLOBALS = {
|
|
509
|
+
// `-h` is help in gh, but is treated as unknown so a word after it is never trusted as the verb.
|
|
510
|
+
gh: { valued: /^(?:-R|--repo|--hostname)$/, flags: /^(?:--help|--version)$/ },
|
|
511
|
+
kubectl: { valued: KUBE_VALUED, flags: KUBE_FLAGS },
|
|
512
|
+
oc: { valued: KUBE_VALUED, flags: KUBE_FLAGS },
|
|
513
|
+
helm: {
|
|
514
|
+
valued: /^(?:-n|--namespace|--kube-context|--kubeconfig|--kube-apiserver|--kube-token|--kube-as-user|--kube-as-group|--kube-ca-file|--kube-tls-server-name|--registry-config|--repository-config|--repository-cache|--burst-limit|--qps)$/,
|
|
515
|
+
flags: /^(?:--debug|--kube-insecure-skip-tls-verify|-h|--help)$/,
|
|
516
|
+
},
|
|
517
|
+
terraform: { valued: /^$/, flags: /^(?:-help|-version|--help|--version)$/ },
|
|
518
|
+
tofu: { valued: /^$/, flags: /^(?:-help|-version|--help|--version)$/ },
|
|
519
|
+
pulumi: {
|
|
520
|
+
valued: /^(?:-C|--cwd|-s|--stack|--color|-v|--verbose|--tracing|--memprofilerate)$/,
|
|
521
|
+
flags: /^(?:--non-interactive|--emoji|--logflow|--logtostderr|--disable-integrity-checking|-e|-h|--help)$/,
|
|
522
|
+
},
|
|
523
|
+
npm: {
|
|
524
|
+
valued: /^(?:--prefix|-C|--registry|--workspace|-w|--userconfig|--globalconfig|--cache|--loglevel|--otp|--tag|--access)$/,
|
|
525
|
+
flags: /^(?:-s|--silent|-q|--quiet|-d|--verbose|-y|--yes|-g|--global|--ws|--workspaces|--dry-run|-h|--help)$/,
|
|
526
|
+
},
|
|
527
|
+
pnpm: {
|
|
528
|
+
valued: /^(?:-C|--dir|--filter|-F|--registry|--loglevel|--reporter)$/,
|
|
529
|
+
flags: /^(?:-r|--recursive|-w|--workspace-root|-s|--silent|--dry-run)$/,
|
|
530
|
+
},
|
|
531
|
+
yarn: { valued: /^(?:--cwd|--registry)$/, flags: /^(?:-s|--silent|--verbose)$/ },
|
|
532
|
+
cargo: {
|
|
533
|
+
valued: /^(?:-C|--config|-Z|--color|--manifest-path)$/,
|
|
534
|
+
flags: /^(?:-v|-vv|-q|--quiet|--frozen|--locked|--offline|--verbose)$/,
|
|
535
|
+
},
|
|
536
|
+
docker: {
|
|
537
|
+
valued: /^(?:-H|--host|-c|--context|--config|-l|--log-level|--tlscacert|--tlscert|--tlskey)$/,
|
|
538
|
+
flags: /^(?:-D|--debug|--tls|--tlsverify)$/,
|
|
539
|
+
},
|
|
540
|
+
podman: {
|
|
541
|
+
valued: /^(?:--url|-c|--connection|--root|--runroot|--log-level)$/,
|
|
542
|
+
flags: /^(?:--remote|-r)$/,
|
|
543
|
+
},
|
|
544
|
+
poetry: {
|
|
545
|
+
valued: /^(?:-C|--directory|-P|--project)$/,
|
|
546
|
+
flags: /^(?:-q|--quiet|-v|-vv|-n|--no-interaction|--ansi|--no-ansi)$/,
|
|
547
|
+
},
|
|
548
|
+
dotnet: { valued: /^$/, flags: /^(?:-d|--diagnostics|-h|--help)$/ },
|
|
549
|
+
az: {
|
|
550
|
+
valued: /^(?:--subscription|-o|--output|--query)$/,
|
|
551
|
+
flags: /^(?:--only-show-errors|--debug|--verbose|-h|--help)$/,
|
|
552
|
+
},
|
|
553
|
+
aws: {
|
|
554
|
+
valued: /^(?:--profile|--region|--output|--endpoint-url|--query|--color|--ca-bundle|--cli-read-timeout|--cli-connect-timeout|--cli-binary-format)$/,
|
|
555
|
+
flags: /^(?:--debug|--no-verify-ssl|--no-paginate|--no-cli-pager|--no-sign-request|--no-cli-auto-prompt)$/,
|
|
556
|
+
},
|
|
557
|
+
gcloud: {
|
|
558
|
+
valued: /^(?:--project|--account|--configuration|--format|--verbosity|--impersonate-service-account|--billing-project|--flags-file|--trace-token)$/,
|
|
559
|
+
flags: /^(?:-q|--quiet|--no-user-output-enabled|--log-http|-h|--help)$/,
|
|
560
|
+
},
|
|
561
|
+
};
|
|
562
|
+
/**
|
|
563
|
+
* The first `count` command words of a CLI invocation once its known global options (and their
|
|
564
|
+
* values) are skipped, and whether an option it does not know came before them: its value could
|
|
565
|
+
* then be one of the words, or hide the real one, so the caller fails closed.
|
|
566
|
+
*/
|
|
567
|
+
function leading(name, args, count,
|
|
568
|
+
/** Stop at the first option after a command word (cloud CLIs take global options only first). */
|
|
569
|
+
stop = false) {
|
|
570
|
+
const known = GLOBALS[name];
|
|
571
|
+
const words = [];
|
|
572
|
+
let unknown = false;
|
|
573
|
+
let options = true;
|
|
574
|
+
for (let i = 0; i < args.length && words.length < count; i++) {
|
|
575
|
+
const arg = args[i];
|
|
576
|
+
if (!options || arg === "-" || !arg.startsWith("-")) {
|
|
577
|
+
words.push(arg);
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
if (stop && words.length)
|
|
581
|
+
break;
|
|
582
|
+
if (arg === "--")
|
|
583
|
+
options = false;
|
|
584
|
+
else if (/^--[^=]+=/.test(arg) && known)
|
|
585
|
+
continue;
|
|
586
|
+
else if (known?.valued.test(arg))
|
|
587
|
+
i++;
|
|
588
|
+
else if (known?.flags.test(arg))
|
|
589
|
+
continue;
|
|
590
|
+
else if (known && /^-[a-zA-Z]./.test(arg) && known.valued.test(arg.slice(0, 2)))
|
|
591
|
+
continue;
|
|
592
|
+
else
|
|
593
|
+
unknown = true;
|
|
594
|
+
}
|
|
595
|
+
return { words, unknown };
|
|
596
|
+
}
|
|
597
|
+
/** Whether a CLI's command word (the first, or with an unknown option any later word) matches. */
|
|
598
|
+
function verbMatches(name, args, verb) {
|
|
599
|
+
if (!verb)
|
|
600
|
+
return false;
|
|
601
|
+
const { words, unknown } = leading(name, args, 1);
|
|
602
|
+
if (unknown)
|
|
603
|
+
return args.some((arg) => !arg.startsWith("-") && verb.test(arg));
|
|
604
|
+
return verb.test(words[0] ?? "");
|
|
605
|
+
}
|
|
606
|
+
/** Whether `gh` runs a floor subcommand (`gh <group> <verb>`, `gh repo deploy-key add`). */
|
|
607
|
+
function ghFloor(args) {
|
|
608
|
+
const { words, unknown } = leading("gh", args, 3);
|
|
609
|
+
const pair = (group, verb, third = "") => GH_DELETE[group]?.test(verb) ||
|
|
610
|
+
(group === "repo" && verb === "deploy-key" && /^(?:add|delete)$/.test(third));
|
|
611
|
+
if (!unknown)
|
|
612
|
+
return !!pair(words[0] ?? "", words[1] ?? "", words[2] ?? "");
|
|
613
|
+
// An option gh does not know came first: any later pair of words could be the subcommand.
|
|
614
|
+
const positional = args.filter((arg) => !arg.startsWith("-"));
|
|
615
|
+
return positional.some((group, k) => positional.slice(k + 1).some((verb, j) => pair(group, verb, positional[k + j + 2] ?? "")));
|
|
616
|
+
}
|
|
617
|
+
/** The floor rules for one literal program. */
|
|
618
|
+
function floorRules(name, cmd, context, rules) {
|
|
619
|
+
const texts = cmd.args.map((word) => word.text);
|
|
620
|
+
if (verbMatches(name, texts, INFRA_WRITE[name]))
|
|
621
|
+
rules.add("cloud-write");
|
|
622
|
+
if (name === "dotnet") {
|
|
623
|
+
const { words, unknown } = leading(name, texts, 2);
|
|
624
|
+
if ((words[0] === "nuget" && words[1] === "push") ||
|
|
625
|
+
(unknown && texts.includes("nuget") && texts.includes("push")))
|
|
626
|
+
rules.add("publish");
|
|
627
|
+
}
|
|
628
|
+
else if (verbMatches(name, texts, PUBLISHERS[name]))
|
|
629
|
+
rules.add("publish");
|
|
630
|
+
if (name === "gh") {
|
|
631
|
+
if (ghFloor(texts))
|
|
632
|
+
rules.add("repo-delete");
|
|
633
|
+
const { words, unknown } = leading("gh", texts, 1);
|
|
634
|
+
if ((words[0] === "api" || (unknown && texts.includes("api"))) && ghApiFloor(cmd.args))
|
|
635
|
+
rules.add("repo-delete");
|
|
636
|
+
}
|
|
637
|
+
if (httpWrite(name, cmd.args.map((word) => word.text)))
|
|
638
|
+
rules.add("cloud-write");
|
|
639
|
+
if (name === "find") {
|
|
640
|
+
const texts = cmd.args.map((word) => word.text);
|
|
641
|
+
const exec = texts.findIndex((text) => /^-(?:exec|execdir|ok|okdir)$/.test(text));
|
|
642
|
+
const deletes = texts.includes("-delete") ||
|
|
643
|
+
(exec >= 0 && /^(?:.*\/)?(?:rm|rmdir|unlink|shred)$/.test(texts[exec + 1] ?? ""));
|
|
644
|
+
// Any action that deletes or runs something, wherever find could reach the state.
|
|
645
|
+
if ((exec >= 0 || texts.includes("-delete")) && findReachesState(texts, context.cwds))
|
|
646
|
+
rules.add("policy-state");
|
|
647
|
+
if (deletes) {
|
|
648
|
+
const start = cmd.args.findIndex((word) => /^[-!(]/.test(word.text));
|
|
649
|
+
const roots = cmd.args.slice(0, start < 0 ? cmd.args.length : start);
|
|
650
|
+
const targets = roots.length ? roots : [{ text: ".", literal: true }];
|
|
651
|
+
if (targets.some((word) => !disposableTarget(word, context)))
|
|
652
|
+
rules.add("rm-outside");
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
if (name === "rm" && cmd.args.some((word) => /^-[a-zA-Z]*[rR]|^--recursive$/.test(word.text)))
|
|
656
|
+
for (const word of cmd.args) {
|
|
657
|
+
if (word.text.startsWith("-") && word.literal)
|
|
658
|
+
continue;
|
|
659
|
+
if (!disposableTarget(word, context))
|
|
660
|
+
rules.add("rm-outside");
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Whether a recursive `rm` target is strictly inside a linked feature worktree, the system temp
|
|
665
|
+
* directory or a profile scratch root. A word that is not literal, or that expands (a glob or a
|
|
666
|
+
* brace) under the home directory, is not.
|
|
667
|
+
*/
|
|
668
|
+
function disposableTarget(word, context) {
|
|
669
|
+
if (!word.literal)
|
|
670
|
+
return false;
|
|
671
|
+
const text = word.text;
|
|
672
|
+
const expands = /[*?[{]/.test(text);
|
|
673
|
+
const base = expands ? text.slice(0, text.search(/[*?[{]/)) : text;
|
|
674
|
+
if (expands && (base === "" || base === "~" || base.startsWith("~/") || base === "/")) {
|
|
675
|
+
// `rm -rf ~/{a,b}` or `rm -rf ~/*`: an expansion in the home directory is never disposable.
|
|
676
|
+
if (base.startsWith("~") || base === "/" || base === "")
|
|
677
|
+
return false;
|
|
678
|
+
}
|
|
679
|
+
if (context.unknownCwd && !base.startsWith("/") && !base.startsWith("~"))
|
|
680
|
+
return false;
|
|
681
|
+
const roots = [...tempRoots(), ...context.scratchRoots];
|
|
682
|
+
const found = resolutions(base || ".", context.cwds);
|
|
683
|
+
// A target that cannot be resolved (`~user/x`, an unknown directory) is not disposable.
|
|
684
|
+
if (!found.length)
|
|
685
|
+
return false;
|
|
686
|
+
for (const path of found) {
|
|
687
|
+
let real = path;
|
|
688
|
+
try {
|
|
689
|
+
real = canonical(path);
|
|
690
|
+
}
|
|
691
|
+
catch {
|
|
692
|
+
/* judged as written */
|
|
693
|
+
}
|
|
694
|
+
if (expands && inside(homedir(), real) && !roots.some((root) => inside(root, real)))
|
|
695
|
+
return false;
|
|
696
|
+
const strictly = roots.some((root) => inside(root, real) && real !== root);
|
|
697
|
+
if (!strictly && !featureWorktree(real))
|
|
698
|
+
return false;
|
|
699
|
+
}
|
|
700
|
+
return true;
|
|
701
|
+
}
|
|
702
|
+
/** Whether a path is strictly inside a linked worktree on a feature branch. */
|
|
703
|
+
function featureWorktree(path) {
|
|
704
|
+
try {
|
|
705
|
+
let dir = path;
|
|
706
|
+
while (!existsSync(dir))
|
|
707
|
+
dir = dirname(dir);
|
|
708
|
+
const top = canonical(git(dir, ["rev-parse", "--show-toplevel"]));
|
|
709
|
+
if (!inside(top, path) || top === path)
|
|
710
|
+
return false;
|
|
711
|
+
const gitDir = git(dir, ["rev-parse", "--path-format=absolute", "--git-dir"]);
|
|
712
|
+
const common = git(dir, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
713
|
+
const branch = git(dir, ["branch", "--show-current"]);
|
|
714
|
+
return gitDir !== common && !!branch && !/^(?:main|master)$/.test(branch);
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
const SECRET_WORD = /(?:secret|credential|password|connection[-_]?strings?|(?:^|[-_])keys?(?:$|[-_])|listKeys|access-token|get-token|kubeconfig)/i;
|
|
721
|
+
/** Programs that delete or move their operands: a directory above the state counts for them. */
|
|
722
|
+
/** Most directories a script is judged in before its directory counts as unknown. */
|
|
723
|
+
const MAX_CWDS = 16;
|
|
724
|
+
const REMOVERS = new Set(["rm", "rmdir", "unlink", "shred", "mv", "trash", "srm", "rsync"]);
|
|
725
|
+
const SHELL_NAMES = new Set(["sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "source", "."]);
|
|
726
|
+
/** Programs that run text they are given (inline code, a here-document, standard input). */
|
|
727
|
+
const INTERPRETERS = new Set([
|
|
728
|
+
...["node", "nodejs", "deno", "bun", "python", "python2", "python3", "perl", "ruby", "php"],
|
|
729
|
+
...["osascript", "pwsh", "powershell", "lua", "tclsh", "expect"],
|
|
730
|
+
...["jshell", "irb", "R", "Rscript", "julia", "swift", "groovy", "scala"],
|
|
731
|
+
]);
|
|
732
|
+
/** Programs that run another command from their arguments or input. */
|
|
733
|
+
const RUNNERS = new Set([
|
|
734
|
+
...["eval", "exec", "xargs", "find", "alias", "ssh", "su", "script", "watch", "parallel"],
|
|
735
|
+
...["tmux", "screen", "docker", "podman", "kubectl", "nohup", "env", "sudo", "doas"],
|
|
736
|
+
]);
|
|
737
|
+
/** Whether a command (after wrappers) can run text as code. Unknown programs count. */
|
|
738
|
+
export function runsText(cmd) {
|
|
739
|
+
const program = cmd.program;
|
|
740
|
+
if (!program)
|
|
741
|
+
return false;
|
|
742
|
+
if (!program.literal)
|
|
743
|
+
return true;
|
|
744
|
+
const name = (program.text.split(/[\\/]/).pop() ?? "").replace(/\d+(?:\.\d+)*$/, "");
|
|
745
|
+
const texts = cmd.args.map((word) => word.text);
|
|
746
|
+
// sed runs a command only through GNU `e` (a command or an `s///e` flag); awk through
|
|
747
|
+
// `system(`, a pipe to or from a command, or `|&`. An ordinary edit or print is data.
|
|
748
|
+
if (name === "sed")
|
|
749
|
+
return texts.some((text) => /(?:^|[;\n{}]\s*)e(?:\s|$)|\/[gpIiMm0-9w]*e[gpIiMm0-9]*\s*(?:$|[;}])/.test(text));
|
|
750
|
+
if (["awk", "gawk", "mawk", "nawk"].includes(name))
|
|
751
|
+
return texts.some((text) => /system\s*\(|\|\s*getline|print[^;]*\|\s*"|\|&/.test(text));
|
|
752
|
+
return (SHELL_NAMES.has(name) ||
|
|
753
|
+
INTERPRETERS.has(name) ||
|
|
754
|
+
INTERPRETERS.has(program.text.split(/[\\/]/).pop() ?? "") ||
|
|
755
|
+
RUNNERS.has(name));
|
|
756
|
+
}
|
|
757
|
+
/** Whether any command of a script can run text as code, or the script could not be read. */
|
|
758
|
+
export function scriptRunsText(script) {
|
|
759
|
+
const { segments, complete } = scan(script);
|
|
760
|
+
return !complete || segments.some((segment) => runsText(command(segment)));
|
|
761
|
+
}
|
|
762
|
+
/** A word's text as the words it could split into (`X="push --force"; git $X`). */
|
|
763
|
+
function split(word) {
|
|
764
|
+
const text = /^[A-Za-z_]\w*\+?=/.test(word.text)
|
|
765
|
+
? word.text.slice(word.text.indexOf("=") + 1)
|
|
766
|
+
: word.text;
|
|
767
|
+
return text.split(/\s+/).filter(Boolean);
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* The commands an awk program runs: the literal ones (`system("cmd")`, `print | "cmd"`,
|
|
771
|
+
* `"cmd" | getline`) and whether any is not a literal string. One pass that skips strings and
|
|
772
|
+
* regular expressions, so a `|` inside `/a|b/` is not a pipe.
|
|
773
|
+
*/
|
|
774
|
+
function awkCommands(program) {
|
|
775
|
+
const literal = [];
|
|
776
|
+
let opaque = false;
|
|
777
|
+
/** Files `print > "f"` and `printf >> "f"` write, and whether a target is not a literal. */
|
|
778
|
+
const writes = [];
|
|
779
|
+
let writesOpaque = false;
|
|
780
|
+
/**
|
|
781
|
+
* Whether the program prints at all (any `print`/`printf`, even in a string: fail closed), and
|
|
782
|
+
* the paren depth. With a print anywhere, every `>`/`>>` outside parentheses is read as an
|
|
783
|
+
* output redirection, whatever control keyword (`if`, `else`, `for`, `while`, `do`) or statement
|
|
784
|
+
* it follows; a comparison there is read the same way, which only fails closed.
|
|
785
|
+
*/
|
|
786
|
+
const prints = /\bprintf?\b/.test(program);
|
|
787
|
+
let braces = 0;
|
|
788
|
+
let parens = 0;
|
|
789
|
+
let last = ""; // the previous significant character
|
|
790
|
+
let lastString; // the string literal just before, if the last token was one
|
|
791
|
+
/** A string from `from`: its text, where it ends, and whether it has escapes (not judged). */
|
|
792
|
+
const readString = (from) => {
|
|
793
|
+
let text = "";
|
|
794
|
+
let escaped = false;
|
|
795
|
+
for (let j = from + 1; j < program.length; j++) {
|
|
796
|
+
const c = program[j];
|
|
797
|
+
if (c === "\\") {
|
|
798
|
+
escaped = true;
|
|
799
|
+
text += c + (program[++j] ?? "");
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
if (c === '"')
|
|
803
|
+
return [text, j, escaped];
|
|
804
|
+
text += c;
|
|
805
|
+
}
|
|
806
|
+
return undefined;
|
|
807
|
+
};
|
|
808
|
+
const skipSpace = (from) => {
|
|
809
|
+
let j = from;
|
|
810
|
+
while (j < program.length && /\s/.test(program[j]))
|
|
811
|
+
j++;
|
|
812
|
+
return j;
|
|
813
|
+
};
|
|
814
|
+
for (let i = 0; i < program.length; i++) {
|
|
815
|
+
const c = program[i];
|
|
816
|
+
if (/\s/.test(c))
|
|
817
|
+
continue;
|
|
818
|
+
if (c === '"') {
|
|
819
|
+
const read = readString(i);
|
|
820
|
+
if (!read) {
|
|
821
|
+
opaque = true;
|
|
822
|
+
break;
|
|
823
|
+
}
|
|
824
|
+
lastString = read[2] ? undefined : read[0];
|
|
825
|
+
i = read[1];
|
|
826
|
+
last = '"';
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
if (c === "/" && (last === "" || "(,~!&|{};:?\n".includes(last))) {
|
|
830
|
+
let j = i + 1;
|
|
831
|
+
while (j < program.length && program[j] !== "/")
|
|
832
|
+
j += program[j] === "\\" ? 2 : 1;
|
|
833
|
+
i = j;
|
|
834
|
+
last = "/";
|
|
835
|
+
lastString = undefined;
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
if (c === "|" && program[i + 1] !== "|" && program[i - 1] !== "|") {
|
|
839
|
+
let j = skipSpace(i + 1 + (program[i + 1] === "&" ? 1 : 0));
|
|
840
|
+
if (program.startsWith("getline", j)) {
|
|
841
|
+
if (lastString === undefined)
|
|
842
|
+
opaque = true;
|
|
843
|
+
else
|
|
844
|
+
literal.push(lastString);
|
|
845
|
+
}
|
|
846
|
+
else if (program[j] === '"') {
|
|
847
|
+
const read = readString(j);
|
|
848
|
+
// Output piped into a shell or interpreter is a script nobody can read here.
|
|
849
|
+
if (!read ||
|
|
850
|
+
read[2] ||
|
|
851
|
+
/^\s*(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|mksh|pwsh|powershell|python\d*(?:\.\d+)?|node|perl|ruby|php)(?:\s|$)/.test(read[0]))
|
|
852
|
+
opaque = true;
|
|
853
|
+
else {
|
|
854
|
+
literal.push(read[0]);
|
|
855
|
+
j = read[1];
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
else
|
|
859
|
+
opaque = true;
|
|
860
|
+
last = "|";
|
|
861
|
+
lastString = undefined;
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
if (c === "(")
|
|
865
|
+
parens++;
|
|
866
|
+
else if (c === ")")
|
|
867
|
+
parens = Math.max(0, parens - 1);
|
|
868
|
+
else if (c === "{")
|
|
869
|
+
braces++;
|
|
870
|
+
else if (c === "}")
|
|
871
|
+
braces = Math.max(0, braces - 1);
|
|
872
|
+
// Output redirection, `print ... > "file"` or `>>`, inside an action and outside parentheses
|
|
873
|
+
// (a pattern such as `$3 > 100`, and anything in parentheses, is a comparison). A target that
|
|
874
|
+
// is not one string literal (a variable, a concatenation) is an opaque write. `>=` compares.
|
|
875
|
+
if (c === ">" && prints && braces > 0 && parens === 0 && program[i + 1] !== "=") {
|
|
876
|
+
const at = skipSpace(i + (program[i + 1] === ">" ? 2 : 1));
|
|
877
|
+
const read = program[at] === '"' ? readString(at) : undefined;
|
|
878
|
+
const after = read ? program[skipSpace(read[1] + 1)] : undefined;
|
|
879
|
+
if (read && !read[2] && (after === undefined || ";})|\n".includes(after)))
|
|
880
|
+
writes.push(read[0]);
|
|
881
|
+
else
|
|
882
|
+
writesOpaque = true;
|
|
883
|
+
if (read)
|
|
884
|
+
i = read[1];
|
|
885
|
+
last = '"';
|
|
886
|
+
lastString = undefined;
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
if (program.startsWith("system", i) && !/\w/.test(program[i - 1] ?? "")) {
|
|
890
|
+
const open = skipSpace(i + 6);
|
|
891
|
+
if (program[open] === "(") {
|
|
892
|
+
const start = skipSpace(open + 1);
|
|
893
|
+
const read = program[start] === '"' ? readString(start) : undefined;
|
|
894
|
+
if (read && !read[2] && program[skipSpace(read[1] + 1)] === ")")
|
|
895
|
+
literal.push(read[0]);
|
|
896
|
+
else
|
|
897
|
+
opaque = true;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
last = c;
|
|
901
|
+
lastString = undefined;
|
|
902
|
+
}
|
|
903
|
+
return { literal, opaque, writes, writesOpaque };
|
|
904
|
+
}
|
|
905
|
+
/** Shells whose script can come from standard input; PowerShell's is never read here. */
|
|
906
|
+
const POWERSHELLS = new Set(["pwsh", "powershell", "pwsh.exe", "powershell.exe"]);
|
|
907
|
+
/** Interpreter options whose value is the code to run (`python3 -c`, `node -e`, `php -r`). */
|
|
908
|
+
const CODE_FLAG = /^(?:-c|-e|-E|-p|-r|--eval|--print)$/;
|
|
909
|
+
/**
|
|
910
|
+
* The text a literal producer writes to its standard output: `echo` and `printf` with literal
|
|
911
|
+
* arguments, or `cat` of a here-document (quoted, or unquoted with no expansion). Undefined when
|
|
912
|
+
* the output cannot be read here.
|
|
913
|
+
*/
|
|
914
|
+
function producedText(segment) {
|
|
915
|
+
const cmd = command(segment);
|
|
916
|
+
const name = cmd.program?.literal ? (cmd.program.text.split("/").pop() ?? "") : "";
|
|
917
|
+
if (cmd.redirects.some((word) => !word.heredoc && !word.writes))
|
|
918
|
+
return undefined;
|
|
919
|
+
if (name === "echo" || name === "printf") {
|
|
920
|
+
if (!cmd.args.every((word) => word.literal))
|
|
921
|
+
return undefined;
|
|
922
|
+
const args = cmd.args.map((word) => word.text);
|
|
923
|
+
const text = (name === "echo" ? args.filter((arg) => !/^-[neE]+$/.test(arg)) : args).join(" ");
|
|
924
|
+
return text.replace(/\\n/g, "\n");
|
|
925
|
+
}
|
|
926
|
+
if (name === "cat" && !cmd.args.length) {
|
|
927
|
+
const docs = segment.filter((word) => word.heredoc || word.herestring);
|
|
928
|
+
if (docs.length !== 1)
|
|
929
|
+
return undefined;
|
|
930
|
+
const doc = docs[0];
|
|
931
|
+
if (!doc.literal || (doc.heredoc && !doc.quoted && /[$`\\]/.test(doc.text)))
|
|
932
|
+
return undefined;
|
|
933
|
+
return doc.text;
|
|
934
|
+
}
|
|
935
|
+
return undefined;
|
|
936
|
+
}
|
|
937
|
+
/** The file a program's own command text writes, per program (the target in group 1 or 2). */
|
|
938
|
+
const SED_WRITES = /(?:^|[;\n{}]|\/[gpIiMme0-9]*|\d|\$)\s*[wW]\s+([^\n;}]+)/g;
|
|
939
|
+
const EX_WRITES = /(?:^|[|\n:+])[ \t]*(?:\d+(?:,\d+)?|%)?(?:w(?:rite)?|wq|x(?:it)?|sav(?:eas)?|up(?:date)?)!?[ \t]+(?:>>[ \t]*)?([^\s|]+)/g;
|
|
940
|
+
const ED_WRITES = /(?:^|\n)[ \t]*[\d,.$]*[wW]q?[ \t]+(\S+)/g;
|
|
941
|
+
const SQLITE_WRITES = /\.(?:output|once|save)\s+(\S+)|\.backup\s+(?:\w+\s+)?(\S+)/g;
|
|
942
|
+
const EDITOR_WRITES = {
|
|
943
|
+
sed: SED_WRITES,
|
|
944
|
+
gsed: SED_WRITES,
|
|
945
|
+
ex: EX_WRITES,
|
|
946
|
+
vi: EX_WRITES,
|
|
947
|
+
vim: EX_WRITES,
|
|
948
|
+
nvim: EX_WRITES,
|
|
949
|
+
view: EX_WRITES,
|
|
950
|
+
ed: ED_WRITES,
|
|
951
|
+
sqlite3: SQLITE_WRITES,
|
|
952
|
+
};
|
|
953
|
+
/**
|
|
954
|
+
* Files a program's own text writes (an awk redirection, a sed `w`, an editor's `w`, a sqlite3
|
|
955
|
+
* `.output`) get the checks a shell redirection does: the policy state, protected configuration.
|
|
956
|
+
* A target that is not a literal (a variable, a concatenation) is `opaque-script`, and text that
|
|
957
|
+
* writes somewhere and names `acp` counts as the policy state.
|
|
958
|
+
*/
|
|
959
|
+
function writeTargets(targets, opaque, text, context, rules) {
|
|
960
|
+
if (opaque)
|
|
961
|
+
rules.add("opaque-script");
|
|
962
|
+
if (!targets.length && !opaque)
|
|
963
|
+
return;
|
|
964
|
+
if (/\bacp/i.test(text))
|
|
965
|
+
rules.add("policy-state");
|
|
966
|
+
for (const target of targets) {
|
|
967
|
+
pathRules(target, rules, false);
|
|
968
|
+
const resolved = resolutions(target, context.cwds);
|
|
969
|
+
for (const path of resolved)
|
|
970
|
+
pathRules(path, rules, false);
|
|
971
|
+
if ([target, ...resolved].some(policyStatePath) || namesState(target, context.cwds, false))
|
|
972
|
+
rules.add("policy-state");
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
/** Shells whose script can come from standard input. Non-POSIX ones are read with sh's rules. */
|
|
976
|
+
const ANY_SHELLS = new Set([
|
|
977
|
+
...["sh", "bash", "zsh", "dash", "ksh", "mksh", "yash", "ash", "rbash", "fish", "csh", "tcsh"],
|
|
978
|
+
...["nu", "elvish", "xonsh", "busybox"],
|
|
979
|
+
]);
|
|
980
|
+
/**
|
|
981
|
+
* How a command reads a script from its standard input: `shell` (a shell with no script operand,
|
|
982
|
+
* or `-s`; `source /dev/stdin`), `code` (an interpreter with no code flag or script), `opaque`
|
|
983
|
+
* (PowerShell, `xargs <shell>`, `sh -c "$var"`, a process substitution), or undefined when it does
|
|
984
|
+
* not. A shell's `-c` script is searched for such a command too (`bash -c 'sh'`).
|
|
985
|
+
*/
|
|
986
|
+
function readsScript(segment, depth = 0) {
|
|
987
|
+
const cmd = command(segment);
|
|
988
|
+
if (!cmd.program?.literal)
|
|
989
|
+
return undefined;
|
|
990
|
+
let name = cmd.program.text.split(/[\\/]/).pop() ?? "";
|
|
991
|
+
let words = cmd.args;
|
|
992
|
+
if (name === "busybox") {
|
|
993
|
+
name = words[0]?.text ?? "";
|
|
994
|
+
words = words.slice(1);
|
|
995
|
+
}
|
|
996
|
+
const args = words.map((word) => word.text);
|
|
997
|
+
const operands = args.filter((arg) => !arg.startsWith("-"));
|
|
998
|
+
const programAt = segment.indexOf(cmd.program);
|
|
999
|
+
const viaXargs = segment.some((word, k) => k < programAt && word.literal && /(?:^|\/)xargs$/.test(word.text));
|
|
1000
|
+
if (ANY_SHELLS.has(name) || POWERSHELLS.has(name.toLowerCase())) {
|
|
1001
|
+
if (viaXargs || POWERSHELLS.has(name.toLowerCase()))
|
|
1002
|
+
return "opaque";
|
|
1003
|
+
const flag = args.findIndex((arg) => /^-[a-zA-Z]*c[a-zA-Z]*$|^--command$/.test(arg));
|
|
1004
|
+
if (flag >= 0) {
|
|
1005
|
+
const body = words[flag + 1];
|
|
1006
|
+
if (!body || !body.literal)
|
|
1007
|
+
return "opaque";
|
|
1008
|
+
if (depth >= 3)
|
|
1009
|
+
return "opaque";
|
|
1010
|
+
for (const inner of scan(body.text).segments) {
|
|
1011
|
+
const kind = readsScript(inner, depth + 1);
|
|
1012
|
+
if (kind)
|
|
1013
|
+
return kind;
|
|
1014
|
+
}
|
|
1015
|
+
return undefined;
|
|
1016
|
+
}
|
|
1017
|
+
if (operands.length && !args.includes("-s"))
|
|
1018
|
+
return undefined; // `bash script.sh`
|
|
1019
|
+
return "shell";
|
|
1020
|
+
}
|
|
1021
|
+
if (name === "source" || name === ".") {
|
|
1022
|
+
const target = words[0];
|
|
1023
|
+
if (!target)
|
|
1024
|
+
return undefined;
|
|
1025
|
+
if (!target.literal)
|
|
1026
|
+
return "opaque"; // `. <(curl ...)`, `source $f`
|
|
1027
|
+
return /^\/dev\/(?:stdin|fd\/0)$|^-$/.test(target.text) ? "shell" : undefined;
|
|
1028
|
+
}
|
|
1029
|
+
if (INTERPRETERS.has(name)) {
|
|
1030
|
+
if (viaXargs)
|
|
1031
|
+
return "opaque";
|
|
1032
|
+
if (words.some((_, i) => i > 0 && CODE_FLAG.test(args[i - 1] ?? "")))
|
|
1033
|
+
return undefined;
|
|
1034
|
+
if (operands.some((arg) => arg !== "-"))
|
|
1035
|
+
return undefined; // `python3 script.py`
|
|
1036
|
+
return "code";
|
|
1037
|
+
}
|
|
1038
|
+
return undefined;
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* A script fed to a shell or interpreter. The stage a pipe feeds is the piped command and, when
|
|
1042
|
+
* it opens a group (`( ... )`, `{ ...; }`, `if`, `while`, `for`, `case`), everything inside the
|
|
1043
|
+
* group; a here-string or a redirected standard input feeds its own command. When any command
|
|
1044
|
+
* there reads its script from standard input (`readsScript`), a literal `echo`, `printf`, quoted
|
|
1045
|
+
* here-document or here-string is judged as the script it is (the floor and every hard rule for a
|
|
1046
|
+
* shell, the interpreter rule for code); anything else is `opaque-script`.
|
|
1047
|
+
*/
|
|
1048
|
+
function stdinScript(segments, k, context, rules, depth) {
|
|
1049
|
+
const segment = segments[k];
|
|
1050
|
+
const first = segment[0];
|
|
1051
|
+
const piped = segment.find((word) => word.piped);
|
|
1052
|
+
const here = segment.filter((word) => word.herestring);
|
|
1053
|
+
const docs = segment.filter((word) => word.heredoc);
|
|
1054
|
+
const cmd = command(segment);
|
|
1055
|
+
const fromFile = cmd.redirects.some((word) => !word.heredoc && !word.herestring && !word.writes && !/^\d*$/.test(word.text));
|
|
1056
|
+
let kind;
|
|
1057
|
+
let text;
|
|
1058
|
+
if (piped) {
|
|
1059
|
+
// The stage: this command, and the rest of a group it opens.
|
|
1060
|
+
const at = piped.pipedAt ?? first?.depth ?? 0;
|
|
1061
|
+
for (let j = k; j < segments.length; j++) {
|
|
1062
|
+
const stage = segments[j];
|
|
1063
|
+
if (j > k && (stage[0]?.depth ?? 0) <= at)
|
|
1064
|
+
break;
|
|
1065
|
+
kind ??= readsScript(stage);
|
|
1066
|
+
if (kind)
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
if (!kind)
|
|
1070
|
+
return;
|
|
1071
|
+
text = producedText(segments[k - 1] ?? []);
|
|
1072
|
+
}
|
|
1073
|
+
else {
|
|
1074
|
+
kind = readsScript(segment);
|
|
1075
|
+
if (!kind)
|
|
1076
|
+
return;
|
|
1077
|
+
if (here.length) {
|
|
1078
|
+
const word = here[here.length - 1];
|
|
1079
|
+
if (word.literal)
|
|
1080
|
+
text = word.text;
|
|
1081
|
+
}
|
|
1082
|
+
else if (docs.length)
|
|
1083
|
+
return; // a here-document: judged as code where it is read
|
|
1084
|
+
else if (!fromFile && kind !== "opaque")
|
|
1085
|
+
return; // nothing is fed in (an interactive shell)
|
|
1086
|
+
}
|
|
1087
|
+
if (kind === "opaque" || text === undefined) {
|
|
1088
|
+
rules.add("opaque-script");
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
context.runsText = true;
|
|
1092
|
+
if (kind === "shell" && depth < 4)
|
|
1093
|
+
analyzeScript(text, context, rules, depth + 1);
|
|
1094
|
+
if (kind === "code" && codeTouchesState(text, context.cwds))
|
|
1095
|
+
rules.add("policy-state");
|
|
1096
|
+
textRules(text, [...context.cwds][0] ?? "", rules);
|
|
1097
|
+
}
|
|
1098
|
+
function analyzeScript(script, context, rules, depth) {
|
|
1099
|
+
const { segments, complete } = scan(script);
|
|
1100
|
+
// Here-document bodies are data unless something in the script runs text as code.
|
|
1101
|
+
const runs = !complete || segments.some((segment) => runsText(command(segment)));
|
|
1102
|
+
if (runs)
|
|
1103
|
+
context.runsText = true;
|
|
1104
|
+
for (const segment of segments)
|
|
1105
|
+
for (const word of segment) {
|
|
1106
|
+
if (word.heredoc)
|
|
1107
|
+
continue;
|
|
1108
|
+
context.words.push(...split(word));
|
|
1109
|
+
if (/^[A-Za-z_]\w*\+?=/.test(word.text))
|
|
1110
|
+
context.assigned.push(...split(word));
|
|
1111
|
+
}
|
|
1112
|
+
// A script the scanner could not read fully is judged on its words alone.
|
|
1113
|
+
if (!complete)
|
|
1114
|
+
opaqueGitRules(context.words, true, rules);
|
|
1115
|
+
for (const [k, segment] of segments.entries()) {
|
|
1116
|
+
analyzeCommand(command(segment), segment, context, rules, depth);
|
|
1117
|
+
stdinScript(segments, k, context, rules, depth);
|
|
1118
|
+
// A here-document fed to a shell, or in a script that runs text (`cat <<EOF | sh`), is code.
|
|
1119
|
+
for (const doc of segment.filter((word) => word.heredoc)) {
|
|
1120
|
+
if (depth >= 4)
|
|
1121
|
+
continue;
|
|
1122
|
+
if (runs) {
|
|
1123
|
+
analyzeScript(doc.text, context, rules, depth + 1);
|
|
1124
|
+
textRules(doc.text, [...context.cwds][0] ?? "", rules);
|
|
1125
|
+
}
|
|
1126
|
+
if (doc.quoted)
|
|
1127
|
+
continue;
|
|
1128
|
+
// Fail closed on an unquoted body: besides its substitutions as the scanner reads them, read
|
|
1129
|
+
// what follows every `$(` and backtick as a script, so text the scanner might mis-read
|
|
1130
|
+
// around them (a stray quote, a backslash, a backtick taken literally) cannot hide a
|
|
1131
|
+
// command that will run.
|
|
1132
|
+
let openers = 0;
|
|
1133
|
+
for (const match of doc.text.matchAll(/\$\(|`/g)) {
|
|
1134
|
+
if (++openers > 32)
|
|
1135
|
+
break;
|
|
1136
|
+
// What a misread could hide starts at the opener; 4,096 characters bound each rescan.
|
|
1137
|
+
const from = (match.index ?? 0) + match[0].length;
|
|
1138
|
+
const rest = doc.text.slice(from, from + 4096);
|
|
1139
|
+
analyzeScript(rest, context, rules, depth + 1);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
function analyzeCommand(cmd, segment, context, rules, depth) {
|
|
1145
|
+
// Every word could name a file: arguments, redirect targets, assignment values. A here-document
|
|
1146
|
+
// body, and an argument with whitespace in it (a message, a PR body), is text, not a path,
|
|
1147
|
+
// unless the script runs text as code.
|
|
1148
|
+
// The policy service's state may be read by a read-only program; anything else that names it
|
|
1149
|
+
// (a write, a move, a delete, a redirection into it, an unknown program) goes to a person.
|
|
1150
|
+
const programName = cmd.program?.text.split(/[\\/]/).pop() ?? "";
|
|
1151
|
+
const reading = !!cmd.program?.literal && readOnly([programName, ...cmd.args.map((word) => word.text)]);
|
|
1152
|
+
const argTexts = cmd.args.map((word) => word.text);
|
|
1153
|
+
// A recursive permission or owner change reaches everything below its operand, so a directory
|
|
1154
|
+
// above the state counts as for a delete.
|
|
1155
|
+
const recursive = /^(?:chmod|chown|chgrp)$/.test(programName) &&
|
|
1156
|
+
argTexts.some((text) => /^-[a-zA-Z]*R|^--recursive$/.test(text));
|
|
1157
|
+
const removes = !cmd.program?.literal || REMOVERS.has(programName) || recursive;
|
|
1158
|
+
// An archive extracted into a directory the state lies in can overwrite it: `tar -x [-C dir]`,
|
|
1159
|
+
// `unzip [-d dir]`, `cpio -i` (into the working directory).
|
|
1160
|
+
if (cmd.program?.literal) {
|
|
1161
|
+
const optionValue = (flags) => {
|
|
1162
|
+
const at = argTexts.findIndex((text) => flags.test(text));
|
|
1163
|
+
if (at < 0)
|
|
1164
|
+
return undefined;
|
|
1165
|
+
const text = argTexts[at];
|
|
1166
|
+
const eq = text.indexOf("=");
|
|
1167
|
+
return eq > 0 ? text.slice(eq + 1) : (argTexts[at + 1] ?? "");
|
|
1168
|
+
};
|
|
1169
|
+
let into;
|
|
1170
|
+
if (programName === "tar" &&
|
|
1171
|
+
argTexts.some((text, k) => ((k === 0 || text.startsWith("-")) && /^-?[a-zA-Z]*x[a-zA-Z]*$/.test(text)) ||
|
|
1172
|
+
/^--(?:extract|get)$/.test(text)))
|
|
1173
|
+
into = optionValue(/^(?:-C|--directory)(?:=|$)/) ?? ".";
|
|
1174
|
+
else if (programName === "unzip")
|
|
1175
|
+
into = optionValue(/^-d$/) ?? ".";
|
|
1176
|
+
else if (programName === "cpio" &&
|
|
1177
|
+
argTexts.some((text) => /^-[a-zA-Z]*i|^--extract$/.test(text)))
|
|
1178
|
+
into = optionValue(/^(?:-D|--directory)(?:=|$)/) ?? ".";
|
|
1179
|
+
if (into !== undefined && namesState(stateText(into, true), context.cwds, true))
|
|
1180
|
+
rules.add("policy-state");
|
|
1181
|
+
}
|
|
1182
|
+
// `xargs <writer>` takes its targets from input nobody can read here; it fails closed when it
|
|
1183
|
+
// could reach the state: it runs where the state lies, or the script names `acp` or a path that
|
|
1184
|
+
// could name the state.
|
|
1185
|
+
const programAt = cmd.program ? segment.indexOf(cmd.program) : -1;
|
|
1186
|
+
const viaXargs = segment.some((word, k) => k < programAt && word.literal && /(?:^|\/)xargs$/.test(word.text));
|
|
1187
|
+
if (viaXargs &&
|
|
1188
|
+
!reading &&
|
|
1189
|
+
(namesState(".", context.cwds, true) ||
|
|
1190
|
+
context.words.some((word) => /acp/i.test(word) ||
|
|
1191
|
+
(/^[/~$]/.test(word) && namesState(stateText(word, false), context.cwds, true)))))
|
|
1192
|
+
rules.add("policy-state");
|
|
1193
|
+
// Inline interpreter code (`python3 -c`, `perl -e`, `node -e`, a here-document) that could
|
|
1194
|
+
// delete, move or write the state.
|
|
1195
|
+
if (cmd.program?.literal && INTERPRETERS.has(programName)) {
|
|
1196
|
+
const code = [
|
|
1197
|
+
...cmd.args.filter((_, k) => /^(?:-c|-e|-E|-p|-r|--eval|--print)$/.test(cmd.args[k - 1]?.text ?? "")),
|
|
1198
|
+
...segment.filter((word) => word.heredoc),
|
|
1199
|
+
].map((word) => word.text);
|
|
1200
|
+
if (code.some((text) => codeTouchesState(text, context.cwds)))
|
|
1201
|
+
rules.add("policy-state");
|
|
1202
|
+
}
|
|
1203
|
+
// awk runs commands through `system(...)` and pipes (`print | "cmd"`, `"cmd" | getline`): a
|
|
1204
|
+
// literal command is judged like `sh -c`, anything else is opaque.
|
|
1205
|
+
if (cmd.program?.literal && /^(?:awk|gawk|mawk|nawk)$/.test(programName)) {
|
|
1206
|
+
const texts = cmd.args.map((word) => word.text);
|
|
1207
|
+
let program;
|
|
1208
|
+
for (let i = 0; i < texts.length; i++) {
|
|
1209
|
+
const text = texts[i];
|
|
1210
|
+
if (/^-[Fvf]$/.test(text)) {
|
|
1211
|
+
if (text === "-f")
|
|
1212
|
+
break; // a program file: not read here
|
|
1213
|
+
i++;
|
|
1214
|
+
}
|
|
1215
|
+
else if (!text.startsWith("-")) {
|
|
1216
|
+
program = text;
|
|
1217
|
+
break;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
if (program !== undefined) {
|
|
1221
|
+
const run = awkCommands(program);
|
|
1222
|
+
if (run.opaque)
|
|
1223
|
+
rules.add("opaque-script");
|
|
1224
|
+
for (const script of run.literal)
|
|
1225
|
+
if (depth < 4) {
|
|
1226
|
+
analyzeScript(script, context, rules, depth + 1);
|
|
1227
|
+
textRules(script, [...context.cwds][0] ?? "", rules);
|
|
1228
|
+
}
|
|
1229
|
+
writeTargets(run.writes, run.writesOpaque, program, context, rules);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
// Editors and tools that write files named inside their own command text: sed `w`, `W` and
|
|
1233
|
+
// `s///w`, ex/vim `-c 'w file'`, ed's `w`, sqlite3 `.output`/`.once`/`.save`/`.backup`.
|
|
1234
|
+
if (cmd.program?.literal && EDITOR_WRITES[programName]) {
|
|
1235
|
+
const texts = cmd.args.map((word) => word.text);
|
|
1236
|
+
const inputs = segment.filter((word) => word.heredoc || word.herestring);
|
|
1237
|
+
const scripts = [...texts, ...inputs.map((word) => word.text)];
|
|
1238
|
+
const targets = [];
|
|
1239
|
+
let opaque = inputs.some((word) => !word.literal && !(word.heredoc && word.quoted));
|
|
1240
|
+
for (const script of scripts)
|
|
1241
|
+
for (const match of script.matchAll(EDITOR_WRITES[programName])) {
|
|
1242
|
+
const target = (match[1] ?? match[2] ?? "").replace(/^(["'])(.*)\1$/, "$2");
|
|
1243
|
+
if (!target)
|
|
1244
|
+
continue;
|
|
1245
|
+
if (/[$`]/.test(target))
|
|
1246
|
+
opaque = true;
|
|
1247
|
+
else
|
|
1248
|
+
targets.push(target);
|
|
1249
|
+
}
|
|
1250
|
+
writeTargets(targets, opaque, scripts.join("\n"), context, rules);
|
|
1251
|
+
}
|
|
1252
|
+
for (const word of segment) {
|
|
1253
|
+
if (word.heredoc)
|
|
1254
|
+
continue;
|
|
1255
|
+
if (!word.redirect && !context.runsText && /\s/.test(word.text))
|
|
1256
|
+
continue;
|
|
1257
|
+
const text = word.text.replace(/^[A-Za-z_]\w*=/, "").replace(/^--?[\w-]+=/, "");
|
|
1258
|
+
if (!text)
|
|
1259
|
+
continue;
|
|
1260
|
+
pathRules(text, rules, true);
|
|
1261
|
+
const resolved = resolutions(text, context.cwds);
|
|
1262
|
+
for (const path of resolved)
|
|
1263
|
+
pathRules(path, rules, true);
|
|
1264
|
+
// A target is matched as the shell would expand it (a glob, a variable read as `*`), and for a
|
|
1265
|
+
// delete or move a directory above the state counts too.
|
|
1266
|
+
// A word that is only an expansion (`"$Q"`) counts for a delete, a move or a redirection.
|
|
1267
|
+
const target = stateText(text, word.literal);
|
|
1268
|
+
const opaque = !word.literal && !/[^*/]/.test(target);
|
|
1269
|
+
if ((word.writes || (!word.redirect && !reading)) &&
|
|
1270
|
+
word !== cmd.program &&
|
|
1271
|
+
([text, ...resolved].some(policyStatePath) ||
|
|
1272
|
+
((!opaque || removes || word.writes) && namesState(target, context.cwds, removes)) ||
|
|
1273
|
+
(context.unknownCwd && !/^[/~]/.test(text) && /acp/i.test(text))))
|
|
1274
|
+
rules.add("policy-state");
|
|
1275
|
+
const relative = !text.startsWith("/") && !text.startsWith("~") && !text.startsWith("$");
|
|
1276
|
+
if (context.unknownCwd && relative && SETTINGS_NAMES.test(text.split("/").pop() ?? ""))
|
|
1277
|
+
rules.add("harness-settings");
|
|
1278
|
+
}
|
|
1279
|
+
const program = cmd.program;
|
|
1280
|
+
if (!program)
|
|
1281
|
+
return;
|
|
1282
|
+
const name = program.text.split(/[\\/]/).pop() ?? "";
|
|
1283
|
+
const args = cmd.args.map((word) => word.text);
|
|
1284
|
+
if (program.literal && name === "cd") {
|
|
1285
|
+
const target = cmd.args.find((word) => !word.text.startsWith("-"));
|
|
1286
|
+
if (!target)
|
|
1287
|
+
context.cwds.add(homedir());
|
|
1288
|
+
else if (!target.literal)
|
|
1289
|
+
context.unknownCwd = true;
|
|
1290
|
+
else {
|
|
1291
|
+
const found = resolutions(target.text, context.cwds);
|
|
1292
|
+
// Every `cd` can double the directories a later word is judged in; past a few the script's
|
|
1293
|
+
// directory is unknown (relative targets then fail closed) instead of judged in thousands.
|
|
1294
|
+
if (!found.length || context.cwds.size + found.length > MAX_CWDS)
|
|
1295
|
+
context.unknownCwd = true;
|
|
1296
|
+
else
|
|
1297
|
+
for (const path of found)
|
|
1298
|
+
context.cwds.add(path);
|
|
1299
|
+
}
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
const inner = innerScript(cmd);
|
|
1303
|
+
if (inner) {
|
|
1304
|
+
if (depth < 4)
|
|
1305
|
+
analyzeScript(inner.script, context, rules, depth + 1);
|
|
1306
|
+
// An expanded script is not known: judge it on every word the script names.
|
|
1307
|
+
if (!inner.literal || depth >= 4)
|
|
1308
|
+
opaqueGitRules(context.words, true, rules);
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
if (program.literal && CLOUD.has(name)) {
|
|
1312
|
+
if (args.some((arg) => SECRET_WORD.test(arg)))
|
|
1313
|
+
rules.add("credential-read");
|
|
1314
|
+
else {
|
|
1315
|
+
// The command path: the words before the first option once known global options are
|
|
1316
|
+
// skipped. An option the CLI does not know before it could hide the path, so it fails closed.
|
|
1317
|
+
const { words, unknown } = leading(name, args, 6, true);
|
|
1318
|
+
const path = [];
|
|
1319
|
+
for (const word of words) {
|
|
1320
|
+
if (!/^[a-z][a-z0-9-]*$/.test(word))
|
|
1321
|
+
break;
|
|
1322
|
+
path.push(word);
|
|
1323
|
+
}
|
|
1324
|
+
const start = args.indexOf(path[0] ?? "");
|
|
1325
|
+
const tail = start < 0 ? [] : args.slice(start);
|
|
1326
|
+
// `az bicep` compiles, lints and formats local files; it never touches the cloud.
|
|
1327
|
+
if (unknown ||
|
|
1328
|
+
(!path.some((word) => CLOUD_READ_VERB.test(word)) &&
|
|
1329
|
+
!cloudGet(tail) &&
|
|
1330
|
+
!(name === "az" && path[0] === "bicep")))
|
|
1331
|
+
rules.add("cloud-write");
|
|
1332
|
+
}
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
if (program.literal)
|
|
1336
|
+
floorRules(name, cmd, context, rules);
|
|
1337
|
+
if (program.literal && name !== "git")
|
|
1338
|
+
return;
|
|
1339
|
+
// `git`, or a program that is not a literal word (`$GIT`), which could be Git.
|
|
1340
|
+
let opaque = !program.literal ||
|
|
1341
|
+
cmd.assignments.some((word) => /^GIT_/.test(word.text)) ||
|
|
1342
|
+
// `env GIT_DIR=...`, `GIT_CONFIG_*` and the like change what Git reads or runs.
|
|
1343
|
+
segment.some((word) => /^GIT_[A-Z_]*=/.test(word.text));
|
|
1344
|
+
let i = 0;
|
|
1345
|
+
/** A `-c remote.*` or `push.*` setting can make a plain push forced or mirrored. */
|
|
1346
|
+
let pushConfig = false;
|
|
1347
|
+
while (i < cmd.args.length && cmd.args[i]?.text.startsWith("-")) {
|
|
1348
|
+
const word = cmd.args[i];
|
|
1349
|
+
if (!word.literal || /^--exec-path/.test(word.text) || /^-c.*alias\./i.test(word.text))
|
|
1350
|
+
opaque = true;
|
|
1351
|
+
if (/^-c(?:remote|push)\./i.test(word.text))
|
|
1352
|
+
pushConfig = true;
|
|
1353
|
+
if (GIT_VALUED.has(word.text)) {
|
|
1354
|
+
const value = cmd.args[i + 1];
|
|
1355
|
+
if ((word.text === "-c" || word.text === "--config-env") &&
|
|
1356
|
+
/^(?:remote|push)\./i.test(value?.text ?? ""))
|
|
1357
|
+
pushConfig = true;
|
|
1358
|
+
// A configuration value can define an alias; a directory (`-C $W`) cannot change what runs.
|
|
1359
|
+
if ((word.text === "-c" || word.text === "--config-env") &&
|
|
1360
|
+
(!value?.literal || /alias\./i.test(value.text)))
|
|
1361
|
+
opaque = true;
|
|
1362
|
+
i += 2;
|
|
1363
|
+
}
|
|
1364
|
+
else
|
|
1365
|
+
i++;
|
|
1366
|
+
}
|
|
1367
|
+
const sub = cmd.args[i];
|
|
1368
|
+
// A literal word Git does not know may be an alias: judge what it expands to, in each
|
|
1369
|
+
// directory the command could run in (with `-C` applied, as Git reads it).
|
|
1370
|
+
if (!opaque && sub?.literal && !KNOWN_GIT.has(sub.text) && program.literal && depth < 4) {
|
|
1371
|
+
const dirs = [...context.cwds].map((dir) => {
|
|
1372
|
+
const at = args.slice(0, i).lastIndexOf("-C");
|
|
1373
|
+
return at >= 0 && args[at + 1] ? resolve(dir, args[at + 1]) : dir;
|
|
1374
|
+
});
|
|
1375
|
+
const rest = shellArgs(args.slice(i + 1));
|
|
1376
|
+
let resolved = false;
|
|
1377
|
+
for (const dir of dirs) {
|
|
1378
|
+
const alias = gitAlias(dir, sub.text);
|
|
1379
|
+
if (alias === undefined)
|
|
1380
|
+
continue;
|
|
1381
|
+
resolved = true;
|
|
1382
|
+
const script = alias.startsWith("!")
|
|
1383
|
+
? `cd ${shellArgs([aliasDirectory(dir)])} && ${alias.slice(1)} ${rest}`
|
|
1384
|
+
: `git -C ${shellArgs([dir])} ${alias} ${rest}`;
|
|
1385
|
+
const nested = { ...context, cwds: new Set([dir]), words: [], assigned: [] };
|
|
1386
|
+
analyzeScript(script, nested, rules, depth + 1);
|
|
1387
|
+
}
|
|
1388
|
+
if (resolved)
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
if (!sub?.literal || !KNOWN_GIT.has(sub.text))
|
|
1392
|
+
opaque = opaque || !!sub;
|
|
1393
|
+
if (opaque) {
|
|
1394
|
+
// A literal `git` with an unknown subcommand could be anything Git runs: any forcing or
|
|
1395
|
+
// deleting flag is enough. An unknown program needs the subcommand's name somewhere too.
|
|
1396
|
+
opaqueGitRules([...segment.flatMap(split), ...context.assigned], !program.literal, rules);
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
if (!sub)
|
|
1400
|
+
return;
|
|
1401
|
+
// A push whose options are only known at run time (`$ARGS`, `${F:- -f}`, `$(echo -f)`), or
|
|
1402
|
+
// that a `remote.*`/`push.*` setting configures, could be forced.
|
|
1403
|
+
if (sub.text === "push" && (pushConfig || cmd.args.slice(i + 1).some((word) => word.bare)))
|
|
1404
|
+
rules.add("force-push");
|
|
1405
|
+
gitRules(sub.text, args.slice(i + 1), rules);
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* The hard rules the command's text names, read as plain words after removing quotes and
|
|
1409
|
+
* backslashes. This catches commands the scanner reads as data but that still run: a script
|
|
1410
|
+
* piped into a shell, `bash <(...)`, `find -exec`, inline interpreter code, a shell alias. Linear
|
|
1411
|
+
* time: splitting only, no backtracking pattern.
|
|
1412
|
+
*/
|
|
1413
|
+
function textRules(script, cwd, rules) {
|
|
1414
|
+
const stripped = script.replace(/['"\\]/g, "");
|
|
1415
|
+
const cwds = new Set(cwd ? [cwd] : []);
|
|
1416
|
+
for (const segment of stripped.split(/[;&|\n()`<>]/)) {
|
|
1417
|
+
const tokens = segment.split(/[\s,]+/).filter(Boolean);
|
|
1418
|
+
tokens.forEach((token, k) => {
|
|
1419
|
+
const word = token.slice(token.lastIndexOf("=") + 1);
|
|
1420
|
+
if (word) {
|
|
1421
|
+
pathRules(word, rules, false);
|
|
1422
|
+
for (const path of resolutions(word, cwds))
|
|
1423
|
+
pathRules(path, rules, false);
|
|
1424
|
+
}
|
|
1425
|
+
if (word.split("/").pop() !== "git")
|
|
1426
|
+
return;
|
|
1427
|
+
let j = k + 1;
|
|
1428
|
+
while (tokens[j]?.startsWith("-"))
|
|
1429
|
+
j += GIT_VALUED.has(tokens[j]) ? 2 : 1;
|
|
1430
|
+
const sub = tokens[j];
|
|
1431
|
+
if (sub && KNOWN_GIT.has(sub))
|
|
1432
|
+
gitRules(sub, tokens.slice(j + 1), rules);
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
/** The hard rules a shell script falls under, judged in its working directory. */
|
|
1437
|
+
export function scriptRules(script, cwd, scratchRoots = []) {
|
|
1438
|
+
const rules = new Set();
|
|
1439
|
+
const context = {
|
|
1440
|
+
cwds: new Set(cwd ? [cwd] : []),
|
|
1441
|
+
unknownCwd: !cwd,
|
|
1442
|
+
words: [],
|
|
1443
|
+
assigned: [],
|
|
1444
|
+
scratchRoots,
|
|
1445
|
+
};
|
|
1446
|
+
analyzeScript(script, context, rules, 0);
|
|
1447
|
+
return rules;
|
|
1448
|
+
}
|
|
1449
|
+
/** The hard rules a request falls under, from what it touches. */
|
|
1450
|
+
function requestRules(request, rules, scratchRoots) {
|
|
1451
|
+
const input = request.input;
|
|
1452
|
+
const cwds = new Set(request.cwd ? [request.cwd] : []);
|
|
1453
|
+
const file = (path, write) => {
|
|
1454
|
+
for (const target of [path, ...resolutions(path, cwds)]) {
|
|
1455
|
+
if (write)
|
|
1456
|
+
pathRules(target, rules, false);
|
|
1457
|
+
if (write && policyStatePath(target))
|
|
1458
|
+
rules.add("policy-state");
|
|
1459
|
+
if (sensitive(slashes(target)))
|
|
1460
|
+
rules.add("credential-read");
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
if (WRITE_TOOLS.has(request.tool) || ["Read", "view", "read_file"].includes(request.tool)) {
|
|
1464
|
+
const path = input.file_path ?? input.path ?? input.notebook_path;
|
|
1465
|
+
if (typeof path === "string")
|
|
1466
|
+
file(path, WRITE_TOOLS.has(request.tool));
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
if (request.tool === "apply_patch") {
|
|
1470
|
+
const patch = input.command ?? input.patch ?? input.input;
|
|
1471
|
+
if (typeof patch !== "string")
|
|
1472
|
+
return;
|
|
1473
|
+
for (const line of patch.split("\n"))
|
|
1474
|
+
if (/^\*\*\* (?:Add File|Update File|Delete File|Move to): /.test(line))
|
|
1475
|
+
file(line.slice(line.indexOf(": ") + 2).trim(), true);
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
const script = input.command ?? input.cmd;
|
|
1479
|
+
if (SHELL_TOOLS.has(request.tool) && typeof script === "string") {
|
|
1480
|
+
for (const rule of scriptRules(script, request.cwd, scratchRoots))
|
|
1481
|
+
rules.add(rule);
|
|
1482
|
+
// The union with the plain-text reading, which catches code the scanner reads as data (a
|
|
1483
|
+
// script piped into a shell, inline interpreter code). Only when something runs text: in a
|
|
1484
|
+
// script that does not, quoted text and here-documents are data (a commit message, a PR body).
|
|
1485
|
+
if (scriptRunsText(script))
|
|
1486
|
+
textRules(script, request.cwd, rules);
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
/** Every hard rule a decision that needs a person falls under, built-in guards first. */
|
|
1490
|
+
export function hardRules(request, decision, scratchRoots = []) {
|
|
1491
|
+
// The engine and the session ask about the same request in turn: answer from a short memo.
|
|
1492
|
+
const key = JSON.stringify([
|
|
1493
|
+
request.tool,
|
|
1494
|
+
request.cwd,
|
|
1495
|
+
request.input,
|
|
1496
|
+
decision.reason,
|
|
1497
|
+
decision.category,
|
|
1498
|
+
decision.userOnly ?? false,
|
|
1499
|
+
scratchRoots,
|
|
1500
|
+
]);
|
|
1501
|
+
const now = Date.now();
|
|
1502
|
+
const hit = ruleMemo.get(key);
|
|
1503
|
+
if (hit && now - hit.at < 2000)
|
|
1504
|
+
return [...hit.rules];
|
|
1505
|
+
const rules = withEvidence(() => hardRulesOnce(request, decision, scratchRoots));
|
|
1506
|
+
if (ruleMemo.size >= 32)
|
|
1507
|
+
ruleMemo.delete(ruleMemo.keys().next().value);
|
|
1508
|
+
ruleMemo.set(key, { at: now, rules });
|
|
1509
|
+
return [...rules];
|
|
1510
|
+
}
|
|
1511
|
+
const ruleMemo = new Map();
|
|
1512
|
+
function hardRulesOnce(request, decision, scratchRoots) {
|
|
1513
|
+
const rules = new Set();
|
|
1514
|
+
if (decision.userOnly || decision.reason === APPROVE_GUARD)
|
|
1515
|
+
rules.add("self-approve");
|
|
1516
|
+
if (FOREIGN_RECORD_REASON.test(decision.reason))
|
|
1517
|
+
rules.add("foreign-classification-record");
|
|
1518
|
+
for (const [pattern, rule] of REASON_RULES)
|
|
1519
|
+
if (pattern.test(decision.reason))
|
|
1520
|
+
rules.add(rule);
|
|
1521
|
+
requestRules(request, rules, scratchRoots);
|
|
1522
|
+
if (decision.category === "sensitive" && !rules.size)
|
|
1523
|
+
rules.add("protected");
|
|
1524
|
+
return [...rules];
|
|
1525
|
+
}
|
|
1526
|
+
/** The first hard rule a decision that needs a person falls under, or undefined. */
|
|
1527
|
+
export function hardRule(request, decision, scratchRoots = []) {
|
|
1528
|
+
if (decision.decision !== "human")
|
|
1529
|
+
return undefined;
|
|
1530
|
+
return hardRules(request, decision, scratchRoots)[0];
|
|
1531
|
+
}
|
|
1532
|
+
/**
|
|
1533
|
+
* `az rest` and `az devops invoke` send a GET unless a method says otherwise: with no method, or
|
|
1534
|
+
* `GET`/`HEAD`, they read.
|
|
1535
|
+
*/
|
|
1536
|
+
function cloudGet(args) {
|
|
1537
|
+
const generic = (args[0] === "rest" ? 1 : 0) || (args[0] === "devops" && args[1] === "invoke" ? 2 : 0);
|
|
1538
|
+
if (!generic)
|
|
1539
|
+
return false;
|
|
1540
|
+
for (let i = 0; i < args.length; i++) {
|
|
1541
|
+
const arg = args[i];
|
|
1542
|
+
const named = /^(?:--method|-m|--http-method)$/.test(arg)
|
|
1543
|
+
? args[i + 1]
|
|
1544
|
+
: /^(?:--method|--http-method)=/.test(arg)
|
|
1545
|
+
? arg.slice(arg.indexOf("=") + 1)
|
|
1546
|
+
: undefined;
|
|
1547
|
+
if (named !== undefined && !/^(?:get|head)$/i.test(named))
|
|
1548
|
+
return false;
|
|
1549
|
+
}
|
|
1550
|
+
return true;
|
|
1551
|
+
}
|
|
1552
|
+
const LOOPBACK = /^(?:localhost|127(?:\.\d+){3}|\[?::1\]?|0\.0\.0\.0)(?::\d+)?$/i;
|
|
1553
|
+
/**
|
|
1554
|
+
* Whether the request goes only to an explicit loopback host: at least one target names
|
|
1555
|
+
* `localhost`, `127.x.x.x` or `::1`, and nothing else looks like a target. A bare host, a
|
|
1556
|
+
* variable, or no recognizable URL at all is not loopback, so a write to it is a floor item.
|
|
1557
|
+
* Neither is a request that reads more targets from a file (curl `-K`/`--config`, wget
|
|
1558
|
+
* `-i`/`--input-file`, `-e`/`--execute`, `--config`).
|
|
1559
|
+
*/
|
|
1560
|
+
function loopbackOnly(name, args) {
|
|
1561
|
+
const fromFile = name === "curl"
|
|
1562
|
+
? /^--config(?:=|$)|^-[a-zA-Z]*K/
|
|
1563
|
+
: name === "wget"
|
|
1564
|
+
? /^--(?:input-file|execute|config)(?:=|$)|^-[a-zA-Z]*[ie]/
|
|
1565
|
+
: undefined;
|
|
1566
|
+
if (fromFile && args.some((arg) => fromFile.test(arg)))
|
|
1567
|
+
return false;
|
|
1568
|
+
const targets = args.filter((arg) => !arg.startsWith("-") && /^(?:https?:\/\/)?[\w.[\]:-]+(?::\d+)?(?:[/?#]|$)/i.test(arg));
|
|
1569
|
+
const hosts = targets.map((arg) => /^(?:https?:\/\/)?([^/?#\s]+)/i.exec(arg)?.[1]?.replace(/^[^@]*@/, "") ?? "");
|
|
1570
|
+
const loopback = hosts.filter((host) => LOOPBACK.test(host));
|
|
1571
|
+
const urls = args.filter((arg) => /^[a-z][\w+.-]*:\/\//i.test(arg) || /\$/.test(arg));
|
|
1572
|
+
return (loopback.length > 0 &&
|
|
1573
|
+
urls.every((url) => LOOPBACK.test(/^[a-z][\w+.-]*:\/\/([^/?#\s]+)/i.exec(url)?.[1]?.replace(/^[^@]*@/, "") ?? "")));
|
|
1574
|
+
}
|
|
1575
|
+
/**
|
|
1576
|
+
* An HTTP client sending anything but GET or HEAD to a host that is not loopback: curl (`-X`,
|
|
1577
|
+
* `--request`, data or form options imply POST, `-T` a PUT, `-G` forces GET), wget (`--method`,
|
|
1578
|
+
* `--post-*`, `--body-*`), httpie (`http`/`https` with a write method or data items), and
|
|
1579
|
+
* PowerShell's `Invoke-RestMethod`/`Invoke-WebRequest` (`-Method`, `-Body`).
|
|
1580
|
+
*/
|
|
1581
|
+
function httpWrite(name, args) {
|
|
1582
|
+
const lower = name.toLowerCase();
|
|
1583
|
+
let method;
|
|
1584
|
+
let body = false;
|
|
1585
|
+
if (name === "curl") {
|
|
1586
|
+
for (let i = 0; i < args.length; i++) {
|
|
1587
|
+
const arg = args[i];
|
|
1588
|
+
if (arg === "-X" || arg === "--request")
|
|
1589
|
+
method = args[++i];
|
|
1590
|
+
else if (/^-X./.test(arg))
|
|
1591
|
+
method = arg.slice(2);
|
|
1592
|
+
else if (arg.startsWith("--request="))
|
|
1593
|
+
method = arg.slice(10);
|
|
1594
|
+
else if (/^(?:-d|-F|--data|--data-\w+|--json|--form|--form-string)(?:=|$)/.test(arg) ||
|
|
1595
|
+
/^-[dF]./.test(arg))
|
|
1596
|
+
body = true;
|
|
1597
|
+
else if (arg === "-T" || arg.startsWith("--upload-file"))
|
|
1598
|
+
method = method ?? "PUT";
|
|
1599
|
+
else if (arg === "-G" || arg === "--get")
|
|
1600
|
+
method = "GET";
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
else if (name === "wget") {
|
|
1604
|
+
for (let i = 0; i < args.length; i++) {
|
|
1605
|
+
const arg = args[i];
|
|
1606
|
+
if (arg === "--method")
|
|
1607
|
+
method = args[++i];
|
|
1608
|
+
else if (arg.startsWith("--method="))
|
|
1609
|
+
method = arg.slice(9);
|
|
1610
|
+
else if (/^--(?:post|body)-(?:data|file)/.test(arg))
|
|
1611
|
+
body = true;
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
else if (name === "http" || name === "https" || name === "xh") {
|
|
1615
|
+
const positional = args.filter((arg) => !arg.startsWith("-"));
|
|
1616
|
+
if (/^[A-Z]+$/.test(positional[0] ?? ""))
|
|
1617
|
+
method = positional[0];
|
|
1618
|
+
else if (positional
|
|
1619
|
+
.slice(1)
|
|
1620
|
+
.some((item) => /^[^=:@]+(?::=|==?|@)/.test(item) && !/^[^=]+==/.test(item)))
|
|
1621
|
+
body = true;
|
|
1622
|
+
}
|
|
1623
|
+
else if (["invoke-restmethod", "invoke-webrequest", "irm", "iwr"].includes(lower)) {
|
|
1624
|
+
for (let i = 0; i < args.length; i++) {
|
|
1625
|
+
const arg = args[i].toLowerCase();
|
|
1626
|
+
if (arg === "-method")
|
|
1627
|
+
method = args[++i];
|
|
1628
|
+
else if (arg === "-body" || arg === "-infile")
|
|
1629
|
+
body = true;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
else
|
|
1633
|
+
return false;
|
|
1634
|
+
const effective = (method ?? (body ? "POST" : "GET")).toUpperCase();
|
|
1635
|
+
return !["GET", "HEAD", "OPTIONS"].includes(effective) && !loopbackOnly(name, args);
|
|
1636
|
+
}
|
|
1637
|
+
//# sourceMappingURL=hard.js.map
|