@agent-corpus/policy-manager 0.8.0 → 0.10.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 +56 -3
- package/dist/adapters.d.ts +9 -0
- package/dist/adapters.js +49 -15
- package/dist/cli.js +63 -18
- package/dist/flow.js +61 -9
- package/dist/grants.js +42 -8
- package/dist/helpers.d.ts +59 -0
- package/dist/helpers.js +304 -0
- package/dist/permissive.d.ts +6 -0
- package/dist/permissive.js +216 -1
- package/dist/policy.js +10 -0
- package/dist/profile.d.ts +13 -0
- package/dist/profile.js +36 -0
- package/dist/review.d.ts +9 -0
- package/dist/review.js +16 -0
- package/dist/service.d.ts +14 -1
- package/dist/service.js +55 -4
- package/dist/session.d.ts +7 -0
- package/dist/session.js +34 -6
- package/dist/setup.d.ts +7 -0
- package/dist/setup.js +33 -5
- package/dist/shell.d.ts +2 -0
- package/dist/shell.js +1 -1
- package/dist/shim.d.ts +24 -0
- package/dist/shim.js +114 -0
- package/dist/tools.d.ts +23 -0
- package/dist/tools.js +66 -0
- package/dist/types.d.ts +6 -0
- package/package.json +1 -1
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether the working file is the committed blob: the same bytes, or, when the blob has no CR,
|
|
3
|
+
* the same bytes once the working file's CRLF line ends become LF (a `core.autocrlf` checkout).
|
|
4
|
+
* No clean filter or `.gitattributes` setting is applied.
|
|
5
|
+
*/
|
|
6
|
+
export declare function sameContent(working: Buffer, blob: Buffer): boolean;
|
|
7
|
+
/**
|
|
8
|
+
* A script allowed to read a credential for one narrow job, such as posting a review as a GitHub
|
|
9
|
+
* App. It is trusted only as committed on the default branch and only with the argument shapes
|
|
10
|
+
* listed for it; anything else stays with a person.
|
|
11
|
+
*/
|
|
12
|
+
export interface CredentialHelper {
|
|
13
|
+
/** Repository-relative path with `/` separators, such as `tools/review-bot.mjs`. */
|
|
14
|
+
path: string;
|
|
15
|
+
/**
|
|
16
|
+
* Accepted argument lists after the script. Each token is a literal, a list of literal
|
|
17
|
+
* alternatives, or a string with placeholders (`repos/<repo>/pulls/<int>/reviews`).
|
|
18
|
+
*/
|
|
19
|
+
args: Array<Array<string | string[]>>;
|
|
20
|
+
/**
|
|
21
|
+
* Where the helper's checkout must come from: normalized `host/owner/` prefixes (or a whole
|
|
22
|
+
* `host/owner/repo`) that `remote.origin.url` must match, such as `github.com/example-org/`.
|
|
23
|
+
*/
|
|
24
|
+
remotes: string[];
|
|
25
|
+
}
|
|
26
|
+
export declare class HelperError extends Error {
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* `host/path` for an https, ssh or scp-style (`git@host:path`) URL, with the host and path in
|
|
30
|
+
* lower case and any `.git` and trailing `/` removed. Anything else (a local path, `file:`) is
|
|
31
|
+
* undefined: its content does not come from a hosted remote.
|
|
32
|
+
*/
|
|
33
|
+
export declare function normalizeRemote(url: string): string | undefined;
|
|
34
|
+
export declare const MAX_HELPERS = 20;
|
|
35
|
+
/** Index of the first shape `args` matches, with the `<file>` values it named. */
|
|
36
|
+
export declare function matchShape(helper: CredentialHelper, args: string[]): {
|
|
37
|
+
index: number;
|
|
38
|
+
files: string[];
|
|
39
|
+
} | undefined;
|
|
40
|
+
/** Validates the profile's `credentialHelpers`. */
|
|
41
|
+
export declare function parseCredentialHelpers(raw: unknown): CredentialHelper[];
|
|
42
|
+
export type HelperMatch = {
|
|
43
|
+
kind: "none";
|
|
44
|
+
} | {
|
|
45
|
+
kind: "match";
|
|
46
|
+
helper: CredentialHelper;
|
|
47
|
+
shape: number;
|
|
48
|
+
files: string[];
|
|
49
|
+
} | {
|
|
50
|
+
kind: "refused";
|
|
51
|
+
reason: string;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Whether `node <script> args...` runs a listed helper. `none`: the script is not a listed helper.
|
|
55
|
+
* `refused`: it is at a listed helper's path but is changed, untracked, linked or run with other
|
|
56
|
+
* arguments, so a person decides. `match`: the committed helper with an accepted shape.
|
|
57
|
+
*/
|
|
58
|
+
export declare function helperMatch(helpers: CredentialHelper[], cwd: string, argv: string[]): HelperMatch;
|
|
59
|
+
//# sourceMappingURL=helpers.d.ts.map
|
package/dist/helpers.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { lstatSync, readFileSync, realpathSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { git } from "./evidence.js";
|
|
5
|
+
/** Git with replace refs ignored, so `refs/replace/*` cannot change what is read. */
|
|
6
|
+
const exact = (top, args) => git(top, ["--no-replace-objects", ...args]);
|
|
7
|
+
/** The raw bytes of a blob, with replace refs ignored and no filters applied. */
|
|
8
|
+
function blobBytes(top, oid) {
|
|
9
|
+
return execFileSync("git", ["-c", "core.fsmonitor=false", "-C", top, "--no-replace-objects", "cat-file", "blob", oid], {
|
|
10
|
+
timeout: 3000,
|
|
11
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
12
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
13
|
+
env: Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Whether the working file is the committed blob: the same bytes, or, when the blob has no CR,
|
|
18
|
+
* the same bytes once the working file's CRLF line ends become LF (a `core.autocrlf` checkout).
|
|
19
|
+
* No clean filter or `.gitattributes` setting is applied.
|
|
20
|
+
*/
|
|
21
|
+
export function sameContent(working, blob) {
|
|
22
|
+
if (working.equals(blob))
|
|
23
|
+
return true;
|
|
24
|
+
if (blob.includes(0x0d))
|
|
25
|
+
return false;
|
|
26
|
+
return Buffer.from(working.toString("latin1").replace(/\r\n/g, "\n"), "latin1").equals(blob);
|
|
27
|
+
}
|
|
28
|
+
export class HelperError extends Error {
|
|
29
|
+
}
|
|
30
|
+
/** A remote prefix: a lowercase host, then at least an owner; a trailing `/` makes it a prefix. */
|
|
31
|
+
const REMOTE_PREFIX = /^[a-z0-9][a-z0-9.-]*(?::[0-9]{1,5})?(?:\/[a-z0-9][a-z0-9_.-]*)+\/?$/;
|
|
32
|
+
/**
|
|
33
|
+
* `host/path` for an https, ssh or scp-style (`git@host:path`) URL, with the host and path in
|
|
34
|
+
* lower case and any `.git` and trailing `/` removed. Anything else (a local path, `file:`) is
|
|
35
|
+
* undefined: its content does not come from a hosted remote.
|
|
36
|
+
*/
|
|
37
|
+
export function normalizeRemote(url) {
|
|
38
|
+
let host;
|
|
39
|
+
let path;
|
|
40
|
+
const full = /^(?:https|ssh|git\+ssh):\/\/(?:[^@/\s]+@)?([^/:\s]+)(?::[0-9]{1,5})?\/(.+)$/i.exec(url);
|
|
41
|
+
const scp = /^(?:[^@/\s:]+@)?([^/:\s]+):(?!\/)(.+)$/.exec(url);
|
|
42
|
+
if (full?.[1] && full[2])
|
|
43
|
+
[host, path] = [full[1], full[2]];
|
|
44
|
+
else if (scp?.[1] && scp[2] && !/^[A-Za-z]$/.test(scp[1]))
|
|
45
|
+
[host, path] = [scp[1], scp[2]];
|
|
46
|
+
else
|
|
47
|
+
return undefined;
|
|
48
|
+
path = path
|
|
49
|
+
.replace(/\/+$/, "")
|
|
50
|
+
.replace(/\.git$/i, "")
|
|
51
|
+
.replace(/\/+$/, "");
|
|
52
|
+
const segments = path.split("/");
|
|
53
|
+
if (!segments.length || segments.some((s) => !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(s)))
|
|
54
|
+
return undefined;
|
|
55
|
+
return `${host}/${path}`.toLowerCase();
|
|
56
|
+
}
|
|
57
|
+
function remoteMatches(remotes, normalized) {
|
|
58
|
+
return remotes.some((prefix) => prefix.endsWith("/") ? normalized.startsWith(prefix) : normalized === prefix);
|
|
59
|
+
}
|
|
60
|
+
export const MAX_HELPERS = 20;
|
|
61
|
+
const MAX_SHAPES = 50;
|
|
62
|
+
const MAX_TOKENS = 40;
|
|
63
|
+
const MAX_WORD = 1024;
|
|
64
|
+
/** Placeholder values. Each is checked whole; none may contain whitespace. */
|
|
65
|
+
const PLACEHOLDERS = {
|
|
66
|
+
// Each segment starts with a letter or digit, so neither is `.` or `..`.
|
|
67
|
+
repo: (v) => /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(v),
|
|
68
|
+
int: (v) => /^[0-9]{1,12}$/.test(v),
|
|
69
|
+
sha: (v) => /^[0-9a-f]{7,40}$/.test(v),
|
|
70
|
+
word: (v) => /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(v),
|
|
71
|
+
url: (v) => /^https:\/\/github\.com\/[A-Za-z0-9_./#-]{1,300}$/.test(v),
|
|
72
|
+
// No pattern characters, no tilde the shell expands, and no device file such as /dev/stdin. The caller also checks
|
|
73
|
+
// where the file is and that it may be read.
|
|
74
|
+
file: (v) => v.length > 0 &&
|
|
75
|
+
!/[*?[\]{}]/.test(v) &&
|
|
76
|
+
// `~` only right after a letter or digit (a Windows short name such as RUNNER~1).
|
|
77
|
+
!/(?:^|[^A-Za-z0-9])~/.test(v) &&
|
|
78
|
+
!/^\/dev\//.test(v),
|
|
79
|
+
// Any one argument; the caller refuses one the shell would expand.
|
|
80
|
+
text: () => true,
|
|
81
|
+
};
|
|
82
|
+
function parts(token) {
|
|
83
|
+
const out = [];
|
|
84
|
+
let rest = token;
|
|
85
|
+
while (rest.length) {
|
|
86
|
+
const open = rest.indexOf("<");
|
|
87
|
+
const close = open < 0 ? -1 : rest.indexOf(">", open);
|
|
88
|
+
const name = close < 0 ? undefined : rest.slice(open + 1, close);
|
|
89
|
+
if (open < 0 || name === undefined || !(name in PLACEHOLDERS)) {
|
|
90
|
+
if (open >= 0 && close >= 0)
|
|
91
|
+
throw new HelperError(`unknown placeholder in ${token}`);
|
|
92
|
+
out.push({ literal: rest });
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
if (open > 0)
|
|
96
|
+
out.push({ literal: rest.slice(0, open) });
|
|
97
|
+
out.push({ placeholder: name });
|
|
98
|
+
rest = rest.slice(close + 1);
|
|
99
|
+
}
|
|
100
|
+
if (out.some((part, i) => i > 0 && "placeholder" in part && "placeholder" in (out[i - 1] ?? {})))
|
|
101
|
+
throw new HelperError(`adjacent placeholders in ${token}`);
|
|
102
|
+
if (out.some((p) => "placeholder" in p && p.placeholder === "text") && out.length > 1)
|
|
103
|
+
throw new HelperError(`<text> must be a whole argument in ${token}`);
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
/** Matches `word` against a token's parts; `files` collects the values of `<file>` placeholders. */
|
|
107
|
+
function matchParts(list, word, files) {
|
|
108
|
+
const [head, ...rest] = list;
|
|
109
|
+
if (!head)
|
|
110
|
+
return word.length === 0;
|
|
111
|
+
if ("literal" in head)
|
|
112
|
+
return (word.startsWith(head.literal) && matchParts(rest, word.slice(head.literal.length), files));
|
|
113
|
+
const check = PLACEHOLDERS[head.placeholder];
|
|
114
|
+
if (!check)
|
|
115
|
+
return false;
|
|
116
|
+
const next = rest[0];
|
|
117
|
+
// A placeholder ends at the end of the word or right before the next literal.
|
|
118
|
+
for (let end = word.length; end >= 1; end--) {
|
|
119
|
+
if (next && "literal" in next && !word.startsWith(next.literal, end))
|
|
120
|
+
continue;
|
|
121
|
+
if (!next && end !== word.length)
|
|
122
|
+
continue;
|
|
123
|
+
const value = word.slice(0, end);
|
|
124
|
+
if (!check(value))
|
|
125
|
+
continue;
|
|
126
|
+
const found = [];
|
|
127
|
+
if (matchParts(rest, word.slice(end), found)) {
|
|
128
|
+
if (head.placeholder === "file")
|
|
129
|
+
files.push(value);
|
|
130
|
+
files.push(...found);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
function matchToken(token, word, files) {
|
|
137
|
+
if (Array.isArray(token))
|
|
138
|
+
return token.includes(word);
|
|
139
|
+
return matchParts(parts(token), word, files);
|
|
140
|
+
}
|
|
141
|
+
/** Index of the first shape `args` matches, with the `<file>` values it named. */
|
|
142
|
+
export function matchShape(helper, args) {
|
|
143
|
+
if (args.some((word) => word.length > MAX_WORD))
|
|
144
|
+
return undefined;
|
|
145
|
+
for (const [index, shape] of helper.args.entries()) {
|
|
146
|
+
if (shape.length !== args.length)
|
|
147
|
+
continue;
|
|
148
|
+
const files = [];
|
|
149
|
+
if (shape.every((token, i) => matchToken(token, args[i] ?? "", files)))
|
|
150
|
+
return { index, files };
|
|
151
|
+
}
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
/** Validates the profile's `credentialHelpers`. */
|
|
155
|
+
export function parseCredentialHelpers(raw) {
|
|
156
|
+
if (raw === undefined)
|
|
157
|
+
return [];
|
|
158
|
+
if (!Array.isArray(raw) || raw.length > MAX_HELPERS)
|
|
159
|
+
throw new HelperError(`credentialHelpers must list at most ${MAX_HELPERS} helpers`);
|
|
160
|
+
return raw.map((entry) => {
|
|
161
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
162
|
+
throw new HelperError("each credential helper must be an object");
|
|
163
|
+
const { path, args, remotes, ...extra } = entry;
|
|
164
|
+
if (!Array.isArray(remotes) ||
|
|
165
|
+
remotes.length === 0 ||
|
|
166
|
+
remotes.length > 20 ||
|
|
167
|
+
remotes.some((r) => typeof r !== "string" || r.length > 200 || !REMOTE_PREFIX.test(r)))
|
|
168
|
+
throw new HelperError("each credential helper needs remotes: lowercase host/owner/ prefixes such as github.com/org/");
|
|
169
|
+
if (Object.keys(extra).length)
|
|
170
|
+
throw new HelperError(`unknown credential helper key: ${Object.keys(extra)[0]}`);
|
|
171
|
+
if (typeof path !== "string" ||
|
|
172
|
+
path.length > 300 ||
|
|
173
|
+
!/^[A-Za-z0-9_.@-]+(?:\/[A-Za-z0-9_.@-]+)*$/.test(path) ||
|
|
174
|
+
path.split("/").some((part) => part === "." || part === ".."))
|
|
175
|
+
throw new HelperError("a credential helper path must be repository-relative, with / separators");
|
|
176
|
+
if (!Array.isArray(args) || args.length === 0 || args.length > MAX_SHAPES)
|
|
177
|
+
throw new HelperError(`credential helper ${path} must list 1 to ${MAX_SHAPES} argument shapes`);
|
|
178
|
+
for (const shape of args) {
|
|
179
|
+
if (!Array.isArray(shape) || shape.length === 0 || shape.length > MAX_TOKENS)
|
|
180
|
+
throw new HelperError(`each argument shape of ${path} must list 1 to ${MAX_TOKENS} tokens`);
|
|
181
|
+
for (const token of shape) {
|
|
182
|
+
if (Array.isArray(token)) {
|
|
183
|
+
if (token.length === 0 ||
|
|
184
|
+
token.some((t) => typeof t !== "string" || t.length === 0 || t.length > 200))
|
|
185
|
+
throw new HelperError(`alternatives in ${path} must be non-empty strings`);
|
|
186
|
+
}
|
|
187
|
+
else if (typeof token !== "string" || token.length === 0 || token.length > 300)
|
|
188
|
+
throw new HelperError(`a token in ${path} must be a non-empty string`);
|
|
189
|
+
else
|
|
190
|
+
parts(token);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return { path, args: args, remotes: remotes };
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The default branch on `origin`, by full ref name only, so a tag or branch called `origin/HEAD`
|
|
198
|
+
* cannot stand in for it: `refs/remotes/origin/HEAD` when it points into `refs/remotes/origin/`,
|
|
199
|
+
* else `refs/remotes/origin/main`.
|
|
200
|
+
*/
|
|
201
|
+
function defaultRef(top) {
|
|
202
|
+
const candidates = [];
|
|
203
|
+
try {
|
|
204
|
+
const target = exact(top, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
|
|
205
|
+
if (/^refs\/remotes\/origin\/[^\s]+$/.test(target) && target !== "refs/remotes/origin/HEAD")
|
|
206
|
+
candidates.push(target);
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
/* no origin/HEAD */
|
|
210
|
+
}
|
|
211
|
+
candidates.push("refs/remotes/origin/main");
|
|
212
|
+
for (const ref of candidates)
|
|
213
|
+
try {
|
|
214
|
+
// `show-ref --verify` takes only a full name and never falls back to a shorter match.
|
|
215
|
+
exact(top, ["show-ref", "--verify", "--quiet", ref]);
|
|
216
|
+
return ref;
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
/* try the next */
|
|
220
|
+
}
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Whether `node <script> args...` runs a listed helper. `none`: the script is not a listed helper.
|
|
225
|
+
* `refused`: it is at a listed helper's path but is changed, untracked, linked or run with other
|
|
226
|
+
* arguments, so a person decides. `match`: the committed helper with an accepted shape.
|
|
227
|
+
*/
|
|
228
|
+
export function helperMatch(helpers, cwd, argv) {
|
|
229
|
+
const program = basename(argv[0] ?? "").toLowerCase();
|
|
230
|
+
const script = argv[1];
|
|
231
|
+
if (!helpers.length || (program !== "node" && program !== "node.exe") || script === undefined)
|
|
232
|
+
return { kind: "none" };
|
|
233
|
+
// Matched by file name first, then by where it really is, so any way of naming it is checked.
|
|
234
|
+
const named = helpers.filter((h) => basename(script) === basename(h.path));
|
|
235
|
+
if (!named.length)
|
|
236
|
+
return { kind: "none" };
|
|
237
|
+
const refused = (reason) => ({ kind: "refused", reason });
|
|
238
|
+
let real;
|
|
239
|
+
let top;
|
|
240
|
+
try {
|
|
241
|
+
const lexical = resolve(cwd, script);
|
|
242
|
+
if (lstatSync(lexical).isSymbolicLink())
|
|
243
|
+
return refused("Credential helper is a symlink");
|
|
244
|
+
real = realpathSync.native(lexical);
|
|
245
|
+
if (!lstatSync(real).isFile())
|
|
246
|
+
return refused("Credential helper is not a regular file");
|
|
247
|
+
top = realpathSync.native(git(dirname(real), ["rev-parse", "--show-toplevel"]));
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return refused("Credential helper is not inside a Git checkout");
|
|
251
|
+
}
|
|
252
|
+
const helper = named.find((h) => join(top, ...h.path.split("/")) === real);
|
|
253
|
+
if (!helper)
|
|
254
|
+
return refused("Credential helper is not at its listed path in the checkout");
|
|
255
|
+
try {
|
|
256
|
+
git(top, ["ls-files", "--error-unmatch", "--", helper.path]);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return refused("Credential helper is not tracked");
|
|
260
|
+
}
|
|
261
|
+
// A clone or `git init` anywhere has its own origin; only a checkout whose origin is a listed
|
|
262
|
+
// hosted remote, read as configured and as git resolves it, can vouch for the helper.
|
|
263
|
+
let origin;
|
|
264
|
+
try {
|
|
265
|
+
const configured = git(top, ["config", "--get", "remote.origin.url"]);
|
|
266
|
+
const resolved = git(top, ["remote", "get-url", "origin"]);
|
|
267
|
+
let pushUrl = "";
|
|
268
|
+
try {
|
|
269
|
+
pushUrl = git(top, ["config", "--get", "remote.origin.pushurl"]);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
/* no push URL */
|
|
273
|
+
}
|
|
274
|
+
if (configured === resolved && !pushUrl)
|
|
275
|
+
origin = normalizeRemote(configured);
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
origin = undefined;
|
|
279
|
+
}
|
|
280
|
+
if (!origin || !remoteMatches(helper.remotes, origin))
|
|
281
|
+
return refused("Credential helper's checkout does not come from a listed remote");
|
|
282
|
+
const ref = defaultRef(top);
|
|
283
|
+
if (!ref)
|
|
284
|
+
return refused("Credential helper's default branch is unknown");
|
|
285
|
+
let committed;
|
|
286
|
+
let current;
|
|
287
|
+
try {
|
|
288
|
+
const oid = exact(top, ["rev-parse", "--verify", "--quiet", `${ref}:${helper.path}`]);
|
|
289
|
+
if (!/^[0-9a-f]{40,64}$/.test(oid))
|
|
290
|
+
throw new Error("not a blob id");
|
|
291
|
+
committed = blobBytes(top, oid);
|
|
292
|
+
current = readFileSync(real);
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
return refused("Credential helper is not on the default branch");
|
|
296
|
+
}
|
|
297
|
+
if (!sameContent(current, committed))
|
|
298
|
+
return refused("Credential helper differs from the default branch");
|
|
299
|
+
const shape = matchShape(helper, argv.slice(2));
|
|
300
|
+
if (!shape)
|
|
301
|
+
return refused("Credential helper run with arguments outside its allowed shapes");
|
|
302
|
+
return { kind: "match", helper, shape: shape.index, files: shape.files };
|
|
303
|
+
}
|
|
304
|
+
//# sourceMappingURL=helpers.js.map
|
package/dist/permissive.d.ts
CHANGED
|
@@ -3,6 +3,12 @@ import { commandDecision } from "./flow.js";
|
|
|
3
3
|
import type { Profile } from "./profile.js";
|
|
4
4
|
import { type Redirect, type SimpleCommand } from "./shell.js";
|
|
5
5
|
import type { Decision, Request } from "./types.js";
|
|
6
|
+
/**
|
|
7
|
+
* The files `sort` writes: its `-o`/`--output` file and its `-T`/`--temporary-directory`. Options
|
|
8
|
+
* are parsed as GNU getopt does (clustered short options, exact or unique long prefixes).
|
|
9
|
+
* Undefined when it may run another program (`--compress-program`) or an option is unknown.
|
|
10
|
+
*/
|
|
11
|
+
export declare function sortWrites(args: string[]): string[] | undefined;
|
|
6
12
|
export declare const BANNED_ENV: RegExp;
|
|
7
13
|
export declare function human(request: Request, category: Decision["category"], reason: string): Decision;
|
|
8
14
|
export declare function permissiveRead(cwd: string, input: string): {
|
package/dist/permissive.js
CHANGED
|
@@ -2,6 +2,7 @@ import { lstatSync, readdirSync, statSync } from "node:fs";
|
|
|
2
2
|
import { basename, delimiter, dirname, join, resolve } from "node:path";
|
|
3
3
|
import { branchEvidence, canonical, disposable, git, inside, isProtectedPath, OUTSIDE_REPOSITORY, pathEvidence, policyState, protectedPath, resolveWord, sensitive, tempRoots, tempWrite, } from "./evidence.js";
|
|
4
4
|
import { commandDecision } from "./flow.js";
|
|
5
|
+
import { helperMatch } from "./helpers.js";
|
|
5
6
|
import { mergedEvidence, remoteTipMatches } from "./merged.js";
|
|
6
7
|
import { evaluateArgv, result } from "./policy.js";
|
|
7
8
|
import { deletesProtected, deletionScriptCwd, gitRmRecoverable, resetRecoverable, restoreRecoverable, rmRecoverable, soleEffect, worktreeDeletion, } from "./recoverable.js";
|
|
@@ -51,6 +52,65 @@ const WRITERS = new Set([
|
|
|
51
52
|
"chown",
|
|
52
53
|
]);
|
|
53
54
|
const WRAPPERS = new Set(["env", "nohup", "time", "command", "nice", "timeout", "xargs"]);
|
|
55
|
+
const SORT_LONG = [
|
|
56
|
+
...["ignore-leading-blanks", "dictionary-order", "ignore-case", "general-numeric-sort"],
|
|
57
|
+
...["ignore-nonprinting", "month-sort", "human-numeric-sort", "numeric-sort", "random-sort"],
|
|
58
|
+
...["random-source", "reverse", "sort", "version-sort", "batch-size", "check", "debug"],
|
|
59
|
+
...["compress-program", "files0-from", "key", "merge", "output", "stable", "buffer-size"],
|
|
60
|
+
...["field-separator", "temporary-directory", "parallel", "unique", "zero-terminated"],
|
|
61
|
+
...["help", "version"],
|
|
62
|
+
];
|
|
63
|
+
const SORT_LONG_VALUE = new Set([
|
|
64
|
+
...["random-source", "sort", "batch-size", "compress-program", "files0-from", "key"],
|
|
65
|
+
...["output", "buffer-size", "field-separator", "temporary-directory", "parallel"],
|
|
66
|
+
]);
|
|
67
|
+
/**
|
|
68
|
+
* The files `sort` writes: its `-o`/`--output` file and its `-T`/`--temporary-directory`. Options
|
|
69
|
+
* are parsed as GNU getopt does (clustered short options, exact or unique long prefixes).
|
|
70
|
+
* Undefined when it may run another program (`--compress-program`) or an option is unknown.
|
|
71
|
+
*/
|
|
72
|
+
export function sortWrites(args) {
|
|
73
|
+
const writes = [];
|
|
74
|
+
for (let i = 0; i < args.length; i++) {
|
|
75
|
+
const arg = args[i] ?? "";
|
|
76
|
+
if (arg === "--")
|
|
77
|
+
break;
|
|
78
|
+
if (arg.startsWith("--")) {
|
|
79
|
+
const [given = "", inline] = arg.slice(2).split(/=(.*)/s, 2);
|
|
80
|
+
const exact = SORT_LONG.includes(given)
|
|
81
|
+
? [given]
|
|
82
|
+
: SORT_LONG.filter((n) => n.startsWith(given));
|
|
83
|
+
if (exact.length !== 1)
|
|
84
|
+
return undefined;
|
|
85
|
+
const name = exact[0] ?? "";
|
|
86
|
+
if (!SORT_LONG_VALUE.has(name))
|
|
87
|
+
continue;
|
|
88
|
+
const value = inline ?? args[++i];
|
|
89
|
+
if (value === undefined)
|
|
90
|
+
return undefined;
|
|
91
|
+
if (name === "compress-program")
|
|
92
|
+
return undefined;
|
|
93
|
+
if (name === "output" || name === "temporary-directory")
|
|
94
|
+
writes.push(value);
|
|
95
|
+
}
|
|
96
|
+
else if (arg.startsWith("-") && arg.length > 1) {
|
|
97
|
+
for (let j = 1; j < arg.length; j++) {
|
|
98
|
+
const flag = arg[j] ?? "";
|
|
99
|
+
if ("ktSTo".includes(flag)) {
|
|
100
|
+
const value = arg.slice(j + 1) || args[++i];
|
|
101
|
+
if (value === undefined)
|
|
102
|
+
return undefined;
|
|
103
|
+
if (flag === "o" || flag === "T")
|
|
104
|
+
writes.push(value);
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
if (!"bdfgiMhnRrVcCmsuz".includes(flag))
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return writes;
|
|
113
|
+
}
|
|
54
114
|
/**
|
|
55
115
|
* Programs whose behaviour cannot be changed by an unknown argument: they only print or compare
|
|
56
116
|
* strings. The output of a command substitution may be an argument of these and of nothing else,
|
|
@@ -808,6 +868,14 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
|
|
|
808
868
|
const ok = (reason = "Permissive profile: Git operation has no destructive effect") => result(request, "impactful-write", reason, true);
|
|
809
869
|
if (!sub)
|
|
810
870
|
return ok();
|
|
871
|
+
const refWrite = remoteRefWrite(cwd, sub, rest);
|
|
872
|
+
if (refWrite)
|
|
873
|
+
return human(request, "sensitive", refWrite);
|
|
874
|
+
if ((sub === "clone" || sub === "init") &&
|
|
875
|
+
rest.some((word) => CLONE_CONFIG.some((option) => word === option || abbreviates(word, option)) ||
|
|
876
|
+
/^-c./.test(word) ||
|
|
877
|
+
(sub === "clone" && /^-[A-Za-z]*[cou]/.test(word) && !word.startsWith("--"))))
|
|
878
|
+
return human(request, "sensitive", `git ${sub} with a configuration, origin, template or separate git directory requires human approval`);
|
|
811
879
|
if (sub === "push")
|
|
812
880
|
return gitPush(request, cwd, rest);
|
|
813
881
|
if (sub === "branch" && (has("-d", "-D", "--delete") || cluster("d") || cluster("D"))) {
|
|
@@ -875,10 +943,119 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
|
|
|
875
943
|
!safeConfigWrite(rest))
|
|
876
944
|
return human(request, "sensitive", "Git configuration can install hooks or credential helpers");
|
|
877
945
|
if (sub === "remote" &&
|
|
878
|
-
["set-url", "remove", "rm", "rename", "set-head"].includes(positional[0] ?? ""))
|
|
946
|
+
["add", "set-url", "remove", "rm", "rename", "set-head", "set-branches"].includes(positional[0] ?? ""))
|
|
879
947
|
return human(request, "impactful-write", "Changing remotes requires human approval");
|
|
880
948
|
return ok();
|
|
881
949
|
}
|
|
950
|
+
/**
|
|
951
|
+
* `git clone`/`init` options that set the new repository's configuration or origin, or run a
|
|
952
|
+
* program: a credential helper trusts a checkout by its configured origin.
|
|
953
|
+
*/
|
|
954
|
+
const CLONE_CONFIG = ["--config", "--origin", "--template", "--separate-git-dir", "--upload-pack"];
|
|
955
|
+
/** Whether a credential helper's file argument lies in the working checkout or a temp/scratch root. */
|
|
956
|
+
function helperFileAllowed(cwd, file, profile) {
|
|
957
|
+
let path;
|
|
958
|
+
try {
|
|
959
|
+
path = canonical(resolveWord(cwd, file));
|
|
960
|
+
}
|
|
961
|
+
catch {
|
|
962
|
+
return false;
|
|
963
|
+
}
|
|
964
|
+
const roots = [...profile.scratchRoots, ...tempRoots()];
|
|
965
|
+
try {
|
|
966
|
+
roots.push(canonical(git(cwd, ["rev-parse", "--show-toplevel"])));
|
|
967
|
+
}
|
|
968
|
+
catch {
|
|
969
|
+
/* not in a checkout: temp and scratch roots only */
|
|
970
|
+
}
|
|
971
|
+
return roots.some((root) => inside(canonical(root), path));
|
|
972
|
+
}
|
|
973
|
+
/** A fetch or push target that is this machine, not a remote: `.`, a path, or a `file:` URL. */
|
|
974
|
+
function localRepository(word) {
|
|
975
|
+
return (word === "." ||
|
|
976
|
+
word === ".." ||
|
|
977
|
+
word.startsWith("/") ||
|
|
978
|
+
word.startsWith("./") ||
|
|
979
|
+
word.startsWith("../") ||
|
|
980
|
+
word.startsWith("~") ||
|
|
981
|
+
word.startsWith("\\") ||
|
|
982
|
+
/^[A-Za-z]:/.test(word) ||
|
|
983
|
+
/^file:/i.test(word) ||
|
|
984
|
+
(!word.includes(":") && word.includes("/")));
|
|
985
|
+
}
|
|
986
|
+
/** Remote names configured in the repository, read locally. */
|
|
987
|
+
function configuredRemotes(cwd) {
|
|
988
|
+
try {
|
|
989
|
+
return new Set(git(cwd, ["remote"]).split("\n").filter(Boolean));
|
|
990
|
+
}
|
|
991
|
+
catch {
|
|
992
|
+
return undefined;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* A local write that moves a remote-tracking ref. Remote-tracking refs are this policy's evidence
|
|
997
|
+
* of what a remote holds (merged branches, unchanged credential helpers), so only fetching the
|
|
998
|
+
* same branch from its own configured remote may move them.
|
|
999
|
+
*/
|
|
1000
|
+
function remoteRefWrite(cwd, sub, rest) {
|
|
1001
|
+
const positional = rest.filter((word) => !word.startsWith("-"));
|
|
1002
|
+
const remoteRef = (word) => /^(?:\+)?refs\/remotes\//.test(word);
|
|
1003
|
+
const why = "Moving a remote-tracking ref locally requires human approval";
|
|
1004
|
+
if (sub === "update-ref") {
|
|
1005
|
+
// Only a plain branch or tag, named in full, that is not a symbolic ref: anything else could
|
|
1006
|
+
// move a remote-tracking ref, a replace ref, or whatever HEAD points to.
|
|
1007
|
+
const name = positional[0] ?? "";
|
|
1008
|
+
if (rest.some((w) => w === "--stdin" || w.startsWith("--no-deref")) ||
|
|
1009
|
+
positional.some(remoteRef) ||
|
|
1010
|
+
!/^refs\/(?:heads|tags)\/[^\s]+$/.test(name))
|
|
1011
|
+
return "Updating a ref other than a plain branch or tag requires human approval";
|
|
1012
|
+
try {
|
|
1013
|
+
git(cwd, ["symbolic-ref", "--quiet", name]);
|
|
1014
|
+
return "Updating a ref through a symbolic ref requires human approval";
|
|
1015
|
+
}
|
|
1016
|
+
catch {
|
|
1017
|
+
return undefined;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
if (sub === "symbolic-ref") {
|
|
1021
|
+
const writes = positional.length > 1 || rest.some((w) => w === "-d" || w === "--delete");
|
|
1022
|
+
return writes && positional.some((w) => /^(?:refs\/)?remotes\//.test(w)) ? why : undefined;
|
|
1023
|
+
}
|
|
1024
|
+
if (sub === "push") {
|
|
1025
|
+
const remote = positional[0];
|
|
1026
|
+
return remote !== undefined && localRepository(remote)
|
|
1027
|
+
? "Pushing to a local repository requires human approval"
|
|
1028
|
+
: undefined;
|
|
1029
|
+
}
|
|
1030
|
+
if (sub !== "fetch" && sub !== "pull")
|
|
1031
|
+
return undefined;
|
|
1032
|
+
if (rest.some((w) => w.startsWith("--refmap") || w === "--stdin"))
|
|
1033
|
+
return "A fetch with a custom ref map requires human approval";
|
|
1034
|
+
const remote = positional[0];
|
|
1035
|
+
if (remote === undefined)
|
|
1036
|
+
return undefined;
|
|
1037
|
+
if (localRepository(remote))
|
|
1038
|
+
return `A ${sub} from a local repository requires human approval`;
|
|
1039
|
+
const remotes = configuredRemotes(cwd);
|
|
1040
|
+
for (const spec of positional.slice(1)) {
|
|
1041
|
+
const colon = spec.indexOf(":");
|
|
1042
|
+
if (colon < 0)
|
|
1043
|
+
continue;
|
|
1044
|
+
const source = spec.slice(spec.startsWith("+") ? 1 : 0, colon);
|
|
1045
|
+
// Git also takes `remotes/<r>/<b>` as a short name for `refs/remotes/<r>/<b>`.
|
|
1046
|
+
const raw = spec.slice(colon + 1);
|
|
1047
|
+
const destination = raw.startsWith("remotes/") ? `refs/${raw}` : raw;
|
|
1048
|
+
if (!destination.startsWith("refs/remotes/"))
|
|
1049
|
+
continue;
|
|
1050
|
+
const [owner = "", ...branch] = destination.slice("refs/remotes/".length).split("/");
|
|
1051
|
+
const name = branch.join("/");
|
|
1052
|
+
if (owner !== remote ||
|
|
1053
|
+
!remotes?.has(remote) ||
|
|
1054
|
+
(source !== name && source !== `refs/heads/${name}`))
|
|
1055
|
+
return why;
|
|
1056
|
+
}
|
|
1057
|
+
return undefined;
|
|
1058
|
+
}
|
|
882
1059
|
/**
|
|
883
1060
|
* `git worktree add` from any clone is approved, except that the main checkout's working tree
|
|
884
1061
|
* stays protected: a new worktree inside it must go under `.worktrees/` or `.claude/worktrees/`.
|
|
@@ -1574,6 +1751,34 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
|
|
|
1574
1751
|
return human(request, "unknown", "wait with options requires human review");
|
|
1575
1752
|
if (program === "set" && !args.every((word) => /^[-+][B-Za-z]+$|^pipefail$/.test(word)))
|
|
1576
1753
|
return human(request, "unknown", "Changing shell settings requires human review");
|
|
1754
|
+
// A listed credential helper reads a secret for one narrow job. It runs only as committed on the
|
|
1755
|
+
// default branch, with an accepted argument shape, and with nothing changing its environment.
|
|
1756
|
+
const helper = helperMatch(profile.credentialHelpers, cwd, argv);
|
|
1757
|
+
if (helper.kind === "refused")
|
|
1758
|
+
return human(request, "sensitive", helper.reason);
|
|
1759
|
+
if (helper.kind === "match") {
|
|
1760
|
+
if (stageIndex > 0 ||
|
|
1761
|
+
command.stdin !== undefined ||
|
|
1762
|
+
command.redirects.some((r) => r.op === "<" || r.fd === "0") ||
|
|
1763
|
+
command.env.length > 0 ||
|
|
1764
|
+
unwrapped.env.length > 0 ||
|
|
1765
|
+
argv.length !== command.argv.length)
|
|
1766
|
+
return human(request, "sensitive", "A credential helper with a changed environment or input requires a person");
|
|
1767
|
+
// A pattern or `~` would let the shell turn one checked word into other words or files.
|
|
1768
|
+
if (argv.some((word, index) => index > 0 && (command.glob?.[index] === true || word.startsWith("~"))))
|
|
1769
|
+
return human(request, "sensitive", "A credential helper argument the shell would expand requires a person");
|
|
1770
|
+
for (const file of helper.files) {
|
|
1771
|
+
const check = permissiveRead(cwd, file);
|
|
1772
|
+
if (!check.allowed)
|
|
1773
|
+
return human(request, check.category, check.reason);
|
|
1774
|
+
if (!helperFileAllowed(cwd, file, profile))
|
|
1775
|
+
return human(request, "sensitive", "A credential helper may only send a file from this checkout or a temp directory");
|
|
1776
|
+
}
|
|
1777
|
+
return {
|
|
1778
|
+
...result(request, "impactful-write", "Listed credential helper", true),
|
|
1779
|
+
credentialHelpers: [`${helper.helper.path}#${helper.shape}`],
|
|
1780
|
+
};
|
|
1781
|
+
}
|
|
1577
1782
|
if (SHELLS.has(program) || INTERPRETERS.has(program)) {
|
|
1578
1783
|
if (stageIndex > 0)
|
|
1579
1784
|
return human(request, "unknown", "Piping into a shell or interpreter requires human review");
|
|
@@ -1611,6 +1816,16 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
|
|
|
1611
1816
|
if (program === "find" &&
|
|
1612
1817
|
args.some((arg) => ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprintf", "-fls"].includes(arg)))
|
|
1613
1818
|
return human(request, "destructive", "find with actions requires human review");
|
|
1819
|
+
if (program === "sort") {
|
|
1820
|
+
const outputs = sortWrites(args);
|
|
1821
|
+
if (outputs === undefined)
|
|
1822
|
+
return human(request, "unknown", "sort with an option that runs a program requires review");
|
|
1823
|
+
for (const file of outputs) {
|
|
1824
|
+
const check = permissiveWrite(cwd, file, profile, fill);
|
|
1825
|
+
if (!check.allowed)
|
|
1826
|
+
return human(request, check.category, check.reason);
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1614
1829
|
if (["chmod", "chown"].includes(program) && args.some((arg) => /^-[a-zA-Z]*R/.test(arg)))
|
|
1615
1830
|
return human(request, "destructive", "Recursive permission changes require human approval");
|
|
1616
1831
|
if ((program === "sed" &&
|
package/dist/policy.js
CHANGED
|
@@ -5,6 +5,7 @@ import { branchEvidence, canonical, git, inside, pathEvidence } from "./evidence
|
|
|
5
5
|
import { commandDecision, permissiveRead, permissiveWrite, WORKTREE_DELETION, } from "./permissive.js";
|
|
6
6
|
import { mcpReadOnly, strictProfile } from "./profile.js";
|
|
7
7
|
import { redactText } from "./redact.js";
|
|
8
|
+
import { defaultAllowed } from "./tools.js";
|
|
8
9
|
import { CATEGORIES, } from "./types.js";
|
|
9
10
|
export function hash(value) {
|
|
10
11
|
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
@@ -315,6 +316,15 @@ function evaluateCore(request, profile) {
|
|
|
315
316
|
...result(request, "unknown", "MCP tool not listed as read-only; left to the harness"),
|
|
316
317
|
decision: "native",
|
|
317
318
|
};
|
|
319
|
+
// Harness tools that are not shell, file, patch or MCP tools (task control, plan mode, asking
|
|
320
|
+
// the user, loading tool schemas) are approved by default under the permissive profile; the
|
|
321
|
+
// profile's toolsDeny keeps chosen ones on the classification path. Each approval names the tool.
|
|
322
|
+
if (profile.mode === "permissive" &&
|
|
323
|
+
defaultAllowed(request.harness, request.tool, profile.toolsDeny[request.harness] ?? []))
|
|
324
|
+
return {
|
|
325
|
+
...result(request, "code-read", "Harness tool approved by default", true),
|
|
326
|
+
defaultTool: request.tool,
|
|
327
|
+
};
|
|
318
328
|
const cwd = input.workdir ?? input.cwd ?? request.cwd;
|
|
319
329
|
if (typeof cwd !== "string" || cwd !== request.cwd)
|
|
320
330
|
return result(request, "unknown", "Execution directory differs from the reviewed directory");
|