fix(cctv): keep main's HLS leases and test them through the middleware

Drop the per-peer lease budget and the lease-to-address binding. Main's
keyless same-site gate already refuses cross-site media requests, while
the budget capped a shared address (Docker gateway, reverse proxy, NAT)
at 8 leases across both sessions and still let one address hold both.
A lease now keeps working when its viewer reconnects from a new address.

Add a middleware test that drives the HLS playlist, segment and DELETE
for viewers on one shared address, on distinct addresses and after an
address change, and fold the media cases (segment read, DELETE, no
catalog request) into the cross-site table test. Remove the redundant
puppeteer flag, the CURRENT-STATE paragraph and the changelog fragment,
which no longer describe a change.
This commit is contained in:
German Khokhlov committed 2026-11-19 19:59:01 +04:00
1 parent 90e464eb5a
commit 0699876e4e
8 files changed
+212 -162

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
// Live HLS through the real /api/cctv middleware: playlist, segment and
// release. HLS leases are random per-playback ids, not bound to the socket
// address, so viewers who share one address (a Docker bridge gateway, a reverse
// proxy, NAT) get the whole per-session budget, and a viewer whose address
// changes mid-playback keeps its lease.
//
// Run with: npm test (node --test)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cctvProxy } from '../../server/providers/cctv.js';
const camera = (id) => ({
id,
name: id,
lat: 30.27,
lon: -97.74,
feedType: 'hls',
url: `https://cams.upstream.invalid/${id}/list.m3u8`,
});
const PLAYLIST =
'#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:12\n#EXTINF:2,\na.ts\n#EXTINF:2,\nb.ts\n#EXTINF:2,\nc.ts\n';
const lease = (index) =>
`00000000-0000-4000-8000-${String(index).padStart(12, '0')}`;
/** Collects what a handler wrote, the way a Node ServerResponse would. */
function recordingResponse() {
const chunks = [];
let finished;
const done = new Promise((resolve) => {
finished = resolve;
});
const res = {
statusCode: 0,
headers: {},
writableEnded: false,
body: '',
writeHead(status, headers) {
res.statusCode = status;
res.headers = { ...res.headers, ...headers };
},
setHeader(name, value) {
res.headers[name] = value;
},
write(chunk) {
chunks.push(Buffer.from(chunk));
return true;
},
end(chunk) {
if (chunk) chunks.push(Buffer.from(chunk));
res.writableEnded = true;
res.body = Buffer.concat(chunks).toString('utf8');
finished();
},
on() {},
once() {},
emit() {},
destroy() {},
};
return { res, done };
}
/** Mount the provider over two HLS cameras whose upstream always answers. */
function mount(t) {
const before = {
json: process.env.CCTV_SOURCES_JSON,
file: process.env.CCTV_SOURCES_FILE,
austin: process.env.CCTV_FORCE_AUSTIN,
};
process.env.CCTV_SOURCES_JSON = JSON.stringify([
camera('cam-a'),
camera('cam-b'),
]);
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
process.env.CCTV_FORCE_AUSTIN = '0';
const nativeFetch = globalThis.fetch;
// The puller binds fetch when cctvProxy() creates it, so mock first.
globalThis.fetch = async (url) =>
new Response(String(url).endsWith('.m3u8') ? PLAYLIST : 'abc');
let handler;
const closers = [];
cctvProxy().configureServer({
httpServer: { on: (_event, fn) => closers.push(fn) },
middlewares: { use: (_route, fn) => (handler = fn) },
});
t.after(() => {
for (const fn of closers) fn();
globalThis.fetch = nativeFetch;
for (const [name, value] of [
['CCTV_SOURCES_JSON', before.json],
['CCTV_SOURCES_FILE', before.file],
['CCTV_FORCE_AUSTIN', before.austin],
]) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
});
return async (url, remoteAddress, method = 'GET') => {
const { res, done } = recordingResponse();
await handler(
{
url,
method,
headers: { host: 'localhost:4173', 'sec-fetch-site': 'same-origin' },
socket: { remoteAddress },
on() {},
},
res,
);
await done;
return res;
};
}
/** Open a playlist and return the first segment path it lists. */
async function openPlaylist(call, cameraId, leaseId, remoteAddress) {
const res = await call(`/media/${cameraId}?lease=${leaseId}`, remoteAddress);
assert.equal(res.statusCode, 200, `playlist ${cameraId} ${leaseId}`);
const segment = res.body
.split('\n')
.find((line) => line.startsWith('/api/cctv/media/'));
assert.ok(segment, 'the playlist lists a segment');
return segment.replace('/api/cctv', '');
}
test('viewers on distinct addresses open, read and release their own leases', async (t) => {
const call = mount(t);
const viewers = Array.from({ length: 9 }, (_, index) => ({
camera: index < 5 ? 'cam-a' : 'cam-b',
lease: lease(index),
// IPv4-mapped form, as a dual-stack listener reports it.
peer: `::ffff:192.168.1.${20 + index}`,
}));
for (const viewer of viewers)
viewer.segment = await openPlaylist(
call,
viewer.camera,
viewer.lease,
viewer.peer,
);
for (const viewer of viewers)
assert.equal((await call(viewer.segment, viewer.peer)).statusCode, 200);
for (const viewer of viewers) {
const release = await call(
`/media/${viewer.camera}?lease=${viewer.lease}`,
viewer.peer,
'DELETE',
);
assert.equal(release.statusCode, 204);
}
});
test('viewers behind one shared address get every session slot', async (t) => {
const call = mount(t);
const shared = '::ffff:172.17.0.1';
for (let index = 0; index < 8; index++)
await openPlaylist(call, 'cam-a', lease(index), shared);
const segment = await openPlaylist(call, 'cam-b', lease(8), shared);
assert.equal((await call(segment, shared)).statusCode, 200);
});
test('a lease keeps working after its viewer reconnects from another address', async (t) => {
const call = mount(t);
await openPlaylist(call, 'cam-a', lease(0), '192.168.1.20');
const segment = await openPlaylist(call, 'cam-a', lease(0), '192.168.1.21');
assert.equal((await call(segment, '192.168.1.21')).statusCode, 200);
const release = await call(
`/media/cam-a?lease=${lease(0)}`,
'192.168.1.21',
'DELETE',
);
assert.equal(release.statusCode, 204);
// Released from the new address: the same lease can no longer read segments.
assert.equal((await call(segment, '192.168.1.21')).statusCode, 404);
});
-37
View File
@@ -294,40 +294,3 @@ test('an abandoned consumer expires while a renewed consumer keeps the session',
assert.equal(entry.controller.signal.aborted, false);
await manager.shutdown();
});
test('client lease ownership covers refresh, segments and release, with a bounded client budget', async (t) => {
const manager = createHlsPuller({
limits: { ...HLS_LIMITS, leasesPerClient: 1, pollMs: 100000 },
fetchImpl: async (url) =>
new Response(url.endsWith('.m3u8') ? playlist : 'abc'),
});
t.after(() => manager.shutdown());
const entry = await manager.ensure('a', base, 'lease-a', 'peer-a');
await manager.waitReady(entry);
await assert.rejects(
manager.ensure('a', base, 'lease-a', 'peer-b'),
/another client/,
);
assert.equal(
manager.getSegment('a', entry.token, 0, 'lease-a', 'peer-b'),
null,
);
await assert.rejects(
manager.buildPlaylist(entry, 'a', 'lease-a', 'peer-b'),
/another client/,
);
manager.release('a', 'lease-a', 'peer-b');
assert.equal(entry.leases.size, 1);
await assert.rejects(
manager.ensure('b', base, 'lease-b', 'peer-a'),
/client lease capacity/,
);
assert.equal(
manager.stats().sessions,
1,
'failed admission reserves no session',
);
await manager.ensure('b', base, 'lease-b', 'peer-b');
manager.release('a', 'lease-a', 'peer-a');
assert.equal(entry.stopping, true);
});
+22 -54
View File
@@ -155,9 +155,9 @@ function mount(t, respond) {
});
assert.ok(handler, 'the CCTV provider must mount a middleware');
const call = async (path, headers = {}) => {
const call = async (path, headers = {}, method = 'GET') => {
const { res, done } = recordingResponse();
await handler({ url: path, headers, method: 'GET', on() {} }, res);
await handler({ url: path, headers, method, on() {} }, res);
await done;
return res;
};
@@ -401,24 +401,35 @@ test('every CCTV route refuses cross-site requests and admits the app itself', a
}),
);
const host = 'localhost:5173';
const paths = [
'/sources',
'/health',
`/stream/${STILL.id}`,
`/frame/${STILL.id}`,
`/media/${VIDEO.id}`,
const lease = '00000000-0000-4000-8000-000000000000';
const routes = [
['GET', '/sources'],
['GET', '/health'],
['GET', `/stream/${STILL.id}`],
['GET', `/frame/${STILL.id}`],
['GET', `/media/${VIDEO.id}`],
['GET', `/media/${VIDEO.id}/seg_0.ts?lease=${lease}`],
['DELETE', `/media/${VIDEO.id}?lease=${lease}`],
];
// A catalog refresh would fetch the live packs: a refused request must not
// start one.
process.env.CCTV_FORCE_AUSTIN = '1';
for (const headers of [
{ host, 'sec-fetch-site': 'cross-site' },
{ host, 'sec-fetch-site': 'same-site' },
{ host, origin: 'https://elsewhere.example' },
{ host, origin: 'null' },
])
for (const path of paths) {
const res = await app.call(path, headers);
assert.equal(res.statusCode, 403, `${path} ${JSON.stringify(headers)}`);
for (const [method, path] of routes) {
const res = await app.call(path, headers, method);
assert.equal(
res.statusCode,
403,
`${method} ${path} ${JSON.stringify(headers)}`,
);
}
assert.deepEqual(app.requests, [], 'a refused request reached an upstream');
process.env.CCTV_FORCE_AUSTIN = '0';
for (const headers of [
{ host, 'sec-fetch-site': 'same-origin' },
{ host, origin: `http://${host}` },
@@ -528,46 +539,3 @@ test('a forwarded same-origin request reaches every CCTV route but not the Stree
assert.equal(direct.body, 'street-view');
assert.equal(streetViewCalls(), 1);
});
test('cross-site media creation, segment reads and release fail before any catalog or media fetch', async (t) => {
let handler;
const originalFetch = globalThis.fetch;
let calls = 0;
globalThis.fetch = async () => {
calls++;
throw new Error('must not fetch');
};
t.after(() => {
globalThis.fetch = originalFetch;
});
cctvProxy().configureServer({
middlewares: {
use: (_path, fn) => {
handler = fn;
},
},
});
for (const headers of [
{ origin: 'https://foreign.example' },
{ origin: 'null' },
{ 'sec-fetch-site': 'cross-site' },
{ 'sec-fetch-site': 'same-site' },
]) {
for (const [method, url] of [
['GET', '/media/camera?lease=test'],
['DELETE', '/media/camera?lease=test'],
['GET', '/media/camera/seg_0.ts?lease=test'],
]) {
const { res } = recordingResponse();
res.setHeader = (name, value) => {
res.headers[name] = value;
};
await handler(
{ method, url, headers: { host: 'localhost:4173', ...headers } },
res,
);
assert.equal(res.statusCode, 403);
}
}
assert.equal(calls, 0);
});