Files
vibemake-pcb-studio/scripts/pcb-object-relay.test.mjs
T

163 lines
6.3 KiB
JavaScript

import { strict as assert } from 'node:assert';
import http from 'node:http';
import { Readable } from 'node:stream';
import { after, before, test } from 'node:test';
import { createObjectRelay } from './pcb-object-relay.mjs';
let backend,
web,
origin,
destination,
relay,
clock = 0,
calls = [],
uploaded,
redirects = false;
const bucket = 'https://example-bucket.oss.example.test';
const signPath = '/api/pcb/workspace/projects/valid/uploads/signature';
const docPath = '/api/pcb/workspace/projects/valid/document';
const coverPath = '/api/uploads/project-covers/signature';
let uploadUrl = bucket,
downloadUrl = bucket + '/private.zip?signed=hidden';
async function listen(server) {
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
return 'http://127.0.0.1:' + server.address().port;
}
before(async () => {
backend = http.createServer(async (req, res) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
calls.push({ method: req.method, path: req.url, headers: req.headers });
if (redirects) {
res.writeHead(302, { Location: 'https://other.example/' });
res.end();
return;
}
if (req.method === 'POST') {
uploaded = Buffer.concat(chunks);
res.end('ok');
return;
}
res.end(Buffer.from([1, 2, 3]));
});
destination = await listen(backend);
relay = createObjectRelay(
'/pcb/',
bucket,
(url, options, callback) => {
assert.equal(url.origin, bucket);
return http.request(new URL(url.pathname + url.search, destination), options, callback);
},
() => clock,
);
web = http.createServer(async (req, res) => {
const url = new URL(req.url, origin);
if (relay.transfer(req, res, url, origin)) return;
const rewrite = relay.prepare(req, url.pathname, origin);
for await (const _ of req) {
/* stand in for the platform handling the request */
}
const data =
url.pathname === docPath
? { downloadUrl, sizeBytes: 3, expiresAt: null }
: {
uploadUrl,
uploadCode: 'v1',
formFields: { key: 'scoped/project.zip' },
coverUrl: bucket + '/cover.webp',
};
const body = JSON.stringify({ code: 'OK', data });
if (!rewrite) {
res.end(body);
return;
}
const stream = Readable.from([Buffer.from(body)]);
stream.statusCode = 200;
stream.headers = { 'content-type': 'application/json' };
await rewrite(stream, res);
});
origin = await listen(web);
});
after(async () => {
for (const srv of [web, backend]) {
srv.closeAllConnections();
await new Promise((resolve) => srv.close(resolve));
}
});
async function issued(path = signPath, auth = true) {
const post = path !== docPath;
return fetch(origin + path, {
method: post ? 'POST' : 'GET',
headers: auth ? { Authorization: 'Bearer my-secret', 'Content-Type': 'application/json' } : {},
...(post ? { body: JSON.stringify({ sizeBytes: 5, fileSize: 5 }) } : {}),
});
}
test('auth-scoped signature returns an opaque local URL, keeps signed form and original cover URL', async () => {
const { data } = await (await issued()).json();
assert.match(data.uploadUrl, new RegExp('^' + origin + '/pcb/storage-transfer/[\\w-]{32}$'));
assert.deepEqual(data.formFields, { key: 'scoped/project.zip' });
assert.equal(data.coverUrl, bucket + '/cover.webp');
assert.equal((await (await issued(coverPath)).json()).data.coverUrl, bucket + '/cover.webp');
const type = 'multipart/form-data; boundary=testing';
const original = Buffer.from('--testing\r\nline\r\n--testing--');
const response = await fetch(data.uploadUrl, {
method: 'POST',
headers: {
Origin: origin,
'Content-Type': type,
Authorization: 'Bearer must-not-leak',
Cookie: 'session=private',
'X-Leak': 'private',
},
body: original,
});
assert.equal(response.status, 200);
assert.deepEqual(uploaded, original);
const forwarded = calls.at(-1);
assert.equal(forwarded.path, '/');
assert.equal(forwarded.headers['content-type'], type);
for (const key of ['authorization', 'cookie', 'origin', 'x-leak', 'referer'])
assert.equal(forwarded.headers[key], undefined);
assert.equal((await fetch(data.uploadUrl)).status, 405);
});
test('download fetches only its exact key and hides storage headers; retry after redirect does not leave bucket', async () => {
const { data } = await (await issued(docPath)).json();
assert.equal(data.expiresAt, null);
assert.ok(!data.downloadUrl.includes('signed') && !data.downloadUrl.includes('private.zip'));
redirects = true;
assert.equal((await fetch(data.downloadUrl)).status, 502);
redirects = false;
const response = await fetch(data.downloadUrl, {
headers: { Cookie: 'no', Authorization: 'Bearer hidden' },
});
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-type'), 'application/octet-stream');
assert.deepEqual(new Uint8Array(await response.arrayBuffer()), new Uint8Array([1, 2, 3]));
assert.equal(calls.at(-1).path, '/private.zip?signed=hidden');
assert.equal(calls.at(-1).headers.authorization, undefined);
});
test('foreign origin, excessive bytes, expired tickets, extra query strings, and foreign targets cannot transfer', async () => {
const { data } = await (await issued()).json();
const send = (headers, body) =>
fetch(data.uploadUrl, {
method: 'POST',
headers: { Origin: origin, 'Content-Type': 'multipart/form-data; boundary=x', ...headers },
body,
});
const beforeCalls = calls.length;
assert.equal((await send({ Origin: 'https://other.test' }, 'bytes')).status, 403);
assert.equal((await send({ 'Content-Type': 'text/plain' }, 'bytes')).status, 415);
assert.equal((await send({}, Buffer.alloc(70000))).status, 413);
assert.equal((await fetch(data.uploadUrl + '?url=https://evil.test')).status, 404);
clock += 301000;
assert.equal((await send({}, 'bytes')).status, 410);
assert.equal(calls.length, beforeCalls);
uploadUrl = 'https://not-trusted.example/object';
assert.equal((await issued()).status, 502);
uploadUrl = bucket;
assert.equal((await (await issued(signPath, false)).json()).data.uploadUrl, bucket);
assert.equal((await (await issued('/api/unrelated')).json()).data.uploadUrl, bucket);
assert.throws(() => createObjectRelay('/pcb/', 'http://127.0.0.1'));
});