Files

341 lines
22 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import crypto from 'node:crypto';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const serverPath = fileURLToPath(new URL('./server.mjs', import.meta.url));
test('relay persists opaque chunks, acknowledges and revokes pairings', async t => {
const dataDir = await mkdtemp(path.join(os.tmpdir(), 'audiorecorder-relay-'));
const setupCodeFile = path.join(dataDir, 'setup-code');
await writeFile(setupCodeFile, 'test-one-time-setup-code', { mode: 0o600 });
const probe = net.createServer();
await new Promise(resolve => probe.listen(0, '127.0.0.1', resolve));
const port = probe.address().port;
await new Promise(resolve => probe.close(resolve));
const env = { ...process.env, PORT: String(port), HOST: '127.0.0.1', RELAY_DATA_DIR: dataDir, RELAY_SETUP_CODE_FILE: setupCodeFile, TURN_HOST: 'turn.test.invalid', TURN_PORT: '3478', TURN_SHARED_SECRET: 'test-only', APNS_ENABLED: 'false' };
let child;
const start = async () => {
child = spawn(process.execPath, [serverPath], { env, stdio: 'ignore' });
for (let attempt = 0; attempt < 80; attempt++) {
try {
if ((await fetch(`http://127.0.0.1:${port}/health`)).ok) return;
} catch {}
await new Promise(resolve => setTimeout(resolve, 50));
}
throw new Error('relay server did not start');
};
const stop = async () => {
if (!child || child.exitCode !== null) return;
await new Promise(resolve => { child.once('exit', resolve); child.kill('SIGTERM'); });
};
const postJSON = (url, body, token) => fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: JSON.stringify(body)
});
t.after(async () => { await stop(); await rm(dataDir, { recursive: true, force: true }); });
await start();
const base = `http://127.0.0.1:${port}`;
const setupResponses = await Promise.all([
postJSON(`${base}/api/v1/auth/setup`, { setupCode: 'test-one-time-setup-code', username: 'owner', password: 'correct-horse-battery' }),
postJSON(`${base}/api/v1/auth/setup`, { setupCode: 'test-one-time-setup-code', username: 'attacker', password: 'correct-horse-battery' })
]);
assert.deepEqual(setupResponses.map(response => response.status).sort(), [201, 409]);
const setupResponse = setupResponses.find(response => response.status === 201);
const owner = await setupResponse.json();
assert.equal(owner.account.role, 'admin');
const repeatedSetup = await postJSON(`${base}/api/v1/auth/setup`, { setupCode: 'test-one-time-setup-code', username: 'attacker', password: 'correct-horse-battery' });
assert.equal(repeatedSetup.status, 409);
const unauthorizedOffer = await postJSON(`${base}/api/v1/pairing/offers`, { protocolVersion: 2, secretHash: 'a'.repeat(64), publicKey: 'mac-key', identityKey: 'mac-identity' });
assert.equal(unauthorizedOffer.status, 401);
const invitationResponse = await postJSON(`${base}/api/v1/admin/invitations`, {}, owner.accessToken);
assert.equal(invitationResponse.status, 201);
const invitation = await invitationResponse.json();
const memberResponses = await Promise.all([
postJSON(`${base}/api/v1/auth/redeem`, { invitationCode: invitation.code, username: 'member', password: 'another-correct-password' }),
postJSON(`${base}/api/v1/auth/redeem`, { invitationCode: invitation.code, username: 'member2', password: 'another-correct-password' })
]);
assert.deepEqual(memberResponses.map(response => response.status).sort(), [201, 401]);
const memberResponse = memberResponses.find(response => response.status === 201);
assert.equal((await memberResponse.json()).account.role, 'member');
const repeatedInvitation = await postJSON(`${base}/api/v1/auth/redeem`, { invitationCode: invitation.code, username: 'member2', password: 'another-correct-password' });
assert.equal(repeatedInvitation.status, 401);
const secretHash = crypto.createHash('sha256').update('test-pairing-secret').digest('hex');
const legacyOffer = await postJSON(`${base}/api/v1/pairing/offers`, { secretHash, publicKey: 'mac-key', identityKey: 'mac-identity' }, owner.accessToken);
assert.equal(legacyOffer.status, 426);
const offerResponse = await postJSON(`${base}/api/v1/pairing/offers`, { protocolVersion: 2, secretHash, publicKey: 'mac-key', identityKey: 'mac-identity', directEndpoints: ['http://192.168.1.2:8787'] }, owner.accessToken);
assert.equal(offerResponse.status, 201);
const offer = await offerResponse.json();
assert.deepEqual(offer.public.directEndpoints, []);
const leakedQueryProof = await fetch(`${base}/api/v1/pairing/offers/${offer.id}?secretHash=${secretHash}`);
assert.equal((await leakedQueryProof.json()).sessionToken, null);
const legacyClaim = await postJSON(`${base}/api/v1/pairing/offers/${offer.id}/claim`, { secretHash, publicKey: 'phone-key', identityKey: 'phone-identity' });
assert.equal(legacyClaim.status, 426);
const claimResponse = await postJSON(`${base}/api/v1/pairing/offers/${offer.id}/claim`, { protocolVersion: 2, secretHash, publicKey: 'phone-key', identityKey: 'phone-identity' });
assert.equal(claimResponse.status, 200);
const claim = await claimResponse.json();
assert.ok(claim.relayToken);
const secondSecretHash = crypto.createHash('sha256').update('second-pairing-secret').digest('hex');
const secondOfferResponse = await postJSON(`${base}/api/v1/pairing/offers`, {
protocolVersion: 2,
secretHash: secondSecretHash,
publicKey: 'mac-key-two',
identityKey: 'mac-identity-two'
}, owner.accessToken);
assert.equal(secondOfferResponse.status, 201);
const secondOffer = await secondOfferResponse.json();
const secondClaimResponse = await postJSON(`${base}/api/v1/pairing/offers/${secondOffer.id}/claim`, {
protocolVersion: 2,
secretHash: secondSecretHash,
publicKey: 'phone-key-two',
identityKey: 'phone-identity-two'
});
assert.equal(secondClaimResponse.status, 200);
const secondClaim = await secondClaimResponse.json();
assert.ok(secondClaim.relayToken);
const persistedPairing = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8')).pairingSessions[0];
assert.equal(persistedPairing.sessionToken, undefined);
assert.equal(persistedPairing.relayToken, undefined);
const claimedOffer = await fetch(`${base}/api/v1/pairing/offers/${offer.id}`, { headers: { authorization: `Bearer ${secretHash}` } });
assert.equal((await claimedOffer.json()).sessionToken, claim.sessionToken);
const sessionPath = `${base}/api/v1/pairing/sessions/${offer.id}`;
const pushPath = `${base}/api/v1/relay/sessions/${offer.id}/push-devices`;
const unauthenticatedPushStatus = await fetch(pushPath);
assert.equal(unauthenticatedPushStatus.status, 401);
const pushStatus = await fetch(pushPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.equal(pushStatus.status, 404);
const deviceToken = 'ab'.repeat(32);
const pushRegistration = await postJSON(pushPath, { token: deviceToken, environment: 'production', bundleID: 'com.example.Meets' }, claim.relayToken);
assert.equal(pushRegistration.status, 404);
const persistedPushState = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8'));
assert.deepEqual(persistedPushState.pushDevices || {}, {});
const malformedNotification = await postJSON(`${base}/api/v1/relay/sessions/${offer.id}/notifications`, { eventID: 'bad', eventType: 'completed' }, claim.relayToken);
assert.equal(malformedNotification.status, 404);
const unavailableNotification = await postJSON(`${base}/api/v1/relay/sessions/${offer.id}/notifications`, { eventID: crypto.randomUUID(), eventType: 'completed', recordingID: crypto.randomUUID() }, claim.relayToken);
assert.equal(unavailableNotification.status, 404);
const legacyHeartbeat = await postJSON(`${sessionPath}/heartbeat`, { side: 'client' }, claim.sessionToken);
assert.equal(legacyHeartbeat.status, 426);
const heartbeat = await postJSON(`${sessionPath}/heartbeat`, { protocolVersion: 2, side: 'client', directEndpoints: ['http://192.168.1.2:8787'] }, claim.sessionToken);
assert.equal(heartbeat.status, 200);
assert.deepEqual((await heartbeat.json()).directEndpoints, []);
const generationResponse = await postJSON(`${sessionPath}/generation`, {}, claim.sessionToken);
assert.equal(generationResponse.status, 200);
const { generationID } = await generationResponse.json();
const signalBody = { protocolVersion: 2, generationID, side: 'client', messageID: crypto.randomUUID(), authenticator: Buffer.alloc(32, 7).toString('base64url'), description: { type: 'offer', sdp: 'v=0\r\n' }, candidates: [] };
const unsignedSignal = await postJSON(`${sessionPath}/signal`, { ...signalBody, authenticator: undefined }, claim.sessionToken);
assert.equal(unsignedSignal.status, 426);
const signalResponse = await postJSON(`${sessionPath}/signal`, signalBody, claim.sessionToken);
assert.equal(signalResponse.status, 202);
const replayedSignal = await postJSON(`${sessionPath}/signal`, signalBody, claim.sessionToken);
assert.equal(replayedSignal.status, 409);
const statusResponse = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
const status = await statusResponse.json();
assert.equal(status.signals[0].protocolVersion, 2);
assert.equal(status.signals[0].generationID, generationID);
assert.equal(status.signals[0].messageID, signalBody.messageID);
assert.equal(status.signals[0].authenticator, signalBody.authenticator);
const id = crypto.randomUUID();
const relayPath = `${base}/api/v1/relay/sessions/${offer.id}`;
const manifest = await postJSON(`${relayPath}/uploads`, { id, size: 3, chunkCount: 1 }, claim.relayToken);
assert.equal(manifest.status, 201);
const ciphertext = Buffer.from([0x81, 0x22, 0xfe]);
const put = await fetch(`${relayPath}/uploads/${id}/chunks/0`, {
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: ciphertext
});
assert.equal(put.status, 200);
await stop();
await start();
// Pairing metadata and bearer credentials must survive a handshake service
// restart; only the WebRTC generation is transient and renegotiated.
const restoredStatusResponse = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
assert.equal(restoredStatusResponse.status, 200);
const restoredStatus = await restoredStatusResponse.json();
assert.equal(restoredStatus.sessionID, offer.id);
assert.equal(restoredStatus.generationID, null);
const restoredHeartbeat = await postJSON(`${sessionPath}/heartbeat`, { protocolVersion: 2, side: 'mac' }, claim.sessionToken);
assert.equal(restoredHeartbeat.status, 200);
const restoredIce = await fetch(`${sessionPath}/ice-servers`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
assert.equal(restoredIce.status, 200);
// RPC jobs use the same encrypted durable store, but separate directional
// queues so the relay cannot route a response back as a new request.
const messageID = crypto.randomUUID();
const messagePath = `${relayPath}/messages`;
const messageManifest = await postJSON(messagePath, { id: messageID, direction: 'request', size: 3, chunkCount: 1 }, claim.relayToken);
assert.equal(messageManifest.status, 201);
const macWait = fetch(`${relayPath}?queue=mac&wait=10`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
await new Promise(resolve => setTimeout(resolve, 75));
const messageCiphertext = Buffer.from([0x35, 0x86, 0xf1]);
const messagePut = await fetch(`${messagePath}/${messageID}/chunks/0`, {
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: messageCiphertext
});
assert.equal(messagePut.status, 200);
const wokenMacWait = await macWait;
assert.equal(wokenMacWait.status, 200);
await stop();
await start();
const requestQueueResponse = await fetch(`${messagePath}?direction=request`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual((await requestQueueResponse.json()).messages.map(message => message.id), [messageID]);
const messageChunk = await fetch(`${messagePath}/${messageID}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual(Buffer.from(await messageChunk.arrayBuffer()), messageCiphertext);
const messageAck = await postJSON(`${messagePath}/${messageID}/ack`, {}, claim.relayToken);
assert.equal(messageAck.status, 200);
const responseWait = fetch(`${messagePath}?direction=response&wait=10`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
await new Promise(resolve => setTimeout(resolve, 75));
const responseID = crypto.randomUUID();
const responseManifest = await postJSON(messagePath, { id: responseID, direction: 'response', size: 2, chunkCount: 1 }, claim.relayToken);
assert.equal(responseManifest.status, 201);
const responsePut = await fetch(`${messagePath}/${responseID}/chunks/0`, {
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: Buffer.from([0x01, 0x02])
});
assert.equal(responsePut.status, 200);
const responseQueueResponse = await responseWait;
assert.equal(responseQueueResponse.status, 200);
assert.deepEqual((await responseQueueResponse.json()).messages.map(message => message.id), [responseID]);
// Large audio replies are advertised in the small RPC envelope and fetched
// as independently authenticated attachment chunks, not base64 RPC bodies.
const attachmentID = crypto.randomUUID();
const attachmentPath = `${messagePath}`;
const attachmentManifest = await postJSON(attachmentPath, { id: attachmentID, direction: 'attachment', size: 21, chunkCount: 1 }, claim.relayToken);
assert.equal(attachmentManifest.status, 201);
const attachmentCiphertext = Buffer.from('encrypted-audio-chunk');
const attachmentPut = await fetch(`${attachmentPath}/${attachmentID}/chunks/0`, {
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: attachmentCiphertext
});
assert.equal(attachmentPut.status, 200);
const attachmentQueue = await fetch(`${messagePath}?direction=response`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual((await attachmentQueue.json()).messages.map(message => message.id), [responseID]);
const attachmentChunk = await fetch(`${attachmentPath}/${attachmentID}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual(Buffer.from(await attachmentChunk.arrayBuffer()), attachmentCiphertext);
const attachmentAck = await postJSON(`${attachmentPath}/${attachmentID}/ack`, {}, claim.relayToken);
assert.equal(attachmentAck.status, 200);
// Exercise the supported maximum audio size as bounded opaque chunks. Keep
// only one chunk buffer in memory while the relay stages the full payload.
const maximumAudioBytes = 500 * 1024 * 1024;
const audioChunkSize = 3 * 1024 * 1024;
const audioChunkCount = Math.ceil(maximumAudioBytes / audioChunkSize);
const largeAudioID = crypto.randomUUID();
const largeAudioManifest = await postJSON(messagePath, {
id: largeAudioID,
direction: 'attachment',
size: maximumAudioBytes,
chunkCount: audioChunkCount
}, claim.relayToken);
assert.equal(largeAudioManifest.status, 201);
let remainingAudioBytes = maximumAudioBytes;
let lastEncryptedChunk;
const reusableEncryptedChunk = Buffer.alloc(audioChunkSize + 16);
for (let index = 0; index < audioChunkCount; index++) {
const plaintextLength = Math.min(audioChunkSize, remainingAudioBytes);
const encryptedLength = plaintextLength + 16;
reusableEncryptedChunk.fill(index & 0xff, 0, encryptedLength);
const encryptedChunk = reusableEncryptedChunk.subarray(0, encryptedLength);
const response = await fetch(`${messagePath}/${largeAudioID}/chunks/${index}`, {
method: 'PUT',
headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' },
body: encryptedChunk
});
assert.equal(response.status, 200);
if (index === audioChunkCount - 1) lastEncryptedChunk = Buffer.from(encryptedChunk);
remainingAudioBytes -= plaintextLength;
}
assert.equal(remainingAudioBytes, 0);
const largeAudioStatus = await fetch(`${messagePath}/${largeAudioID}`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.equal(largeAudioStatus.status, 200);
assert.equal((await largeAudioStatus.json()).chunkCount, audioChunkCount);
const lastAudioChunkResponse = await fetch(`${messagePath}/${largeAudioID}/chunks?index=${audioChunkCount - 1}`, {
headers: { authorization: `Bearer ${claim.relayToken}` }
});
assert.deepEqual(Buffer.from(await lastAudioChunkResponse.arrayBuffer()), lastEncryptedChunk);
const largeAudioAck = await postJSON(`${messagePath}/${largeAudioID}/ack`, {}, claim.relayToken);
assert.equal(largeAudioAck.status, 200);
let listing = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual((await listing.json()).uploads.map(upload => upload.id), [id]);
const chunk = await fetch(`${relayPath}/uploads/${id}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual(Buffer.from(await chunk.arrayBuffer()), ciphertext);
const ack = await postJSON(`${relayPath}/uploads/${id}/ack`, {}, claim.relayToken);
assert.equal(ack.status, 200);
listing = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual((await listing.json()).uploads, []);
const revoke = await fetch(relayPath, { method: 'DELETE', headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.equal(revoke.status, 200);
const unauthorized = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.equal(unauthorized.status, 401);
// Exhaust the general-purpose IP bucket and verify it cannot block the
// paired session heartbeat, which has its own pairing budget.
let defaultLimitReached = false;
let defaultLimitResponse;
for (let attempt = 0; attempt < 610; attempt++) {
const response = await fetch(`${base}/health`);
if (response.status === 429) {
defaultLimitReached = true;
defaultLimitResponse = response;
break;
}
assert.equal(response.status, 200);
}
assert.equal(defaultLimitReached, true);
assert.equal(defaultLimitResponse.headers.get('retry-after'), '60');
assert.deepEqual(await defaultLimitResponse.json(), { error: 'rate_limited', retryAfterSeconds: 60 });
const heartbeatAfterDefaultLimit = await postJSON(
`${sessionPath}/heartbeat`,
{ protocolVersion: 2, side: 'client' },
claim.sessionToken
);
assert.equal(heartbeatAfterDefaultLimit.status, 200);
// Flood one authenticated pairing while another pairing continues to poll
// concurrently from the same simulated public IP. The session-scoped limit
// must reject only the busy pairing and keep the other inbox responsive.
const sessionScopedRelayPath = `${base}/api/v1/relay/sessions/${offer.id}/messages?direction=request`;
const sameNATHeaders = { authorization: `Bearer ${claim.relayToken}`, 'x-forwarded-for': '203.0.113.19' };
const secondSessionRelayPath = `${base}/api/v1/relay/sessions/${secondOffer.id}/messages?direction=request`;
const secondSessionHeaders = { authorization: `Bearer ${secondClaim.relayToken}`, 'x-forwarded-for': '203.0.113.19' };
let sessionLimitReached = false;
for (let batch = 0; batch < 19 && !sessionLimitReached; batch++) {
const [responses, independentResponses] = await Promise.all([
Promise.all(Array.from({ length: 100 }, () => fetch(sessionScopedRelayPath, { headers: sameNATHeaders }))),
Promise.all(Array.from({ length: 50 }, () => fetch(secondSessionRelayPath, { headers: secondSessionHeaders })))
]);
assert.ok(independentResponses.every(response => response.status === 200), 'The independent pairing must remain responsive during the concurrent flood.');
sessionLimitReached = responses.some(response => response.status === 429);
}
assert.equal(sessionLimitReached, true);
const otherSessionPoll = await fetch(secondSessionRelayPath, { headers: secondSessionHeaders });
assert.equal(otherSessionPoll.status, 200);
// The Mac's long poll uses the session root. Keep that high-frequency
// endpoint in its own budget so a stuck poll cannot throttle iPhone RPCs.
const macQueuePollPath = `${base}/api/v1/relay/sessions/${secondOffer.id}?queue=mac&wait=0`;
const macQueuePolls = await Promise.all(Array.from({ length: 190 }, () => fetch(macQueuePollPath, { headers: secondSessionHeaders })));
assert.ok(macQueuePolls.some(response => response.status === 429), 'The Mac queue poll must remain bounded.');
const rpcAfterQueueFlood = await fetch(secondSessionRelayPath, { headers: secondSessionHeaders });
assert.equal(rpcAfterQueueFlood.status, 200, 'A Mac queue poll flood must not block iPhone relay RPCs.');
const revokePairing = await fetch(sessionPath, { method: 'DELETE', headers: { authorization: `Bearer ${claim.sessionToken}` } });
assert.equal(revokePairing.status, 200);
const revokeSecondPairing = await fetch(`${base}/api/v1/pairing/sessions/${secondOffer.id}`, {
method: 'DELETE', headers: { authorization: `Bearer ${secondClaim.sessionToken}` }
});
assert.equal(revokeSecondPairing.status, 200);
const afterUnpair = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8'));
assert.equal(afterUnpair.pushDevices[offer.id], undefined);
assert.equal(afterUnpair.pushEvents[offer.id], undefined);
const revokedStatus = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
assert.equal(revokedStatus.status, 404);
});