From e83926fb7cd2a6324f5322860ce47a6f496f1baa Mon Sep 17 00:00:00 2001 From: Ben Francis Date: Fri, 4 Dec 2026 19:06:36 +0000 Subject: [PATCH] Implement BearerSecurityScheme - closes #30 --- README.md | 28 ++++ package-lock.json | 12 +- package.json | 3 +- src/thing-server.js | 260 +++++++++++++++++++++++++++++++++- src/thing.js | 5 +- src/types.js | 9 +- test/security.test.js | 314 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 620 insertions(+), 11 deletions(-) create mode 100644 test/security.test.js diff --git a/README.md b/README.md index 0e97ac8..4ac2aec 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,34 @@ secureServer.start(8443); The certificate and key must be obtained and renewed by your deployment; do not commit private keys to your project. Without `tls` options, the server continues to use HTTP. +To require JWT bearer authentication, define a bearer scheme in the partial Thing Description and configure trusted JWT verification keys when constructing the server: + +```javascript +const partialTD = { + title: 'Private Thing', + securityDefinitions: { + bearer_sc: { + scheme: 'bearer', + format: 'jwt', + alg: 'RS256', + }, + }, + security: 'bearer_sc', +}; + +const thing = new Thing(partialTD); +const server = new ThingServer(thing, { + jwt: { + issuer: 'https://issuer.example.com/', + audience: 'my-thing', + // Supply a static public JWKS, a JWKS URI, or both. + jwksUri: 'https://issuer.example.com/.well-known/jwks.json', + }, +}); +``` + +Consumers must send `Authorization: Bearer ` when accessing Thing interaction endpoints. `GET /` remains public so consumers can retrieve the Thing Description. Static keys can be supplied as a standard public JWKS using `jwt.jwks`; when both `jwks` and `jwksUri` are configured, static keys are checked first and remote keys are resolved on demand. The token signature, issuer, audience, and required expiration (`exp`) claim are verified. The server supports signed JWTs using asymmetric algorithms; if `alg` is omitted from the TD, the WoT default `ES256` is enforced. Remote JWKS URLs must use HTTPS, except for loopback addresses used in local development. Bearer JWTs should only be sent over HTTPS, either directly to the Thing Server or through a trusted TLS-terminating proxy. + ## Development ### Type Checking diff --git a/package-lock.json b/package-lock.json index 02cc3e7..7901acb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,8 @@ "license": "MPL-2.0", "dependencies": { "ajv": "^8.20.0", - "express": "^5.1.0" + "express": "^5.1.0", + "jose": "^6.2.19" }, "devDependencies": { "@eslint/js": "^10.0.1", @@ -1209,6 +1210,15 @@ "dev": true, "license": "ISC" }, + "node_modules/jose": { + "version": "6.2.19", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.19.tgz", + "integrity": "sha512-NnThKzdK4dJTUQOBoMB0bF3Xmw4EtbFTo4xzeLaoBwcuOdBVDQcKB3/86DUTWjVMXkZOdaqZVo2OU6DllhS+9Q==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/json-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", diff --git a/package.json b/package.json index 620e25d..5309a0d 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,8 @@ "homepage": "https://github.com/benfrancis/webthing-node-2#readme", "dependencies": { "ajv": "^8.20.0", - "express": "^5.1.0" + "express": "^5.1.0", + "jose": "^6.2.19" }, "devDependencies": { "@eslint/js": "^10.0.1", diff --git a/src/thing-server.js b/src/thing-server.js index 1ca3e55..1a395b0 100644 --- a/src/thing-server.js +++ b/src/thing-server.js @@ -1,23 +1,232 @@ import express from 'express'; import { createServer } from 'node:https'; +import { createLocalJWKSet, createRemoteJWKSet, errors, jwtVerify } from 'jose'; /** @typedef {import('./thing.js').default} Thing */ /** @typedef {express.Request} Request */ /** @typedef {express.Response} Response */ /** @typedef {import('node:https').ServerOptions} HttpsServerOptions */ -/** @typedef {{ tls?: HttpsServerOptions, domain?: string }} ThingServerOptions */ +/** @typedef {import('jose').JSONWebKeySet} JSONWebKeySet */ +const publicKeyJWTAlgorithms = new Set([ + 'ES256', + 'ES384', + 'ES512', + 'EdDSA', + 'Ed25519', + 'PS256', + 'PS384', + 'PS512', + 'RS256', + 'RS384', + 'RS512', +]); + +/** + * @typedef {{ + * issuer: string|Array, + * audience: string|Array, + * jwks?: JSONWebKeySet, + * jwksUri?: string|URL + * }} JWTVerificationOptions + */ +/** + * @typedef {{ + * tls?: HttpsServerOptions, + * domain?: string, + * jwt?: JWTVerificationOptions + * }} ThingServerOptions + */ + +class JWTKeySourceError extends Error { + /** + * @param {unknown} cause + */ + constructor(cause) { + super('Failed to resolve a JWT verification key', { cause }); + } +} + +/** + * @param {JWTVerificationOptions} options + * @param {string} algorithm + * @returns {(token: string) => Promise} + */ +function createJWTVerifier(options, algorithm) { + /** @param {string|Array} value */ + const isNonEmptyValue = (value) => + typeof value === 'string' + ? value.trim().length > 0 + : Array.isArray(value) && + value.length > 0 && + value.every( + (item) => typeof item === 'string' && item.trim().length > 0, + ); + if (!isNonEmptyValue(options.issuer) || !isNonEmptyValue(options.audience)) { + throw new TypeError('JWT options must include an issuer and audience'); + } + if (!options.jwks && !options.jwksUri) { + throw new TypeError('JWT options must include a JWKS or JWKS URI'); + } + if ( + options.jwks && + (!Array.isArray(options.jwks.keys) || options.jwks.keys.length === 0) + ) { + throw new TypeError('Static JWKS must include a non-empty keys array'); + } + if (options.jwks?.keys.some((key) => !key || typeof key !== 'object')) { + throw new TypeError('Static JWKS must contain public JWK objects'); + } + if ( + options.jwks?.keys.some( + (key) => + key.kty === 'oct' || + 'd' in key || + 'p' in key || + 'q' in key || + 'dp' in key || + 'dq' in key || + 'qi' in key || + 'oth' in key || + 'k' in key, + ) + ) { + throw new TypeError('Static JWKS must contain public asymmetric keys'); + } + + const localKeySet = options.jwks + ? createLocalJWKSet(options.jwks) + : undefined; + const jwksUrl = options.jwksUri + ? options.jwksUri instanceof URL + ? options.jwksUri + : new URL(options.jwksUri) + : undefined; + if ( + jwksUrl && + jwksUrl.protocol !== 'https:' && + !['localhost', '127.0.0.1', '[::1]'].includes(jwksUrl.hostname) + ) { + throw new TypeError('Remote JWKS URLs must use HTTPS'); + } + if (jwksUrl && (jwksUrl.username || jwksUrl.password)) { + throw new TypeError('Remote JWKS URLs must not contain credentials'); + } + const remoteKeySet = jwksUrl ? createRemoteJWKSet(jwksUrl) : undefined; + + /** + * @param {import('jose').JWTHeaderParameters} protectedHeader + * @param {import('jose').FlattenedJWSInput} token + */ + const getKey = async (protectedHeader, token) => { + if (localKeySet) { + try { + return await localKeySet(protectedHeader, token); + } catch (error) { + if (error instanceof errors.JWKSNoMatchingKey && remoteKeySet) { + // A static key miss can be satisfied by the remote JWKS. + } else if (error instanceof errors.JWKSNoMatchingKey) { + throw error; + } else { + throw new JWTKeySourceError(error); + } + } + } + if (remoteKeySet) { + try { + return await remoteKeySet(protectedHeader, token); + } catch (error) { + if (error instanceof errors.JWKSNoMatchingKey) { + throw error; + } + throw new JWTKeySourceError(error); + } + } + throw new errors.JWKSNoMatchingKey(); + }; + + const verifyOptions = { + issuer: options.issuer, + audience: options.audience, + requiredClaims: ['exp'], + algorithms: [algorithm], + }; + + return async (token) => { + await jwtVerify(token, getKey, verifyOptions); + }; +} class ThingServer { + /** @type {((token: string) => Promise)|undefined} */ + #verifyJWT; + /** * Construct the Thing Server. * * @param {Thing} thing The Thing to serve. - * @param {ThingServerOptions} [options] Optional TLS and public domain settings. + * @param {ThingServerOptions} [options] Optional TLS, public domain and JWT settings. */ constructor(thing, options = {}) { this.thing = thing; this.tlsOptions = options.tls; this.domain = options.domain; + const securityNames = Array.isArray(thing.security) + ? thing.security + : [thing.security]; + if (securityNames.length !== 1) { + throw new TypeError( + 'ThingServer supports one top-level security scheme at a time', + ); + } + const securityScheme = thing.securityDefinitions[securityNames[0]]; + if (!securityScheme) { + throw new TypeError( + `Thing security scheme "${securityNames[0]}" is not defined`, + ); + } + + this.#verifyJWT = undefined; + if (securityScheme.scheme === 'bearer') { + if (securityScheme.format && securityScheme.format !== 'jwt') { + throw new TypeError('ThingServer only supports bearer JWT tokens'); + } + if (securityScheme.in && securityScheme.in !== 'header') { + throw new TypeError( + 'ThingServer bearer JWTs must be provided in the Authorization header', + ); + } + if ( + securityScheme.name && + securityScheme.name.toLowerCase() !== 'authorization' + ) { + throw new TypeError( + 'ThingServer bearer JWTs must use the Authorization header', + ); + } + if (!options.jwt) { + throw new TypeError( + 'JWT verification options are required for bearer security', + ); + } + const algorithm = securityScheme.alg ?? 'ES256'; + if (!publicKeyJWTAlgorithms.has(algorithm)) { + throw new TypeError( + 'ThingServer only supports signed JWTs using asymmetric algorithms', + ); + } + this.#verifyJWT = createJWTVerifier(options.jwt, algorithm); + } else if (securityScheme.scheme === 'nosec') { + if (options.jwt) { + throw new TypeError( + 'JWT verification options require a bearer security scheme', + ); + } + } else { + throw new TypeError( + `ThingServer does not support the "${securityScheme.scheme}" security scheme`, + ); + } + if ( this.tlsOptions && !this.tlsOptions.pfx && @@ -28,8 +237,6 @@ class ThingServer { ); } this.app = express(); - // Use JSON middleware and allow bare primite values as valid JSON - this.app.use(express.json({ strict: false })); /** @type {import('node:net').Server | null} */ this.server = null; @@ -48,6 +255,51 @@ class ThingServer { }, ); + if (this.#verifyJWT) { + const verifyJWT = this.#verifyJWT; + this.app.use( + /** + * Authenticate requests to Thing interaction endpoints. + * + * @param {Request} request + * @param {Response} response + * @param {import('express').NextFunction} next + */ + async (request, response, next) => { + const authorization = request.get('authorization'); + const match = authorization?.match(/^Bearer\s+(\S+)$/i); + if (!match) { + response.set('WWW-Authenticate', 'Bearer').status(401).send(); + return; + } + + try { + await verifyJWT(match[1]); + } catch (error) { + if (error instanceof JWTKeySourceError) { + console.error('Error verifying bearer JWT:', error.cause); + response.status(503).send(); + return; + } + if ( + error instanceof errors.JOSEError && + !(error instanceof errors.JWKSTimeout) + ) { + response.set('WWW-Authenticate', 'Bearer').status(401).send(); + return; + } + console.error('Error verifying bearer JWT:', error); + response.status(503).send(); + return; + } + next(); + }, + ); + } + + // Parse request bodies only after authenticating protected requests. + this.app.use(express.json({ strict: false })); + this.app.get( '/properties/:name', /** diff --git a/src/thing.js b/src/thing.js index 4f5de11..2fe9f96 100644 --- a/src/thing.js +++ b/src/thing.js @@ -117,13 +117,12 @@ class Thing extends EventEmitter { validationError.merge(error); } - // Hard code the nosec security scheme for now - this.securityDefinitions = { + this.securityDefinitions = partialTD.securityDefinitions ?? { nosec_sc: { scheme: 'nosec', }, }; - this.security = 'nosec_sc'; + this.security = partialTD.security ?? 'nosec_sc'; // TODO: Parse other members diff --git a/src/types.js b/src/types.js index 3866f8f..47f5cfe 100644 --- a/src/types.js +++ b/src/types.js @@ -7,6 +7,11 @@ * descriptions?: Record, * proxy?: string, * scheme?: string, + * authorization?: string, + * name?: string, + * alg?: string, + * format?: string, + * in?: string, * }} SecurityScheme */ @@ -166,7 +171,7 @@ * events?: Record, * forms?: Array
, * security: string|Array, - * securityDefinitions: string|Record + * securityDefinitions: Record * }} ThingDescription */ @@ -188,7 +193,7 @@ * events?: Record, * forms?: Array, * security?: string|Array, - * securityDefinitions?: string|Record + * securityDefinitions?: Record * }} PartialThingDescription */ diff --git a/test/security.test.js b/test/security.test.js new file mode 100644 index 0000000..b3e173e --- /dev/null +++ b/test/security.test.js @@ -0,0 +1,314 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { generateKeyPairSync } from 'node:crypto'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import { exportJWK, SignJWT } from 'jose'; +import Thing from '../src/thing.js'; +import ThingServer from '../src/thing-server.js'; + +const issuer = 'https://issuer.example.com/'; +const audience = 'my-thing'; + +async function createKeyPair(kid) { + const { privateKey, publicKey } = generateKeyPairSync('rsa', { + modulusLength: 2048, + }); + const jwk = await exportJWK(publicKey); + return { + privateKey, + jwk: { ...jwk, kid, alg: 'RS256', use: 'sig' }, + }; +} + +async function createToken(privateKey, claims = {}) { + return new SignJWT({}) + .setProtectedHeader({ alg: 'RS256', kid: claims.kid }) + .setIssuer(claims.issuer ?? issuer) + .setAudience(claims.audience ?? audience) + .setIssuedAt() + .setExpirationTime(claims.expirationTime ?? '5m') + .sign(privateKey); +} + +function createBearerThing( + securityScheme = { + scheme: 'bearer', + format: 'jwt', + alg: 'RS256', + }, +) { + const thing = new Thing({ + title: 'Protected Thing', + securityDefinitions: { + bearer_sc: securityScheme, + }, + security: 'bearer_sc', + properties: { + status: { type: 'string' }, + }, + }); + thing.setPropertyReadHandler('status', async () => 'ready'); + return thing; +} + +async function listen(server) { + const httpServer = server.app.listen(0, '127.0.0.1'); + server.server = httpServer; + await once(httpServer, 'listening'); + const address = httpServer.address(); + assert.ok(address && typeof address !== 'string'); + return `http://127.0.0.1:${address.port}`; +} + +async function closeServer(server) { + if (server.server) { + await new Promise((resolve, reject) => { + server.server.close((error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); + } +} + +describe('Bearer JWT security', () => { + it('preserves the supplied security definition in the Thing Description', () => { + const thing = createBearerThing(); + const td = thing.getThingDescription(); + + assert.deepEqual(td.securityDefinitions, { + bearer_sc: { scheme: 'bearer', format: 'jwt', alg: 'RS256' }, + }); + assert.equal(td.security, 'bearer_sc'); + }); + + it('authenticates interactions with static and remote JWKS while leaving the TD public', async () => { + const staticKeys = await createKeyPair('static-key'); + const remoteKeys = await createKeyPair('remote-key'); + let remoteFetches = 0; + const jwksServer = createServer((_request, response) => { + remoteFetches += 1; + response.writeHead(200, { + 'Cache-Control': 'public, max-age=300', + 'Content-Type': 'application/json', + }); + response.end(JSON.stringify({ keys: [remoteKeys.jwk] })); + }); + jwksServer.listen(0, '127.0.0.1'); + await once(jwksServer, 'listening'); + const jwksAddress = jwksServer.address(); + assert.ok(jwksAddress && typeof jwksAddress !== 'string'); + + const server = new ThingServer(createBearerThing(), { + jwt: { + issuer, + audience, + jwks: { keys: [staticKeys.jwk] }, + jwksUri: `http://127.0.0.1:${jwksAddress.port}/jwks`, + }, + }); + + try { + const baseUrl = await listen(server); + const descriptionResponse = await fetch(`${baseUrl}/`); + assert.equal(descriptionResponse.status, 200); + assert.equal((await descriptionResponse.json()).security, 'bearer_sc'); + + const missingTokenResponse = await fetch(`${baseUrl}/properties/status`); + assert.equal(missingTokenResponse.status, 401); + assert.equal( + missingTokenResponse.headers.get('www-authenticate'), + 'Bearer', + ); + + const unauthenticatedBodyResponse = await fetch( + `${baseUrl}/properties/status`, + { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: '{', + }, + ); + assert.equal(unauthenticatedBodyResponse.status, 401); + + const invalidTokenResponse = await fetch(`${baseUrl}/properties/status`, { + headers: { Authorization: 'Bearer not-a-jwt' }, + }); + assert.equal(invalidTokenResponse.status, 401); + + const unauthenticatedEventResponse = await fetch( + `${baseUrl}/events/reset`, + { headers: { Accept: 'text/event-stream' } }, + ); + assert.equal(unauthenticatedEventResponse.status, 401); + + const staticToken = await createToken(staticKeys.privateKey, { + kid: 'static-key', + }); + const staticTokenResponse = await fetch(`${baseUrl}/properties/status`, { + headers: { Authorization: `Bearer ${staticToken}` }, + }); + assert.equal(staticTokenResponse.status, 200); + assert.equal(await staticTokenResponse.json(), 'ready'); + assert.equal(remoteFetches, 0); + + const remoteToken = await createToken(remoteKeys.privateKey, { + kid: 'remote-key', + }); + const remoteTokenResponse = await fetch(`${baseUrl}/properties/status`, { + headers: { Authorization: `Bearer ${remoteToken}` }, + }); + assert.equal(remoteTokenResponse.status, 200); + assert.equal(await remoteTokenResponse.json(), 'ready'); + assert.equal(remoteFetches, 1); + + const wrongAudienceToken = await createToken(staticKeys.privateKey, { + kid: 'static-key', + audience: 'another-thing', + }); + const wrongAudienceResponse = await fetch( + `${baseUrl}/properties/status`, + { + headers: { Authorization: `Bearer ${wrongAudienceToken}` }, + }, + ); + assert.equal(wrongAudienceResponse.status, 401); + + const tokenWithoutExpiration = await new SignJWT({}) + .setProtectedHeader({ alg: 'RS256', kid: 'static-key' }) + .setIssuer(issuer) + .setAudience(audience) + .setIssuedAt() + .sign(staticKeys.privateKey); + const missingExpirationResponse = await fetch( + `${baseUrl}/properties/status`, + { + headers: { Authorization: `Bearer ${tokenWithoutExpiration}` }, + }, + ); + assert.equal(missingExpirationResponse.status, 401); + + const expiredToken = await createToken(staticKeys.privateKey, { + kid: 'static-key', + expirationTime: Math.floor(Date.now() / 1000) - 10, + }); + const expiredTokenResponse = await fetch(`${baseUrl}/properties/status`, { + headers: { Authorization: `Bearer ${expiredToken}` }, + }); + assert.equal(expiredTokenResponse.status, 401); + } finally { + await closeServer(server); + await new Promise((resolve, reject) => { + jwksServer.close((error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); + } + }); + + it('requires JWT verification options when bearer security is enabled', () => { + assert.throws(() => new ThingServer(createBearerThing()), { + name: 'TypeError', + message: 'JWT verification options are required for bearer security', + }); + }); + + it('accepts a static JWKS without requiring a remote JWKS URI', async () => { + const signingKey = await createKeyPair('static-only'); + const server = new ThingServer(createBearerThing(), { + jwt: { + issuer, + audience, + jwks: { keys: [signingKey.jwk] }, + }, + }); + + try { + const baseUrl = await listen(server); + const token = await createToken(signingKey.privateKey, { + kid: 'static-only', + }); + const response = await fetch(`${baseUrl}/properties/status`, { + headers: { Authorization: `Bearer ${token}` }, + }); + assert.equal(response.status, 200); + assert.equal(await response.json(), 'ready'); + } finally { + await closeServer(server); + } + }); + + it('uses the TD default ES256 algorithm when alg is omitted', async () => { + const signingKey = await createKeyPair('default-algorithm'); + const server = new ThingServer(createBearerThing({ scheme: 'bearer' }), { + jwt: { + issuer, + audience, + jwks: { keys: [signingKey.jwk] }, + }, + }); + + try { + const baseUrl = await listen(server); + const token = await createToken(signingKey.privateKey, { + kid: 'default-algorithm', + }); + const response = await fetch(`${baseUrl}/properties/status`, { + headers: { Authorization: `Bearer ${token}` }, + }); + assert.equal(response.status, 401); + } finally { + await closeServer(server); + } + }); + + it('returns a service error when the remote JWKS endpoint fails', async () => { + const signingKey = await createKeyPair('remote-only'); + const jwksServer = createServer((_request, response) => { + response.writeHead(503); + response.end(); + }); + jwksServer.listen(0, '127.0.0.1'); + await once(jwksServer, 'listening'); + const jwksAddress = jwksServer.address(); + assert.ok(jwksAddress && typeof jwksAddress !== 'string'); + + const server = new ThingServer(createBearerThing(), { + jwt: { + issuer, + audience, + jwksUri: `http://127.0.0.1:${jwksAddress.port}/jwks`, + }, + }); + + try { + const baseUrl = await listen(server); + const token = await createToken(signingKey.privateKey, { + kid: 'remote-only', + }); + const response = await fetch(`${baseUrl}/properties/status`, { + headers: { Authorization: `Bearer ${token}` }, + }); + assert.equal(response.status, 503); + } finally { + await closeServer(server); + await new Promise((resolve, reject) => { + jwksServer.close((error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); + } + }); +});