Repository navigation
Expand file tree
/
Copy pathsecurity.test.mjs
More file actions
248 lines (240 loc) · 8.26 KB
/
Copy pathsecurity.test.mjs
File metadata and controls
248 lines (240 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/** 安全回归:不可信指标、仓库来源绑定与同步前的路径边界。 */
import test from "node:test";
import assert from "node:assert/strict";
import {
mkdtemp,
mkdir,
writeFile,
readFile,
rm,
symlink,
access,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { catalog, metrics, stats } from "../src/catalog.ts";
import { detailMarkup } from "../src/html.ts";
import { validateCatalog, validateMetrics } from "./validation.mjs";
const entry = catalog.find((item) => item.repo);
const metric = stats(entry);
const snapshotFor = (value) => ({
...metrics,
repositories: { [entry.id]: value },
});
test("detail renders external text and attribute values as inert HTML", () => {
const attack = "\"><img src=x onerror=alert(1)>&'";
const html = detailMarkup(
{
...entry,
name: attack,
vendor: attack,
description: attack,
docs: `https://example.com/${attack}`,
icon: attack,
id: attack,
install: attack,
repo: attack,
},
{ ...metric, language: attack, license: attack },
);
assert(!html.includes(attack));
assert(!html.includes("<img src=x"));
assert(!html.includes('src="/icons/"'));
const escaped = ""><img src=x onerror=alert(1)>&'";
assert(html.includes(`<span>${escaped}</span>`));
assert(html.includes(`许可证:${escaped}<br>`));
assert(html.includes(`data-copy="${escaped}"`));
});
test("complete metrics contract rejects malformed fields and HTML metrics", () => {
validateMetrics(metrics, catalog);
for (const [field, value] of Object.entries({
stars: -1,
forks: 0.5,
pushedAt: "bad date",
archived: "false",
language: {},
license: 1,
}))
assert.throws(() =>
validateMetrics(snapshotFor({ ...metric, [field]: value }), [entry]),
);
for (const field of Object.keys(metric)) {
const incomplete = { ...metric };
delete incomplete[field];
assert.throws(() => validateMetrics(snapshotFor(incomplete), [entry]));
}
for (const field of ["language", "license"])
assert.throws(() =>
validateMetrics(
snapshotFor({ ...metric, [field]: "<img src=x onerror=alert(1)>" }),
[entry],
),
);
assert.throws(() =>
validateMetrics({ ...snapshotFor(metric), fetchedAt: null }, [entry]),
);
assert.throws(() =>
validateMetrics(snapshotFor({ ...metric, extra: true }), [entry]),
);
assert.throws(() => validateMetrics(snapshotFor(null), [entry]));
assert.throws(() =>
validateMetrics(snapshotFor(metric), [
{ ...entry, repo: "different/repository" },
]),
);
assert.throws(() =>
validateMetrics({ ...metrics, repositories: {} }, catalog),
);
});
test("catalog contract rejects duplicate ids, repositories and unsafe icons", () => {
validateCatalog(catalog);
assert.throws(() =>
validateCatalog([entry, { ...entry, repo: "other/project" }]),
);
assert.throws(() =>
validateCatalog([
entry,
{ ...entry, id: "other", repo: entry.repo.toUpperCase() },
]),
);
assert.throws(() =>
validateCatalog([{ ...entry, icon: "../../../outside.png" }]),
);
});
async function fixture(run) {
const root = await mkdtemp(join(tmpdir(), "supercli-security-"));
const cwd = join(root, "work");
await mkdir(join(cwd, "data"), { recursive: true });
await mkdir(join(cwd, "public/icons"), { recursive: true });
const sentinel = join(root, "network-called");
const mock = join(root, "network.mjs");
const iconWrites = join(root, "icon-writes");
await writeFile(
mock,
`import { appendFileSync } from "node:fs";
import fs from "node:fs/promises";
import { syncBuiltinESMExports } from "node:module";
const writeFile = fs.writeFile;
fs.writeFile = async (path, ...args) => {
if (String(path).startsWith("public/icons/"))
appendFileSync(${JSON.stringify(iconWrites)}, String(path) + "\\n");
return writeFile(path, ...args);
};
syncBuiltinESMExports();
globalThis.fetch = async (url) => {
appendFileSync(${JSON.stringify(sentinel)}, String(url) + "\\n");
if (String(url).startsWith("https://example.com/avatar")) {
await new Promise((resolve) => setTimeout(resolve, 25));
return new Response("shared icon");
}
return new Response(JSON.stringify({ stargazers_count: 1, forks_count: 0,
pushed_at: "2026-10-20T00:00:00Z", archived: false, language: "Go",
license: { spdx_id: "MIT" }, owner: { avatar_url: "https://example.com/avatar?x=1" } }));
};`,
);
const sync = (rows) => {
return writeFile(join(cwd, "data/catalog.json"), JSON.stringify(rows)).then(
() =>
spawnSync(
process.execPath,
[
"--import",
mock,
fileURLToPath(new URL("./sync.mjs", import.meta.url)),
"--icons",
],
{
cwd,
encoding: "utf8",
timeout: 10000,
env: { ...process.env, GITHUB_TOKEN: "" },
},
),
);
};
try {
await run({ root, cwd, sentinel, iconWrites, sync });
} finally {
await rm(root, { recursive: true, force: true });
}
}
test("sync rejects malformed catalogs before fetch or writes, including traversal", async () => {
await fixture(async ({ root, cwd, sentinel, sync }) => {
for (const rows of [
[{ ...entry, icon: "../../../outside.png" }],
[entry, entry],
[{ ...entry, docs: "javascript:alert(1)" }],
]) {
const result = await sync(rows);
assert.notEqual(result.status, 0, result.stdout);
assert.match(result.stderr, /AssertionError/);
await assert.rejects(access(sentinel));
await assert.rejects(access(join(root, "outside.png")));
await assert.rejects(access(join(cwd, "data/metrics.json")));
await assert.rejects(access(join(cwd, "data/metrics.json.tmp")));
}
});
});
for (const link of ["public", "public/icons", `public/icons/${entry.icon}`]) {
test(`sync rejects symlink ${link} before fetch or writes`, async () => {
await fixture(async ({ root, cwd, sentinel, sync }) => {
const outside = join(root, "outside");
await mkdir(outside);
await rm(join(cwd, link), { recursive: true, force: true });
await symlink(outside, join(cwd, link));
const result = await sync([entry]);
assert.notEqual(result.status, 0);
assert.match(result.stderr, /禁止符号链接/);
await assert.rejects(access(sentinel));
await assert.rejects(access(join(outside, entry.icon)));
await assert.rejects(access(join(cwd, "data/metrics.json")));
});
});
}
test("sync accepts valid catalog without old metrics and produces validated snapshot", async () => {
await fixture(async ({ cwd, sentinel, sync }) => {
const result = await sync([entry]);
assert.equal(result.status, 0, result.stderr);
await access(sentinel);
const snapshot = JSON.parse(
await readFile(join(cwd, "data/metrics.json"), "utf8"),
);
validateMetrics(snapshot, [entry]);
assert.equal(snapshot.repositories[entry.id].repo, entry.repo);
await access(join(cwd, `public/icons/${entry.icon}`));
});
});
test("sync shares one icon download and exclusive write across different repositories", async () => {
await fixture(async ({ cwd, sentinel, iconWrites, sync }) => {
const rows = [
entry,
{ ...entry, id: "shared-icon-peer", repo: "other/project" },
];
const result = await sync(rows);
assert.equal(result.status, 0, result.stderr);
const snapshot = JSON.parse(
await readFile(join(cwd, "data/metrics.json"), "utf8"),
);
validateMetrics(snapshot, rows);
const requests = (await readFile(sentinel, "utf8")).trim().split("\n");
assert.equal(
requests.filter((url) => url.startsWith("https://api.github.com/repos/"))
.length,
2,
);
assert.equal(
requests.filter((url) => url.startsWith("https://example.com/avatar"))
.length,
1,
);
assert.deepEqual((await readFile(iconWrites, "utf8")).trim().split("\n"), [
`public/icons/${entry.icon}`,
]);
assert.equal(
await readFile(join(cwd, `public/icons/${entry.icon}`), "utf8"),
"shared icon",
);
});
});