Elffuss BraidHub

utopia-ia/elffuss-code public

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