Elffuss BraidHub

utopia-ia/elffuss-code public

885e56ef5ed2 · 9.6 KiBRawPermalink
1// Headers of the level 2 sandbox, as served. Read-only: only GET requests.
2//
3// node tests/x2_headers.mjs
4// against its own test server (tests/lib/x2-server.mjs)
5// X2_SANDBOX=https://x2.<domain> X2_CODE=https://code.elffuss.com node tests/x2_headers.mjs
6// against a deployment (after deploy-sandbox.sh, deploy-vendor.sh and deploy.sh)
7//
8// Checks:
9// H1 both sandbox documents, with their exact query shape: status 200, every
10// header from sandbox/x2/headers.json with exactly its value, and no
11// cookie, no reporting endpoint, no CORS header; the body is the
12// committed document byte for byte;
13// H2 anything else on the sandbox site is a 404: other paths, the documents
14// with any other query (an extra parameter, another parent origin, an
15// upper-case id, none), other methods;
16// H3 Code's site never serves /x2/;
17// H4 the vendor files of the committed manifest on Code's site: octet-stream,
18// immutable for a year, nosniff, never re-compressed, and their SRI holds;
19// H5 a vendor file that is not there is a 404 that is not cached as
20// immutable (a cached failure would outlive the upload);
21// H6 (local only) the generated nginx snippets set the charset the way
22// headers.json says, and the template's vendor location has no
23// `always` on Cache-Control.
24import fs from 'node:fs';
25import path from 'node:path';
26import crypto from 'node:crypto';
27import { fileURLToPath } from 'node:url';
28import { headersFor, originsFor, loadSpec, DOCS_DIR } from '../sandbox/x2/headers.mjs';
29import { startServer } from './lib/x2-server.mjs';
30
31const HERE = path.dirname(fileURLToPath(import.meta.url));
32let fails = 0;
33const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
34
35const remote = !!process.env.X2_SANDBOX;
36let srv = null, code, sandbox, origins;
37if (remote) {
38 sandbox = new URL(process.env.X2_SANDBOX).origin;
39 code = new URL(process.env.X2_CODE || loadSpec().environments.production.code[0]).origin;
40 origins = { code: loadSpec().environments.production.code, sandbox };
41} else {
42 srv = await startServer();
43 code = srv.codeOrigin;
44 sandbox = srv.sandboxOrigin;
45 origins = originsFor('dev', { port: srv.port });
46}
47console.log(`Code ${code} · sandbox ${sandbox}`);
48
49const get = (url, opts = {}) => fetch(url, { redirect: 'manual', cache: 'no-store', ...opts });
50const uuid = () => crypto.randomUUID();
51const exthostQuery = (parent = sandbox, id = uuid()) => `?parentOrigin=${encodeURIComponent(parent)}&vscodeWebWorkerExtHostId=${id}`;
52const spec = loadSpec();
53const DOC = name => spec.documents[name].path;
54
55// ── H1: los dos documentos ──
56for (const [name, query] of [['sandbox.html', ''], ['exthost-iframe.html', exthostQuery()]]) {
57 const r = await get(sandbox + DOC(name) + query);
58 const body = Buffer.from(await r.arrayBuffer());
59 ok(`H1 ${name}: 200`, r.status === 200, String(r.status));
60 const want = headersFor(name, origins);
61 const wrong = Object.entries(want).filter(([k, v]) => r.headers.get(k) !== v).map(([k, v]) => `${k}: got ${JSON.stringify(r.headers.get(k))}, want ${JSON.stringify(v.slice(0, 80))}…`);
62 ok(`H1 ${name}: every header from headers.json, with exactly its value (${Object.keys(want).length})`, !wrong.length, wrong.slice(0, 3).join(' | '));
63 const csp = r.headers.get('content-security-policy') || '';
64 const fa = /frame-ancestors ([^;]*)/.exec(csp)?.[1].split(/\s+/) || [];
65 const wantFa = name === 'exthost-iframe.html' ? ["'self'", ...origins.code] : origins.code;
66 ok(`H1 ${name}: framed only by ${name === 'exthost-iframe.html' ? 'the sandbox and ' : ''}Code`, JSON.stringify(fa) === JSON.stringify(wantFa), fa.join(' '));
67 const extra = ['set-cookie', 'report-to', 'reporting-endpoints', 'nel', 'access-control-allow-origin', 'content-security-policy-report-only'].filter(k => r.headers.has(k));
68 ok(`H1 ${name}: no cookie, no reporting endpoint, no CORS`, !extra.length && !/report-(uri|to)/.test(csp), extra.join(' '));
69 const committed = fs.readFileSync(path.join(DOCS_DIR, name));
70 ok(`H1 ${name}: the committed document, byte for byte`, body.equals(committed), `${body.length} vs ${committed.length} bytes`);
71}
72
73// ── H2: nada más en el sitio del recinto ──
74const goodId = uuid();
75const notFound = [
76 ['/', ''], ['/x2/', ''], ['/x2/v1/', ''], ['/x2/v1/other.html', ''], ['/x2/v2/sandbox.html', ''], ['/X2/v1/sandbox.html', ''],
77 ['/x2/v1/sandbox.html/', ''], ['/index.html', ''], ['/js/main.js', ''], ['/robots.txt', ''],
78 [DOC('sandbox.html'), '?x=1'], [DOC('sandbox.html'), '?parentOrigin=' + encodeURIComponent(sandbox)],
79 [DOC('exthost-iframe.html'), ''],
80 [DOC('exthost-iframe.html'), exthostQuery(sandbox, goodId) + '&x=1'],
81 [DOC('exthost-iframe.html'), exthostQuery(code, goodId)],
82 [DOC('exthost-iframe.html'), exthostQuery('https://evil.invalid', goodId)],
83 [DOC('exthost-iframe.html'), exthostQuery(sandbox, goodId.toUpperCase())],
84 [DOC('exthost-iframe.html'), exthostQuery(sandbox, 'not-a-uuid')],
85 [DOC('exthost-iframe.html'), `?vscodeWebWorkerExtHostId=${goodId}&parentOrigin=${encodeURIComponent(sandbox)}`],
86];
87const manifest = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/vendor-manifest.json'), 'utf8'));
88notFound.push([`/vendor/x2/${manifest.buildId}/${manifest.files[0].name}.gz`, '']);
89const served = [];
90for (const [p, q] of notFound) {
91 const r = await get(sandbox + p + q);
92 await r.arrayBuffer().catch(() => {});
93 if (r.status !== 404) served.push(`${p}${q.slice(0, 40)} → ${r.status}`);
94}
95ok(`H2 on the sandbox site everything else is a 404 (${notFound.length} paths and query shapes)`, !served.length, served.slice(0, 4).join(' | '));
96const methods = [];
97for (const m of ['POST', 'PUT', 'DELETE']) {
98 const r = await get(sandbox + DOC('sandbox.html'), { method: m, body: m === 'DELETE' ? undefined : 'x' });
99 await r.arrayBuffer().catch(() => {});
100 if (r.status !== 404 && r.status !== 405) methods.push(`${m} → ${r.status}`);
101}
102ok('H2 other methods are refused (404 or 405)', !methods.length, methods.join(' | '));
103
104// ── H3: el sitio de Code no sirve /x2/ ──
105const fromCode = [];
106for (const [p, q] of [[DOC('sandbox.html'), ''], [DOC('exthost-iframe.html'), exthostQuery()], ['/x2/', '']]) {
107 const r = await get(code + p + q);
108 await r.arrayBuffer().catch(() => {});
109 if (r.status !== 404) fromCode.push(`${p} → ${r.status}`);
110}
111ok('H3 Code’s site never serves /x2/', !fromCode.length, fromCode.join(' | '));
112
113// ── H4: el bundle en el sitio de Code ──
114const local = path.join(HERE, '../web/vendor/x2', manifest.buildId);
115if (!remote && !fs.existsSync(local)) {
116 console.log(`⏭️ NOT RUN H4 — web/vendor/x2/${manifest.buildId} is not built here (vendor/vscode-ext2/build.mjs)`);
117} else {
118 for (const f of manifest.files) {
119 const r = await get(`${code}/vendor/x2/${manifest.buildId}/${f.name}.gz`, { headers: { 'Accept-Encoding': 'gzip, br' } });
120 const body = Buffer.from(await r.arrayBuffer());
121 const sri = 'sha256-' + crypto.createHash('sha256').update(body).digest('base64');
122 const h = k => r.headers.get(k) || '';
123 const problems = [];
124 if (r.status !== 200) problems.push('status ' + r.status);
125 if (h('content-type') !== 'application/octet-stream') problems.push('type ' + h('content-type'));
126 if (!/max-age=31536000/.test(h('cache-control')) || !/immutable/.test(h('cache-control'))) problems.push('cache ' + h('cache-control'));
127 if (h('x-content-type-options') !== 'nosniff') problems.push('no nosniff');
128 if (r.headers.has('content-encoding')) problems.push('re-compressed: ' + h('content-encoding'));
129 if (sri !== f.sriGz) problems.push('SRI does not match the manifest');
130 if (body.length !== f.gz) problems.push(`${body.length} bytes, manifest says ${f.gz}`);
131 ok(`H4 ${f.name}.gz: octet-stream, immutable, nosniff, not re-compressed, SRI as in the manifest`, !problems.length, problems.join(' | '));
132 }
133}
134
135// ── H5: un fichero del bundle que no está es un 404 que NO se guarda un año ──
136// (con «always» en el Cache-Control de nginx, el fallo quedaría en la caché
137// del navegador como inmutable, y el buildId es un hash: subir luego los
138// mismos bytes no lo arreglaría)
139{
140 const r = await get(`${code}/vendor/x2/ffffffffffffffff/sandbox-main.js.gz`);
141 await r.arrayBuffer().catch(() => {});
142 const cc = r.headers.get('cache-control') || '';
143 ok('H5 a missing vendor file: 404, and not cached as immutable', r.status === 404 && !/immutable|max-age=[1-9]/.test(cc), `${r.status} cache-control: ${JSON.stringify(cc)}`);
144}
145
146// ── H6: lo que se genera para nginx dice lo mismo que headers.json ──
147if (!remote) {
148 const { nginx } = await import('../sandbox/x2/headers.mjs');
149 const conf = nginx('https://x2.sandbox.example');
150 ok('H6 the nginx snippets set the charset (charset utf-8;), not default_type, and every header with always',
151 (conf.match(/^charset utf-8;$/gm) || []).length === 2 && !/default_type/.test(conf) && (conf.match(/^add_header /gm) || []).every(Boolean)
152 && (conf.match(/^add_header .* always;$/gm) || []).length === (conf.match(/^add_header /gm) || []).length, conf.slice(0, 200));
153 const example = fs.readFileSync(path.join(HERE, '../sandbox/x2/nginx.conf.example'), 'utf8');
154 const vendorBlock = /location \^~ \/vendor\/x2\/ \{[\s\S]*?\}/.exec(example)?.[0] || '';
155 ok('H6 the template for Code’s vendor location adds Cache-Control only to successful responses (no always)',
156 /add_header Cache-Control "public, max-age=31536000, immutable";/.test(vendorBlock) && !/Cache-Control[^\n]*always/.test(vendorBlock), vendorBlock.replace(/\s+/g, ' ').slice(0, 200));
157}
158
159await srv?.close();
160console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
161process.exit(fails ? 1 : 0);