Commitb5426aaaRecorded18 Oct 2026Repositorysigil-nat

Enforce requested lease bounds and verify owned mapping cleanup

Changed
 tools/nat/lease.mjs          |  15 +++++++++------
 tools/nat/socket-cleanup.mjs |  18 ++++++++++++++++++
 tools/nat/test-lease.mjs     | 135 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 tools/nat/test-upnp.mjs      |  76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 tools/nat/upnp.mjs           |  21 ++++++++++++---------
 5 files changed, 249 insertions(+), 16 deletions(-)
Diff
tools/nat/lease.mjsmodified
@@ -69,11 +69,12 @@ export class SingleUdpLease {
69
if (seconds < 1 || this.stopping) throw new Error('Mapping run deadline reached or stopping');
70
return seconds;
71
}
−72
async accept(response) {
+72
async accept(response, requestedLifetime) {
73
// A success reply may describe an unacceptable lease. Preserve that state
74
// for deletion rather than treating it as a clean rejection/fallback.
75
await this.record('uncertain', { mapping: response });
−76
if (!Number.isInteger(response.lifetime) || response.lifetime < 1 || response.lifetime > 1800 ||
+76
if (!Number.isInteger(response.lifetime) || response.lifetime < 1 || response.lifetime > requestedLifetime ||
+77
response.lifetime * 1000 > this.deadline - this.now() ||
78
!Number.isInteger(response.externalPort) || response.externalPort < 1 || response.externalPort > 65535 ||
79
typeof response.externalAddress !== 'string')
80
throw new MappingUncertain('Router granted an invalid or over-cap mapping');
@@ -82,11 +83,13 @@ export class SingleUdpLease {
83
}
84
async removeOwned() {
85
if (!this.current) return;
−85
await this.record('deleting');
+86
// A full disk must not prevent the network cleanup of an owned mapping.
+87
try { await this.record('deleting'); }
+88
catch { /* State was retained in memory; still attempt deletion. */ }
89
try {
90
const response = await this.current.exchange(0, this.state.mapping);
91
if (response.lifetime !== 0) throw new Error('Deletion did not acknowledge zero lifetime');
−89
await this.record('deleted');
+92
await this.record('deleted', { deletion: response });
93
} catch (error) {
94
await this.record('uncertain', { error: `Deletion unconfirmed: ${error.message}` });
95
throw new MappingUncertain(this.state.error);
@@ -113,7 +116,7 @@ export class SingleUdpLease {
116
continue;
117
}
118
try {
−116
const active = await this.accept(response);
+119
const active = await this.accept(response, lifetime);
120
if (this.stopping) {
121
await this.removeOwned();
122
throw new Error('Lease stopped during creation');
@@ -135,7 +138,7 @@ export class SingleUdpLease {
138
try {
139
const lifetime = this.requestedLifetime();
140
await this.record('renewing');
−138
return await this.accept(await this.current.exchange(lifetime, this.state.mapping));
+141
return await this.accept(await this.current.exchange(lifetime, this.state.mapping), lifetime);
142
} catch (error) {
143
await this.record('uncertain', { error: `Renewal failed: ${error.message}` });
144
await this.removeOwned();
tools/nat/socket-cleanup.mjsadded
@@ -0,0 +1,18 @@
+1
// Memoize shutdown before asking dgram to close: callbacks, signals and error
+2
// paths can all request cleanup concurrently. Resolve only after socket close.
+3
const closing = new WeakMap();
+4
export function closeUdpSocket(socket) {
+5
if (closing.has(socket)) return closing.get(socket);
+6
let done;
+7
let failed;
+8
const result = new Promise((resolve, reject) => { done = resolve; failed = reject; });
+9
closing.set(socket, result);
+10
socket.once('close', done);
+11
try { socket.close(); }
+12
catch (error) {
+13
socket.off('close', done);
+14
if (error.code === 'ERR_SOCKET_DGRAM_NOT_RUNNING') done();
+15
else failed(error);
+16
}
+17
return result;
+18
}
tools/nat/test-lease.mjsadded
@@ -0,0 +1,135 @@
+1
import assert from 'node:assert/strict';
+2
import { test } from 'node:test';
+3
import { createSocket } from 'node:dgram';
+4
import { once } from 'node:events';
+5
import { SingleUdpLease, MappingRejected } from './lease.mjs';
+6
import { closeUdpSocket } from './socket-cleanup.mjs';
+7
+8
const mapping = { lifetime: 120, externalPort: 43123, externalAddress: '198.51.100.4' };
+9
const options = candidates => ({ candidates, deadline: 150000, now: () => 0 });
+10
const candidate = exchange => ({ protocol: 'fixture', identity: { owner: 'fixture' }, exchange });
+11
+12
test('an excessive grant is deleted before any fallback', async () => {
+13
const calls = [];
+14
const lease = new SingleUdpLease(options([candidate(async lifetime => {
+15
calls.push(lifetime);
+16
return { ...mapping, lifetime: lifetime ? 121 : 0 };
+17
})]));
+18
await assert.rejects(lease.create(), /over-cap/);
+19
assert.deepEqual(calls, [120, 0]);
+20
assert.equal(lease.state.phase, 'deleted');
+21
});
+22
+23
test('a lost create reply must be deleted before the next protocol', async () => {
+24
const calls = [];
+25
const first = candidate(async lifetime => {
+26
calls.push(['first', lifetime]);
+27
if (lifetime) throw new Error('lost reply');
+28
return { lifetime: 0 };
+29
});
+30
const second = candidate(async lifetime => {
+31
calls.push(['second', lifetime]);
+32
return { ...mapping, lifetime };
+33
});
+34
const lease = new SingleUdpLease(options([first, second]));
+35
await lease.create();
+36
await lease.close();
+37
assert.deepEqual(calls, [['first', 120], ['first', 0], ['second', 120], ['second', 0]]);
+38
});
+39
+40
test('unconfirmed deletion blocks fallback and remains uncertain', async () => {
+41
let fallback = false;
+42
const lease = new SingleUdpLease(options([
+43
candidate(async () => { throw new Error('network lost'); }),
+44
candidate(async () => { fallback = true; return mapping; }),
+45
]));
+46
await assert.rejects(lease.create(), /Deletion unconfirmed/);
+47
assert.equal(lease.state.phase, 'uncertain');
+48
assert.equal(fallback, false);
+49
});
+50
+51
test('a rejected request may fall back without pretending it created a lease', async () => {
+52
const calls = [];
+53
const lease = new SingleUdpLease(options([
+54
candidate(async lifetime => { calls.push(lifetime); throw new MappingRejected('unsupported'); }),
+55
candidate(async lifetime => ({ ...mapping, lifetime })),
+56
]));
+57
await lease.create();
+58
await lease.close();
+59
assert.deepEqual(calls, [120]);
+60
});
+61
+62
test('close during creation serializes deletion and repeated close is harmless', async () => {
+63
let release;
+64
let started;
+65
const beginning = new Promise(done => { started = done; });
+66
const calls = [];
+67
const lease = new SingleUdpLease(options([candidate(async lifetime => {
+68
calls.push(lifetime);
+69
if (!lifetime) return { lifetime: 0 };
+70
started();
+71
await new Promise(done => { release = done; });
+72
return mapping;
+73
})]));
+74
const creating = lease.create();
+75
const rejected = assert.rejects(creating, /stopped during creation/);
+76
await beginning;
+77
const closing = lease.close();
+78
release();
+79
await rejected;
+80
await closing;
+81
await lease.close();
+82
assert.deepEqual(calls, [120, 0]);
+83
assert.equal(lease.state.phase, 'deleted');
+84
});
+85
+86
test('renewal failure deletes the old owned mapping and cancels maintenance', async () => {
+87
const calls = [];
+88
const tasks = new Map();
+89
let id = 0;
+90
const lease = new SingleUdpLease({ ...options([candidate(async lifetime => {
+91
calls.push(lifetime);
+92
if (calls.length === 2) throw new Error('renewal reply lost');
+93
return { ...mapping, lifetime };
+94
})]), schedule: (callback, delay) => { tasks.set(++id, { callback, delay }); return id; },
+95
cancel: timer => tasks.delete(timer) });
+96
await lease.create();
+97
lease.maintain();
+98
assert.deepEqual([...tasks.values()].map(task => task.delay), [150000, 60000]);
+99
await assert.rejects(lease.renew(), /renewal reply lost/);
+100
await lease.close();
+101
assert.deepEqual(calls, [120, 120, 0]);
+102
assert.equal(tasks.size, 0);
+103
});
+104
+105
test('journal failure on teardown cannot suppress the delete request', async () => {
+106
let deleting = false;
+107
const lease = new SingleUdpLease({ ...options([candidate(async lifetime => {
+108
if (!lifetime) deleting = true;
+109
return { ...mapping, lifetime };
+110
})]), journal: state => { if (state.phase === 'deleting') throw new Error('disk full'); } });
+111
await lease.create();
+112
await lease.close();
+113
assert.equal(deleting, true);
+114
assert.equal(lease.state.phase, 'deleted');
+115
});
+116
+117
test('concurrent UDP cleanup waits for one close event and permits retry after close', async () => {
+118
const socket = createSocket('udp4');
+119
socket.bind(0, '127.0.0.1');
+120
await once(socket, 'listening');
+121
let closes = 0;
+122
socket.on('close', () => { closes += 1; });
+123
const first = closeUdpSocket(socket);
+124
const second = closeUdpSocket(socket);
+125
assert.equal(first, second);
+126
await Promise.all([first, second]);
+127
await closeUdpSocket(socket);
+128
assert.equal(closes, 1);
+129
});
+130
+131
test('cleanup of an unbound socket does not crash the error path', async () => {
+132
const socket = createSocket('udp4');
+133
await closeUdpSocket(socket);
+134
await closeUdpSocket(socket);
+135
});
tools/nat/test-upnp.mjsmodified
@@ -1,6 +1,6 @@
1
import assert from 'node:assert/strict';
2
import { test } from 'node:test';
−3
import { parseIgdDescription, upnpUdpCandidate } from './upnp.mjs';
+3
import { parseIgdDescription, upnpUdpCandidate, UpnpIgdClient } from './upnp.mjs';
4
5
6
const gateway = '192.0.2.1';
@@ -56,3 +56,77 @@ test('UPnP mapping candidate refuses an occupied port and excessive leases', asy
56
await assert.rejects(candidate.exchange(120), /unoccupied/);
57
await assert.rejects(candidate.exchange(1801), /30 minutes/);
58
});
+59
+60
function fakeGateway({ granted = 120, ignoredDelete = false, lostDeleteReply = false } = {}) {
+61
const entries = new Map();
+62
let deletes = 0;
+63
const client = {
+64
async getMapping(port) { return entries.get(port); },
+65
async addMapping(entry) {
+66
entries.set(entry.externalPort, { ...entry, enabled: '1', lifetime: granted });
+67
},
+68
async deleteMapping(port) {
+69
deletes += 1;
+70
if (!ignoredDelete) entries.delete(port);
+71
if (lostDeleteReply) throw new Error('lost delete reply');
+72
},
+73
};
+74
const candidate = upnpUdpCandidate(client, { internalPort: 43123,
+75
internalClient: '192.0.2.44', externalAddress: '198.51.100.4' });
+76
return { candidate, entries, deletes: () => deletes };
+77
}
+78
+79
test('delete success without actual absence is rejected', async () => {
+80
const gateway = fakeGateway({ ignoredDelete: true });
+81
const active = await gateway.candidate.exchange(120);
+82
await assert.rejects(gateway.candidate.exchange(0, active), /still exists/);
+83
assert.equal(gateway.entries.size, 1);
+84
});
+85
+86
test('foreign owner installed before cleanup is never deleted', async () => {
+87
const gateway = fakeGateway();
+88
const active = await gateway.candidate.exchange(120);
+89
gateway.entries.get(active.externalPort).description = 'foreign';
+90
await assert.rejects(gateway.candidate.exchange(0, active), /does not own/);
+91
assert.equal(gateway.deletes(), 0);
+92
});
+93
+94
test('owned disabled mappings remain eligible for verified cleanup', async () => {
+95
const gateway = fakeGateway();
+96
const active = await gateway.candidate.exchange(120);
+97
gateway.entries.get(active.externalPort).enabled = '0';
+98
const result = await gateway.candidate.exchange(0, active);
+99
assert.equal(result.absenceCode, 714);
+100
});
+101
+102
test('grant above the requested 120 seconds is refused and can be cleaned up', async () => {
+103
const gateway = fakeGateway({ granted: 121 });
+104
await assert.rejects(gateway.candidate.exchange(120), /bounded leased/);
+105
const result = await gateway.candidate.exchange(0);
+106
assert.equal(result.absenceCode, 714);
+107
assert.equal(gateway.deletes(), 1);
+108
});
+109
+110
test('lost delete replies are reconciled by explicit absence lookup', async () => {
+111
const gateway = fakeGateway({ lostDeleteReply: true });
+112
const active = await gateway.candidate.exchange(120);
+113
const result = await gateway.candidate.exchange(0, active);
+114
assert.equal(result.absenceCode, 714);
+115
assert.equal(gateway.entries.size, 0);
+116
});
+117
+118
test('only GetSpecificPortMappingEntry fault 714 counts as absence', async () => {
+119
const client = new UpnpIgdClient({ protocol: 'upnp-igd',
+120
serviceType: 'urn:schemas-upnp-org:service:WANIPConnection:1',
+121
controlUrl: `http://${gateway}:52869/control` }, { gateway, localAddress: '192.0.2.44' });
+122
let code = 714;
+123
client.action = async action => {
+124
assert.equal(action, 'GetSpecificPortMappingEntry');
+125
const error = new Error('SOAP failure');
+126
error.upnpCode = code;
+127
throw error;
+128
};
+129
assert.equal(await client.getMapping(43123), undefined);
+130
code = 501;
+131
await assert.rejects(client.getMapping(43123), /SOAP failure/);
+132
});
tools/nat/upnp.mjsmodified
@@ -114,9 +114,11 @@ function requestHttp(url, { gateway, localAddress, method, headers = {}, body =
114
const parts = [];
115
let length = 0;
116
let settled = false;
+117
const deadline = setTimeout(() => finish(new Error('UPnP HTTP absolute deadline')), 3000);
118
const finish = (error, response) => {
119
if (settled) return;
120
settled = true;
+121
clearTimeout(deadline);
122
socket.destroy();
123
if (error) reject(error); else resolve(response);
124
};
@@ -246,15 +248,14 @@ export function upnpUdpCandidate(client, { internalPort, internalClient, externa
248
randomPort = () => 49152 + randomBytes(2).readUInt16BE(0) % 16384 }) {
249
const owner = `sigil-nat:${randomBytes(12).toString('hex')}`;
250
let ownedPort;
−249
let current;
251
async function verifyOwned(port, requireBoundLease = true) {
252
const entry = await client.getMapping(port, 'UDP');
253
if (!entry) return undefined;
254
requireValue(entry.description === owner && entry.internalPort === internalPort &&
−254
entry.internalClient === internalClient && entry.enabled === '1',
+255
entry.internalClient === internalClient,
256
'UPnP port is occupied by a mapping this process does not own');
257
if (requireBoundLease)
−257
requireValue(Number.isInteger(entry.lifetime) && entry.lifetime >= 1 && entry.lifetime <= 1800,
+258
requireValue(entry.enabled === '1' && Number.isInteger(entry.lifetime) && entry.lifetime >= 1 && entry.lifetime <= 1800,
259
'UPnP router granted an invalid or over-cap lease');
260
return entry;
261
}
@@ -267,11 +268,14 @@ export function upnpUdpCandidate(client, { internalPort, internalClient, externa
268
ownedPort = port;
269
if (lifetime === 0) {
270
const entry = await verifyOwned(port, false);
−270
if (!entry) return { lifetime: 0 };
−271
await client.deleteMapping(port);
+271
if (!entry) return { lifetime: 0, externalPort: port, absenceCode: 714 };
+272
try { await client.deleteMapping(port); }
+273
catch (error) {
+274
// Lost delete replies are reconciled by the same 714 lookup below.
+275
if (await client.getMapping(port, 'UDP')) throw error;
+276
}
277
requireValue(!(await client.getMapping(port, 'UDP')), 'UPnP mapping still exists after deletion');
−273
current = undefined;
−274
return { lifetime: 0, externalPort: port, externalAddress };
+278
return { lifetime: 0, externalPort: port, externalAddress, absenceCode: 714 };
279
}
280
if (!previous) {
281
let free;
@@ -294,9 +298,8 @@ export function upnpUdpCandidate(client, { internalPort, internalClient, externa
298
if (!entry) throw error;
299
}
300
const entry = await verifyOwned(ownedPort);
−297
requireValue(entry && entry.lifetime > 0 && entry.lifetime <= 1800,
+301
requireValue(entry && entry.lifetime > 0 && entry.lifetime <= lifetime,
302
'UPnP did not install a bounded leased mapping');
−299
current = entry;
303
return { lifetime: entry.lifetime, externalPort: ownedPort, externalAddress };
304
},
305
};