diff --git a/CHANGELOG.md b/CHANGELOG.md index a52aad6e..6161122d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ ### Fixed - **NATS operator rotation on Kubernetes** — resolver reconciliation writes the new operator JWT into `iofog-nats-config` when that line differs. The NATS image reloads `server.conf`. The `nats` StatefulSet is not rolled for this change. +- **Embedded OIDC token call** — the Controller's own authorization-code exchange dials `127.0.0.1` on the API port instead of the public issuer. The browser still uses the public HTTPS URL. When the listener is HTTPS, the loopback connection pins the listener certificate. When the listener is HTTP, including dev mode with TLS files set, the dial is plain HTTP. External issuers are unchanged. +- **WebSocket per-address limits behind a proxy** — the connection cap and the handshake cap use the same hop count as `TRUST_PROXY`. `true` is one hop, the address the closest proxy appended. A hop count, including `"2"`, trusts that many hops. With trust-proxy off, `X-Forwarded-For` is ignored. Closing the socket frees that same address. ### Changed @@ -21,6 +23,7 @@ - **`@google-cloud/secret-manager` ^6.1.1 → ^7.2.0** — drop production `glob` 10.5.0 and nested `minimatch` 9.0.9 pulled in through `google-gax` 5 and `rimraf` 5 (GHSA-3g3m-2fjr-6pw4, GHSA-g3hv-75wg-m249). Secret Manager client calls are unchanged. The same advisories remain on dev-only `mocha`, `nyc`, and `sequelize-cli`. `better-npm-audit audit -p` is clean. - Dockerfile base image digest pins refreshed for **`node:24-bookworm`** (console-builder and builder) and **`ubi9/nodejs-24-minimal`**. - Embedded **EdgeOps Console** default **v1.1.3 → v1.1.4** +- **`node-forge` ^1.4.2 → ^1.4.3**. ### Unchanged diff --git a/Dockerfile b/Dockerfile index db54fe5a..1a6489e8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,7 +2,7 @@ # ioFog overrides: EDGEOPS_CONSOLE_REPO=https://github.com/eclipse-iofog/edgeops-console # EDGEOPS_CONSOLE_FLAVOR=iofog # node:24-bookworm — pin manifest list digest for reproducible multi-arch builds -FROM node:24-bookworm@sha256:8fa96264f302f58bbb13aa7339c541547b56975766ce956c875da149452a3e40 AS console-builder +FROM node:24-bookworm@sha256:9d266751ca3d7fdbe651c878ffd5ad0a42fed49a18c283509267c97f025b7496 AS console-builder ARG EDGEOPS_CONSOLE_REPO=https://github.com/Datasance/edgeops-console ARG EDGEOPS_CONSOLE_VERSION=v1.1.4 @@ -28,7 +28,7 @@ RUN test -f build/index.html \ && cp -a build /tmp/console/build -FROM node:24-bookworm@sha256:8fa96264f302f58bbb13aa7339c541547b56975766ce956c875da149452a3e40 AS builder +FROM node:24-bookworm@sha256:9d266751ca3d7fdbe651c878ffd5ad0a42fed49a18c283509267c97f025b7496 AS builder ARG PKG_VERSION @@ -48,7 +48,7 @@ RUN npm pack # ubi9/nodejs-24-minimal:latest — pin manifest list digest for reproducible multi-arch builds -FROM registry.access.redhat.com/ubi9/nodejs-24-minimal@sha256:da724df0db4baceb0b89ebdc160dfe330fe3b215925742ee9e65efdfc6038850 +FROM registry.access.redhat.com/ubi9/nodejs-24-minimal@sha256:94e1482b6fe50b5a99692d4cea62309b54201f405d12766f2ebe37ab49692f29 ARG EDGEOPS_CONSOLE_VERSION=v1.1.4 ARG IMAGE_REGISTRY diff --git a/package-lock.json b/package-lock.json index 972dc344..519a57b3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -51,7 +51,7 @@ "mysql2": "3.23.1", "nconf": "0.12.1", "node-fetch-npm": "^2.0.4", - "node-forge": "^1.4.2", + "node-forge": "^1.4.3", "oidc-provider": "^9.11.3", "openid-client": "^6.8.4", "otplib": "^13.4.1", @@ -59,6 +59,7 @@ "pino": "9.13.1", "pino-std-serializers": "7.0.0", "portscanner": "2.2.0", + "proxy-addr": "2.0.8", "qs": "6.16.1", "rhea": "^3.0.4", "sequelize": "6.37.8", @@ -9623,9 +9624,9 @@ } }, "node_modules/node-forge": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.2.tgz", - "integrity": "sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==", + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", + "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==", "license": "(BSD-3-Clause OR GPL-2.0)", "engines": { "node": ">= 6.13.0" diff --git a/package.json b/package.json index 7a6d0f3e..000634b9 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "@nats-io/transport-node": "^3.4.0", "nconf": "0.12.1", "node-fetch-npm": "^2.0.4", - "node-forge": "^1.4.2", + "node-forge": "^1.4.3", "oidc-provider": "^9.11.3", "openid-client": "^6.8.4", "otplib": "^13.4.1", @@ -126,6 +126,7 @@ "pino": "9.13.1", "pino-std-serializers": "7.0.0", "portscanner": "2.2.0", + "proxy-addr": "2.0.8", "qs": "6.16.1", "rhea": "^3.0.4", "sequelize": "6.37.8", diff --git a/src/config/oidc-fetch.js b/src/config/oidc-fetch.js index d0508e6f..d4307966 100644 --- a/src/config/oidc-fetch.js +++ b/src/config/oidc-fetch.js @@ -1,16 +1,27 @@ const https = require('https') const tls = require('tls') -const { Agent, fetch: undiciFetch } = require('undici') +const { X509Certificate } = require('crypto') +const { Agent, buildConnector, fetch: undiciFetch } = require('undici') const config = require('./index') +const { getPublicUrl } = require('./auth-urls') const { loadCertificate } = require('../utils/ssl-utils') -const { getListenerTlsMaterial, getListenerTrustCaBuffers } = require('../utils/tls-config') +const { getListenerTlsMaterial } = require('../utils/tls-config') + +const LOOPBACK_HOST = '127.0.0.1' -let cachedFetch let cachedExternalFetch let cachedExternalCaKey +const loopbackAgents = new Map() function resetEmbeddedOidcFetchForTests () { - cachedFetch = undefined + for (const agent of loopbackAgents.values()) { + try { + agent.destroy() + } catch { + // Agent cleanup is best-effort between tests. + } + } + loopbackAgents.clear() } function resetExternalOidcFetchForTests () { @@ -83,32 +94,121 @@ function createExternalIssuerHttpsAgent (caBuffer) { }) } -function createEmbeddedOidcFetch () { - const material = getListenerTlsMaterial() - if (!material.enabled) { - return undefined +function getApiListenPort () { + return String(process.env.API_PORT || config.get('server.port')) +} + +function embeddedIssuerUrl () { + const publicUrl = getPublicUrl() + if (!publicUrl) { + return null } + try { + return new URL(`${publicUrl}/oidc`) + } catch { + return null + } +} - const caBuffers = getListenerTrustCaBuffers(material) - if (!caBuffers?.length) { - return undefined +function isEmbeddedIssuerUrl (target, issuer) { + const issuerPath = issuer.pathname.replace(/\/$/, '') + return target.origin === issuer.origin && + (target.pathname === issuerPath || target.pathname.startsWith(`${issuerPath}/`)) +} + +// Browser and discovery URLs stay on CONTROLLER_PUBLIC_URL. This process dials +// its own listener instead, so embedded token and JWKS calls do not hairpin +// through ingress TLS. +function rewriteEmbeddedBackchannelUrl (input) { + const target = new URL(typeof input === 'string' ? input : String(input)) + const issuer = embeddedIssuerUrl() + if (!issuer || !isEmbeddedIssuerUrl(target, issuer)) { + return { href: target.href, local: false, tls: false } } - if (!cachedFetch) { - const agent = new Agent({ - connect: { - ca: caBuffers, - rejectUnauthorized: true + const material = getListenerTlsMaterial() + target.protocol = material.enabled ? 'https:' : 'http:' + target.hostname = LOOPBACK_HOST + target.port = getApiListenPort() + return { href: target.href, local: true, tls: material.enabled === true } +} + +function readListenerLeafFingerprint (material) { + const leaf = loadCertificate(material.cert, material.isBase64) + return new X509Certificate(leaf).fingerprint256 +} + +function createLoopbackTlsAgent (expectedFingerprint) { + const connector = buildConnector({ rejectUnauthorized: false }) + return new Agent({ + connect (opts, callback) { + const hostname = opts.hostname || opts.host + if (hostname !== LOOPBACK_HOST) { + callback(new Error('embedded loopback agent refused a non-local connection')) + return } - }) - cachedFetch = (url, init) => undiciFetch(url, { ...init, dispatcher: agent }) + + connector({ ...opts, rejectUnauthorized: false }, (err, socket) => { + if (err) { + callback(err) + return + } + + let peerFingerprint = '' + try { + peerFingerprint = socket.getPeerCertificate().fingerprint256 || '' + } catch (error) { + socket.destroy() + callback(error) + return + } + + if (!peerFingerprint || peerFingerprint !== expectedFingerprint) { + socket.destroy() + callback(new Error('loopback certificate does not match the listener certificate')) + return + } + + callback(null, socket) + }) + } + }) +} + +function getLoopbackAgent (fingerprint) { + let agent = loopbackAgents.get(fingerprint) + if (!agent) { + agent = createLoopbackTlsAgent(fingerprint) + loopbackAgents.set(fingerprint, agent) } + return agent +} + +function createEmbeddedOidcFetch () { + return function embeddedOidcFetch (url, init) { + const rewritten = rewriteEmbeddedBackchannelUrl(url) + if (!rewritten.local || !rewritten.tls) { + return undiciFetch(rewritten.href, init) + } - return cachedFetch + const material = getListenerTlsMaterial() + let fingerprint + try { + fingerprint = readListenerLeafFingerprint(material) + } catch (error) { + return Promise.reject(error) + } + + return undiciFetch(rewritten.href, { + ...init, + dispatcher: getLoopbackAgent(fingerprint) + }) + } } module.exports = { createEmbeddedOidcFetch, + rewriteEmbeddedBackchannelUrl, resetEmbeddedOidcFetchForTests, hasExternalIssuerCaConfig, getExternalIssuerCaBuffer, diff --git a/src/websocket/client-ip.js b/src/websocket/client-ip.js new file mode 100644 index 00000000..8d37de01 --- /dev/null +++ b/src/websocket/client-ip.js @@ -0,0 +1,30 @@ +'use strict' + +const proxyaddr = require('proxy-addr') +const { getTrustProxySetting } = require('../config/trust-proxy') + +function normalizeIp (ip) { + if (ip && ip.startsWith('::ffff:')) return ip.slice(7) + return ip || 'unknown' +} + +function hopCount (trust) { + if (!trust) return 0 + if (trust === true) return 1 + const hops = Number(trust) + if (!Number.isInteger(hops) || hops < 1) return 0 + return hops +} + +function websocketClientIp (req) { + const socketIp = req && req.socket && req.socket.remoteAddress + const hops = hopCount(getTrustProxySetting()) + if (!hops) return normalizeIp(socketIp) + return normalizeIp(proxyaddr(req, function (address, index) { + return index < hops + })) +} + +module.exports = { + websocketClientIp +} diff --git a/src/websocket/server.js b/src/websocket/server.js index 10c248a1..c590b435 100644 --- a/src/websocket/server.js +++ b/src/websocket/server.js @@ -30,6 +30,7 @@ const FogManager = require('../data/managers/iofog-manager') const FogStates = require('../enums/fog-state') const Sequelize = require('sequelize') const Op = Sequelize.Op +const { websocketClientIp } = require('./client-ip') const MESSAGE_TYPES = { STDIN: 0, @@ -1498,8 +1499,9 @@ class WebSocketServer { return } - // Check connection limits - const clientIp = info.req.socket.remoteAddress + // Check connection limits. Behind a trusted proxy this is the forwarded + // client, using the same hop count Express uses for req.ip. + const clientIp = websocketClientIp(info.req) const currentConnections = this.connectionLimits.get(clientIp) || 0 if (currentConnections >= (process.env.WS_SECURITY_MAX_CONNECTIONS_PER_IP || config.get('server.webSocket.security.maxConnectionsPerIp'))) { callback(new Error('Too many connections'), false) @@ -1540,7 +1542,7 @@ class WebSocketServer { } trackConnectionLimit (ws, req) { - const clientIp = req.socket.remoteAddress + const clientIp = websocketClientIp(req) let released = false const release = () => { if (released) return diff --git a/test/src/config/oidc.test.js b/test/src/config/oidc.test.js index cdff275c..f057ccd0 100644 --- a/test/src/config/oidc.test.js +++ b/test/src/config/oidc.test.js @@ -286,7 +286,28 @@ describe('OIDC config', () => { }) }) - it('attaches listener TLS trust for embedded HTTPS without NODE_EXTRA_CA_CERTS', async () => { + it('rewrites only issuer paths onto the API listen port', () => { + const { rewriteEmbeddedBackchannelUrl } = require('../../../src/config/oidc-fetch') + process.env.CONTROLLER_PUBLIC_URL = 'https://controller.example.com' + process.env.API_PORT = '51121' + + try { + expect(rewriteEmbeddedBackchannelUrl('https://controller.example.com/oidc/token?x=1')) + .to.deep.equal({ + href: 'http://127.0.0.1:51121/oidc/token?x=1', + local: true, + tls: false + }) + expect(rewriteEmbeddedBackchannelUrl('https://controller.example.com/oidc-extra').local) + .to.equal(false) + expect(rewriteEmbeddedBackchannelUrl('https://idp.example.com/oidc/token').local) + .to.equal(false) + } finally { + delete process.env.API_PORT + } + }) + + it('dials the API loopback for embedded HTTPS and keeps the public issuer', async () => { const path = require('path') const https = require('https') const oidcClient = require('openid-client') @@ -300,9 +321,10 @@ describe('OIDC config', () => { intermedKey: path.join(certDir, 'ca.crt'), isBase64: false }) + const seen = [] applyEmbeddedEnv({ - CONTROLLER_PUBLIC_URL: 'https://localhost:0', + CONTROLLER_PUBLIC_URL: 'https://controller.example.com', OIDC_CLIENT_SECRET: 'embedded-oauth-test-secret' }) @@ -320,15 +342,16 @@ describe('OIDC config', () => { const server = await new Promise((resolve, reject) => { const listener = https.createServer(sslOptions, (req, res) => { + seen.push({ url: req.url, method: req.method, encrypted: Boolean(req.socket.encrypted) }) res.writeHead(200, { 'content-type': 'application/json' }) - res.end(JSON.stringify({ issuer: 'https://localhost:0/oidc' })) + res.end('{}') }) - listener.listen(0, 'localhost', () => resolve(listener)) + listener.listen(0, '127.0.0.1', () => resolve(listener)) listener.on('error', reject) }) const { port } = server.address() - process.env.CONTROLLER_PUBLIC_URL = `https://localhost:${port}` + process.env.API_PORT = String(port) try { resetEmbeddedOidcFetchForTests() @@ -336,15 +359,23 @@ describe('OIDC config', () => { oidc.initOidc() const clientConfig = await oidc.getOauthClientConfiguration() - expect(clientConfig.serverMetadata().issuer).to.equal(`https://localhost:${port}/oidc`) + expect(clientConfig.serverMetadata().issuer).to.equal('https://controller.example.com/oidc') + expect(clientConfig.serverMetadata().token_endpoint).to.equal('https://controller.example.com/oidc/token') const customFetch = clientConfig[oidcClient.customFetch] expect(customFetch).to.be.a('function') - const response = await customFetch( - `https://localhost:${port}/oidc/.well-known/openid-configuration` - ) + const response = await customFetch('https://controller.example.com/oidc/token', { + method: 'POST', + headers: { authorization: 'Basic test-secret' }, + body: 'grant_type=authorization_code' + }) expect(response.status).to.equal(200) + expect(seen).to.deep.equal([{ + url: '/oidc/token', + method: 'POST', + encrypted: true + }]) } finally { await new Promise((resolve, reject) => { server.close((error) => (error ? reject(error) : resolve())) @@ -352,6 +383,179 @@ describe('OIDC config', () => { delete process.env.TLS_PATH_KEY delete process.env.TLS_PATH_CERT delete process.env.TLS_PATH_INTERMEDIATE_CERT + delete process.env.API_PORT + resetEmbeddedOidcFetchForTests() + } + }) + + it('rejects a loopback peer that is not the listener certificate', async () => { + const fs = require('fs') + const os = require('os') + const path = require('path') + const https = require('https') + const { execFileSync } = require('child_process') + const oidcClient = require('openid-client') + const { createSSLOptions } = require('../../../src/utils/ssl-utils') + const { resetEmbeddedOidcFetchForTests } = require('../../../src/config/oidc-fetch') + + const otherDir = fs.mkdtempSync(path.join(os.tmpdir(), 'oidc-loopback-')) + const otherKey = path.join(otherDir, 'key.pem') + const otherCert = path.join(otherDir, 'cert.pem') + execFileSync('openssl', [ + 'req', '-x509', '-newkey', 'rsa:2048', + '-keyout', otherKey, + '-out', otherCert, + '-days', '1', + '-nodes', + '-subj', '/CN=other-listener' + ], { stdio: 'ignore' }) + + const certDir = path.join(__dirname, '../../tls-cert') + const sslOptions = createSSLOptions({ + key: path.join(certDir, 'tls.key'), + cert: path.join(certDir, 'tls.crt'), + isBase64: false + }) + + applyEmbeddedEnv({ + CONTROLLER_PUBLIC_URL: 'https://controller.example.com', + OIDC_CLIENT_SECRET: 'embedded-oauth-test-secret' + }) + + const originalGetBoolean = config.getBoolean.bind(config) + $sandbox.stub(config, 'getBoolean').callsFake((key, defaultValue = false) => { + if (key === 'server.devMode') { + return false + } + return originalGetBoolean(key, defaultValue) + }) + + process.env.TLS_PATH_KEY = otherKey + process.env.TLS_PATH_CERT = otherCert + + const server = await new Promise((resolve, reject) => { + const listener = https.createServer(sslOptions, (req, res) => { + res.writeHead(200) + res.end('{}') + }) + listener.listen(0, '127.0.0.1', () => resolve(listener)) + listener.on('error', reject) + }) + + process.env.API_PORT = String(server.address().port) + + try { + resetEmbeddedOidcFetchForTests() + const oidc = reloadOidcModule() + oidc.initOidc() + const clientConfig = await oidc.getOauthClientConfiguration() + const customFetch = clientConfig[oidcClient.customFetch] + + let error + try { + await customFetch('https://controller.example.com/oidc/jwks') + } catch (err) { + error = err + } + + const message = `${error && error.message} ${error && error.cause && error.cause.message}` + expect(message).to.match(/loopback certificate does not match the listener certificate/) + } finally { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + delete process.env.TLS_PATH_KEY + delete process.env.TLS_PATH_CERT + delete process.env.API_PORT + fs.rmSync(otherDir, { recursive: true, force: true }) + resetEmbeddedOidcFetchForTests() + } + }) + + it('dials plain loopback when the listener is HTTP, including dev mode with TLS files set', async () => { + const http = require('http') + const path = require('path') + const oidcClient = require('openid-client') + const { resetEmbeddedOidcFetchForTests } = require('../../../src/config/oidc-fetch') + + const seen = [] + const server = await new Promise((resolve, reject) => { + const listener = http.createServer((req, res) => { + seen.push({ + url: req.url, + method: req.method, + authorization: req.headers.authorization || '', + encrypted: Boolean(req.socket.encrypted) + }) + res.writeHead(200, { 'content-type': 'application/json' }) + res.end('{}') + }) + listener.listen(0, '127.0.0.1', () => resolve(listener)) + listener.on('error', reject) + }) + + const foreignSeen = [] + const foreign = await new Promise((resolve, reject) => { + const listener = http.createServer((req, res) => { + foreignSeen.push(req.url) + res.writeHead(200, { 'content-type': 'text/plain' }) + res.end('foreign') + }) + listener.listen(0, '127.0.0.1', () => resolve(listener)) + listener.on('error', reject) + }) + + const certDir = path.join(__dirname, '../../tls-cert') + process.env.TLS_PATH_KEY = path.join(certDir, 'tls.key') + process.env.TLS_PATH_CERT = path.join(certDir, 'tls.crt') + process.env.API_PORT = String(server.address().port) + + applyEmbeddedEnv({ + CONTROLLER_PUBLIC_URL: 'https://controller.example.com', + OIDC_CLIENT_SECRET: 'embedded-oauth-test-secret' + }) + + try { + resetEmbeddedOidcFetchForTests() + const oidc = reloadOidcModule() + oidc.initOidc() + const clientConfig = await oidc.getOauthClientConfiguration() + expect(clientConfig.serverMetadata().token_endpoint).to.equal('https://controller.example.com/oidc/token') + + const customFetch = clientConfig[oidcClient.customFetch] + const tokenResponse = await customFetch('https://controller.example.com/oidc/token', { + method: 'POST', + headers: { authorization: 'Basic test-secret' }, + body: 'grant_type=authorization_code' + }) + const jwksResponse = await customFetch('https://controller.example.com/oidc/jwks') + const foreignResponse = await customFetch(`http://127.0.0.1:${foreign.address().port}/health`) + + expect(tokenResponse.status).to.equal(200) + expect(jwksResponse.status).to.equal(200) + expect(await foreignResponse.text()).to.equal('foreign') + expect(seen).to.deep.equal([ + { + url: '/oidc/token', + method: 'POST', + authorization: 'Basic test-secret', + encrypted: false + }, + { + url: '/oidc/jwks', + method: 'GET', + authorization: '', + encrypted: false + } + ]) + expect(foreignSeen).to.deep.equal(['/health']) + } finally { + await Promise.all([server, foreign].map((listener) => new Promise((resolve, reject) => { + listener.close((error) => (error ? reject(error) : resolve())) + }))) + delete process.env.TLS_PATH_KEY + delete process.env.TLS_PATH_CERT + delete process.env.API_PORT resetEmbeddedOidcFetchForTests() } }) diff --git a/test/src/websocket/ws-security.test.js b/test/src/websocket/ws-security.test.js index ab77168b..42713ae9 100644 --- a/test/src/websocket/ws-security.test.js +++ b/test/src/websocket/ws-security.test.js @@ -273,6 +273,173 @@ describe('WebSocket session security', () => { }) }) + describe('upgrade client address behind a proxy', () => { + let wsServer + let config + let originalGet + let trustProxy + + beforeEach(() => { + resetWebSocketServerSingleton(WebSocketServerClass) + wsServer = new WebSocketServerClass() + config = require('../../../src/config') + originalGet = config.get.bind(config) + trustProxy = false + config.get = (key, defaultValue) => { + if (key === 'server.trustProxy') return trustProxy + return originalGet(key, defaultValue) + } + }) + + afterEach(() => { + config.get = originalGet + }) + + function setTrust (value) { + trustProxy = value + } + + function upgrade (socketIp, forwardedFor) { + const headers = {} + if (forwardedFor !== undefined) headers['x-forwarded-for'] = forwardedFor + return { headers, socket: { remoteAddress: socketIp } } + } + + it('ignores X-Forwarded-For when trust proxy is off', (done) => { + setTrust(false) + const configModule = require('../../../src/config') + const maxConnections = configModule.get('server.webSocket.security.maxConnectionsPerIp') + const req = upgrade('10.0.0.8', '203.0.113.5') + wsServer.connectionLimits.set('203.0.113.5', maxConnections) + + wsServer.verifyClient({ req }, (err, ok) => { + if (err && err.message.match(/Too many connections/i)) return done(err) + expect(ok).to.equal(true) + expect(wsServer.connectionLimits.get('10.0.0.8')).to.equal(1) + expect(wsServer.connectionLimits.get('203.0.113.5')).to.equal(maxConnections) + + wsServer.connectionLimits.set('10.0.0.8', maxConnections) + wsServer.verifyClient({ req }, (limitErr, limited) => { + expect(limited).to.equal(false) + expect(limitErr.message).to.match(/Too many connections/i) + done() + }) + }) + }) + + it('counts the forwarded client when trust proxy trusts one hop', (done) => { + setTrust(true) + const maxConnections = config.get('server.webSocket.security.maxConnectionsPerIp') + const ingress = upgrade('10.0.0.8', '203.0.113.5') + const otherClient = upgrade('10.0.0.8', '203.0.113.6') + let accepted = 0 + + function next () { + if (accepted === maxConnections) { + wsServer.verifyClient({ req: ingress }, (err, ok) => { + expect(ok).to.equal(false) + expect(err.message).to.match(/Too many connections/i) + wsServer.verifyClient({ req: otherClient }, (otherErr, otherOk) => { + if (otherErr) return done(otherErr) + expect(otherOk).to.equal(true) + expect(wsServer.connectionLimits.get('203.0.113.5')).to.equal(maxConnections) + expect(wsServer.connectionLimits.get('203.0.113.6')).to.equal(1) + expect(wsServer.connectionLimits.has('10.0.0.8')).to.equal(false) + done() + }) + }) + return + } + wsServer.verifyClient({ req: ingress }, (err, ok) => { + if (err) return done(err) + expect(ok).to.equal(true) + accepted++ + next() + }) + } + + next() + }) + + it('uses the address the closest proxy appended, not the leftmost header value', (done) => { + setTrust(true) + const maxConnections = config.get('server.webSocket.security.maxConnectionsPerIp') + const req = upgrade('10.0.0.8', '1.1.1.1, 203.0.113.5') + wsServer.connectionLimits.set('1.1.1.1', maxConnections) + + wsServer.verifyClient({ req }, (err, ok) => { + if (err) return done(err) + expect(ok).to.equal(true) + expect(wsServer.connectionLimits.get('203.0.113.5')).to.equal(1) + + wsServer.connectionLimits.set('203.0.113.5', maxConnections) + wsServer.verifyClient({ req }, (limitErr, limited) => { + expect(limited).to.equal(false) + expect(limitErr.message).to.match(/Too many connections/i) + done() + }) + }) + }) + + it('trusts a numeric hop count, including a numeric string', (done) => { + setTrust('2') + const maxConnections = config.get('server.webSocket.security.maxConnectionsPerIp') + const req = upgrade('10.0.0.8', '203.0.113.5, 10.1.1.1') + wsServer.connectionLimits.set('10.1.1.1', maxConnections) + + wsServer.verifyClient({ req }, (err, ok) => { + if (err) return done(err) + expect(ok).to.equal(true) + expect(wsServer.connectionLimits.get('203.0.113.5')).to.equal(1) + expect(wsServer.connectionLimits.get('10.1.1.1')).to.equal(maxConnections) + done() + }) + }) + + it('releases the same address it counted when the socket closes', (done) => { + setTrust(true) + const req = upgrade('10.0.0.8', '203.0.113.5') + let release + const ws = { + once (event, fn) { + if (event === 'close') release = fn + } + } + + wsServer.verifyClient({ req }, (err, ok) => { + if (err) return done(err) + expect(ok).to.equal(true) + expect(wsServer.connectionLimits.get('203.0.113.5')).to.equal(1) + wsServer.trackConnectionLimit(ws, req) + release() + expect(wsServer.connectionLimits.has('203.0.113.5')).to.equal(false) + done() + }) + }) + + it('normalizes an IPv4-mapped socket address so close frees the slot', (done) => { + setTrust(false) + const req = upgrade('::ffff:10.0.0.8') + let release + const ws = { + once (event, fn) { + if (event === 'close') release = fn + } + } + + wsServer.verifyClient({ req }, (err, ok) => { + if (err) return done(err) + expect(ok).to.equal(true) + expect(wsServer.connectionLimits.get('10.0.0.8')).to.equal(1) + expect(wsServer.connectionLimits.has('::ffff:10.0.0.8')).to.equal(false) + wsServer.trackConnectionLimit(ws, req) + release() + expect(wsServer.connectionLimits.has('10.0.0.8')).to.equal(false) + done() + }) + }) + }) + describe('agent message blocked before auth', () => { it('does not attach message handler until agent validation succeeds', async () => { resetWebSocketServerSingleton(WebSocketServerClass)