diff --git a/Dockerfile b/Dockerfile index 7f8f579..7add41a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -22,7 +22,8 @@ ARG BUILD_ID=unknown ENV BUILD_ID=$BUILD_ID ENV NODE_ENV=production -ENV APP_PORT=8080 +ENV APP_PORT=8443 +ENV API_HEALTH_PORT=8081 ENV DRAIN_DELAY_MS=5000 COPY --from=build /usr/src/app/package.json /usr/src/app/package-lock.json ./ COPY --from=build /usr/src/app/node_modules ./node_modules @@ -30,9 +31,9 @@ COPY --from=build /usr/src/app/dist ./dist USER node -EXPOSE 8080 +EXPOSE 8443 HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \ - CMD node -e "const port=process.env.APP_PORT||'8080'; fetch('http://127.0.0.1:'+port+'/health/ready').then((response) => { if (!response.ok) process.exit(1); }).catch(() => process.exit(1))" + CMD node -e "const port=process.env.API_HEALTH_PORT||'8081'; fetch('http://127.0.0.1:'+port+'/health/ready').then((response) => { if (!response.ok) process.exit(1); }).catch(() => process.exit(1))" CMD ["node", "dist/main.js"] diff --git a/app/package-lock.json b/app/package-lock.json index c0894d9..a62a955 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -14,7 +14,6 @@ "@nestjs/common": "^12.0.1", "@nestjs/config": "^12.0.0", "@nestjs/core": "^12.0.1", - "@nestjs/platform-express": "^12.0.1", "@nestjs/platform-fastify": "^12.0.3", "@opentelemetry/api": "1.9.0", "@opentelemetry/api-logs": "0.203.0", @@ -39,14 +38,13 @@ "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", "sharp": "^0.35.5", - "zod": "^4.6.5" + "zod": "^4.6.6" }, "devDependencies": { "@nestjs/cli": "^12.0.0", "@nestjs/mau": "^0.2.6", "@nestjs/schematics": "^12.0.0", "@nestjs/testing": "^12.0.1", - "@types/express": "^5.0.0", "@types/node": "^24.0.0", "@types/pg": "^8.23.1", "@types/supertest": "^7.0.0", @@ -2398,6 +2396,8 @@ "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-12.0.3.tgz", "integrity": "sha512-q9ImjCMjbYYgqvRHHro6sAypNwhjspIAHad0RTL2ww5wYd9gwUGWMss7Q+ACCw5Sksu7Q8S/3rjSLhB+W6B6bg==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "cors": "2.8.6", "express": "5.2.1", @@ -3705,17 +3705,6 @@ "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", "license": "MIT" }, - "node_modules/@types/body-parser": { - "version": "1.19.6", - "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", - "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/connect": "*", - "@types/node": "*" - } - }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -3727,16 +3716,6 @@ "assertion-error": "^2.0.1" } }, - "node_modules/@types/connect": { - "version": "3.4.38", - "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", - "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/cookiejar": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz", @@ -3758,38 +3737,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/express": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", - "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/body-parser": "*", - "@types/express-serve-static-core": "^5.0.0", - "@types/serve-static": "^2" - } - }, - "node_modules/@types/express-serve-static-core": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz", - "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*", - "@types/send": "*" - } - }, - "node_modules/@types/http-errors": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", - "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/methods": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", @@ -3818,41 +3765,6 @@ "pg-types": "^2.2.0" } }, - "node_modules/@types/qs": { - "version": "6.15.1", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", - "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/range-parser": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", - "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", - "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/serve-static": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz", - "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/http-errors": "*", - "@types/node": "*" - } - }, "node_modules/@types/superagent": { "version": "8.1.11", "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-8.1.11.tgz", @@ -4058,6 +3970,8 @@ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" @@ -4164,7 +4078,9 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/argon2": { "version": "0.45.1", @@ -4302,6 +4218,8 @@ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", @@ -4326,6 +4244,8 @@ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=18" }, @@ -4389,6 +4309,8 @@ "version": "1.6.0", "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "optional": true, + "peer": true, "dependencies": { "streamsearch": "^1.1.0" }, @@ -4401,6 +4323,8 @@ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -4409,6 +4333,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "devOptional": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -4422,6 +4347,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "devOptional": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -4658,6 +4584,8 @@ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=18" }, @@ -4671,6 +4599,8 @@ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -4687,6 +4617,8 @@ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -4695,6 +4627,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "devOptional": true, "license": "MIT", "engines": { "node": ">=6.6.0" @@ -4712,6 +4645,8 @@ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "object-assign": "^4", "vary": "^1" @@ -4810,6 +4745,8 @@ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -4890,6 +4827,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "devOptional": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.1", @@ -4904,7 +4842,9 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/emoji-regex": { "version": "8.0.0", @@ -4925,6 +4865,8 @@ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -4933,6 +4875,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -4942,6 +4885,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -4958,6 +4902,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "devOptional": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -5040,7 +4985,9 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/escape-string-regexp": { "version": "1.0.5", @@ -5081,6 +5028,8 @@ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -5100,6 +5049,8 @@ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", @@ -5398,6 +5349,8 @@ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", @@ -5491,6 +5444,8 @@ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -5500,6 +5455,8 @@ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -5523,6 +5480,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "devOptional": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -5545,6 +5503,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "devOptional": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -5569,6 +5528,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "devOptional": true, "license": "MIT", "dependencies": { "dunder-proto": "^1.0.1", @@ -5589,6 +5549,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -5611,6 +5572,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -5639,6 +5601,7 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "devOptional": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -5659,6 +5622,8 @@ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", @@ -5678,6 +5643,7 @@ "version": "0.7.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "devOptional": true, "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -5714,6 +5680,7 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "devOptional": true, "license": "ISC" }, "node_modules/inquirer": { @@ -5842,6 +5809,8 @@ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.10" } @@ -5873,7 +5842,9 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/is-unicode-supported": { "version": "2.1.0", @@ -6402,6 +6373,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -6412,6 +6384,8 @@ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" }, @@ -6425,6 +6399,8 @@ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=18" }, @@ -6460,6 +6436,8 @@ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6469,6 +6447,8 @@ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "^1.54.0" }, @@ -6540,6 +6520,8 @@ "resolved": "https://registry.npmjs.org/multer/-/multer-2.4.0.tgz", "integrity": "sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", @@ -6558,6 +6540,8 @@ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6567,6 +6551,8 @@ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6576,6 +6562,8 @@ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -6588,6 +6576,8 @@ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -6630,6 +6620,8 @@ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "content-type": "^2.1.0" }, @@ -6646,6 +6638,8 @@ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=18" }, @@ -6709,6 +6703,8 @@ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -6717,6 +6713,7 @@ "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -6753,6 +6750,8 @@ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ee-first": "1.1.1" }, @@ -6764,6 +6763,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "devOptional": true, "license": "ISC", "dependencies": { "wrappy": "1" @@ -6980,6 +6980,8 @@ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -7294,6 +7296,8 @@ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" @@ -7310,6 +7314,7 @@ "version": "6.16.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", @@ -7333,6 +7338,8 @@ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" }, @@ -7346,6 +7353,8 @@ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", @@ -7510,6 +7519,8 @@ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", @@ -7596,6 +7607,7 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "devOptional": true, "license": "MIT" }, "node_modules/secure-json-parse": { @@ -7631,6 +7643,8 @@ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", @@ -7657,6 +7671,8 @@ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", @@ -7681,7 +7697,9 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "license": "ISC" + "license": "ISC", + "optional": true, + "peer": true }, "node_modules/sharp": { "version": "0.35.5", @@ -7757,6 +7775,7 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "devOptional": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -7776,6 +7795,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "devOptional": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -7792,6 +7812,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "devOptional": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -7810,6 +7831,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "devOptional": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -7929,6 +7951,8 @@ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -7957,6 +7981,8 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" } @@ -8170,6 +8196,8 @@ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.6" } @@ -8250,6 +8278,8 @@ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", @@ -8268,6 +8298,8 @@ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=18" }, @@ -8345,6 +8377,8 @@ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -8370,6 +8404,8 @@ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -8494,6 +8530,22 @@ } } }, + "node_modules/vite-tsconfig-paths/node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/vite/node_modules/picomatch": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", @@ -8668,6 +8720,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "devOptional": true, "license": "ISC" }, "node_modules/xtend": { @@ -8693,9 +8746,9 @@ } }, "node_modules/zod": { - "version": "4.6.5", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", - "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/app/package.json b/app/package.json index 324d7c4..61ffb5b 100644 --- a/app/package.json +++ b/app/package.json @@ -33,7 +33,6 @@ "@nestjs/common": "^12.0.1", "@nestjs/config": "^12.0.0", "@nestjs/core": "^12.0.1", - "@nestjs/platform-express": "^12.0.1", "@nestjs/platform-fastify": "^12.0.3", "@opentelemetry/api": "1.9.0", "@opentelemetry/api-logs": "0.203.0", @@ -58,14 +57,13 @@ "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", "sharp": "^0.35.5", - "zod": "^4.6.5" + "zod": "^4.6.6" }, "devDependencies": { "@nestjs/cli": "^12.0.0", "@nestjs/mau": "^0.2.6", "@nestjs/schematics": "^12.0.0", "@nestjs/testing": "^12.0.1", - "@types/express": "^5.0.0", "@types/node": "^24.0.0", "@types/pg": "^8.23.1", "@types/supertest": "^7.0.0", diff --git a/app/src/app.module.ts b/app/src/app.module.ts index a1b259c..1d886c4 100644 --- a/app/src/app.module.ts +++ b/app/src/app.module.ts @@ -1,21 +1,23 @@ import { Module } from '@nestjs/common'; -import { AppConfigModule } from './config/app-config.module.js'; -import { DatabaseModule } from './database/database.module.js'; -import { RedisModule } from './redis/redis.module.js'; +import { APP_FILTER } from '@nestjs/core'; +import { AttachmentsModule } from './attachments/attachments.module.js'; import { AuthModule } from './auth/auth.module.js'; import { ChatsModule } from './chats/chats.module.js'; +import { ApiExceptionFilter } from './common/errors/api-exception.filter.js'; +import { AppConfigModule } from './config/app-config.module.js'; +import { DatabaseModule } from './database/database.module.js'; import { HealthModule } from './health/health.module.js'; -import { AttachmentsModule } from './attachments/attachments.module.js'; import { MessagesModule } from './messages/messages.module.js'; import { MetricsModule } from './metrics/metrics.module.js'; -import { UsersModule } from './users/users.module.js'; -import { APP_FILTER } from '@nestjs/core'; -import { ApiExceptionFilter } from './common/errors/api-exception.filter.js'; +import { RedisModule } from './redis/redis.module.js'; +import { SecurityModule } from './security/security.module.js'; import { QueueStatsService } from './telemetry/queue-stats.service.js'; +import { UsersModule } from './users/users.module.js'; @Module({ imports: [ AppConfigModule, + SecurityModule, DatabaseModule, RedisModule, UsersModule, diff --git a/app/src/attachments/attachments-sweep.cli.ts b/app/src/attachments/attachments-sweep.cli.ts index 91d0c36..bf21cf5 100644 --- a/app/src/attachments/attachments-sweep.cli.ts +++ b/app/src/attachments/attachments-sweep.cli.ts @@ -2,33 +2,48 @@ import { fileURLToPath } from 'node:url'; import { parseAppConfig } from '../config/app-config.schema.js'; import { DatabaseClient } from '../database/database.client.js'; import { MetricsService } from '../metrics/metrics.service.js'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from '../security/tls-material.js'; import { ObjectStorage } from '../storage/object-storage.js'; import { AttachmentSweeper } from './attachment-sweeper.service.js'; import { AttachmentsRepository } from './attachments.repository.js'; // Manual operator pass over unfinished uploads (the API also sweeps in the // background). Never touches rows before expiry + ATTACHMENT_SWEEP_GRACE_SECONDS. -// in the stand: docker compose exec api node dist/attachments/attachments-sweep.cli.js -// on the host: npm run attachments:sweep (needs reachable DATABASE_URL and S3) async function main(): Promise { - const config = parseAppConfig(process.env as Record); + const rawEnv = process.env as Record; + const config = parseAppConfig(rawEnv); + const tlsMaterial = TlsMaterialManager.initFromEnv('cli', rawEnv); + const secretsStore = await RuntimeSecretsStore.bootstrap( + 'api', + tlsMaterial, + rawEnv, + undefined, + { background: false }, + ); const configService = { + get: (key: keyof typeof config) => config[key], getOrThrow: (key: keyof typeof config) => config[key], } as never; const metrics = new MetricsService(); - const database = new DatabaseClient(configService, metrics); + const database = new DatabaseClient( + configService, + metrics, + tlsMaterial, + secretsStore, + ); + const storage = new ObjectStorage(configService, tlsMaterial, secretsStore); try { const sweeper = new AttachmentSweeper( configService, new AttachmentsRepository(database), - new ObjectStorage(configService), + storage, metrics, ); let total = 0; for (;;) { const { claimed, deleted } = await sweeper.sweepOnce(); total += deleted; - // A pass that claimed rows but could not delete any would loop forever. if (claimed === 0 || deleted === 0) break; } process.stdout.write( @@ -36,6 +51,9 @@ async function main(): Promise { ); } finally { await database.onModuleDestroy(); + storage.onModuleDestroy(); + secretsStore.close(); + tlsMaterial.onModuleDestroy(); } } diff --git a/app/src/auth/auth.controller.ts b/app/src/auth/auth.controller.ts index 265696d..9b65bd1 100644 --- a/app/src/auth/auth.controller.ts +++ b/app/src/auth/auth.controller.ts @@ -7,16 +7,20 @@ import { HttpCode, HttpStatus, Post, + Req, UnauthorizedException, UseGuards, } from '@nestjs/common'; +import type { FastifyRequest } from 'fastify'; import { TextDecoder } from 'node:util'; -import { AuthService } from './auth.service.js'; import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import { AuthService } from './auth.service.js'; +import { extractClientIp } from './login-rate-limiter.service.js'; const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u; const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'; +const BEARER_HEADER_RE = /^Bearer[ \t]+([^ \t]+)$/iu; function basicUnauthorized(): UnauthorizedException { return new UnauthorizedException({ @@ -57,13 +61,15 @@ export class AuthController { create( @Headers('authorization') authorization: string | undefined, @Body() body: unknown, + @Req() request: FastifyRequest, ) { const [username, password] = parseBasic(authorization); if (body !== undefined) throw new BadRequestException( 'Session creation does not accept a body', ); - return this.auth.createSession(username, password); + const clientIp = extractClientIp(request.headers, request.ip); + return this.auth.createSession(username, password, clientIp); } @Delete('current') @@ -72,8 +78,9 @@ export class AuthController { async delete( @Headers('authorization') authorization: string | undefined, ): Promise { - if (!authorization || !/^Bearer\s+[^\s]+$/iu.test(authorization)) - throw bearerUnauthorized(); - await this.auth.deleteSession(authorization.slice(7).trim()); + if (!authorization) throw bearerUnauthorized(); + const match = BEARER_HEADER_RE.exec(authorization); + if (!match) throw bearerUnauthorized(); + await this.auth.deleteSession(match[1]); } } diff --git a/app/src/auth/auth.module.ts b/app/src/auth/auth.module.ts index c29483b..d6c5c80 100644 --- a/app/src/auth/auth.module.ts +++ b/app/src/auth/auth.module.ts @@ -1,16 +1,15 @@ import { Module } from '@nestjs/common'; import { DatabaseModule } from '../database/database.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; import { RedisModule } from '../redis/redis.module.js'; import { UsersModule } from '../users/users.module.js'; import { AuthController } from './auth.controller.js'; import { AuthService } from './auth.service.js'; -import { SessionRepository } from './session.repository.js'; -import { MetricsModule } from '../metrics/metrics.module.js'; @Module({ imports: [UsersModule, DatabaseModule, RedisModule, MetricsModule], controllers: [AuthController], - providers: [AuthService, SessionRepository], - exports: [AuthService, SessionRepository], + providers: [AuthService], + exports: [AuthService], }) export class AuthModule {} diff --git a/app/src/auth/auth.service.ts b/app/src/auth/auth.service.ts index f983358..8628f03 100644 --- a/app/src/auth/auth.service.ts +++ b/app/src/auth/auth.service.ts @@ -3,9 +3,12 @@ import { ServiceUnavailableException, UnauthorizedException, } from '@nestjs/common'; -import argon2 from 'argon2'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { appLogger } from '../telemetry/logger.js'; import type { User } from '../users/user.js'; import { UsersService } from '../users/users.service.js'; +import { LoginRateLimiterService } from './login-rate-limiter.service.js'; +import { PasswordHasherService } from './password-hasher.service.js'; import { SessionRepository } from './session.repository.js'; export type SessionResponse = { @@ -20,19 +23,48 @@ export class AuthService { constructor( private readonly users: UsersService, private readonly sessions: SessionRepository, + private readonly hasher: PasswordHasherService, + private readonly rateLimiter: LoginRateLimiterService, + private readonly metrics: MetricsService, ) {} async createSession( username: string, password: string, + clientIp = 'unknown', ): Promise { + await this.rateLimiter.consumeLogin(username, clientIp); + const storedUser = await this.users.findByUsername(username); - if ( - !storedUser || - !(await argon2.verify(storedUser.password_hash, password)) - ) { + const verification = await this.hasher.verifyAndUpgrade( + storedUser?.password_hash, + password, + ); + if (!storedUser || !verification.valid) { throw new UnauthorizedException(); } + + if (verification.upgradedHash) { + try { + await this.users.updatePasswordHash( + storedUser.id, + verification.upgradedHash, + ); + this.metrics.increment('auth.password_rehashed'); + appLogger.event( + 'INFO', + 'auth.password_rehashed', + 'Upgraded stored password hash to current Argon2id parameters', + ); + } catch (error) { + appLogger.event( + 'WARN', + 'auth.rehash_failed', + `Password hash upgrade write failed: ${error instanceof Error ? error.name : 'unknown error'}`, + ); + } + } + const user: User = { id: storedUser.id, username: storedUser.username, diff --git a/app/src/auth/login-rate-limiter.service.spec.ts b/app/src/auth/login-rate-limiter.service.spec.ts new file mode 100644 index 0000000..70d6a50 --- /dev/null +++ b/app/src/auth/login-rate-limiter.service.spec.ts @@ -0,0 +1,104 @@ +import { + HttpException, + HttpStatus, + ServiceUnavailableException, +} from '@nestjs/common'; +import { describe, expect, it, vi } from 'vitest'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { + extractClientIp, + LoginRateLimiterService, +} from './login-rate-limiter.service.js'; + +describe('LoginRateLimiterService', () => { + function makeSharedRedis() { + const counts = new Map(); + const redis = { + eval: vi.fn( + async (_script: string, keys: string[], args: string[]) => { + const key = keys[0]; + const next = (counts.get(key) ?? 0) + 1; + counts.set(key, next); + return [next, Number(args[0])]; + }, + ), + }; + return { redis, counts }; + } + + function makeLimiter( + redis: ReturnType['redis'], + overrides: Record = {}, + ) { + const values: Record = { + LOGIN_RATE_LIMIT_USER_MAX: 3, + LOGIN_RATE_LIMIT_IP_MAX: 5, + REGISTER_RATE_LIMIT_IP_MAX: 2, + LOGIN_RATE_LIMIT_WINDOW_SECONDS: 60, + ...overrides, + }; + const config = { + getOrThrow: (key: string) => values[key], + }; + return new LoginRateLimiterService( + redis as never, + config as never, + new MetricsService(), + ); + } + + it('shares per-username and per-IP counters across API replicas and hashes username keys', async () => { + const { redis, counts } = makeSharedRedis(); + const replica1 = makeLimiter(redis); + const replica2 = makeLimiter(redis); + + await replica1.consumeLogin('Alice', '10.0.0.1'); + await replica2.consumeLogin('alice', '10.0.0.2'); + await replica1.consumeLogin('ALICE', '10.0.0.3'); + + // 4th attempt across replicas must trigger 429 with Retry-After >= 1. + try { + await replica2.consumeLogin('alice', '10.0.0.4'); + expect.unreachable('expected 429'); + } catch (error) { + expect(error).toBeInstanceOf(HttpException); + const exc = error as HttpException; + expect(exc.getStatus()).toBe(HttpStatus.TOO_MANY_REQUESTS); + expect(exc.getResponse()).toMatchObject({ retryAfter: 60 }); + } + + // Raw username must not appear in Redis keys. + for (const key of counts.keys()) { + expect(key.toLowerCase()).not.toContain('alice'); + } + }); + + it('enforces registration per-IP rate limit and fails closed (503) on Redis failure', async () => { + const { redis } = makeSharedRedis(); + const limiter = makeLimiter(redis); + + await limiter.consumeRegister('203.0.113.10'); + await limiter.consumeRegister('203.0.113.10'); + await expect( + limiter.consumeRegister('203.0.113.10'), + ).rejects.toBeInstanceOf(HttpException); + + redis.eval.mockRejectedValueOnce(new Error('Connection is closed')); + await expect( + limiter.consumeLogin('bob', '203.0.113.11'), + ).rejects.toBeInstanceOf(ServiceUnavailableException); + }); + + it('extracts LB-set X-Forwarded-For with clean fallback', () => { + expect( + extractClientIp({ 'x-forwarded-for': '198.51.100.7' }, '127.0.0.1'), + ).toBe('198.51.100.7'); + expect( + extractClientIp( + { 'x-forwarded-for': '1.2.3.4, 198.51.100.8' }, + '127.0.0.1', + ), + ).toBe('198.51.100.8'); + expect(extractClientIp({}, '172.18.0.5')).toBe('172.18.0.5'); + }); +}); diff --git a/app/src/auth/login-rate-limiter.service.ts b/app/src/auth/login-rate-limiter.service.ts new file mode 100644 index 0000000..a6b5da7 --- /dev/null +++ b/app/src/auth/login-rate-limiter.service.ts @@ -0,0 +1,121 @@ +import { + HttpException, + HttpStatus, + Injectable, + ServiceUnavailableException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { createHash } from 'node:crypto'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { RedisClient } from '../redis/redis.client.js'; + +const FIXED_WINDOW_LUA = ` +local c = redis.call('INCR', KEYS[1]) +if c == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end +local ttl = redis.call('PTTL', KEYS[1]) +return {c, ttl} +`.trim(); + +export function extractClientIp( + headers: Record | undefined, + fallbackIp: string | undefined, +): string { + const rawXff = headers?.['x-forwarded-for']; + const xff = Array.isArray(rawXff) ? rawXff[rawXff.length - 1] : rawXff; + if (typeof xff === 'string' && xff.trim().length > 0) { + const parts = xff + .split(',') + .map((p) => p.trim()) + .filter((p) => p.length > 0); + if (parts.length > 0) return parts[parts.length - 1]; + } + return fallbackIp && fallbackIp.trim().length > 0 + ? fallbackIp.trim() + : 'unknown'; +} + +export function hashRateLimitKeyPart(value: string): string { + return createHash('sha256') + .update(value.toLowerCase(), 'utf8') + .digest('hex') + .slice(0, 32); +} + +@Injectable() +export class LoginRateLimiterService { + private readonly userMax: number; + private readonly ipMax: number; + private readonly registerIpMax: number; + private readonly windowMs: number; + + constructor( + private readonly redis: RedisClient, + config: ConfigService, + private readonly metrics: MetricsService, + ) { + this.userMax = config.getOrThrow('LOGIN_RATE_LIMIT_USER_MAX'); + this.ipMax = config.getOrThrow('LOGIN_RATE_LIMIT_IP_MAX'); + this.registerIpMax = config.getOrThrow('REGISTER_RATE_LIMIT_IP_MAX'); + this.windowMs = + config.getOrThrow('LOGIN_RATE_LIMIT_WINDOW_SECONDS') * 1000; + } + + async consumeLogin(username: string, clientIp: string): Promise { + const userKey = `rl:login:user:${hashRateLimitKeyPart(username)}`; + const ipKey = `rl:login:ip:${clientIp}`; + const [userRes, ipRes] = await Promise.all([ + this.hit(userKey), + this.hit(ipKey), + ]); + const userExceeded = userRes.count > this.userMax; + const ipExceeded = ipRes.count > this.ipMax; + if (userExceeded || ipExceeded) { + this.metrics.increment('auth.rate_limited'); + const retryMs = Math.max( + userExceeded ? userRes.pttlMs : 0, + ipExceeded ? ipRes.pttlMs : 0, + ); + const retryAfter = Math.max(1, Math.ceil(retryMs / 1000)); + throw new HttpException( + { message: 'Too many login attempts', retryAfter }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + } + + async consumeRegister(clientIp: string): Promise { + const ipKey = `rl:register:ip:${clientIp}`; + const res = await this.hit(ipKey); + if (res.count > this.registerIpMax) { + this.metrics.increment('auth.register_rate_limited'); + const retryAfter = Math.max(1, Math.ceil(res.pttlMs / 1000)); + throw new HttpException( + { message: 'Too many registration attempts', retryAfter }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + } + + private async hit(key: string): Promise<{ count: number; pttlMs: number }> { + let raw: unknown; + try { + raw = await this.redis.eval( + FIXED_WINDOW_LUA, + [key], + [String(this.windowMs)], + ); + } catch { + throw new ServiceUnavailableException('Session store unavailable'); + } + if (!Array.isArray(raw) || raw.length < 2) { + throw new ServiceUnavailableException('Session store unavailable'); + } + const count = Number(raw[0]); + const pttlMs = Number(raw[1]); + return { + count: Number.isFinite(count) ? count : this.userMax + 1, + pttlMs: Number.isFinite(pttlMs) && pttlMs > 0 ? pttlMs : this.windowMs, + }; + } +} diff --git a/app/src/auth/password-hasher.service.spec.ts b/app/src/auth/password-hasher.service.spec.ts new file mode 100644 index 0000000..0f2e32d --- /dev/null +++ b/app/src/auth/password-hasher.service.spec.ts @@ -0,0 +1,122 @@ +import { HttpException, HttpStatus } from '@nestjs/common'; +import argon2 from 'argon2'; +import { randomBytes, scryptSync } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { PasswordHasherService } from './password-hasher.service.js'; + +function makeHasher(overrides: Record = {}): PasswordHasherService { + const values: Record = { + ARGON2_MEMORY_KIB: 32768, + ARGON2_ITERATIONS: 2, + ARGON2_PARALLELISM: 1, + AUTH_HASH_MAX_CONCURRENT: 4, + AUTH_HASH_MAX_QUEUE: 8, + AUTH_HASH_QUEUE_TIMEOUT_MS: 2000, + ...overrides, + }; + const config = { + getOrThrow: (key: string) => values[key], + }; + return new PasswordHasherService(config as never, new MetricsService()); +} + +describe('PasswordHasherService', () => { + it('hashes passwords with explicit Argon2id PHC format and unique salts', async () => { + const hasher = makeHasher(); + const h1 = await hasher.hash('correct-horse-battery-staple'); + const h2 = await hasher.hash('correct-horse-battery-staple'); + + expect(h1).toMatch(/^\$argon2id\$v=19\$[^$]+\$[^$]+\$[^$]+$/u); + const params = h1.split('$')[3].split(','); + expect(params).toContain('m=32768'); + expect(params).toContain('t=2'); + expect(params).toContain('p=1'); + expect(h1).not.toBe(h2); + + const ok = await hasher.verify(h1, 'correct-horse-battery-staple'); + expect(ok).toEqual({ valid: true, needsRehash: false }); + + const wrong = await hasher.verify(h1, 'wrong-password'); + expect(wrong).toEqual({ valid: false, needsRehash: false }); + }); + + it('handles unknown users and malformed hashes via dummy verify without throwing', async () => { + const hasher = makeHasher(); + await hasher.onModuleInit(); + + expect(await hasher.verify(undefined, 'any-pass')).toEqual({ + valid: false, + needsRehash: false, + }); + expect(await hasher.verify('$argon2id$corrupted', 'any-pass')).toEqual({ + valid: false, + needsRehash: false, + }); + expect(await hasher.verify('plaintext-not-phc', 'any-pass')).toEqual({ + valid: false, + needsRehash: false, + }); + }); + + it('transparently upgrades weaker Argon2id and legacy $scrypt$ hashes on login', async () => { + const hasher = makeHasher({ ARGON2_MEMORY_KIB: 32768, ARGON2_ITERATIONS: 2 }); + + const weakArgon = await argon2.hash('secret-123', { + type: argon2.argon2id, + memoryCost: 19456, + timeCost: 2, + parallelism: 1, + }); + const weakResult = await hasher.verifyAndUpgrade(weakArgon, 'secret-123'); + expect(weakResult.valid).toBe(true); + expect(weakResult.upgradedHash).toMatch(/^\$argon2id\$v=19\$/u); + expect(weakResult.upgradedHash?.split('$')[3].split(',')).toEqual( + expect.arrayContaining(['m=32768', 't=2', 'p=1']), + ); + expect(await hasher.verify(weakResult.upgradedHash, 'secret-123')).toEqual({ + valid: true, + needsRehash: false, + }); + + const salt = randomBytes(16); + const derived = scryptSync('legacy-pass', salt, 32, { N: 1 << 14, r: 8, p: 1 }); + const legacyScrypt = `$scrypt$ln=14,r=8,p=1$${salt.toString('base64')}$${derived.toString('base64')}`; + + const wrongScrypt = await hasher.verifyAndUpgrade(legacyScrypt, 'nope'); + expect(wrongScrypt).toEqual({ valid: false }); + + const okScrypt = await hasher.verifyAndUpgrade(legacyScrypt, 'legacy-pass'); + expect(okScrypt.valid).toBe(true); + expect(okScrypt.upgradedHash).toMatch(/^\$argon2id\$v=19\$/u); + expect(okScrypt.upgradedHash?.split('$')[3].split(',')).toEqual( + expect.arrayContaining(['m=32768', 't=2', 'p=1']), + ); + }); + + it('sheds excess concurrent hashing load with HTTP 429 and Retry-After', async () => { + const hasher = makeHasher({ + AUTH_HASH_MAX_CONCURRENT: 1, + AUTH_HASH_MAX_QUEUE: 0, + AUTH_HASH_QUEUE_TIMEOUT_MS: 500, + }); + await hasher.onModuleInit(); + + const results = await Promise.allSettled([ + hasher.hash('pw-1'), + hasher.hash('pw-2'), + hasher.hash('pw-3'), + ]); + + const fulfilled = results.filter((r) => r.status === 'fulfilled'); + const rejected = results.filter((r) => r.status === 'rejected'); + expect(fulfilled).toHaveLength(1); + expect(rejected).toHaveLength(2); + for (const item of rejected) { + expect(item.reason).toBeInstanceOf(HttpException); + const exc = item.reason as HttpException; + expect(exc.getStatus()).toBe(HttpStatus.TOO_MANY_REQUESTS); + expect(exc.getResponse()).toMatchObject({ retryAfter: 1 }); + } + }); +}); diff --git a/app/src/auth/password-hasher.service.ts b/app/src/auth/password-hasher.service.ts new file mode 100644 index 0000000..ac1271d --- /dev/null +++ b/app/src/auth/password-hasher.service.ts @@ -0,0 +1,344 @@ +import { + HttpException, + HttpStatus, + Injectable, + OnModuleInit, + Optional, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import argon2 from 'argon2'; +import { + randomBytes, + scrypt as cryptoScrypt, + timingSafeEqual, +} from 'node:crypto'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { meter } from '../telemetry/instruments.js'; + +export type PasswordVerifyResult = { + readonly valid: boolean; + readonly needsRehash: boolean; +}; + +export type PasswordVerifyAndUpgradeResult = { + readonly valid: boolean; + readonly upgradedHash?: string; +}; + +type Waiter = { + resolve: () => void; + reject: (error: Error) => void; + timer: NodeJS.Timeout; +}; + +const SCRYPT_PHC_RE = + /^\$scrypt\$ln=(\d+),r=(\d+),p=(\d+)\$([A-Za-z0-9+/=_-]+)\$([A-Za-z0-9+/=_-]+)$/u; + +function scryptAsync( + password: string, + salt: Buffer, + keyLen: number, + options: { N: number; r: number; p: number; maxmem: number }, +): Promise { + return new Promise((resolve, reject) => { + cryptoScrypt(password, salt, keyLen, options, (error, derivedKey) => { + if (error) reject(error); + else resolve(derivedKey); + }); + }); +} + +function decodeBase64Flexible(encoded: string): Buffer { + const normalized = encoded.replace(/-/gu, '+').replace(/_/gu, '/'); + const pad = normalized.length % 4; + const padded = + pad === 0 ? normalized : `${normalized}${'='.repeat(4 - pad)}`; + return Buffer.from(padded, 'base64'); +} + +async function verifyLegacyScrypt( + storedHash: string, + password: string, +): Promise { + const match = SCRYPT_PHC_RE.exec(storedHash); + if (!match) return undefined; + const ln = Number(match[1]); + const r = Number(match[2]); + const p = Number(match[3]); + if ( + !Number.isInteger(ln) || + ln < 10 || + ln > 18 || + !Number.isInteger(r) || + r < 1 || + r > 16 || + !Number.isInteger(p) || + p < 1 || + p > 4 + ) { + return undefined; + } + const salt = decodeBase64Flexible(match[4]); + const expected = decodeBase64Flexible(match[5]); + if (salt.length < 8 || expected.length < 16 || expected.length > 64) { + return undefined; + } + const N = 2 ** ln; + const maxmem = Math.max(128 * N * r * 2, 32 * 1024 * 1024); + const derived = await scryptAsync(password, salt, expected.length, { + N, + r, + p, + maxmem, + }); + if (derived.length !== expected.length) return false; + return timingSafeEqual(derived, expected); +} + +@Injectable() +export class PasswordHasherService implements OnModuleInit { + private readonly memoryCost: number; + private readonly timeCost: number; + private readonly parallelism: number; + private readonly maxConcurrent: number; + private readonly maxQueue: number; + private readonly queueTimeoutMs: number; + private dummyHash: string | undefined; + private dummyInitPromise: Promise | undefined; + private active = 0; + private readonly queue: Waiter[] = []; + + constructor( + config: ConfigService, + @Optional() private readonly metrics?: MetricsService, + ) { + this.memoryCost = config.getOrThrow('ARGON2_MEMORY_KIB'); + this.timeCost = config.getOrThrow('ARGON2_ITERATIONS'); + this.parallelism = config.getOrThrow('ARGON2_PARALLELISM'); + this.maxConcurrent = config.getOrThrow('AUTH_HASH_MAX_CONCURRENT'); + this.maxQueue = config.getOrThrow('AUTH_HASH_MAX_QUEUE'); + this.queueTimeoutMs = config.getOrThrow('AUTH_HASH_QUEUE_TIMEOUT_MS'); + } + + async onModuleInit(): Promise { + this.observeConcurrency(); + await this.ensureDummyHash(); + } + + get activeCount(): number { + return this.active; + } + + get queuedCount(): number { + return this.queue.length; + } + + async hash(password: string): Promise { + return this.withPermit(() => this.computeHash(password)); + } + + async verify( + storedHash: string | undefined, + password: string, + ): Promise { + return this.withPermit(() => this.verifyInternal(storedHash, password)); + } + + /** + * Verifies a password and, if valid and parameters/algorithm are outdated, + * computes the upgraded Argon2id hash inside the SAME concurrency permit so + * a single login never double-acquires permits or deadlocks under load. + */ + async verifyAndUpgrade( + storedHash: string | undefined, + password: string, + ): Promise { + return this.withPermit(async () => { + const result = await this.verifyInternal(storedHash, password); + if (!result.valid) return { valid: false }; + if (!result.needsRehash) return { valid: true }; + const upgradedHash = await this.computeHash(password); + return { valid: true, upgradedHash }; + }); + } + + private async verifyInternal( + storedHash: string | undefined, + password: string, + ): Promise { + const dummy = await this.ensureDummyHash(); + if (!storedHash) { + await argon2.verify(dummy, password).catch(() => false); + return { valid: false, needsRehash: false }; + } + + if ( + storedHash.startsWith('$argon2id$') || + storedHash.startsWith('$argon2i$') || + storedHash.startsWith('$argon2d$') + ) { + try { + const valid = await argon2.verify(storedHash, password); + if (!valid) return { valid: false, needsRehash: false }; + const needsRehash = + !storedHash.startsWith('$argon2id$') || + argon2.needsRehash(storedHash, { + memoryCost: this.memoryCost, + timeCost: this.timeCost, + parallelism: this.parallelism, + }); + return { valid: true, needsRehash }; + } catch { + await argon2.verify(dummy, password).catch(() => false); + return { valid: false, needsRehash: false }; + } + } + + if (storedHash.startsWith('$scrypt$')) { + try { + const valid = await verifyLegacyScrypt(storedHash, password); + if (valid === undefined) { + await argon2.verify(dummy, password).catch(() => false); + return { valid: false, needsRehash: false }; + } + return { valid, needsRehash: valid }; + } catch { + await argon2.verify(dummy, password).catch(() => false); + return { valid: false, needsRehash: false }; + } + } + + await argon2.verify(dummy, password).catch(() => false); + return { valid: false, needsRehash: false }; + } + + private computeHash(password: string): Promise { + return argon2.hash(password, { + type: argon2.argon2id, + memoryCost: this.memoryCost, + timeCost: this.timeCost, + parallelism: this.parallelism, + hashLength: 32, + }); + } + + private ensureDummyHash(): Promise { + if (this.dummyHash) return Promise.resolve(this.dummyHash); + if (!this.dummyInitPromise) { + this.dummyInitPromise = this.computeHash( + randomBytes(32).toString('hex'), + ) + .then((computed) => { + this.dummyHash = computed; + return computed; + }) + .finally(() => { + this.dummyInitPromise = undefined; + }); + } + return this.dummyInitPromise; + } + + private async withPermit(work: () => Promise): Promise { + await this.acquire(); + const started = performance.now(); + try { + return await work(); + } finally { + const elapsedMs = performance.now() - started; + this.metrics?.increment('auth.hash.completed'); + this.recordDuration(elapsedMs); + this.release(); + } + } + + private acquire(): Promise { + if (this.active < this.maxConcurrent) { + this.active += 1; + return Promise.resolve(); + } + if (this.queue.length >= this.maxQueue) { + this.metrics?.increment('auth.hash.rejected'); + return Promise.reject( + new HttpException( + { + message: 'Too many authentication requests', + retryAfter: 1, + }, + HttpStatus.TOO_MANY_REQUESTS, + ), + ); + } + return new Promise((resolve, reject) => { + const waiter: Waiter = { + resolve, + reject, + timer: setTimeout(() => { + const idx = this.queue.indexOf(waiter); + if (idx >= 0) this.queue.splice(idx, 1); + this.metrics?.increment('auth.hash.rejected'); + reject( + new HttpException( + { + message: 'Too many authentication requests', + retryAfter: 1, + }, + HttpStatus.TOO_MANY_REQUESTS, + ), + ); + }, this.queueTimeoutMs), + }; + waiter.timer.unref(); + this.queue.push(waiter); + }); + } + + private release(): void { + const next = this.queue.shift(); + if (next) { + clearTimeout(next.timer); + next.resolve(); + return; + } + this.active = Math.max(0, this.active - 1); + } + + private durationHistogram: + | ReturnType['createHistogram']> + | undefined; + + private recordDuration(ms: number): void { + try { + this.durationHistogram ??= meter().createHistogram( + 'auth.hash.duration_ms', + { + unit: 'ms', + description: 'Password hashing/verification duration', + }, + ); + this.durationHistogram.record(ms); + } catch { + // Best-effort telemetry recording. + } + } + + private observeConcurrency(): void { + const m = meter(); + const activeGauge = m.createObservableUpDownCounter('auth.hash.active', { + unit: '{operation}', + description: 'In-flight password hash/verify operations', + }); + const queuedGauge = m.createObservableUpDownCounter('auth.hash.queued', { + unit: '{operation}', + description: 'Queued password hash/verify operations', + }); + m.addBatchObservableCallback( + (result) => { + result.observe(activeGauge, this.active); + result.observe(queuedGauge, this.queue.length); + }, + [activeGauge, queuedGauge], + ); + } +} diff --git a/app/src/auth/session.repository.spec.ts b/app/src/auth/session.repository.spec.ts new file mode 100644 index 0000000..29897bf --- /dev/null +++ b/app/src/auth/session.repository.spec.ts @@ -0,0 +1,125 @@ +import { + ServiceUnavailableException, + UnauthorizedException, + type ExecutionContext, +} from '@nestjs/common'; +import { describe, expect, it, vi } from 'vitest'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { + hashSessionToken, + SessionRepository, + sessionRedisKey, +} from './session.repository.js'; + +describe('SessionRepository & CurrentUserGuard', () => { + function makeRepo() { + const store = new Map(); + const redis = { + set: vi.fn(async (key: string, value: string) => { + store.set(key, value); + return 'OK'; + }), + get: vi.fn(async (key: string) => store.get(key) ?? null), + del: vi.fn(async (key: string) => (store.delete(key) ? 1 : 0)), + }; + const config = { + getOrThrow: (key: string) => + key === 'SESSION_TTL_SECONDS' ? 3600 : undefined, + }; + const repo = new SessionRepository( + redis as never, + config as never, + new MetricsService(), + ); + return { repo, store, redis }; + } + + it('stores SHA-256 hashed Bearer tokens and never writes raw tokens to Redis', async () => { + const { repo, store } = makeRepo(); + const created = await repo.create('user-123'); + const expectedKey = sessionRedisKey(created.token); + + expect(expectedKey).toBe(`session:sha256:${hashSessionToken(created.token)}`); + expect(expectedKey).toMatch(/^session:sha256:[a-f0-9]{64}$/u); + expect(store.has(expectedKey)).toBe(true); + + for (const [k, v] of store.entries()) { + expect(k).not.toContain(created.token); + expect(v).not.toContain(created.token); + } + + expect(await repo.findUserId(created.token)).toBe('user-123'); + expect(await repo.delete(created.token)).toBe(1); + expect(await repo.findUserId(created.token)).toBeUndefined(); + }); + + it('rejects expired and malformed session records', async () => { + const { repo, store } = makeRepo(); + const token = 'expired-token-value'; + store.set( + sessionRedisKey(token), + JSON.stringify({ + user_id: 'user-1', + expires_at: new Date(Date.now() - 10_000).toISOString(), + }), + ); + expect(await repo.findUserId(token)).toBeUndefined(); + + store.set(sessionRedisKey('broken'), '{not-json'); + expect(await repo.findUserId('broken')).toBeUndefined(); + }); + + it('enforces Bearer token in CurrentUserGuard and ignores X-User-Id', async () => { + const { repo, redis } = makeRepo(); + const user = { + id: 'user-1', + username: 'alice', + display_name: 'Alice', + created_at: new Date().toISOString(), + }; + const users = { + findById: vi.fn(async (id: string) => + id === 'user-1' ? user : undefined, + ), + }; + const guard = new CurrentUserGuard(repo, users as never); + + const ctxFor = (headers: Record) => { + const req: Record = { headers }; + return { + req, + ctx: { + switchToHttp: () => ({ getRequest: () => req }), + } as unknown as ExecutionContext, + }; + }; + + // Forged X-User-Id without Bearer must return 401. + await expect( + guard.canActivate(ctxFor({ 'x-user-id': 'user-1' }).ctx), + ).rejects.toBeInstanceOf(UnauthorizedException); + + // Basic auth on protected route must return 401. + await expect( + guard.canActivate(ctxFor({ authorization: 'Basic dXNlcjpwYXNz' }).ctx), + ).rejects.toBeInstanceOf(UnauthorizedException); + + // Valid Bearer succeeds and binds session owner even if X-User-Id is spoofed. + const session = await repo.create('user-1'); + const valid = ctxFor({ + authorization: `Bearer ${session.token}`, + 'x-user-id': 'other-user', + }); + expect(await guard.canActivate(valid.ctx)).toBe(true); + expect(valid.req.currentUser).toEqual(user); + + // Redis outage returns 503. + redis.get.mockRejectedValueOnce(new Error('ECONNREFUSED')); + await expect( + guard.canActivate( + ctxFor({ authorization: `Bearer ${session.token}` }).ctx, + ), + ).rejects.toBeInstanceOf(ServiceUnavailableException); + }); +}); diff --git a/app/src/auth/session.repository.ts b/app/src/auth/session.repository.ts index 57eb282..b3dd1f3 100644 --- a/app/src/auth/session.repository.ts +++ b/app/src/auth/session.repository.ts @@ -1,10 +1,21 @@ import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { randomBytes } from 'node:crypto'; +import { createHash, randomBytes } from 'node:crypto'; import type { AppConfig } from '../config/app-config.schema.js'; import { RedisClient } from '../redis/redis.client.js'; import { MetricsService } from '../metrics/metrics.service.js'; +const ISO_TIMESTAMP_RE = + /^(?:\d{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u; + +export function hashSessionToken(token: string): string { + return createHash('sha256').update(token, 'utf8').digest('hex'); +} + +export function sessionRedisKey(token: string): string { + return `session:sha256:${hashSessionToken(token)}`; +} + @Injectable() export class SessionRepository { constructor( @@ -21,15 +32,42 @@ export class SessionRepository { const expiresAt = new Date(Date.now() + ttl * 1000).toISOString(); this.metrics.increment('session_set'); await this.redis.set( - `session:${token}`, + sessionRedisKey(token), JSON.stringify({ user_id: userId, expires_at: expiresAt }), { EX: ttl }, ); return { token, expiresAt }; } + async findUserId(token: string): Promise { + this.metrics.increment('session_get'); + const raw = await this.redis.get(sessionRedisKey(token)); + if (!raw) return undefined; + try { + const parsed: unknown = JSON.parse(raw); + if ( + typeof parsed !== 'object' || + parsed === null || + !('user_id' in parsed) || + typeof parsed.user_id !== 'string' || + !('expires_at' in parsed) || + typeof parsed.expires_at !== 'string' || + !ISO_TIMESTAMP_RE.test(parsed.expires_at) + ) { + return undefined; + } + const expiresAt = Date.parse(parsed.expires_at); + if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt) { + return undefined; + } + return parsed.user_id; + } catch { + return undefined; + } + } + delete(token: string): Promise { this.metrics.increment('session_del'); - return this.redis.del(`session:${token}`); + return this.redis.del(sessionRedisKey(token)); } } diff --git a/app/src/common/auth/current-user.guard.ts b/app/src/common/auth/current-user.guard.ts index ae400b1..07a71aa 100644 --- a/app/src/common/auth/current-user.guard.ts +++ b/app/src/common/auth/current-user.guard.ts @@ -6,70 +6,41 @@ import { UnauthorizedException, } from '@nestjs/common'; import type { FastifyRequest } from 'fastify'; +import { SessionRepository } from '../../auth/session.repository.js'; import type { User } from '../../users/user.js'; -import { RedisClient } from '../../redis/redis.client.js'; import { UsersService } from '../../users/users.service.js'; -import { MetricsService } from '../../metrics/metrics.service.js'; + +const BEARER_HEADER_RE = /^Bearer[ \t]+([^ \t]+)$/iu; + +function bearerUnauthorized(): UnauthorizedException { + return new UnauthorizedException({ + message: 'Unauthorized', + challenge: 'Bearer realm="messenger"', + }); +} @Injectable() export class CurrentUserGuard implements CanActivate { constructor( - private readonly redis: RedisClient, + private readonly sessions: SessionRepository, private readonly users: UsersService, - private readonly metrics: MetricsService, ) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const authorization = request.headers.authorization; - if ( - typeof authorization !== 'string' || - !/^Bearer\s+[^\s]+$/u.test(authorization) - ) { - throw new UnauthorizedException({ - message: 'Unauthorized', - challenge: 'Bearer realm="messenger"', - }); - } - let session: string | null; + if (typeof authorization !== 'string') throw bearerUnauthorized(); + const match = BEARER_HEADER_RE.exec(authorization); + if (!match) throw bearerUnauthorized(); + + let userId: string | undefined; try { - this.metrics.increment('session_get'); - session = await this.redis.get( - `session:${authorization.slice(7).trim()}`, - ); + userId = await this.sessions.findUserId(match[1]); } catch { throw new ServiceUnavailableException('Session store unavailable'); } - if (!session) - throw new UnauthorizedException({ - message: 'Unauthorized', - challenge: 'Bearer realm="messenger"', - }); - let userId: string; - try { - const parsed: unknown = JSON.parse(session); - if ( - typeof parsed !== 'object' || - parsed === null || - !('user_id' in parsed) || - typeof parsed.user_id !== 'string' || - !('expires_at' in parsed) || - typeof parsed.expires_at !== 'string' || - !/^(?:\d{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u.test( - parsed.expires_at, - ) - ) - throw new Error('invalid session'); - const expiresAt = Date.parse(parsed.expires_at); - if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt) - throw new Error('expired session'); - userId = parsed.user_id; - } catch { - throw new UnauthorizedException({ - message: 'Unauthorized', - challenge: 'Bearer realm="messenger"', - }); - } + if (!userId) throw bearerUnauthorized(); + let user: User | undefined; try { user = await this.users.findById(userId); @@ -78,7 +49,7 @@ export class CurrentUserGuard implements CanActivate { 'Authentication service unavailable', ); } - if (!user) throw new UnauthorizedException(); + if (!user) throw bearerUnauthorized(); request.currentUser = user; return true; } diff --git a/app/src/common/errors/api-exception.filter.spec.ts b/app/src/common/errors/api-exception.filter.spec.ts new file mode 100644 index 0000000..148b764 --- /dev/null +++ b/app/src/common/errors/api-exception.filter.spec.ts @@ -0,0 +1,77 @@ +import { + HttpException, + HttpStatus, + type ArgumentsHost, +} from '@nestjs/common'; +import { describe, expect, it, vi } from 'vitest'; +import { ApiExceptionFilter } from './api-exception.filter.js'; + +describe('ApiExceptionFilter (Lab 7 error normalization)', () => { + function runFilter(exception: unknown, method = 'POST', url = '/api/v1/auth/sessions') { + const headers: Record = {}; + let repliedBody: unknown; + let repliedStatus = 0; + + const adapterHost = { + httpAdapter: { + setHeader: vi.fn((_res: unknown, k: string, v: string) => { + headers[k] = v; + }), + reply: vi.fn((_res: unknown, body: unknown, status: number) => { + repliedBody = body; + repliedStatus = status; + }), + }, + }; + const config = { + get: () => undefined, + }; + const filter = new ApiExceptionFilter(adapterHost as never, config as never); + const request = { method, url, routeOptions: { url } }; + const host = { + switchToHttp: () => ({ + getRequest: () => request, + getResponse: () => ({}), + }), + } as unknown as ArgumentsHost; + + filter.catch(exception, host); + return { headers, status: repliedStatus, body: repliedBody as Record }; + } + + it('maps Fastify body-too-large errors cleanly to 413 payload_too_large without leaking internals', () => { + const res = runFilter({ + statusCode: 413, + code: 'FST_ERR_CTP_BODY_TOO_LARGE', + message: 'Request body is too large internal detail', + }); + expect(res.status).toBe(413); + expect(res.body.error.code).toBe('payload_too_large'); + expect(res.body.error.message).toBe('Payload too large'); + expect(res.headers['X-Instance-Id']).toMatch(/^rep-[0-9a-f]{12}$/u); + }); + + it('maps PG 28P01 auth rotation errors to 503 unavailable without leaking secrets', () => { + const res = runFilter( + Object.assign(new Error('password authentication failed for user messenger_api'), { + code: '28P01', + }), + ); + expect(res.status).toBe(503); + expect(res.body.error.code).toBe('unavailable'); + expect(res.body.error.message).toBe('Service unavailable'); + expect(JSON.stringify(res.body)).not.toContain('messenger_api'); + }); + + it('emits 429 rate_limited with integer Retry-After >= 1', () => { + const res = runFilter( + new HttpException( + { message: 'Too many login attempts', retryAfter: 17.2 }, + HttpStatus.TOO_MANY_REQUESTS, + ), + ); + expect(res.status).toBe(429); + expect(res.body.error.code).toBe('rate_limited'); + expect(res.headers['Retry-After']).toBe('18'); + }); +}); diff --git a/app/src/common/errors/api-exception.filter.ts b/app/src/common/errors/api-exception.filter.ts index 303e4d4..079c216 100644 --- a/app/src/common/errors/api-exception.filter.ts +++ b/app/src/common/errors/api-exception.filter.ts @@ -29,7 +29,8 @@ type ExceptionBody = { retryAfter?: unknown; }; -// Connection/session loss codes reported by node-postgres and the network layer. +// Connection/session loss and transient auth/TLS rotation codes reported by +// node-postgres, node-redis, and the TLS/network layer. const UNAVAILABLE_ERROR_CODES: Record = { ECONNREFUSED: true, ECONNRESET: true, @@ -38,29 +39,27 @@ const UNAVAILABLE_ERROR_CODES: Record = { EAI_AGAIN: true, ETIMEDOUT: true, EPIPE: true, + EPROTO: true, + ERR_TLS_CERT_ALTNAME_INVALID: true, + CERT_HAS_EXPIRED: true, + DEPTH_ZERO_SELF_SIGNED_CERT: true, + UNABLE_TO_VERIFY_LEAF_SIGNATURE: true, '08000': true, '08001': true, '08003': true, '08004': true, '08006': true, + '28000': true, + '28P01': true, '57P01': true, '57P02': true, '57P03': true, '53300': true, - // Transient aborts: the statement was cancelled by statement_timeout, the - // transaction was rolled back by a serialization failure or a deadlock. The - // work was never confirmed, so callers see a retryable 503 instead of an - // internal error. Without this, such an abort would be recorded as the final - // result of an idempotent operation. '57014': true, '40001': true, '40P01': true, }; -// Some driver failures carry no `code` at all: node-postgres raises plain errors -// when a connection dies or its pool attempt times out, and node-redis reports a -// closed socket the same way. Without these patterns a stopped database would -// surface as an internal fault instead of a bounded outage. const UNAVAILABLE_ERROR_MESSAGES = [ 'Connection terminated unexpectedly', 'Connection terminated due to connection timeout', @@ -68,6 +67,8 @@ const UNAVAILABLE_ERROR_MESSAGES = [ 'Client has encountered a connection error and is not queryable', 'Socket closed unexpectedly', 'Connection is closed', + 'WRONGPASS', + 'NOAUTH', ]; function isDependencyOutage(exception: unknown): boolean { @@ -82,10 +83,44 @@ function isDependencyOutage(exception: unknown): boolean { ); } +function fastifyClientErrorStatus(exception: unknown): number | undefined { + if (typeof exception !== 'object' || exception === null) return undefined; + const statusCode = (exception as { statusCode?: unknown }).statusCode; + if ( + statusCode === HttpStatus.BAD_REQUEST || + statusCode === HttpStatus.PAYLOAD_TOO_LARGE || + statusCode === HttpStatus.UNSUPPORTED_MEDIA_TYPE + ) { + return statusCode; + } + const code = (exception as { code?: unknown }).code; + if (code === 'FST_ERR_CTP_BODY_TOO_LARGE') + return HttpStatus.PAYLOAD_TOO_LARGE; + if ( + code === 'FST_ERR_CTP_INVALID_MEDIA_TYPE' || + code === 'FST_ERR_CTP_INVALID_CONTENT_LENGTH' + ) + return HttpStatus.UNSUPPORTED_MEDIA_TYPE; + if ( + code === 'FST_ERR_CTP_INVALID_JSON_BODY' || + code === 'FST_ERR_CTP_EMPTY_JSON_BODY' + ) + return HttpStatus.BAD_REQUEST; + return undefined; +} + +function safeMessageForFastifyStatus(status: number): string { + if (status === HttpStatus.PAYLOAD_TOO_LARGE) return 'Payload too large'; + if (status === HttpStatus.UNSUPPORTED_MEDIA_TYPE) + return 'Unsupported media type'; + return 'Invalid request payload'; +} + function errorCodeForStatus(status: number): string { const codes: Record = { [HttpStatus.BAD_REQUEST]: 'invalid_request', [HttpStatus.UNAUTHORIZED]: 'unauthorized', + [HttpStatus.FORBIDDEN]: 'forbidden', [HttpStatus.NOT_FOUND]: 'not_found', [HttpStatus.CONFLICT]: 'conflict', [HttpStatus.PAYLOAD_TOO_LARGE]: 'payload_too_large', @@ -99,8 +134,6 @@ function errorCodeForStatus(status: number): string { @Catch() export class ApiExceptionFilter implements ExceptionFilter { private readonly logger = new Logger(ApiExceptionFilter.name); - // Guards and pipes run before interceptors, so an error response may be the - // first thing the filter writes: it must carry the replica identity too. private readonly instanceId: string; constructor( @@ -122,6 +155,11 @@ export class ApiExceptionFilter implements ExceptionFilter { let message = 'Internal server error'; let challenge: string | undefined; let retryAfter = 1; + const fastifyStatus = + exception instanceof HttpException + ? undefined + : fastifyClientErrorStatus(exception); + if (exception instanceof HttpException) { status = exception.getStatus(); const body = exception.getResponse(); @@ -152,8 +190,10 @@ export class ApiExceptionFilter implements ExceptionFilter { status === HttpStatus.SERVICE_UNAVAILABLE ? 'Service unavailable' : 'Internal server error'; + } else if (fastifyStatus !== undefined) { + status = fastifyStatus; + message = safeMessageForFastifyStatus(fastifyStatus); } else if (isDependencyOutage(exception)) { - // A dropped dependency is a bounded outage, not an internal fault. status = HttpStatus.SERVICE_UNAVAILABLE; message = 'Service unavailable'; this.logger.warn( diff --git a/app/src/config/app-config.schema.spec.ts b/app/src/config/app-config.schema.spec.ts new file mode 100644 index 0000000..524cf77 --- /dev/null +++ b/app/src/config/app-config.schema.spec.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from 'vitest'; +import { + parseAppConfig, + parseDatabaseConfig, + parseWorkerConfig, +} from './app-config.schema.js'; + +const BASE_LOCAL_ENV: Record = { + TLS_ENABLED: 'false', + BAO_ENABLED: 'false', + DATABASE_URL: 'postgresql://user:pass@localhost:5432/messenger', + REDIS_URL: 'redis://localhost:6379', + BROKER_URL: 'amqp://localhost:5672/messenger', + S3_ENDPOINT: 'http://localhost:9000', + S3_PUBLIC_ENDPOINT: 'http://localhost:9000', + S3_BUCKET: 'messenger-attachments', + S3_ACCESS_KEY_ID: 'key', + S3_SECRET_ACCESS_KEY: 'secret', +}; + +const BASE_PROD_ENV: Record = { + TLS_ENABLED: 'true', + TLS_CA_FILE: '/run/certs/ca.crt', + BAO_ENABLED: 'true', + BAO_ADDR: 'https://openbao:8200', + PG_HOST: 'postgres', + PG_DATABASE: 'messenger', + REDIS_HOST: 'redis', + BROKER_HOST: 'broker', + S3_ENDPOINT: 'https://s3:9000', + S3_PUBLIC_ENDPOINT: 'https://localhost:9000', + S3_BUCKET: 'messenger-attachments', +}; + +describe('app-config.schema (Lab 7 security floors)', () => { + it('enforces Argon2id minimum floors (>= 19456 KiB, t >= 2, p >= 1)', () => { + const defaults = parseAppConfig(BASE_LOCAL_ENV); + expect(defaults.ARGON2_MEMORY_KIB).toBe(32768); + expect(defaults.ARGON2_ITERATIONS).toBe(2); + expect(defaults.ARGON2_PARALLELISM).toBe(1); + + expect(() => + parseAppConfig({ ...BASE_LOCAL_ENV, ARGON2_MEMORY_KIB: '16384' }), + ).toThrow(); + expect(() => + parseAppConfig({ ...BASE_LOCAL_ENV, ARGON2_ITERATIONS: '1' }), + ).toThrow(); + expect(() => + parseAppConfig({ ...BASE_LOCAL_ENV, ARGON2_PARALLELISM: '0' }), + ).toThrow(); + }); + + it('strictly forbids BAO_TOKEN and VAULT_TOKEN when BAO_ENABLED=true', () => { + expect(() => + parseAppConfig({ ...BASE_PROD_ENV, BAO_TOKEN: 'hvs.root-secret' }), + ).toThrow(/forbidden/i); + expect(() => + parseWorkerConfig({ + ...BASE_PROD_ENV, + VAULT_TOKEN: 's.static-token', + }), + ).toThrow(/forbidden/i); + expect(() => + parseDatabaseConfig({ + TLS_ENABLED: 'true', + TLS_CA_FILE: '/run/certs/ca.crt', + BAO_ENABLED: 'true', + BAO_ADDR: 'https://openbao:8200', + PG_HOST: 'postgres', + PG_DATABASE: 'messenger', + BAO_TOKEN: 'hvs.bad', + }), + ).toThrow(/forbidden/i); + }); + + it('accepts zero-secret OpenBao env for API, Worker (no Redis/public S3), and Migrator', () => { + const api = parseAppConfig(BASE_PROD_ENV); + expect(api.APP_PORT).toBe(8443); + expect(api.TLS_ALLOWED_CLIENT_SANS).toBe('haproxy-lb'); + expect(api.MAX_JSON_BODY_BYTES).toBe(65536); + expect(api.BROKER_ROLE).toBe('producer'); + expect(api.BROKER_AUTH_MECHANISM).toBe('external'); + expect(api.BROKER_PASSIVE_TOPOLOGY).toBe(true); + expect(api.DATABASE_URL).toBeUndefined(); + expect(api.S3_SECRET_ACCESS_KEY).toBeUndefined(); + + const workerEnv = { ...BASE_PROD_ENV }; + delete workerEnv.REDIS_HOST; + delete workerEnv.S3_PUBLIC_ENDPOINT; + const worker = parseWorkerConfig(workerEnv); + expect(worker.BROKER_ROLE).toBe('consumer'); + expect(worker.REDIS_HOST).toBeUndefined(); + expect(worker.S3_PUBLIC_ENDPOINT).toBeUndefined(); + + const migrator = parseDatabaseConfig({ + TLS_ENABLED: 'true', + TLS_CA_FILE: '/run/certs/ca.crt', + BAO_ENABLED: 'true', + BAO_ADDR: 'https://openbao:8200', + DATABASE_HOST: 'postgres', + DATABASE_NAME: 'messenger', + BAO_AUTH_ROLE: 'messenger-migrator', + }); + expect(migrator.PG_HOST).toBe('postgres'); + expect(migrator.PG_DATABASE).toBe('messenger'); + expect(migrator.BAO_CERT_ROLE).toBe('messenger-migrator'); + }); + + it('refuses plaintext S3 endpoints when TLS_ENABLED=true', () => { + expect(() => + parseAppConfig({ + ...BASE_PROD_ENV, + S3_ENDPOINT: 'http://s3:9000', + }), + ).toThrow(/https:\/\//); + expect(() => + parseAppConfig({ + ...BASE_PROD_ENV, + S3_PUBLIC_ENDPOINT: 'http://localhost:9000', + }), + ).toThrow(/https:\/\//); + }); +}); diff --git a/app/src/config/app-config.schema.ts b/app/src/config/app-config.schema.ts index 4e0949c..2048104 100644 --- a/app/src/config/app-config.schema.ts +++ b/app/src/config/app-config.schema.ts @@ -21,21 +21,241 @@ function numeric( ); } +function optionalNumeric( + name: string, + minimum: number, + maximum: number | undefined, +) { + let schema = z + .number({ message: `${name} must be a number` }) + .int() + .min(minimum); + if (maximum !== undefined) schema = schema.max(maximum); + return z.preprocess((value) => { + if (value === undefined || value === null) return undefined; + if (typeof value === 'string') { + const trimmed = value.trim(); + return trimmed === '' ? undefined : Number(trimmed); + } + return value; + }, schema.optional()); +} + +function booleanFlag(name: string, fallback: boolean) { + return z.preprocess((value) => { + if (value === undefined || value === null) return undefined; + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value !== 0; + if (typeof value === 'string') { + const normalized = value.trim().toLowerCase(); + if (normalized === '') return undefined; + if (['true', '1', 'yes', 'on'].includes(normalized)) return true; + if (['false', '0', 'no', 'off'].includes(normalized)) return false; + } + return value; + }, z.boolean({ message: `${name} must be a boolean` }).default(fallback)); +} + +function optionalString() { + return z.preprocess((value) => { + if (typeof value !== 'string') return value; + const trimmed = value.trim(); + return trimmed.length === 0 ? undefined : trimmed; + }, z.string().min(1).optional()); +} + function requiredString(name: string) { return z .string({ message: `${name} is required` }) .min(1, `${name} is required`); } -export const appConfigSchema = z +function resolveSecret( + raw: Record, + key: + | 'DATABASE_URL' + | 'REDIS_URL' + | 'BROKER_URL' + | 'S3_ACCESS_KEY_ID' + | 'S3_SECRET_ACCESS_KEY' + | 'METRICS_TOKEN', +): unknown { + const fileKey = `${key}_FILE`; + const path = raw[fileKey]; + if (typeof path !== 'string' || path.length === 0) return raw[key]; + try { + const value = readFileSync(path, 'utf8').trim(); + if (value.length === 0) + throw new Error(`${fileKey} contains an empty value`); + return value; + } catch (error) { + if ( + error instanceof Error && + error.message.includes('contains an empty value') + ) + throw error; + throw new Error(`${fileKey} could not be read`); + } +} + +export function resolveBooleanEnv( + value: unknown, + fallback: boolean, +): boolean { + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value !== 0; + if (typeof value === 'string') { + const normalized = value.trim().toLowerCase(); + if (normalized === '') return fallback; + if (['true', '1', 'yes', 'on'].includes(normalized)) return true; + if (['false', '0', 'no', 'off'].includes(normalized)) return false; + } + return fallback; +} + +export function resolveTlsEnabled(raw: Record): boolean { + const hasExplicit = + raw.TLS_ENABLED !== undefined && + String(raw.TLS_ENABLED).trim() !== ''; + if (hasExplicit) return resolveBooleanEnv(raw.TLS_ENABLED, true); + const hasCaFile = + typeof raw.TLS_CA_FILE === 'string' && raw.TLS_CA_FILE.trim().length > 0; + const isProduction = + typeof raw.NODE_ENV === 'string' && + raw.NODE_ENV.trim().toLowerCase() === 'production'; + return hasCaFile || isProduction; +} + +export function resolveBaoEnabled(raw: Record): boolean { + const hasExplicit = + raw.BAO_ENABLED !== undefined && + String(raw.BAO_ENABLED).trim() !== ''; + if (hasExplicit) return resolveBooleanEnv(raw.BAO_ENABLED, false); + return ( + typeof raw.BAO_ADDR === 'string' && raw.BAO_ADDR.trim().length > 0 + ); +} + +export function assertNoStaticBaoToken(raw: Record): void { + if (!resolveBaoEnabled(raw)) return; + const baoToken = + typeof raw.BAO_TOKEN === 'string' ? raw.BAO_TOKEN.trim() : ''; + const vaultToken = + typeof raw.VAULT_TOKEN === 'string' ? raw.VAULT_TOKEN.trim() : ''; + if (baoToken.length > 0 || vaultToken.length > 0) { + throw new Error( + 'Static BAO_TOKEN/VAULT_TOKEN is forbidden when BAO_ENABLED=true', + ); + } +} + +function firstNonEmpty(...values: unknown[]): unknown { + for (const value of values) { + if (typeof value === 'string' && value.trim().length > 0) + return value.trim(); + if (typeof value === 'number' && Number.isFinite(value)) return value; + } + return undefined; +} + +const baseConfigSchema = z .object({ APP_HOST: z.string().min(1).default('0.0.0.0'), - APP_PORT: numeric('APP_PORT', 1, 65535, 8080), + APP_PORT: numeric('APP_PORT', 1, 65535, 8443), + API_HEALTH_PORT: numeric('API_HEALTH_PORT', 0, 65535, 8081), APP_ENV: z.string().min(1).default('lab'), SESSION_TTL_SECONDS: numeric('SESSION_TTL_SECONDS', 2, undefined, 3600), - DATABASE_URL: requiredString('DATABASE_URL'), - REDIS_URL: requiredString('REDIS_URL'), - BROKER_URL: requiredString('BROKER_URL'), + // Argon2id hard floor (OWASP & Lab 7 minimum: >= 19 MiB, t >= 2, p >= 1). + ARGON2_MEMORY_KIB: numeric('ARGON2_MEMORY_KIB', 19456, 262144, 32768), + ARGON2_ITERATIONS: numeric('ARGON2_ITERATIONS', 2, 20, 2), + ARGON2_PARALLELISM: numeric('ARGON2_PARALLELISM', 1, 4, 1), + // Bounded login/register hashing concurrency budget to prevent OOM DoS. + AUTH_HASH_MAX_CONCURRENT: numeric('AUTH_HASH_MAX_CONCURRENT', 1, 16, 4), + AUTH_HASH_MAX_QUEUE: numeric('AUTH_HASH_MAX_QUEUE', 0, 128, 8), + AUTH_HASH_QUEUE_TIMEOUT_MS: numeric( + 'AUTH_HASH_QUEUE_TIMEOUT_MS', + 100, + 10000, + 2000, + ), + // Shared Redis fixed-window rate limits across replicas. + LOGIN_RATE_LIMIT_USER_MAX: numeric( + 'LOGIN_RATE_LIMIT_USER_MAX', + 1, + 10000, + 10, + ), + LOGIN_RATE_LIMIT_IP_MAX: numeric( + 'LOGIN_RATE_LIMIT_IP_MAX', + 1, + 10000, + 60, + ), + REGISTER_RATE_LIMIT_IP_MAX: numeric( + 'REGISTER_RATE_LIMIT_IP_MAX', + 1, + 10000, + 60, + ), + LOGIN_RATE_LIMIT_WINDOW_SECONDS: numeric( + 'LOGIN_RATE_LIMIT_WINDOW_SECONDS', + 1, + 3600, + 60, + ), + MAX_JSON_BODY_BYTES: numeric('MAX_JSON_BODY_BYTES', 1024, 1048576, 65536), + // TLS / mTLS configuration. + TLS_ENABLED: booleanFlag('TLS_ENABLED', false), + TLS_CA_FILE: optionalString(), + TLS_CRL_FILE: optionalString(), + TLS_SERVER_CERT_FILE: optionalString(), + TLS_SERVER_KEY_FILE: optionalString(), + TLS_CLIENT_CERT_FILE: optionalString(), + TLS_CLIENT_KEY_FILE: optionalString(), + TLS_ALLOWED_CLIENT_SANS: z.string().default('haproxy-lb'), + TLS_REVOKED_SERIALS_FILE: optionalString(), + TLS_RELOAD_INTERVAL_MS: numeric('TLS_RELOAD_INTERVAL_MS', 0, 300000, 5000), + PG_TLS_MTLS: booleanFlag('PG_TLS_MTLS', false), + REDIS_TLS_MTLS: booleanFlag('REDIS_TLS_MTLS', true), + // OpenBao configuration (BAO_TOKEN / VAULT_TOKEN strictly forbidden when enabled). + BAO_ENABLED: booleanFlag('BAO_ENABLED', false), + BAO_ADDR: optionalString(), + BAO_CACERT: optionalString(), + BAO_AUTH_METHOD: z.enum(['cert', 'approle']).default('cert'), + BAO_CERT_ROLE: optionalString(), + BAO_ROLE_ID_FILE: optionalString(), + BAO_SECRET_ID_FILE: optionalString(), + BAO_WRAPPED_SECRET_ID_FILE: optionalString(), + BAO_SECRET_PATH: optionalString(), + BAO_REFRESH_INTERVAL_MS: numeric( + 'BAO_REFRESH_INTERVAL_MS', + 1000, + 300000, + 15000, + ), + BAO_TIMEOUT_MS: numeric('BAO_TIMEOUT_MS', 500, 30000, 5000), + BAO_STARTUP_RETRIES: numeric('BAO_STARTUP_RETRIES', 1, 30, 5), + // Database connection (either discrete host/port/db + OpenBao or legacy DATABASE_URL). + DATABASE_URL: optionalString(), + PG_HOST: optionalString(), + PG_PORT: optionalNumeric('PG_PORT', 1, 65535), + PG_DATABASE: optionalString(), + PG_USER: optionalString(), + PG_PASSWORD: optionalString(), + // Redis connection (API only; omitted on worker). + REDIS_URL: optionalString(), + REDIS_HOST: optionalString(), + REDIS_PORT: optionalNumeric('REDIS_PORT', 1, 65535), + REDIS_USER: optionalString(), + REDIS_PASSWORD: optionalString(), + // Broker connection (AMQPS + mTLS EXTERNAL or legacy BROKER_URL). + BROKER_URL: optionalString(), + BROKER_HOST: optionalString(), + BROKER_PORT: optionalNumeric('BROKER_PORT', 1, 65535), + BROKER_VHOST: optionalString(), + BROKER_ROLE: z.enum(['producer', 'consumer', 'both']).default('both'), + BROKER_AUTH_MECHANISM: z.enum(['external', 'plain']).default('external'), + BROKER_PASSIVE_TOPOLOGY: booleanFlag('BROKER_PASSIVE_TOPOLOGY', true), BROKER_PUBLISH_TIMEOUT_MS: numeric( 'BROKER_PUBLISH_TIMEOUT_MS', 100, @@ -61,16 +281,14 @@ export const appConfigSchema = z undefined, 30000, ), - // Бюджет зависимостей в /health/ready: LB проверяет ту же ручку, поэтому - // проба готовности обязана уложиться в timeout check HAProxy (500 ms). HEALTH_TIMEOUT_MS: numeric('HEALTH_TIMEOUT_MS', 1, undefined, 400), CACHE_TTL_SECONDS: numeric('CACHE_TTL_SECONDS', 1, undefined, 30), CACHE_MODE: z.enum(['protected', 'naive']).default('protected'), CACHE_LOCK_TTL_MS: numeric('CACHE_LOCK_TTL_MS', 1, undefined, 1000), CACHE_MISS_DELAY_MS: numeric('CACHE_MISS_DELAY_MS', 0, undefined, 0), - METRICS_TOKEN: z.string().min(1).optional(), + METRICS_TOKEN: optionalString(), DRAIN_DELAY_MS: numeric('DRAIN_DELAY_MS', 0, undefined, 5000), - INSTANCE_ID: z.string().min(1).optional(), + INSTANCE_ID: optionalString(), IDEMPOTENCY_TTL_SECONDS: numeric( 'IDEMPOTENCY_TTL_SECONDS', 60, @@ -78,11 +296,11 @@ export const appConfigSchema = z 86400, ), S3_ENDPOINT: requiredString('S3_ENDPOINT'), - S3_PUBLIC_ENDPOINT: requiredString('S3_PUBLIC_ENDPOINT'), + S3_PUBLIC_ENDPOINT: optionalString(), S3_REGION: z.string().min(1).default('us-east-1'), S3_BUCKET: requiredString('S3_BUCKET'), - S3_ACCESS_KEY_ID: requiredString('S3_ACCESS_KEY_ID'), - S3_SECRET_ACCESS_KEY: requiredString('S3_SECRET_ACCESS_KEY'), + S3_ACCESS_KEY_ID: optionalString(), + S3_SECRET_ACCESS_KEY: optionalString(), S3_CONNECT_TIMEOUT_MS: numeric( 'S3_CONNECT_TIMEOUT_MS', 1, @@ -111,7 +329,6 @@ export const appConfigSchema = z 64, 1, ), - // 0 отключает фоновый проход уборщика (остаётся ручной CLI). ATTACHMENT_SWEEP_INTERVAL_MS: numeric( 'ATTACHMENT_SWEEP_INTERVAL_MS', 0, @@ -156,7 +373,6 @@ export const appConfigSchema = z undefined, 2000, ), - // 0 отключает фоновую уборку staging (ручной запуск остаётся). STAGING_CLEANUP_INTERVAL_MS: numeric( 'STAGING_CLEANUP_INTERVAL_MS', 0, @@ -170,8 +386,6 @@ export const appConfigSchema = z 86400, ), WORKER_HEALTH_PORT: numeric('WORKER_HEALTH_PORT', 1, 65535, 8081), - // lab6: как часто API пересчитывает глубину и возраст очереди задач для - // метрик messenger.jobs.queue.* (один дешёвый агрегат по частичным индексам). QUEUE_STATS_INTERVAL_MS: numeric( 'QUEUE_STATS_INTERVAL_MS', 1000, @@ -200,8 +414,146 @@ export const appConfigSchema = z }) .strip(); -export const databaseConfigSchema = appConfigSchema.pick({ +function normalizeRawConfig( + raw: Record, + role: 'api' | 'worker' | 'database', +): Record { + const tlsEnabled = resolveTlsEnabled(raw); + const baoEnabled = resolveBaoEnabled(raw); + const defaultPort = tlsEnabled ? 8443 : 8080; + const defaultBrokerAuth = tlsEnabled ? 'external' : 'plain'; + const defaultBrokerPassive = tlsEnabled; + const defaultBrokerRole = + role === 'worker' ? 'consumer' : role === 'api' ? 'producer' : 'both'; + + return { + ...raw, + APP_PORT: firstNonEmpty(raw.APP_PORT) ?? defaultPort, + TLS_ENABLED: tlsEnabled, + BAO_ENABLED: baoEnabled, + BAO_CERT_ROLE: firstNonEmpty(raw.BAO_CERT_ROLE, raw.BAO_AUTH_ROLE), + TLS_SERVER_CERT_FILE: firstNonEmpty( + raw.TLS_SERVER_CERT_FILE, + raw.TLS_CERT_FILE, + ), + TLS_SERVER_KEY_FILE: firstNonEmpty( + raw.TLS_SERVER_KEY_FILE, + raw.TLS_KEY_FILE, + ), + TLS_CLIENT_CERT_FILE: firstNonEmpty( + raw.TLS_CLIENT_CERT_FILE, + raw.TLS_CERT_FILE, + ), + TLS_CLIENT_KEY_FILE: firstNonEmpty( + raw.TLS_CLIENT_KEY_FILE, + raw.TLS_KEY_FILE, + ), + DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'), + PG_HOST: + firstNonEmpty(raw.PG_HOST, raw.DATABASE_HOST) ?? + (baoEnabled ? 'postgres' : undefined), + PG_PORT: firstNonEmpty(raw.PG_PORT, raw.DATABASE_PORT), + PG_DATABASE: + firstNonEmpty(raw.PG_DATABASE, raw.DATABASE_NAME) ?? + (baoEnabled ? 'messenger' : undefined), + PG_USER: firstNonEmpty(raw.PG_USER, raw.DATABASE_USER), + PG_PASSWORD: firstNonEmpty(raw.PG_PASSWORD, raw.DATABASE_PASSWORD), + REDIS_URL: resolveSecret(raw, 'REDIS_URL'), + REDIS_HOST: + firstNonEmpty(raw.REDIS_HOST) ?? + (role === 'api' && baoEnabled ? 'redis' : undefined), + BROKER_URL: resolveSecret(raw, 'BROKER_URL'), + BROKER_PORT: firstNonEmpty(raw.BROKER_PORT), + BROKER_ROLE: firstNonEmpty(raw.BROKER_ROLE) ?? defaultBrokerRole, + BROKER_AUTH_MECHANISM: + firstNonEmpty(raw.BROKER_AUTH_MECHANISM) ?? defaultBrokerAuth, + BROKER_PASSIVE_TOPOLOGY: + raw.BROKER_PASSIVE_TOPOLOGY !== undefined && + String(raw.BROKER_PASSIVE_TOPOLOGY).trim() !== '' + ? raw.BROKER_PASSIVE_TOPOLOGY + : defaultBrokerPassive, + S3_ACCESS_KEY_ID: resolveSecret(raw, 'S3_ACCESS_KEY_ID'), + S3_SECRET_ACCESS_KEY: resolveSecret(raw, 'S3_SECRET_ACCESS_KEY'), + METRICS_TOKEN: resolveSecret(raw, 'METRICS_TOKEN'), + }; +} + +function validateCrossFields( + parsed: z.infer, + role: 'api' | 'worker', +): z.infer { + if (parsed.BAO_ENABLED) { + if (!parsed.BAO_ADDR) + throw new Error('BAO_ADDR is required when BAO_ENABLED=true'); + if (!parsed.BAO_ADDR.startsWith('https://')) + throw new Error('BAO_ADDR must use https:// when BAO_ENABLED=true'); + } + if (parsed.TLS_ENABLED) { + if (!parsed.TLS_CA_FILE) + throw new Error('TLS_CA_FILE is required when TLS_ENABLED=true'); + if (!parsed.S3_ENDPOINT.startsWith('https://')) + throw new Error('S3_ENDPOINT must use https:// when TLS_ENABLED=true'); + if ( + parsed.S3_PUBLIC_ENDPOINT && + !parsed.S3_PUBLIC_ENDPOINT.startsWith('https://') + ) + throw new Error( + 'S3_PUBLIC_ENDPOINT must use https:// when TLS_ENABLED=true', + ); + } + if (!parsed.DATABASE_URL && (!parsed.PG_HOST || !parsed.PG_DATABASE)) { + throw new Error( + 'DATABASE_URL or PG_HOST + PG_DATABASE must be configured', + ); + } + if (role === 'api') { + if (!parsed.REDIS_URL && !parsed.REDIS_HOST) { + throw new Error('REDIS_URL or REDIS_HOST is required for API'); + } + if (!parsed.S3_PUBLIC_ENDPOINT) { + throw new Error('S3_PUBLIC_ENDPOINT is required for API'); + } + } + if (!parsed.BROKER_URL && !parsed.BROKER_HOST) { + throw new Error('BROKER_URL or BROKER_HOST is required'); + } + if ( + !parsed.BAO_ENABLED && + (!parsed.S3_ACCESS_KEY_ID || !parsed.S3_SECRET_ACCESS_KEY) + ) { + throw new Error( + 'S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are required when BAO_ENABLED=false', + ); + } + return parsed; +} + +export const appConfigSchema = baseConfigSchema; + +export const databaseConfigSchema = baseConfigSchema.pick({ + TLS_ENABLED: true, + TLS_CA_FILE: true, + TLS_CRL_FILE: true, + TLS_CLIENT_CERT_FILE: true, + TLS_CLIENT_KEY_FILE: true, + PG_TLS_MTLS: true, + BAO_ENABLED: true, + BAO_ADDR: true, + BAO_CACERT: true, + BAO_AUTH_METHOD: true, + BAO_CERT_ROLE: true, + BAO_ROLE_ID_FILE: true, + BAO_SECRET_ID_FILE: true, + BAO_WRAPPED_SECRET_ID_FILE: true, + BAO_SECRET_PATH: true, + BAO_TIMEOUT_MS: true, + BAO_STARTUP_RETRIES: true, DATABASE_URL: true, + PG_HOST: true, + PG_PORT: true, + PG_DATABASE: true, + PG_USER: true, + PG_PASSWORD: true, DATABASE_POOL_MAX: true, DATABASE_CONNECTION_TIMEOUT_MS: true, DATABASE_STATEMENT_TIMEOUT_MS: true, @@ -209,55 +561,45 @@ export const databaseConfigSchema = appConfigSchema.pick({ HEALTH_TIMEOUT_MS: true, IDEMPOTENCY_TTL_SECONDS: true, }); -export type DatabaseConfig = z.infer; +export type DatabaseConfig = z.infer; export type AppConfig = z.infer; export type AppConfigKey = keyof AppConfig; -function resolveSecret( - raw: Record, - key: - | 'DATABASE_URL' - | 'REDIS_URL' - | 'BROKER_URL' - | 'S3_ACCESS_KEY_ID' - | 'S3_SECRET_ACCESS_KEY', -): unknown { - const fileKey = `${key}_FILE`; - const path = raw[fileKey]; - if (typeof path !== 'string' || path.length === 0) return raw[key]; - try { - const value = readFileSync(path, 'utf8').trim(); - if (value.length === 0) - throw new Error(`${fileKey} contains an empty value`); - return value; - } catch (error) { - if ( - error instanceof Error && - error.message.includes('contains an empty value') - ) - throw error; - throw new Error(`${fileKey} could not be read`); - } +export function parseAppConfig(raw: Record): AppConfig { + assertNoStaticBaoToken(raw); + const parsed = appConfigSchema.parse(normalizeRawConfig(raw, 'api')); + return validateCrossFields(parsed, 'api'); } -export function parseAppConfig(raw: Record): AppConfig { - return appConfigSchema.parse({ - ...raw, - DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'), - REDIS_URL: resolveSecret(raw, 'REDIS_URL'), - BROKER_URL: resolveSecret(raw, 'BROKER_URL'), - S3_ACCESS_KEY_ID: resolveSecret(raw, 'S3_ACCESS_KEY_ID'), - S3_SECRET_ACCESS_KEY: resolveSecret(raw, 'S3_SECRET_ACCESS_KEY'), - }); +export function parseWorkerConfig(raw: Record): AppConfig { + assertNoStaticBaoToken(raw); + const parsed = appConfigSchema.parse(normalizeRawConfig(raw, 'worker')); + return validateCrossFields(parsed, 'worker'); } // Для процессов, которым нужна только БД (миграции, GC идемпотентности). export function parseDatabaseConfig( raw: Record, ): DatabaseConfig { - return databaseConfigSchema.parse({ - ...raw, - DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'), - }); + assertNoStaticBaoToken(raw); + const parsed = databaseConfigSchema.parse( + normalizeRawConfig(raw, 'database'), + ); + if (parsed.BAO_ENABLED) { + if (!parsed.BAO_ADDR || !parsed.BAO_ADDR.startsWith('https://')) { + throw new Error( + 'BAO_ADDR (https://) is required when BAO_ENABLED=true', + ); + } + } + if (parsed.TLS_ENABLED && !parsed.TLS_CA_FILE) { + throw new Error('TLS_CA_FILE is required when TLS_ENABLED=true'); + } + if (!parsed.DATABASE_URL && (!parsed.PG_HOST || !parsed.PG_DATABASE)) { + throw new Error( + 'DATABASE_URL or PG_HOST + PG_DATABASE must be configured', + ); + } + return parsed; } diff --git a/app/src/config/instance-id.spec.ts b/app/src/config/instance-id.spec.ts new file mode 100644 index 0000000..54b98e5 --- /dev/null +++ b/app/src/config/instance-id.spec.ts @@ -0,0 +1,44 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { hostname, tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + getProcessInstanceId, + persistInstanceIdFile, + resetInstanceIdForTest, +} from './instance-id.js'; + +describe('instance-id (opaque replica alias)', () => { + const savedInstanceId = process.env.INSTANCE_ID; + + afterEach(() => { + if (savedInstanceId === undefined) delete process.env.INSTANCE_ID; + else process.env.INSTANCE_ID = savedInstanceId; + resetInstanceIdForTest(); + }); + + it('generates a stable process-singleton opaque alias without exposing os.hostname()', () => { + delete process.env.INSTANCE_ID; + resetInstanceIdForTest(); + const first = getProcessInstanceId('rep'); + const second = getProcessInstanceId('rep'); + expect(first).toBe(second); + expect(first).toMatch(/^rep-[0-9a-f]{12}$/u); + expect(first).not.toBe(hostname()); + + resetInstanceIdForTest(); + const wrk = getProcessInstanceId('wrk'); + expect(wrk).toMatch(/^wrk-[0-9a-f]{12}$/u); + }); + + it('persists the opaque alias to disk for stop-one.sh matching', () => { + const dir = mkdtempSync(join(tmpdir(), 'lab7-inst-')); + try { + const file = join(dir, 'instance-id'); + persistInstanceIdFile('rep-a1b2c3d4e5f6', file); + expect(readFileSync(file, 'utf8').trim()).toBe('rep-a1b2c3d4e5f6'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/app/src/config/instance-id.ts b/app/src/config/instance-id.ts index e42f2f4..d72da63 100644 --- a/app/src/config/instance-id.ts +++ b/app/src/config/instance-id.ts @@ -1,14 +1,62 @@ -import { randomUUID } from 'node:crypto'; -import { hostname } from 'node:os'; import type { ConfigService } from '@nestjs/config'; +import { randomBytes } from 'node:crypto'; +import { writeFileSync } from 'node:fs'; import type { AppConfig } from './app-config.schema.js'; -// A replica must be identifiable from the outside. Inside Docker the hostname is -// the short container ID, so X-Instance-Id can be mapped back to exactly one -// container; INSTANCE_ID exists for platforms where that mapping is not useful. -export function resolveInstanceId(config: ConfigService): string { - const configured = config.get('INSTANCE_ID'); - if (configured) return configured; - const host = hostname(); - return host.length > 0 ? host : randomUUID(); +export type InstancePrefix = 'rep' | 'wrk'; + +let singletonInstanceId: string | undefined; + +function detectPrefix(override?: InstancePrefix): InstancePrefix { + if (override) return override; + const serviceName = process.env.OTEL_SERVICE_NAME?.trim().toLowerCase() ?? ''; + return serviceName.includes('worker') ? 'wrk' : 'rep'; +} + +/** + * Process-singleton opaque replica/worker alias (`rep-<12hex>` or `wrk-<12hex>`). + * Never exposes os.hostname(), container ID, or IP addresses. + */ +export function getProcessInstanceId(prefix?: InstancePrefix): string { + if (singletonInstanceId) return singletonInstanceId; + const configured = process.env.INSTANCE_ID?.trim(); + singletonInstanceId = + configured && configured.length > 0 + ? configured + : `${detectPrefix(prefix)}-${randomBytes(6).toString('hex')}`; + return singletonInstanceId; +} + +export function resolveInstanceId( + config?: ConfigService, + prefix?: InstancePrefix, +): string { + const configured = + typeof config?.get === 'function' ? config.get('INSTANCE_ID') : undefined; + if (typeof configured === 'string' && configured.trim().length > 0) { + singletonInstanceId = configured.trim(); + return singletonInstanceId; + } + return getProcessInstanceId(prefix); +} + +/** + * Persists the opaque instance alias to `/tmp/instance-id` inside the + * container-private tmpfs so `scripts/stop-one.sh` can match the exact replica + * without leaking container hostnames on the wire. + */ +export function persistInstanceIdFile( + instanceId: string, + path = '/tmp/instance-id', +): void { + try { + writeFileSync(path, `${instanceId}\n`, { mode: 0o644 }); + } catch { + // Best-effort: unit/host tests may run without writable /tmp/instance-id. + } +} + +/** Test-only helper to reset the process singleton between isolated unit tests. */ +export function resetInstanceIdForTest(): void { + singletonInstanceId = undefined; } diff --git a/app/src/config/worker-config.module.ts b/app/src/config/worker-config.module.ts new file mode 100644 index 0000000..0a12fb0 --- /dev/null +++ b/app/src/config/worker-config.module.ts @@ -0,0 +1,16 @@ +import { Global, Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { parseWorkerConfig } from './app-config.schema.js'; + +@Global() +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + cache: true, + validate: parseWorkerConfig, + }), + ], + exports: [ConfigModule], +}) +export class WorkerConfigModule {} diff --git a/app/src/database/database.client.ts b/app/src/database/database.client.ts index 9238cc9..c8bb0c1 100644 --- a/app/src/database/database.client.ts +++ b/app/src/database/database.client.ts @@ -1,9 +1,18 @@ -import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'; +import { + Inject, + Injectable, + Logger, + OnModuleDestroy, + Optional, +} from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { SpanKind, type Attributes, type Span } from '@opentelemetry/api'; +import { URL } from 'node:url'; import pg from 'pg'; -import { MetricsService } from '../metrics/metrics.service.js'; import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from '../security/tls-material.js'; import { instruments, meter } from '../telemetry/instruments.js'; import { errorType, withChildSpan } from '../telemetry/tracing.js'; @@ -14,13 +23,11 @@ const TRANSACTION_CONTROL = const SQL_TARGET = /\b(?:FROM|INTO|UPDATE|JOIN)\s+"?([A-Za-z_][A-Za-z0-9_]*)"?/iu; -/** First SQL keyword (SELECT, INSERT, WITH, …): a bounded attribute. */ function sqlOperation(text: string): string { const match = /^\s*([A-Za-z]+)/u.exec(text); return match ? match[1].toUpperCase() : 'OTHER'; } -/** Best-effort table name for span names; never used as a metric label. */ function sqlTarget(text: string): string | undefined { return SQL_TARGET.exec(text)?.[1]?.toLowerCase(); } @@ -62,13 +69,37 @@ function statementAttributes( }; } -/** - * Inside a traced transaction every statement gets its own CLIENT span - * (`UPDATE attachment_jobs`, `INSERT job_outbox`, …) while repository code - * stays unaware of tracing. Transaction control, callback-style calls and - * submittables (cursors, streams) pass through untouched. SQL text and - * parameter values are never recorded. - */ +function isPgAuthError(error: unknown): boolean { + if (typeof error !== 'object' || error === null) return false; + const code = (error as { code?: unknown }).code; + return code === '28P01' || code === '28000'; +} + +function parseDatabaseUrl(urlString: string | undefined): { + host?: string; + port?: number; + database?: string; + user?: string; + password?: string; +} { + if (!urlString) return {}; + try { + const parsed = new URL(urlString); + const dbName = parsed.pathname.replace(/^\/+/u, ''); + return { + host: parsed.hostname || undefined, + port: parsed.port ? Number(parsed.port) : undefined, + database: dbName || undefined, + user: parsed.username ? decodeURIComponent(parsed.username) : undefined, + password: parsed.password + ? decodeURIComponent(parsed.password) + : undefined, + }; + } catch { + return {}; + } +} + function tracedClient(client: pg.PoolClient, label: string): pg.PoolClient { return new Proxy(client, { get(target, property) { @@ -95,58 +126,32 @@ function tracedClient(client: pg.PoolClient, label: string): pg.PoolClient { @Injectable() export class DatabaseClient implements OnModuleDestroy { - readonly pool: pg.Pool; - private readonly healthPool: pg.Pool; + private activePool: pg.Pool; + private activeHealthPool: pg.Pool; private readonly logger = new Logger(DatabaseClient.name); + private readonly onRotateDb: () => void; + private readonly onTlsReload: () => void; constructor( private readonly config: ConfigService, private readonly metrics: MetricsService, + @Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager, + @Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore, ) { - this.pool = new pg.Pool({ - connectionString: this.config.getOrThrow('DATABASE_URL'), - max: this.config.getOrThrow('DATABASE_POOL_MAX'), - connectionTimeoutMillis: this.config.getOrThrow( - 'DATABASE_CONNECTION_TIMEOUT_MS', - ), - statement_timeout: this.config.getOrThrow( - 'DATABASE_STATEMENT_TIMEOUT_MS', - ), - // A relay that waits on the broker must not leave the transaction - // idle forever if confirm handling stalls. - options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS')}`, - }); - // Idle clients emit 'error' on the pool when the database drops; without a - // listener Node treats it as uncaught and terminates the process. - this.pool.on('error', (error: Error) => { - this.metrics.increment('database.pool_error'); - this.logger.warn(`PostgreSQL pool error: ${error.message}`); - }); - // Проба готовности не должна стоять в очереди за бизнес-запросами: занятый - // общий пул — это перегрузка, а не потеря зависимости. - this.healthPool = new pg.Pool({ - connectionString: this.config.getOrThrow('DATABASE_URL'), - max: 1, - idleTimeoutMillis: 0, - connectionTimeoutMillis: - this.config.getOrThrow('HEALTH_TIMEOUT_MS'), - query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'), - }); - this.healthPool.on('error', (error: Error) => { - this.metrics.increment('database.health_pool_error'); - this.logger.warn( - `PostgreSQL health connection error: ${error.message}`, - ); - }); + this.activePool = this.createMainPool(); + this.activeHealthPool = this.createHealthPool(); this.observePool(this.config.getOrThrow('DATABASE_POOL_MAX')); + + this.onRotateDb = () => this.rotatePools('secret_rotated'); + this.onTlsReload = () => this.rotatePools('tls_reloaded'); + this.secrets?.on('rotated:db', this.onRotateDb); + this.tls?.on('reloaded', this.onTlsReload); + } + + get pool(): pg.Pool { + return this.activePool; } - /** - * Same contract as pg.Pool#query — a failed query destroys its connection — - * but the checkout is explicit, so the wait for a pooled connection is - * measured apart from the statement: «the pool is exhausted» and «the - * database is slow» are different incidents with different runbooks. - */ query( label: string, text: string, @@ -167,6 +172,7 @@ export class DatabaseClient implements OnModuleDestroy { try { return await client.query({ text, values: [...values] }); } catch (error) { + this.maybeRefreshOnAuthError(error); failure ??= error instanceof Error ? error : new Error('Query failed'); throw error; @@ -180,7 +186,12 @@ export class DatabaseClient implements OnModuleDestroy { async health(): Promise { this.metrics.increment('health.database'); - await this.healthPool.query('SELECT 1'); + try { + await this.activeHealthPool.query('SELECT 1'); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } withTransaction( @@ -189,20 +200,12 @@ export class DatabaseClient implements OnModuleDestroy { return this.transaction('transaction', work); } - /** - * A labelled transaction: one span for the unit of work with a child span - * per statement and one db.client.operation.duration sample (pool wait - * included) with db.operation.name = TRANSACTION. - */ transaction( label: string, work: (client: pg.PoolClient) => Promise, ): Promise { return this.observe(label, 'TRANSACTION', undefined, async (span) => { const client = await this.checkout(); - // A server-side idle_in_transaction_session_timeout or a network drop - // can emit 'error' on a checked-out client after pg-pool removed its - // idle listener. Without this listener Node treats it as uncaught. let fatal: Error | undefined; const onError = (error: Error): void => { fatal = error; @@ -216,6 +219,7 @@ export class DatabaseClient implements OnModuleDestroy { await client.query('COMMIT'); return result; } catch (error) { + this.maybeRefreshOnAuthError(error); try { await client.query('ROLLBACK'); } catch (rollbackError) { @@ -224,7 +228,6 @@ export class DatabaseClient implements OnModuleDestroy { `Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`, ); } - // Callers must see the operation error, not the rollback error. throw error; } finally { client.removeListener('error', onError); @@ -234,7 +237,114 @@ export class DatabaseClient implements OnModuleDestroy { } async onModuleDestroy(): Promise { - await Promise.all([this.pool.end(), this.healthPool.end()]); + this.secrets?.off('rotated:db', this.onRotateDb); + this.tls?.off('reloaded', this.onTlsReload); + await Promise.all([this.activePool.end(), this.activeHealthPool.end()]); + } + + private buildConnectionFields(): pg.PoolConfig { + const getOpt = (key: K): AppConfig[K] | undefined => + typeof this.config.get === 'function' ? this.config.get(key) : undefined; + const parsed = parseDatabaseUrl(getOpt('DATABASE_URL')); + const host = getOpt('PG_HOST') ?? parsed.host ?? 'postgres'; + const port = getOpt('PG_PORT') ?? parsed.port ?? 5432; + const database = getOpt('PG_DATABASE') ?? parsed.database ?? 'messenger'; + const creds = this.secrets?.getDbCredentials(); + const user = creds?.user ?? getOpt('PG_USER') ?? parsed.user; + const password = + creds?.password ?? getOpt('PG_PASSWORD') ?? parsed.password; + + const tlsEnabled = this.tls?.enabled ?? Boolean(getOpt('TLS_ENABLED')); + const pgMtls = Boolean(getOpt('PG_TLS_MTLS')); + + let ssl: pg.PoolConfig['ssl']; + if (tlsEnabled) { + if (!this.tls?.ca) { + throw new Error( + 'PostgreSQL TLS requires CA certificate (TLS_CA_FILE)', + ); + } + ssl = { + ca: this.tls.ca, + rejectUnauthorized: true, + servername: host, + minVersion: 'TLSv1.2', + ...(pgMtls && this.tls.clientCert && this.tls.clientKey + ? { cert: this.tls.clientCert, key: this.tls.clientKey } + : {}), + }; + } + + return { + host, + port, + database, + user, + password, + ...(ssl ? { ssl } : {}), + }; + } + + private createMainPool(): pg.Pool { + const pool = new pg.Pool({ + ...this.buildConnectionFields(), + max: this.config.getOrThrow('DATABASE_POOL_MAX'), + connectionTimeoutMillis: this.config.getOrThrow( + 'DATABASE_CONNECTION_TIMEOUT_MS', + ), + statement_timeout: this.config.getOrThrow( + 'DATABASE_STATEMENT_TIMEOUT_MS', + ), + options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS')}`, + }); + pool.on('error', (error: Error) => { + this.metrics.increment('database.pool_error'); + this.maybeRefreshOnAuthError(error); + this.logger.warn(`PostgreSQL pool error: ${error.message}`); + }); + return pool; + } + + private createHealthPool(): pg.Pool { + const pool = new pg.Pool({ + ...this.buildConnectionFields(), + max: 1, + idleTimeoutMillis: 0, + connectionTimeoutMillis: + this.config.getOrThrow('HEALTH_TIMEOUT_MS'), + query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'), + }); + pool.on('error', (error: Error) => { + this.metrics.increment('database.health_pool_error'); + this.maybeRefreshOnAuthError(error); + this.logger.warn( + `PostgreSQL health connection error: ${error.message}`, + ); + }); + return pool; + } + + private rotatePools(reason: string): void { + try { + const nextMain = this.createMainPool(); + const nextHealth = this.createHealthPool(); + const oldMain = this.activePool; + const oldHealth = this.activeHealthPool; + this.activePool = nextMain; + this.activeHealthPool = nextHealth; + this.logger.log(`Swapped PostgreSQL pools (${reason})`); + void Promise.allSettled([oldMain.end(), oldHealth.end()]); + } catch (error) { + this.logger.warn( + `PostgreSQL pool swap skipped (${reason}): ${error instanceof Error ? error.name : 'unknown error'}`, + ); + } + } + + private maybeRefreshOnAuthError(error: unknown): void { + if (isPgAuthError(error)) { + void this.secrets?.refreshNow('pg_auth_error'); + } } private observe( @@ -271,8 +381,9 @@ export class DatabaseClient implements OnModuleDestroy { const started = process.hrtime.bigint(); let failure: string | undefined; try { - return await this.pool.connect(); + return await this.activePool.connect(); } catch (error) { + this.maybeRefreshOnAuthError(error); failure = errorType(error); throw error; } finally { @@ -283,7 +394,6 @@ export class DatabaseClient implements OnModuleDestroy { } } - /** Pool saturation: used vs max connections and callers queued for one. */ private observePool(max: number): void { const m = meter(); const pool = { 'db.client.connection.pool.name': POOL_NAME }; @@ -307,8 +417,9 @@ export class DatabaseClient implements OnModuleDestroy { ); m.addBatchObservableCallback( (result) => { - const idle = this.pool.idleCount; - result.observe(count, this.pool.totalCount - idle, { + const current = this.activePool; + const idle = current.idleCount; + result.observe(count, current.totalCount - idle, { ...pool, 'db.client.connection.state': 'used', }); @@ -317,7 +428,7 @@ export class DatabaseClient implements OnModuleDestroy { 'db.client.connection.state': 'idle', }); result.observe(limit, max, pool); - result.observe(pending, this.pool.waitingCount, pool); + result.observe(pending, current.waitingCount, pool); }, [count, limit, pending], ); diff --git a/app/src/database/migration.runner.ts b/app/src/database/migration.runner.ts index 5e101c3..e5955c4 100644 --- a/app/src/database/migration.runner.ts +++ b/app/src/database/migration.runner.ts @@ -1,9 +1,11 @@ import { readdir, readFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { DatabaseClient } from './database.client.js'; -import { MetricsService } from '../metrics/metrics.service.js'; import { parseDatabaseConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from '../security/tls-material.js'; +import { DatabaseClient } from './database.client.js'; const migrationsDirectory = join( dirname(fileURLToPath(import.meta.url)), @@ -46,17 +48,31 @@ export async function runMigrations(database: DatabaseClient): Promise { } async function main(): Promise { - const config = parseDatabaseConfig(process.env as Record); + const rawEnv = process.env as Record; + const config = parseDatabaseConfig(rawEnv); + const tlsMaterial = TlsMaterialManager.initFromEnv('migrator', rawEnv); + const secretsStore = await RuntimeSecretsStore.bootstrap( + 'migrator', + tlsMaterial, + rawEnv, + undefined, + { background: false }, + ); const database = new DatabaseClient( { + get: (key: keyof typeof config) => config[key], getOrThrow: (key: keyof typeof config) => config[key], } as never, new MetricsService(), + tlsMaterial, + secretsStore, ); try { await runMigrations(database); } finally { await database.onModuleDestroy(); + secretsStore.close(); + tlsMaterial.onModuleDestroy(); } } diff --git a/app/src/database/migrations/010_least_privilege_grants.sql b/app/src/database/migrations/010_least_privilege_grants.sql new file mode 100644 index 0000000..a7e46ab --- /dev/null +++ b/app/src/database/migrations/010_least_privilege_grants.sql @@ -0,0 +1,63 @@ +-- Lab 7: Least-privilege PostgreSQL grants for messenger_api and messenger_worker. +-- Executed by messenger_migrator (owner of all tables & sequences in public). +-- Wrapped in role-existence checks so standalone e2e test databases without +-- pre-created least-privilege roles continue to migrate cleanly. + +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_api') THEN + REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC, messenger_api; + REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC, messenger_api; + + GRANT SELECT, INSERT ON TABLE users TO messenger_api; + GRANT UPDATE (password_hash) ON TABLE users TO messenger_api; + + GRANT SELECT, INSERT ON TABLE chats TO messenger_api; + GRANT UPDATE (message_version) ON TABLE chats TO messenger_api; + + GRANT SELECT, INSERT ON TABLE chat_members, messages, message_attachments TO messenger_api; + GRANT SELECT, INSERT, DELETE ON TABLE idempotency_keys TO messenger_api; + GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE attachments TO messenger_api; + GRANT SELECT, INSERT, UPDATE ON TABLE attachment_jobs TO messenger_api; + GRANT SELECT ON TABLE attachment_variants TO messenger_api; + + GRANT SELECT, INSERT ON TABLE job_outbox TO messenger_api; + GRANT UPDATE (published_at) ON TABLE job_outbox TO messenger_api; + GRANT USAGE, SELECT ON SEQUENCE job_outbox_id_seq TO messenger_api; + + GRANT SELECT, INSERT ON TABLE job_events TO messenger_api; + GRANT USAGE, SELECT ON SEQUENCE job_events_id_seq TO messenger_api; + END IF; + + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_worker') THEN + REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC, messenger_worker; + REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC, messenger_worker; + + GRANT SELECT ON TABLE attachments TO messenger_worker; + GRANT UPDATE (status, staging_key, error_code, ready_pipeline_version, updated_at) + ON TABLE attachments TO messenger_worker; + + GRANT SELECT ON TABLE attachment_jobs TO messenger_worker; + GRANT UPDATE ( + status, + attempt, + next_attempt_at, + lease_owner, + lease_token, + lease_until, + last_error_code, + last_reconciled_at, + updated_at, + finished_at + ) ON TABLE attachment_jobs TO messenger_worker; + + GRANT SELECT, INSERT, UPDATE ON TABLE attachment_variants TO messenger_worker; + + GRANT SELECT, INSERT, DELETE ON TABLE job_outbox TO messenger_worker; + GRANT USAGE, SELECT ON SEQUENCE job_outbox_id_seq TO messenger_worker; + + GRANT SELECT, INSERT, DELETE ON TABLE job_events TO messenger_worker; + GRANT USAGE, SELECT ON SEQUENCE job_events_id_seq TO messenger_worker; + END IF; +END +$$; diff --git a/app/src/jobs/broker.client.spec.ts b/app/src/jobs/broker.client.spec.ts new file mode 100644 index 0000000..95d80cc --- /dev/null +++ b/app/src/jobs/broker.client.spec.ts @@ -0,0 +1,170 @@ +import { EventEmitter } from 'node:events'; +import { describe, expect, it, vi } from 'vitest'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { + BrokerClient, + BrokerUnavailableError, + type AmqpConnectFn, +} from './broker.client.js'; +import { JOB_EXCHANGE, JOB_QUEUE } from './broker.topology.js'; + +function makeConfig(overrides: Record = {}) { + const values: Record = { + BROKER_HOST: 'broker', + BROKER_PORT: 5671, + BROKER_VHOST: 'messenger', + BROKER_ROLE: 'consumer', + BROKER_AUTH_MECHANISM: 'external', + BROKER_PASSIVE_TOPOLOGY: true, + BROKER_DELIVERY_LIMIT: 10, + BROKER_PUBLISH_TIMEOUT_MS: 2000, + TLS_ENABLED: true, + ...overrides, + }; + return { + get: (k: string) => values[k], + getOrThrow: (k: string) => values[k], + }; +} + +function makeFakeTls() { + const emitter = new EventEmitter(); + return Object.assign(emitter, { + enabled: true, + ca: Buffer.from('CA'), + clientCert: Buffer.from('CERT'), + clientKey: Buffer.from('KEY'), + }); +} + +describe('BrokerClient least-privilege consumer & producer modes', () => { + it('consumer mode uses AMQPS EXTERNAL, ZERO confirmChannel, passive checkQueue, and plain channel for queueDepth', async () => { + const checkQueue = vi.fn(async () => ({ + queue: JOB_QUEUE, + messageCount: 4, + consumerCount: 1, + })); + const assertExchange = vi.fn(); + const assertQueue = vi.fn(); + const consume = vi.fn(async () => ({ consumerTag: 'ctag-1' })); + const prefetch = vi.fn(async () => undefined); + const closeChannel = vi.fn(async () => undefined); + + const createConfirmChannel = vi.fn(); + const createChannel = vi.fn(async () => + Object.assign(new EventEmitter(), { + checkQueue, + assertExchange, + assertQueue, + consume, + prefetch, + close: closeChannel, + cancel: vi.fn(async () => undefined), + }), + ); + + const connection = Object.assign(new EventEmitter(), { + createConfirmChannel, + createChannel, + close: vi.fn(async () => undefined), + }); + + const connectFn = vi.fn(async () => connection as never); + const client = new BrokerClient( + makeConfig({ BROKER_ROLE: 'consumer' }) as never, + new MetricsService(), + makeFakeTls() as never, + undefined, + connectFn, + ); + + try { + // queueDepth must work in consumer mode without confirmChannel! + const depth = await client.queueDepth(JOB_QUEUE); + expect(depth).toEqual({ messages: 4, consumers: 1 }); + expect(createConfirmChannel).not.toHaveBeenCalled(); + expect(assertExchange).not.toHaveBeenCalled(); + expect(assertQueue).not.toHaveBeenCalled(); + expect(closeChannel).toHaveBeenCalledTimes(1); + + // Verify AMQPS + EXTERNAL + mTLS socket options were passed. + const [target, sockOpts] = connectFn.mock.calls[0]; + expect(target).toMatchObject({ + protocol: 'amqps', + hostname: 'broker', + port: 5671, + vhost: 'messenger', + }); + expect((target as { credentials?: { mechanism?: string } }).credentials?.mechanism).toBe( + 'EXTERNAL', + ); + expect(sockOpts).toMatchObject({ + servername: 'broker', + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + }); + + // Consumer cannot publish. + await expect( + client.publish(Buffer.from('forged')), + ).rejects.toBeInstanceOf(BrokerUnavailableError); + + // Subscribe uses passive checkQueue only. + client.consume(2, async () => undefined); + await vi.waitFor(() => expect(client.isConsuming()).toBe(true)); + expect(createConfirmChannel).not.toHaveBeenCalled(); + expect(assertQueue).not.toHaveBeenCalled(); + expect(consume).toHaveBeenCalledWith( + JOB_QUEUE, + expect.any(Function), + { noAck: false }, + ); + } finally { + await client.onModuleDestroy(); + } + }); + + it('producer mode uses confirmChannel + passive checkExchange and refuses consume()', async () => { + const checkExchange = vi.fn(async () => ({})); + const assertExchange = vi.fn(); + const publish = vi.fn( + ( + _ex: string, + _rk: string, + _buf: Buffer, + _opts: unknown, + cb: (err: Error | null) => void, + ) => cb(null), + ); + + const confirm = Object.assign(new EventEmitter(), { + checkExchange, + assertExchange, + publish, + }); + const connection = Object.assign(new EventEmitter(), { + createConfirmChannel: vi.fn(async () => confirm), + createChannel: vi.fn(), + close: vi.fn(async () => undefined), + }); + + const client = new BrokerClient( + makeConfig({ BROKER_ROLE: 'producer' }) as never, + new MetricsService(), + makeFakeTls() as never, + undefined, + vi.fn(async () => connection as never), + ); + + try { + await client.publish(Buffer.from('job')); + expect(checkExchange).toHaveBeenCalledWith(JOB_EXCHANGE); + expect(assertExchange).not.toHaveBeenCalled(); + expect(() => client.consume(1, async () => undefined)).toThrow( + /producer cannot consume/i, + ); + } finally { + await client.onModuleDestroy(); + } + }); +}); diff --git a/app/src/jobs/broker.client.ts b/app/src/jobs/broker.client.ts index e74185c..806405b 100644 --- a/app/src/jobs/broker.client.ts +++ b/app/src/jobs/broker.client.ts @@ -1,9 +1,11 @@ import { connect as amqpConnect, + credentials as amqpCredentials, type Channel, type ChannelModel, type ConfirmChannel, type ConsumeMessage, + type Options, } from 'amqplib'; import { context, @@ -12,15 +14,22 @@ import { type Span, } from '@opentelemetry/api'; import { + Inject, Injectable, Logger, OnModuleDestroy, + Optional, ServiceUnavailableException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { randomUUID } from 'node:crypto'; +import { URL } from 'node:url'; import type { AppConfig } from '../config/app-config.schema.js'; import { MetricsService } from '../metrics/metrics.service.js'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from '../security/tls-material.js'; +import { instruments } from '../telemetry/instruments.js'; +import { markSpanError, tracer } from '../telemetry/tracing.js'; import { assertTopology, JOB_EXCHANGE, @@ -28,8 +37,6 @@ import { JOB_ROUTING_KEY, } from './broker.topology.js'; import type { JobMessage } from './job-message.js'; -import { instruments } from '../telemetry/instruments.js'; -import { markSpanError, tracer } from '../telemetry/tracing.js'; export class BrokerUnavailableError extends ServiceUnavailableException { constructor() { @@ -37,6 +44,9 @@ export class BrokerUnavailableError extends ServiceUnavailableException { } } +export type BrokerRole = 'producer' | 'consumer' | 'both'; +export type BrokerAuthMechanism = 'external' | 'plain'; + export type ConsumeHandler = ( message: ConsumeMessage, channel: Channel, @@ -44,12 +54,64 @@ export type ConsumeHandler = ( const MAX_RECONNECT_DELAY_MS = 10_000; +function isAmqpAuthError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + return ( + error.message.includes('ACCESS_REFUSED') || + error.message.includes('403') + ); +} + +function parseBrokerUrl(urlString: string | undefined): { + protocol?: string; + hostname?: string; + port?: number; + vhost?: string; + username?: string; + password?: string; +} { + if (!urlString) return {}; + try { + const parsed = new URL(urlString); + const rawPath = parsed.pathname.replace(/^\/+/u, ''); + const vhost = rawPath ? decodeURIComponent(rawPath) : undefined; + return { + protocol: parsed.protocol.replace(/:$/u, ''), + hostname: parsed.hostname || undefined, + port: parsed.port ? Number(parsed.port) : undefined, + vhost, + username: parsed.username + ? decodeURIComponent(parsed.username) + : undefined, + password: parsed.password + ? decodeURIComponent(parsed.password) + : undefined, + }; + } catch { + return {}; + } +} + +export type AmqpConnectFn = ( + url: string | Options.Connect, + socketOptions?: unknown, +) => Promise; + @Injectable() export class BrokerClient implements OnModuleDestroy { private readonly logger = new Logger(BrokerClient.name); - private readonly url: string; + private readonly rawUrl: string | undefined; + private readonly host: string; + private readonly port: number; + private readonly vhost: string; + private readonly urlUser: string | undefined; + private readonly urlPass: string | undefined; + private readonly role: BrokerRole; + private readonly authMechanism: BrokerAuthMechanism; + private readonly passiveTopology: boolean; private readonly deliveryLimit: number; private readonly publishTimeoutMs: number; + private readonly connectFn: AmqpConnectFn; private connection: ChannelModel | undefined; private confirmChannel: ConfirmChannel | undefined; private consumeChannel: Channel | undefined; @@ -63,28 +125,53 @@ export class BrokerClient implements OnModuleDestroy { private reconnectDelayMs = 1000; private subscribeDelayMs = 1000; private closing = false; - // Unroutable messages are returned before their confirm; the map lets the - // return listener reject the exact publish that produced it. private readonly returned = new Map void>(); + private readonly onRotate: () => void; constructor( - config: ConfigService, + private readonly config: ConfigService, private readonly metrics: MetricsService, + @Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager, + @Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore, + connectOverride?: AmqpConnectFn, ) { - this.url = config.getOrThrow('BROKER_URL'); + const getOpt = (key: K): AppConfig[K] | undefined => + typeof config.get === 'function' ? config.get(key) : undefined; + this.rawUrl = getOpt('BROKER_URL'); + const parsed = parseBrokerUrl(this.rawUrl); + const tlsEnabled = + this.tls?.enabled ?? + (Boolean(getOpt('TLS_ENABLED')) || parsed.protocol === 'amqps'); + + this.host = getOpt('BROKER_HOST') ?? parsed.hostname ?? 'broker'; + this.port = + getOpt('BROKER_PORT') ?? parsed.port ?? (tlsEnabled ? 5671 : 5672); + this.vhost = getOpt('BROKER_VHOST') ?? parsed.vhost ?? 'messenger'; + this.urlUser = parsed.username; + this.urlPass = parsed.password; + this.role = getOpt('BROKER_ROLE') ?? 'both'; + this.authMechanism = + getOpt('BROKER_AUTH_MECHANISM') ?? + (tlsEnabled ? 'external' : 'plain'); + this.passiveTopology = getOpt('BROKER_PASSIVE_TOPOLOGY') ?? tlsEnabled; this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT'); - this.publishTimeoutMs = config.getOrThrow( - 'BROKER_PUBLISH_TIMEOUT_MS', - ); + this.publishTimeoutMs = config.getOrThrow('BROKER_PUBLISH_TIMEOUT_MS'); + this.connectFn = + connectOverride ?? + ((target, sockOpts) => + amqpConnect(target, sockOpts as Record)); + + this.onRotate = () => { + void this.forceReconnect('rotation'); + }; + this.tls?.on('reloaded', this.onRotate); + this.secrets?.on('rotated:broker', this.onRotate); } - /** - * PRODUCER span around publish + broker confirm. Its context goes into the - * AMQP headers (W3C traceparent/tracestate), so the worker's CONSUMER span - * becomes its child; the body keeps the context of the transaction that - * wrote the outbox row. - */ async publish(message: JobMessage | Buffer): Promise { + if (this.role === 'consumer') { + throw new BrokerUnavailableError(); + } const attributes = { 'messaging.system': 'rabbitmq', 'messaging.operation.type': 'send', @@ -131,7 +218,7 @@ export class BrokerClient implements OnModuleDestroy { traceHeaders: Record, ): Promise { const channel = await this.withTimeout( - this.ensureConnected(), + this.ensureConfirmChannel(), this.publishTimeoutMs, ); const content = Buffer.isBuffer(message) @@ -190,9 +277,12 @@ export class BrokerClient implements OnModuleDestroy { } consume(prefetch: number, handler: ConsumeHandler): void { + if (this.role === 'producer') { + throw new Error('BrokerClient configured as producer cannot consume'); + } this.prefetch = prefetch; this.handler = handler; - this.ensureConnected() + this.ensureConnection() .then(() => this.subscribe()) .catch(() => this.scheduleSubscribe()); } @@ -201,18 +291,42 @@ export class BrokerClient implements OnModuleDestroy { return this.consumerTag !== undefined; } + /** + * Queries queue depth using a short-lived plain channel on the active + * connection — NEVER requires `confirmChannel` or `write`/`configure` + * permissions, so `BROKER_ROLE=consumer` (worker LeaseReaper) works cleanly + * and a denied `checkQueue` cannot terminate `consumeChannel` or `confirmChannel`. + */ async queueDepth( queue: string, ): Promise<{ messages: number; consumers: number }> { - const channel = await this.withTimeout( - this.ensureConnected(), + const connection = await this.withTimeout( + this.ensureConnection(), this.publishTimeoutMs, ); - const result = await channel.checkQueue(queue); - return { - messages: result.messageCount, - consumers: result.consumerCount, - }; + const channel = await this.withTimeout( + connection.createChannel(), + this.publishTimeoutMs, + ); + channel.on('error', () => { + // Channel-level errors (e.g. 403/404) are handled by the rejected checkQueue promise. + }); + try { + const result = await this.withTimeout( + channel.checkQueue(queue), + this.publishTimeoutMs, + ); + return { + messages: result.messageCount, + consumers: result.consumerCount, + }; + } finally { + try { + await channel.close(); + } catch { + // Already closed by broker on channel exception. + } + } } async stopConsuming(): Promise { @@ -227,7 +341,7 @@ export class BrokerClient implements OnModuleDestroy { try { await channel.cancel(tag); } catch { - // The channel is already closing; there is nothing to cancel. + // The channel is already closing. } } if (channel) { @@ -241,6 +355,8 @@ export class BrokerClient implements OnModuleDestroy { async onModuleDestroy(): Promise { this.closing = true; + this.tls?.off('reloaded', this.onRotate); + this.secrets?.off('rotated:broker', this.onRotate); clearTimeout(this.reconnectTimer); clearTimeout(this.subscribeTimer); this.reconnectTimer = undefined; @@ -255,14 +371,26 @@ export class BrokerClient implements OnModuleDestroy { try { await connection.close(); } catch { - // Shutdown is best effort; channels are already unusable. + // Shutdown is best effort. } } } - private async ensureConnected(): Promise { + private async forceReconnect(reason: string): Promise { + if (this.closing) return; + const connection = this.connection; + if (!connection) return; + this.logger.log(`Closing AMQP connection for reconnect (${reason})`); + try { + await connection.close(); + } catch { + this.handleClose(); + } + } + + private async ensureConnection(): Promise { if (this.closing) throw new BrokerUnavailableError(); - if (this.confirmChannel) return this.confirmChannel; + if (this.connection) return this.connection; if (!this.connecting) { this.connecting = this.connect() .then(() => undefined) @@ -271,14 +399,91 @@ export class BrokerClient implements OnModuleDestroy { }); } await this.connecting; + if (!this.connection) throw new BrokerUnavailableError(); + return this.connection; + } + + private async ensureConfirmChannel(): Promise { + await this.ensureConnection(); if (!this.confirmChannel) throw new BrokerUnavailableError(); return this.confirmChannel; } + private buildConnectArgs(): { + target: string | Options.Connect; + socketOptions?: Record; + } { + const tlsEnabled = this.tls?.enabled ?? false; + if (tlsEnabled) { + if (!this.tls?.ca || !this.tls.clientCert || !this.tls.clientKey) { + throw new Error( + 'Broker AMQPS mTLS requires CA, client certificate, and client key', + ); + } + const socketOptions = { + ca: this.tls.ca, + cert: this.tls.clientCert, + key: this.tls.clientKey, + servername: this.host, + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + }; + if (this.authMechanism === 'external') { + return { + target: { + protocol: 'amqps', + hostname: this.host, + port: this.port, + vhost: this.vhost, + credentials: amqpCredentials.external(), + }, + socketOptions, + }; + } + const creds = this.secrets?.getBrokerCredentials(); + return { + target: { + protocol: 'amqps', + hostname: this.host, + port: this.port, + vhost: this.vhost, + username: creds?.user ?? this.urlUser, + password: creds?.password ?? this.urlPass, + }, + socketOptions, + }; + } + + if (this.rawUrl) return { target: this.rawUrl }; + const creds = this.secrets?.getBrokerCredentials(); + return { + target: { + protocol: 'amqp', + hostname: this.host, + port: this.port, + vhost: this.vhost, + username: creds?.user ?? this.urlUser, + password: creds?.password ?? this.urlPass, + }, + }; + } + private async connect(): Promise { - const connection = await amqpConnect(this.url); + const { target, socketOptions } = this.buildConnectArgs(); + let connection: ChannelModel; + try { + connection = await this.connectFn(target, socketOptions); + } catch (error) { + if (isAmqpAuthError(error)) { + void this.secrets?.refreshNow('broker_auth_error'); + } + throw error; + } connection.on('error', (error: Error) => { this.metrics.increment('broker.error'); + if (isAmqpAuthError(error)) { + void this.secrets?.refreshNow('broker_auth_error'); + } this.logger.warn(`Broker connection error: ${error.message}`); }); connection.on('close', () => { @@ -286,22 +491,32 @@ export class BrokerClient implements OnModuleDestroy { this.handleClose(); }); try { - const confirm = await connection.createConfirmChannel(); - confirm.on('return', (message) => { - const correlationId = message.properties?.correlationId; - if (!correlationId) return; - const reject = this.returned.get(correlationId); - if (!reject) return; - this.returned.delete(correlationId); - this.logger.warn('Broker returned an unroutable job message'); - reject(); - }); - await assertTopology(confirm, this.deliveryLimit); - confirm.on('error', (error: Error) => { - this.metrics.increment('broker.confirm_error'); - this.logger.warn(`Broker confirm channel error: ${error.message}`); - }); - confirm.on('close', () => this.handleConfirmClose(confirm)); + let confirm: ConfirmChannel | undefined; + if (this.role !== 'consumer') { + confirm = await connection.createConfirmChannel(); + confirm.on('return', (message) => { + const correlationId = message.properties?.correlationId; + if (!correlationId) return; + const reject = this.returned.get(correlationId); + if (!reject) return; + this.returned.delete(correlationId); + this.logger.warn('Broker returned an unroutable job message'); + reject(); + }); + if (this.passiveTopology) { + await confirm.checkExchange(JOB_EXCHANGE); + } else { + await assertTopology(confirm, this.deliveryLimit); + } + confirm.on('error', (error: Error) => { + this.metrics.increment('broker.confirm_error'); + this.logger.warn( + `Broker confirm channel error: ${error.message}`, + ); + }); + confirm.on('close', () => this.handleConfirmClose(confirm!)); + } + this.connection = connection; this.confirmChannel = confirm; this.reconnectDelayMs = 1000; @@ -309,6 +524,9 @@ export class BrokerClient implements OnModuleDestroy { this.reconnectTimer = undefined; this.metrics.increment('broker.connected'); } catch (error) { + if (isAmqpAuthError(error)) { + void this.secrets?.refreshNow('broker_auth_error'); + } if (this.connection === connection) { this.connection = undefined; this.confirmChannel = undefined; @@ -360,6 +578,9 @@ export class BrokerClient implements OnModuleDestroy { try { channel.on('error', (error: Error) => { this.metrics.increment('broker.consumer_error'); + if (isAmqpAuthError(error)) { + void this.secrets?.refreshNow('broker_auth_error'); + } this.logger.warn( `Broker consumer channel error: ${error.message}`, ); @@ -367,7 +588,11 @@ export class BrokerClient implements OnModuleDestroy { }); channel.on('close', () => this.handleConsumerClose(channel)); await channel.prefetch(this.prefetch); - await assertTopology(channel, this.deliveryLimit); + if (this.passiveTopology) { + await channel.checkQueue(JOB_QUEUE); + } else { + await assertTopology(channel, this.deliveryLimit); + } if (this.handler !== handler) { await channel.close(); return; @@ -376,8 +601,6 @@ export class BrokerClient implements OnModuleDestroy { JOB_QUEUE, (message) => { if (!message) { - // basic.cancel from the broker: the worker must not stay - // healthy while deaf. this.handleConsumerClose(channel); void channel.close().catch(() => undefined); return; @@ -387,8 +610,6 @@ export class BrokerClient implements OnModuleDestroy { this.logger.error( `Job handler crashed: ${error instanceof Error ? error.message : 'unknown error'}`, ); - // Hold the message briefly instead of burning the - // quorum delivery limit in a tight nack loop. setTimeout(() => { try { channel.nack(message, false, true); @@ -404,6 +625,9 @@ export class BrokerClient implements OnModuleDestroy { this.consumerTag = consumer.consumerTag; this.subscribeDelayMs = 1000; } catch (error) { + if (isAmqpAuthError(error)) { + void this.secrets?.refreshNow('broker_auth_error'); + } try { await channel.close(); } catch { @@ -444,7 +668,7 @@ export class BrokerClient implements OnModuleDestroy { this.metrics.increment('broker.reconnect_scheduled'); this.reconnectTimer = setTimeout(() => { this.reconnectTimer = undefined; - this.ensureConnected() + this.ensureConnection() .then(() => this.subscribe()) .catch(() => this.scheduleReconnect()); }, delay); @@ -460,7 +684,7 @@ export class BrokerClient implements OnModuleDestroy { this.metrics.increment('broker.subscribe_scheduled'); this.subscribeTimer = setTimeout(() => { this.subscribeTimer = undefined; - this.ensureConnected() + this.ensureConnection() .then(() => this.subscribe()) .catch(() => this.scheduleSubscribe()); }, delay); diff --git a/app/src/jobs/fault-injector.ts b/app/src/jobs/fault-injector.ts index bcc4120..4b3932c 100644 --- a/app/src/jobs/fault-injector.ts +++ b/app/src/jobs/fault-injector.ts @@ -1,4 +1,4 @@ -import { Injectable, Logger } from '@nestjs/common'; +import { Inject, Injectable, Logger, Optional } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { AppConfig } from '../config/app-config.schema.js'; import { MetricsService } from '../metrics/metrics.service.js'; @@ -44,7 +44,7 @@ export class FaultInjector { constructor( config: ConfigService, - private readonly redis: RedisClient, + @Optional() @Inject(RedisClient) private readonly redis: RedisClient | undefined, private readonly metrics: MetricsService, ) { this.enabled = config.getOrThrow('FAULT_INJECTION_ENABLED') === 1; @@ -55,7 +55,7 @@ export class FaultInjector { target?: FaultTarget, signal?: AbortSignal, ): Promise { - if (!this.enabled) return; + if (!this.enabled || !this.redis) return; const keys = target ? [ `fault:${name}:${target.attachmentId}:${target.pipelineVersion}`, diff --git a/app/src/jobs/jobs.cli.ts b/app/src/jobs/jobs.cli.ts index c931582..414b239 100644 --- a/app/src/jobs/jobs.cli.ts +++ b/app/src/jobs/jobs.cli.ts @@ -1,23 +1,28 @@ import { Module } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; +import { WorkerConfigModule } from '../config/worker-config.module.js'; import type { AppConfig } from '../config/app-config.schema.js'; -import { AppConfigModule } from '../config/app-config.module.js'; import { DatabaseModule } from '../database/database.module.js'; import { MetricsModule } from '../metrics/metrics.module.js'; -import { RedisModule } from '../redis/redis.module.js'; +import { + RuntimeSecretsStore, + type SecretRole, +} from '../openbao/runtime-secrets.service.js'; +import { SecurityModule, registerBootstrappedSecurity } from '../security/security.module.js'; +import { TlsMaterialManager } from '../security/tls-material.js'; import { ObjectStorage } from '../storage/object-storage.js'; import { StorageModule } from '../storage/storage.module.js'; -import { DEAD_LETTER_QUEUE, JOB_QUEUE } from './broker.topology.js'; import { BrokerClient } from './broker.client.js'; +import { DEAD_LETTER_QUEUE, JOB_QUEUE } from './broker.topology.js'; import { JobsModule } from './jobs.module.js'; import { JobsRepository } from './jobs.repository.js'; @Module({ imports: [ - AppConfigModule, + WorkerConfigModule, + SecurityModule, DatabaseModule, - RedisModule, MetricsModule, StorageModule, JobsModule, @@ -58,9 +63,28 @@ async function s3State( : { exists: false, etag: null, last_modified: null }; } +function detectCliRole(raw: Record): SecretRole { + const certRole = String(raw.BAO_CERT_ROLE ?? raw.BAO_AUTH_ROLE ?? ''); + const brokerRole = String(raw.BROKER_ROLE ?? ''); + if (certRole.includes('worker') || brokerRole === 'consumer') return 'worker'; + return 'api'; +} + async function main(): Promise { const args = process.argv.slice(2); const command = args[0]; + const rawEnv = process.env as Record; + const role = detectCliRole(rawEnv); + const tlsMaterial = TlsMaterialManager.initFromEnv('cli', rawEnv); + const secretsStore = await RuntimeSecretsStore.bootstrap( + role, + tlsMaterial, + rawEnv, + undefined, + { background: false }, + ); + registerBootstrappedSecurity(tlsMaterial, secretsStore); + const app = await NestFactory.createApplicationContext(JobsCliModule, { logger: false, }); diff --git a/app/src/jobs/jobs.module.ts b/app/src/jobs/jobs.module.ts index 26e251d..128682a 100644 --- a/app/src/jobs/jobs.module.ts +++ b/app/src/jobs/jobs.module.ts @@ -1,13 +1,12 @@ import { Module } from '@nestjs/common'; import { DatabaseModule } from '../database/database.module.js'; import { MetricsModule } from '../metrics/metrics.module.js'; -import { RedisModule } from '../redis/redis.module.js'; import { BrokerClient } from './broker.client.js'; import { FaultInjector } from './fault-injector.js'; import { JobsRepository } from './jobs.repository.js'; @Module({ - imports: [DatabaseModule, RedisModule, MetricsModule], + imports: [DatabaseModule, MetricsModule], providers: [BrokerClient, JobsRepository, FaultInjector], exports: [BrokerClient, JobsRepository, FaultInjector], }) diff --git a/app/src/main.ts b/app/src/main.ts index 11c043d..24a58ce 100644 --- a/app/src/main.ts +++ b/app/src/main.ts @@ -1,44 +1,171 @@ // Must stay the first import: the OpenTelemetry SDK has to be registered // before any module creates instruments or handles a request. import './telemetry/api-bootstrap.js'; -import { NestFactory } from '@nestjs/core'; -import { HttpAdapterHost } from '@nestjs/core'; -import { ConfigService } from '@nestjs/config'; import { ValidationPipe } from '@nestjs/common'; -import type { UploadRequest } from './attachments/upload-request.js'; +import { ConfigService } from '@nestjs/config'; +import { HttpAdapterHost, NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication, } from '@nestjs/platform-fastify'; +import type { FastifyReply, FastifyRequest } from 'fastify'; +import { randomUUID } from 'node:crypto'; +import http from 'node:http'; +import type https from 'node:https'; +import type tls from 'node:tls'; import { AppModule } from './app.module.js'; +import type { UploadRequest } from './attachments/upload-request.js'; +import { RequestIdInterceptor } from './common/http/request-id.interceptor.js'; +import { + persistInstanceIdFile, + resolveInstanceId, +} from './config/instance-id.js'; import { HealthService } from './health/health.service.js'; import { MetricsService } from './metrics/metrics.service.js'; -import { RequestIdInterceptor } from './common/http/request-id.interceptor.js'; -import { installHttpTelemetry } from './telemetry/http.js'; +import { RuntimeSecretsStore } from './openbao/runtime-secrets.service.js'; +import { registerBootstrappedSecurity } from './security/security.module.js'; +import { TlsMaterialManager } from './security/tls-material.js'; +import { installHttpTelemetry, routeTemplate } from './telemetry/http.js'; import { appLogger } from './telemetry/logger.js'; -import { shutdownTelemetry } from './telemetry/sdk.js'; +import { attachTelemetryTls, shutdownTelemetry } from './telemetry/sdk.js'; const UPLOAD_ROUTE = '/api/v1/chats/:chatId/attachments'; const UPLOAD_STREAM_TYPE = 'application/x-messenger-upload-stream'; +function parseBodyLimitFromEnv(): number { + const raw = Number(process.env.MAX_JSON_BODY_BYTES); + if (Number.isInteger(raw) && raw >= 1024 && raw <= 1048576) return raw; + return 65536; +} + +async function startLoopbackHealthServer( + port: number, + health: HealthService, +): Promise { + if (port <= 0) return undefined; + const server = http.createServer((request, response) => { + if (request.method === 'GET' && request.url === '/health/live') { + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify(health.getLiveness())); + return; + } + if (request.method === 'GET' && request.url === '/health/ready') { + void health + .getReadiness() + .then((body) => { + response.writeHead(200, { + 'content-type': 'application/json', + }); + response.end(JSON.stringify(body)); + }) + .catch(() => { + response.writeHead(503, { + 'content-type': 'application/json', + }); + response.end(JSON.stringify({ status: 'unavailable' })); + }); + return; + } + // Never expose any business API or internal route on the loopback health port. + response.writeHead(404, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ status: 'not_found' })); + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(port, '127.0.0.1', () => { + server.off('error', reject); + resolve(); + }); + }); + return server; +} + async function bootstrap(): Promise { + const tlsMaterial = TlsMaterialManager.initFromEnv('api'); + attachTelemetryTls(tlsMaterial); + const secretsStore = await RuntimeSecretsStore.bootstrap('api', tlsMaterial); + registerBootstrappedSecurity(tlsMaterial, secretsStore); + + const bodyLimit = parseBodyLimitFromEnv(); + const adapterOptions = tlsMaterial.enabled + ? { + logger: false as const, + bodyLimit, + https: tlsMaterial.serverOptions(), + } + : { + logger: false as const, + bodyLimit, + }; + const app = await NestFactory.create( AppModule, - // Fastify's pino access log is replaced by the structured http.request - // event (telemetry/http.ts): pino logged raw URLs with identifiers. - new FastifyAdapter({ logger: false }), + new FastifyAdapter(adapterOptions), { logger: appLogger }, ); + + const config = app.get(ConfigService); + const metrics = app.get(MetricsService); + const health = app.get(HealthService); + const instanceId = resolveInstanceId(config, 'rep'); + persistInstanceIdFile(instanceId); + + const fastify = app.getHttpAdapter().getInstance(); + + // Enforce peer X.509 SAN allowlist & CRL revocation BEFORE telemetry, + // upload streaming, body parsing, or any Nest route/guard runs. + if (tlsMaterial.enabled) { + tlsMaterial.trackServer(fastify.server as unknown as https.Server); + fastify.addHook( + 'onRequest', + async (request: FastifyRequest, reply: FastifyReply) => { + const socket = request.raw.socket as tls.TLSSocket; + const peer = + socket.authorized && + typeof socket.getPeerX509Certificate === 'function' + ? socket.getPeerX509Certificate() + : undefined; + const verdict = tlsMaterial.verifyPeerCertificate(peer); + if (!verdict.allowed) { + const requestId = randomUUID(); + metrics.increment('security.mtls.denied'); + appLogger.event( + 'WARN', + 'security.mtls_identity_denied', + `mTLS client identity denied (${verdict.reason})`, + { + reason: verdict.reason, + peer_serial: verdict.serial, + peer_cn: verdict.cn, + peer_sans: verdict.sans.join(','), + method: request.method, + route: routeTemplate(request.routeOptions?.url), + }, + ); + reply + .code(403) + .header('Connection', 'close') + .header('X-Request-Id', requestId) + .header('X-Instance-Id', instanceId) + .send({ + error: { + code: 'forbidden', + message: 'Client identity not allowed', + request_id: requestId, + }, + }); + return reply; + } + }, + ); + } + + installHttpTelemetry(fastify); + // The upload route receives its body as an unread stream whatever the // declared Content-Type: the service checks the type itself, after the - // auth guard (401 before 415, contracts/README.md), and bounds the body by - // its own limits, not Fastify's bodyLimit. The declared type is kept on the - // request; all other routes keep Fastify's parsers untouched. - const fastify = app.getHttpAdapter().getInstance(); - // Telemetry hooks go first, so every request is measured even if a later - // hook answers it. Routes are registered at init, after the onRoute hook, - // so their handlers run inside the request span. - installHttpTelemetry(fastify); + // auth guard (401 before 415/413, contracts/README.md), and bounds the + // body by its own limits, not Fastify's JSON bodyLimit. fastify.addHook( 'onRequest', (request: UploadRequest, _reply: unknown, done: () => void) => { @@ -54,17 +181,19 @@ async function bootstrap(): Promise { ); fastify.addContentTypeParser( UPLOAD_STREAM_TYPE, + { bodyLimit: Number.MAX_SAFE_INTEGER }, ( _request: unknown, payload: unknown, done: (error: Error | null, body?: unknown) => void, ) => done(null, payload), ); + app.useGlobalInterceptors( new RequestIdInterceptor( app.get(HttpAdapterHost), - app.get(MetricsService), - app.get(ConfigService), + metrics, + config, ), ); app.useGlobalPipes( @@ -75,18 +204,30 @@ async function bootstrap(): Promise { }), ); - const config = app.get(ConfigService); const port = config.getOrThrow('APP_PORT'); const host = config.getOrThrow('APP_HOST'); await app.listen(port, host); - // Drain before teardown. Nest's own shutdown sequence destroys providers - // (closing the database pool and Redis) before `beforeApplicationShutdown` - // runs, so relying on it would keep the replica listed in the load balancer - // while it can no longer serve: SIGTERM must first turn the replica - // not-ready for the LB probe, then wait DRAIN_DELAY_MS, and only then close - // the server and the pools. - const health = app.get(HealthService); + const healthPort = config.getOrThrow('API_HEALTH_PORT'); + const healthServer = await startLoopbackHealthServer(healthPort, health); + + appLogger.event( + 'INFO', + 'api.ready', + `API listening on ${tlsMaterial.enabled ? 'https' : 'http'}://${host}:${port}`, + { + tls_enabled: tlsMaterial.enabled, + health_port: healthPort, + bao_enabled: secretsStore.baoEnabled, + }, + ); + + // Live reload certificates, CRL, and OpenBao secrets on SIGHUP without restart. + process.on('SIGHUP', () => { + tlsMaterial.reload('sighup'); + void secretsStore.refreshNow('sighup'); + }); + const drainDelayMs = config.getOrThrow('DRAIN_DELAY_MS'); let shuttingDown = false; const shutdown = async (): Promise => { @@ -97,11 +238,16 @@ async function bootstrap(): Promise { await new Promise((resolve) => setTimeout(resolve, drainDelayMs), ); + if (healthServer) { + await new Promise((resolve) => + healthServer.close(() => resolve()), + ); + } await app.close(); await shutdownTelemetry(); process.exit(0); }; - for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) + for (const signal of ['SIGTERM', 'SIGINT'] as const) process.once(signal, () => { void shutdown(); }); diff --git a/app/src/messages/idempotency/idempotency-gc.cli.ts b/app/src/messages/idempotency/idempotency-gc.cli.ts index 4e473bc..993ed11 100644 --- a/app/src/messages/idempotency/idempotency-gc.cli.ts +++ b/app/src/messages/idempotency/idempotency-gc.cli.ts @@ -2,20 +2,30 @@ import { fileURLToPath } from 'node:url'; import { parseDatabaseConfig } from '../../config/app-config.schema.js'; import { DatabaseClient } from '../../database/database.client.js'; import { MetricsService } from '../../metrics/metrics.service.js'; +import { RuntimeSecretsStore } from '../../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from '../../security/tls-material.js'; import { IdempotencyRepository } from './idempotency.repository.js'; -// Manual operator pass over the idempotency ledger: the API also purges expired -// claims in the background, but an operator must be able to reclaim space -// without waiting for traffic. It never touches unexpired claims. -// in the stand: docker compose exec api node dist/messages/idempotency/idempotency-gc.cli.js -// on the host: npm run idempotency:gc (needs a reachable DATABASE_URL) +// Manual operator pass over the idempotency ledger. async function main(): Promise { - const config = parseDatabaseConfig(process.env as Record); + const rawEnv = process.env as Record; + const config = parseDatabaseConfig(rawEnv); + const tlsMaterial = TlsMaterialManager.initFromEnv('cli', rawEnv); + const secretsStore = await RuntimeSecretsStore.bootstrap( + 'api', + tlsMaterial, + rawEnv, + undefined, + { background: false }, + ); const database = new DatabaseClient( { + get: (key: keyof typeof config) => config[key], getOrThrow: (key: keyof typeof config) => config[key], } as never, new MetricsService(), + tlsMaterial, + secretsStore, ); try { const repository = new IdempotencyRepository(database); @@ -27,6 +37,8 @@ async function main(): Promise { ); } finally { await database.onModuleDestroy(); + secretsStore.close(); + tlsMaterial.onModuleDestroy(); } } diff --git a/app/src/metrics/metrics.controller.spec.ts b/app/src/metrics/metrics.controller.spec.ts new file mode 100644 index 0000000..dc9bded --- /dev/null +++ b/app/src/metrics/metrics.controller.spec.ts @@ -0,0 +1,32 @@ +import { UnauthorizedException } from '@nestjs/common'; +import { describe, expect, it } from 'vitest'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { MetricsController } from './metrics.controller.js'; +import { MetricsService } from './metrics.service.js'; + +describe('MetricsController', () => { + it('verifies Bearer metrics_token from RuntimeSecretsStore in constant time', () => { + const config = { + get: () => undefined, + }; + const secrets = RuntimeSecretsStore.fromEnvOnly('api', { + METRICS_TOKEN: 'super-secret-metrics-token', + }); + const controller = new MetricsController( + config as never, + new MetricsService(), + secrets, + ); + + expect(() => controller.get(undefined)).toThrow(UnauthorizedException); + expect(() => controller.get('Bearer wrong-token')).toThrow( + UnauthorizedException, + ); + expect(() => + controller.get('Basic c3VwZXItc2VjcmV0LW1ldHJpY3MtdG9rZW4='), + ).toThrow(UnauthorizedException); + + const snap = controller.get('Bearer super-secret-metrics-token'); + expect(snap.instance_id).toMatch(/^rep-[0-9a-f]{12}$/u); + }); +}); diff --git a/app/src/metrics/metrics.controller.ts b/app/src/metrics/metrics.controller.ts index 9c2100d..438eb46 100644 --- a/app/src/metrics/metrics.controller.ts +++ b/app/src/metrics/metrics.controller.ts @@ -4,14 +4,23 @@ import { Headers, HttpCode, HttpStatus, + Optional, Post, UnauthorizedException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; +import { createHash, timingSafeEqual } from 'node:crypto'; import type { AppConfig } from '../config/app-config.schema.js'; import { resolveInstanceId } from '../config/instance-id.js'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; import { MetricsService } from './metrics.service.js'; +const BEARER_RE = /^Bearer[ \t]+([^ \t]+)$/iu; + +function sha256Buffer(value: string): Buffer { + return createHash('sha256').update(value, 'utf8').digest(); +} + @Controller('internal') export class MetricsController { private readonly instanceId: string; @@ -20,6 +29,7 @@ export class MetricsController { constructor( private readonly config: ConfigService, private readonly metrics: MetricsService, + @Optional() private readonly secrets?: RuntimeSecretsStore, ) { this.instanceId = resolveInstanceId(config); this.buildId = process.env.BUILD_ID ?? 'unknown'; @@ -44,11 +54,24 @@ export class MetricsController { } private requireToken(authorization?: string): void { - const token = this.config.get('METRICS_TOKEN'); - if (!token || authorization !== `Bearer ${token}`) + const expected = + this.secrets?.getMetricsToken() ?? + this.config.get('METRICS_TOKEN'); + const presented = + typeof authorization === 'string' + ? BEARER_RE.exec(authorization)?.[1] + : undefined; + if (!expected || !presented) { throw new UnauthorizedException({ message: 'Unauthorized', challenge: 'Bearer realm="metrics"', }); + } + if (!timingSafeEqual(sha256Buffer(presented), sha256Buffer(expected))) { + throw new UnauthorizedException({ + message: 'Unauthorized', + challenge: 'Bearer realm="metrics"', + }); + } } } diff --git a/app/src/openbao/openbao.client.spec.ts b/app/src/openbao/openbao.client.spec.ts new file mode 100644 index 0000000..8eef73d --- /dev/null +++ b/app/src/openbao/openbao.client.spec.ts @@ -0,0 +1,265 @@ +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import https from 'node:https'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type tls from 'node:tls'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { OpenBaoClient, OpenBaoHttpError } from './openbao.client.js'; + +function genTestCerts() { + const dir = mkdtempSync(join(tmpdir(), 'lab7-bao-client-')); + const run = (args: string[]) => + execFileSync('openssl', args, { cwd: dir, stdio: 'pipe' }); + + run(['ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', 'ca.key']); + run([ + 'req', + '-x509', + '-new', + '-key', + 'ca.key', + '-sha256', + '-days', + '10', + '-subj', + '/CN=bao-test-ca', + '-out', + 'ca.crt', + ]); + + // Foreign CA + run(['ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', 'other-ca.key']); + run([ + 'req', + '-x509', + '-new', + '-key', + 'other-ca.key', + '-sha256', + '-days', + '10', + '-subj', + '/CN=foreign-ca', + '-out', + 'other-ca.crt', + ]); + + // Server cert for localhost + writeFileSync( + join(dir, 'server.ext'), + 'basicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:localhost\n', + ); + run(['ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', 'server.key']); + run(['req', '-new', '-key', 'server.key', '-subj', '/CN=localhost', '-out', 'server.csr']); + run([ + 'x509', + '-req', + '-in', + 'server.csr', + '-CA', + 'ca.crt', + '-CAkey', + 'ca.key', + '-CAcreateserial', + '-out', + 'server.crt', + '-days', + '10', + '-sha256', + '-extfile', + 'server.ext', + ]); + + // Client cert + writeFileSync( + join(dir, 'client.ext'), + 'basicConstraints=CA:FALSE\nextendedKeyUsage=clientAuth\nsubjectAltName=DNS:messenger-api\n', + ); + run(['ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', 'client.key']); + run(['req', '-new', '-key', 'client.key', '-subj', '/CN=messenger-api-g1', '-out', 'client.csr']); + run([ + 'x509', + '-req', + '-in', + 'client.csr', + '-CA', + 'ca.crt', + '-CAkey', + 'ca.key', + '-CAcreateserial', + '-out', + 'client.crt', + '-days', + '10', + '-sha256', + '-extfile', + 'client.ext', + ]); + + return { + dir, + ca: readFileSync(join(dir, 'ca.crt')), + otherCa: readFileSync(join(dir, 'other-ca.crt')), + serverCert: readFileSync(join(dir, 'server.crt')), + serverKey: readFileSync(join(dir, 'server.key')), + clientCert: readFileSync(join(dir, 'client.crt')), + clientKey: readFileSync(join(dir, 'client.key')), + }; +} + +describe('OpenBaoClient (HTTPS + mTLS auth/cert)', () => { + let certs: ReturnType; + let server: https.Server; + let port = 0; + let sealed = false; + + beforeAll(async () => { + certs = genTestCerts(); + server = https.createServer( + { + ca: certs.ca, + cert: certs.serverCert, + key: certs.serverKey, + requestCert: true, + rejectUnauthorized: false, + }, + (req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + if (sealed) { + res.writeHead(503, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ errors: ['Vault is sealed'] })); + return; + } + const body = chunks.length + ? (JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record< + string, + unknown + >) + : {}; + if (req.method === 'POST' && req.url === '/v1/auth/cert/login') { + const sock = req.socket as tls.TLSSocket; + if (!sock.authorized || body.name !== 'messenger-api') { + res.writeHead(403, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ errors: ['permission denied'] })); + return; + } + res.writeHead(200, { 'content-type': 'application/json' }); + res.end( + JSON.stringify({ + auth: { + client_token: 'hvs.test-service-token-123456', + lease_duration: 300, + renewable: true, + policies: ['api-policy'], + }, + }), + ); + return; + } + if (req.method === 'POST' && req.url === '/v1/auth/token/renew-self') { + if (req.headers['x-vault-token'] !== 'hvs.test-service-token-123456') { + res.writeHead(403, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ errors: ['bad token'] })); + return; + } + res.writeHead(200, { 'content-type': 'application/json' }); + res.end( + JSON.stringify({ + auth: { lease_duration: 300, renewable: true }, + }), + ); + return; + } + if (req.method === 'GET' && req.url === '/v1/secret/data/messenger/api') { + if (req.headers['x-vault-token'] !== 'hvs.test-service-token-123456') { + res.writeHead(403, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ errors: ['permission denied'] })); + return; + } + res.writeHead(200, { 'content-type': 'application/json' }); + res.end( + JSON.stringify({ + data: { + data: { + db_user: 'messenger_api', + db_password: 'pg-secret-v1', + metrics_token: 'metrics-v1', + }, + metadata: { version: 3 }, + }, + }), + ); + return; + } + res.writeHead(404); + res.end(); + }); + }, + ); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + port = (server.address() as { port: number }).port; + }); + + afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); + rmSync(certs.dir, { recursive: true, force: true }); + }); + + it('authenticates via auth/cert, renews token, reads KV v2, and surfaces 503 sealed errors', async () => { + sealed = false; + const client = new OpenBaoClient({ + addr: `https://localhost:${port}`, + authMethod: 'cert', + certRole: 'messenger-api', + tlsProvider: () => ({ + ca: certs.ca, + cert: certs.clientCert, + key: certs.clientKey, + }), + }); + + const login = await client.login(); + expect(login.clientToken).toBe('hvs.test-service-token-123456'); + expect(login.leaseDuration).toBe(300); + + const renewed = await client.renewSelf(login.clientToken); + expect(renewed).toEqual({ leaseDuration: 300, renewable: true }); + + const secret = await client.readKvV2( + login.clientToken, + 'secret/data/messenger/api', + ); + expect(secret.version).toBe(3); + expect(secret.data.db_user).toBe('messenger_api'); + expect(secret.data.db_password).toBe('pg-secret-v1'); + + sealed = true; + try { + await client.readKvV2(login.clientToken, 'secret/data/messenger/api'); + expect.unreachable('expected 503'); + } catch (error) { + expect(error).toBeInstanceOf(OpenBaoHttpError); + expect((error as OpenBaoHttpError).sealed).toBe(true); + expect((error as OpenBaoHttpError).statusCode).toBe(503); + } finally { + sealed = false; + } + }); + + it('rejects untrusted CA certificates (verify-full)', async () => { + const untrusted = new OpenBaoClient({ + addr: `https://localhost:${port}`, + authMethod: 'cert', + certRole: 'messenger-api', + tlsProvider: () => ({ + ca: certs.otherCa, + cert: certs.clientCert, + key: certs.clientKey, + }), + }); + await expect(untrusted.login()).rejects.toThrow(); + }); +}); diff --git a/app/src/openbao/openbao.client.ts b/app/src/openbao/openbao.client.ts new file mode 100644 index 0000000..0010f2c --- /dev/null +++ b/app/src/openbao/openbao.client.ts @@ -0,0 +1,320 @@ +import { readFileSync } from 'node:fs'; +import https from 'node:https'; +import { URL } from 'node:url'; + +export class OpenBaoHttpError extends Error { + readonly sealed: boolean; + + constructor( + readonly statusCode: number, + message: string, + ) { + super(message); + this.name = 'OpenBaoHttpError'; + this.sealed = statusCode === 503; + } +} + +export type OpenBaoLoginResult = { + readonly clientToken: string; + readonly leaseDuration: number; + readonly renewable: boolean; + readonly policies: readonly string[]; +}; + +export type OpenBaoRenewResult = { + readonly leaseDuration: number; + readonly renewable: boolean; +}; + +export type OpenBaoSecretResult = { + readonly data: Record; + readonly version: number; +}; + +export type OpenBaoTlsMaterialProvider = () => { + readonly ca: Buffer; + readonly cert?: Buffer; + readonly key?: Buffer; +}; + +export type OpenBaoClientOptions = { + readonly addr: string; + readonly authMethod: 'cert' | 'approle'; + readonly certRole?: string; + readonly roleIdFile?: string; + readonly secretIdFile?: string; + readonly wrappedSecretIdFile?: string; + readonly timeoutMs?: number; + readonly tlsProvider: OpenBaoTlsMaterialProvider; +}; + +type BaoEnvelope = { + auth?: { + client_token?: string; + lease_duration?: number; + renewable?: boolean; + policies?: string[]; + }; + data?: { + data?: Record; + metadata?: { version?: number }; + secret_id?: string; + [key: string]: unknown; + }; + errors?: string[]; +}; + +export class OpenBaoClient { + private readonly baseUrl: URL; + private readonly timeoutMs: number; + + constructor(private readonly options: OpenBaoClientOptions) { + this.baseUrl = new URL(options.addr); + if (this.baseUrl.protocol !== 'https:') { + throw new Error('OpenBao address must use https://'); + } + this.timeoutMs = options.timeoutMs ?? 5000; + } + + async login(): Promise { + if (this.options.authMethod === 'approle') { + return this.loginAppRole(); + } + return this.loginCert(); + } + + private async loginCert(): Promise { + const body = this.options.certRole + ? { name: this.options.certRole } + : {}; + const response = await this.request( + 'POST', + '/v1/auth/cert/login', + undefined, + body, + true, + ); + return this.parseAuth(response); + } + + private async loginAppRole(): Promise { + if (!this.options.roleIdFile) { + throw new Error( + 'BAO_ROLE_ID_FILE is required for approle authentication', + ); + } + const roleId = readFileSync(this.options.roleIdFile, 'utf8').trim(); + if (!roleId) throw new Error('BAO_ROLE_ID_FILE is empty'); + + let secretId: string; + if (this.options.wrappedSecretIdFile) { + const wrappingToken = readFileSync( + this.options.wrappedSecretIdFile, + 'utf8', + ).trim(); + if (!wrappingToken) + throw new Error('BAO_WRAPPED_SECRET_ID_FILE is empty'); + const unwrapped = await this.request( + 'POST', + '/v1/sys/wrapping/unwrap', + wrappingToken, + undefined, + false, + ); + const extracted = unwrapped.data?.secret_id; + if (typeof extracted !== 'string' || extracted.length === 0) { + throw new Error('Unwrapped AppRole response missing secret_id'); + } + secretId = extracted; + } else if (this.options.secretIdFile) { + secretId = readFileSync(this.options.secretIdFile, 'utf8').trim(); + if (!secretId) throw new Error('BAO_SECRET_ID_FILE is empty'); + } else { + throw new Error( + 'BAO_WRAPPED_SECRET_ID_FILE or BAO_SECRET_ID_FILE is required for approle', + ); + } + + const response = await this.request( + 'POST', + '/v1/auth/approle/login', + undefined, + { role_id: roleId, secret_id: secretId }, + false, + ); + return this.parseAuth(response); + } + + async renewSelf(token: string): Promise { + const response = await this.request( + 'POST', + '/v1/auth/token/renew-self', + token, + {}, + false, + ); + const auth = response.auth; + if (!auth || typeof auth.lease_duration !== 'number') { + throw new Error('OpenBao renew-self response missing lease_duration'); + } + return { + leaseDuration: auth.lease_duration, + renewable: Boolean(auth.renewable), + }; + } + + async readKvV2( + token: string, + secretPath: string, + ): Promise { + const trimmed = secretPath.replace(/^\/+/u, ''); + const apiPath = trimmed.startsWith('v1/') + ? `/${trimmed}` + : `/v1/${trimmed}`; + const response = await this.request('GET', apiPath, token, undefined, false); + const rawData = + response.data?.data && typeof response.data.data === 'object' + ? response.data.data + : response.data; + if (!rawData || typeof rawData !== 'object') { + throw new Error('OpenBao secret response missing data'); + } + const version = + typeof response.data?.metadata?.version === 'number' + ? response.data.metadata.version + : 0; + const data: Record = {}; + for (const [key, value] of Object.entries(rawData)) { + if (typeof value === 'string') { + data[key] = value; + } else if (typeof value === 'number' || typeof value === 'boolean') { + data[key] = String(value); + } + } + return { data, version }; + } + + private parseAuth(envelope: BaoEnvelope): OpenBaoLoginResult { + const auth = envelope.auth; + if ( + !auth || + typeof auth.client_token !== 'string' || + auth.client_token.length === 0 + ) { + throw new Error('OpenBao login response missing client_token'); + } + return { + clientToken: auth.client_token, + leaseDuration: + typeof auth.lease_duration === 'number' && auth.lease_duration > 0 + ? auth.lease_duration + : 300, + renewable: Boolean(auth.renewable), + policies: Array.isArray(auth.policies) ? auth.policies : [], + }; + } + + private request( + method: 'GET' | 'POST', + path: string, + token: string | undefined, + payload: Record | undefined, + requireClientCert: boolean, + ): Promise { + const tlsMaterial = this.options.tlsProvider(); + if (requireClientCert && (!tlsMaterial.cert || !tlsMaterial.key)) { + return Promise.reject( + new Error( + 'Client TLS certificate and key are required for OpenBao auth/cert login', + ), + ); + } + const serialized = + payload !== undefined ? JSON.stringify(payload) : undefined; + const headers: Record = { + accept: 'application/json', + }; + if (token) headers['X-Vault-Token'] = token; + if (serialized !== undefined) { + headers['content-type'] = 'application/json'; + headers['content-length'] = Buffer.byteLength(serialized); + } + + return new Promise((resolve, reject) => { + let settled = false; + const finish = (error: Error | null, result?: BaoEnvelope): void => { + if (settled) return; + settled = true; + if (error) reject(error); + else resolve(result ?? {}); + }; + + const req = https.request( + { + protocol: this.baseUrl.protocol, + hostname: this.baseUrl.hostname, + port: this.baseUrl.port ? Number(this.baseUrl.port) : 443, + path, + method, + headers, + // Use a fresh TLS connection per OpenBao call so leaf cert + // rotation and CRL revocation take effect immediately. + agent: false, + ca: tlsMaterial.ca, + ...(tlsMaterial.cert && tlsMaterial.key + ? { cert: tlsMaterial.cert, key: tlsMaterial.key } + : {}), + servername: this.baseUrl.hostname, + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + timeout: this.timeoutMs, + }, + (res) => { + const chunks: Buffer[] = []; + let totalBytes = 0; + res.on('data', (chunk: Buffer) => { + totalBytes += chunk.length; + if (totalBytes <= 1024 * 1024) chunks.push(chunk); + }); + res.on('end', () => { + const status = res.statusCode ?? 0; + const bodyText = Buffer.concat(chunks).toString('utf8'); + let parsed: BaoEnvelope = {}; + if (bodyText.trim().length > 0) { + try { + parsed = JSON.parse(bodyText) as BaoEnvelope; + } catch { + parsed = {}; + } + } + if (status >= 200 && status < 300) { + finish(null, parsed); + return; + } + const reason = + Array.isArray(parsed.errors) && parsed.errors.length > 0 + ? parsed.errors[0] + : `HTTP ${status}`; + finish( + new OpenBaoHttpError( + status, + `OpenBao ${method} ${path} failed (${status}): ${reason}`, + ), + ); + }); + }, + ); + + req.on('timeout', () => { + req.destroy(new Error(`OpenBao request timed out after ${this.timeoutMs}ms`)); + }); + req.on('error', (error: Error) => { + finish(error); + }); + + if (serialized !== undefined) req.write(serialized); + req.end(); + }); + } +} diff --git a/app/src/openbao/runtime-secrets.service.spec.ts b/app/src/openbao/runtime-secrets.service.spec.ts new file mode 100644 index 0000000..e2a78fd --- /dev/null +++ b/app/src/openbao/runtime-secrets.service.spec.ts @@ -0,0 +1,160 @@ +import { describe, expect, it, vi } from 'vitest'; +import { TlsMaterialManager } from '../security/tls-material.js'; +import { OpenBaoHttpError } from './openbao.client.js'; +import { + RuntimeSecretsStore, + type OpenBaoClientLike, +} from './runtime-secrets.service.js'; + +function disabledTls(): TlsMaterialManager { + return new TlsMaterialManager({ + enabled: false, + requireServerCert: false, + requireClientCert: false, + allowedClientSans: [], + reloadIntervalMs: 0, + }); +} + +describe('RuntimeSecretsStore', () => { + it('strictly forbids static BAO_TOKEN or VAULT_TOKEN when BAO_ENABLED=true', async () => { + await expect( + RuntimeSecretsStore.bootstrap('api', disabledTls(), { + BAO_ENABLED: 'true', + BAO_ADDR: 'https://openbao:8200', + BAO_TOKEN: 'hvs.forbidden', + }), + ).rejects.toThrow(/forbidden/i); + + await expect( + RuntimeSecretsStore.bootstrap('worker', disabledTls(), { + BAO_ENABLED: 'true', + BAO_ADDR: 'https://openbao:8200', + VAULT_TOKEN: 's.forbidden', + }), + ).rejects.toThrow(/forbidden/i); + }); + + it('handles secret rotation, 403 re-auth, 503 sealed bounded degradation, and recovery without writing to process.env', async () => { + let version = 1; + let dbPass = 'db-pass-v1'; + let sealed = false; + let revokedToken = false; + let loginCount = 0; + + const mockClient: OpenBaoClientLike = { + login: vi.fn(async () => { + if (sealed) throw new OpenBaoHttpError(503, 'Vault is sealed'); + loginCount += 1; + revokedToken = false; + return { + clientToken: `hvs.token-${loginCount}`, + leaseDuration: 300, + renewable: true, + policies: ['api-policy'], + }; + }), + renewSelf: vi.fn(async () => { + if (sealed) throw new OpenBaoHttpError(503, 'Vault is sealed'); + if (revokedToken) + throw new OpenBaoHttpError(403, 'permission denied'); + return { leaseDuration: 300, renewable: true }; + }), + readKvV2: vi.fn(async () => { + if (sealed) throw new OpenBaoHttpError(503, 'Vault is sealed'); + if (revokedToken) + throw new OpenBaoHttpError(403, 'permission denied'); + return { + version, + data: { + db_user: 'messenger_api', + db_password: dbPass, + redis_user: 'messenger_api', + redis_password: 'redis-pass-v1', + s3_access_key_id: 's3-key-v1', + s3_secret_access_key: 's3-sec-v1', + metrics_token: 'metrics-v1', + }, + }; + }), + }; + + const store = await RuntimeSecretsStore.bootstrap( + 'api', + disabledTls(), + { + BAO_ENABLED: 'true', + BAO_ADDR: 'https://openbao:8200', + BAO_SECRET_PATH: 'secret/data/messenger/api', + }, + mockClient, + { background: false, reactiveCooldownMs: 10 }, + ); + + try { + expect(store.getDbCredentials()).toEqual({ + user: 'messenger_api', + password: 'db-pass-v1', + }); + expect(store.getMetricsToken()).toBe('metrics-v1'); + expect(JSON.stringify(store)).not.toContain('db-pass-v1'); + expect(process.env.PG_PASSWORD).not.toBe('db-pass-v1'); + + // Seal OpenBao -> keeps serving cached credentials in degraded mode. + sealed = true; + expect(await store.refreshNow('poll')).toBe(false); + expect(store.isDegraded).toBe(true); + expect(store.getDbCredentials()?.password).toBe('db-pass-v1'); + + // Unseal + revoke old token + rotate DB password -> re-auths on 403 & emits rotated:db only. + sealed = false; + revokedToken = true; + version = 2; + dbPass = 'db-pass-v2'; + + const rotatedEvents: string[] = []; + store.on('rotated:db', () => rotatedEvents.push('db')); + store.on('rotated:redis', () => rotatedEvents.push('redis')); + + expect(await store.refreshNow('sighup')).toBe(true); + expect(store.isDegraded).toBe(false); + expect(loginCount).toBe(2); + expect(store.getDbCredentials()?.password).toBe('db-pass-v2'); + expect(store.kvVersion).toBe(2); + expect(rotatedEvents).toEqual(['db']); + + // Token renewal succeeds and handles 403 re-auth cleanly. + expect(await store.renewTokenNow()).toBe(true); + revokedToken = true; + expect(await store.renewTokenNow()).toBe(true); + expect(loginCount).toBe(3); + } finally { + store.close(); + } + }); + + it('loads env fallback cleanly when BAO_ENABLED=false', async () => { + const store = await RuntimeSecretsStore.bootstrap('api', disabledTls(), { + BAO_ENABLED: 'false', + DATABASE_URL: 'postgresql://localuser:localpass@localhost:5432/messenger', + REDIS_URL: 'redis://ruser:rpass@localhost:6379', + S3_ACCESS_KEY_ID: 'local-key', + S3_SECRET_ACCESS_KEY: 'local-sec', + METRICS_TOKEN: 'local-metrics', + }); + expect(store.baoEnabled).toBe(false); + expect(store.getDbCredentials()).toEqual({ + user: 'localuser', + password: 'localpass', + }); + expect(store.getRedisCredentials()).toEqual({ + user: 'ruser', + password: 'rpass', + }); + expect(store.getS3Credentials()).toEqual({ + accessKeyId: 'local-key', + secretAccessKey: 'local-sec', + }); + expect(store.getMetricsToken()).toBe('local-metrics'); + }); +}); diff --git a/app/src/openbao/runtime-secrets.service.ts b/app/src/openbao/runtime-secrets.service.ts new file mode 100644 index 0000000..dc6a287 --- /dev/null +++ b/app/src/openbao/runtime-secrets.service.ts @@ -0,0 +1,638 @@ +import { OnModuleDestroy } from '@nestjs/common'; +import crypto from 'node:crypto'; +import { EventEmitter } from 'node:events'; +import { readFileSync } from 'node:fs'; +import { URL } from 'node:url'; +import { + assertNoStaticBaoToken, + resolveBaoEnabled, +} from '../config/app-config.schema.js'; +import type { TlsMaterialManager } from '../security/tls-material.js'; +import { appLogger } from '../telemetry/logger.js'; +import { + OpenBaoClient, + OpenBaoHttpError, + type OpenBaoLoginResult, + type OpenBaoSecretResult, +} from './openbao.client.js'; + +export type SecretRole = 'api' | 'worker' | 'migrator' | 'cli'; + +export type DbCredentials = { + readonly user: string; + readonly password: string; +}; + +export type RedisCredentials = { + readonly user?: string; + readonly password?: string; +}; + +export type S3Credentials = { + readonly accessKeyId: string; + readonly secretAccessKey: string; +}; + +export type BrokerCredentials = { + readonly user?: string; + readonly password?: string; +}; + +export type OpenBaoClientLike = Pick< + OpenBaoClient, + 'login' | 'renewSelf' | 'readKvV2' +>; + +type SecretSnapshot = { + readonly db?: DbCredentials; + readonly redis?: RedisCredentials; + readonly s3?: S3Credentials; + readonly broker?: BrokerCredentials; + readonly metricsToken?: string; + readonly kvVersion: number; +}; + +type StoreOptions = { + readonly role: SecretRole; + readonly baoEnabled: boolean; + readonly client?: OpenBaoClientLike; + readonly secretPath?: string; + readonly refreshIntervalMs: number; + readonly reactiveCooldownMs?: number; + readonly background: boolean; + readonly initialSnapshot: SecretSnapshot; + readonly initialAuth?: OpenBaoLoginResult; +}; + +const MAX_DEGRADED_BACKOFF_MS = 30_000; +const INITIAL_DEGRADED_BACKOFF_MS = 5_000; +const WARN_THROTTLE_MS = 30_000; + +function fingerprint(value: unknown): string { + return crypto + .createHash('sha256') + .update(JSON.stringify(value ?? null)) + .digest('hex'); +} + +function readEnvOrFile( + raw: Record, + key: string, +): string | undefined { + const filePath = raw[`${key}_FILE`]; + if (typeof filePath === 'string' && filePath.trim().length > 0) { + return readFileSync(filePath.trim(), 'utf8').trim(); + } + const val = raw[key]; + if (typeof val === 'string' && val.trim().length > 0) return val.trim(); + return undefined; +} + +function parseUrlCredentials( + urlString: string | undefined, +): { user?: string; password?: string } { + if (!urlString) return {}; + try { + const parsed = new URL(urlString); + return { + user: parsed.username ? decodeURIComponent(parsed.username) : undefined, + password: parsed.password + ? decodeURIComponent(parsed.password) + : undefined, + }; + } catch { + return {}; + } +} + +function snapshotFromKv(result: OpenBaoSecretResult): SecretSnapshot { + const d = result.data; + const db = + d.db_user && d.db_password + ? { user: d.db_user, password: d.db_password } + : undefined; + const redis = + d.redis_user || d.redis_password + ? { user: d.redis_user, password: d.redis_password } + : undefined; + const s3 = + d.s3_access_key_id && d.s3_secret_access_key + ? { + accessKeyId: d.s3_access_key_id, + secretAccessKey: d.s3_secret_access_key, + } + : undefined; + const broker = + d.broker_user || d.broker_password + ? { user: d.broker_user, password: d.broker_password } + : undefined; + return { + db, + redis, + s3, + broker, + metricsToken: d.metrics_token || undefined, + kvVersion: result.version, + }; +} + +function snapshotFromEnv(raw: Record): SecretSnapshot { + const dbUrlCreds = parseUrlCredentials(readEnvOrFile(raw, 'DATABASE_URL')); + const dbUser = + readEnvOrFile(raw, 'PG_USER') ?? + readEnvOrFile(raw, 'DATABASE_USER') ?? + dbUrlCreds.user; + const dbPassword = + readEnvOrFile(raw, 'PG_PASSWORD') ?? + readEnvOrFile(raw, 'DATABASE_PASSWORD') ?? + dbUrlCreds.password; + + const redisUrlCreds = parseUrlCredentials(readEnvOrFile(raw, 'REDIS_URL')); + const redisUser = readEnvOrFile(raw, 'REDIS_USER') ?? redisUrlCreds.user; + const redisPassword = + readEnvOrFile(raw, 'REDIS_PASSWORD') ?? redisUrlCreds.password; + + const s3AccessKeyId = readEnvOrFile(raw, 'S3_ACCESS_KEY_ID'); + const s3SecretAccessKey = readEnvOrFile(raw, 'S3_SECRET_ACCESS_KEY'); + + const brokerUrlCreds = parseUrlCredentials(readEnvOrFile(raw, 'BROKER_URL')); + + return { + db: + dbUser !== undefined && dbPassword !== undefined + ? { user: dbUser, password: dbPassword } + : undefined, + redis: + redisUser !== undefined || redisPassword !== undefined + ? { user: redisUser, password: redisPassword } + : undefined, + s3: + s3AccessKeyId && s3SecretAccessKey + ? { + accessKeyId: s3AccessKeyId, + secretAccessKey: s3SecretAccessKey, + } + : undefined, + broker: + brokerUrlCreds.user || brokerUrlCreds.password + ? brokerUrlCreds + : undefined, + metricsToken: readEnvOrFile(raw, 'METRICS_TOKEN'), + kvVersion: 0, + }; +} + +function defaultRoleName(role: SecretRole): string { + if (role === 'worker') return 'messenger-worker'; + if (role === 'migrator') return 'messenger-migrator'; + return 'messenger-api'; +} + +function defaultSecretPath(role: SecretRole): string { + if (role === 'worker') return 'secret/data/messenger/worker'; + if (role === 'migrator') return 'secret/data/messenger/migrator'; + return 'secret/data/messenger/api'; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Heap-only runtime secret store. Never persists secrets to disk or process.env. + * Manages OpenBao token renewal (at 66% TTL), 15s secret version polling, + * SIGHUP / debounced reactive refresh on auth failures, and bounded degraded + * survival while OpenBao is sealed or temporarily unreachable. + */ +export class RuntimeSecretsStore extends EventEmitter implements OnModuleDestroy { + private snapshot: SecretSnapshot; + private token: string | undefined; + private leaseDurationSec = 0; + private renewable = false; + private renewTimer: NodeJS.Timeout | undefined; + private pollTimer: NodeJS.Timeout | undefined; + private refreshInFlight: Promise | undefined; + private reauthInFlight: Promise | undefined; + private lastReactiveRefreshAt = 0; + private degraded = false; + private degradedBackoffMs = INITIAL_DEGRADED_BACKOFF_MS; + private lastWarnAt = 0; + private closed = false; + private readonly reactiveCooldownMs: number; + + constructor(private readonly options: StoreOptions) { + super(); + this.snapshot = options.initialSnapshot; + this.reactiveCooldownMs = options.reactiveCooldownMs ?? 5_000; + if (options.initialAuth) { + this.token = options.initialAuth.clientToken; + this.leaseDurationSec = options.initialAuth.leaseDuration; + this.renewable = options.initialAuth.renewable; + } + if (options.baoEnabled && options.background) { + this.scheduleNextRenewal(); + this.startPolling(); + } + } + + static async bootstrap( + role: SecretRole, + tlsMaterial: TlsMaterialManager, + raw: Record = process.env as Record, + clientOverride?: OpenBaoClientLike, + opts?: { background?: boolean; reactiveCooldownMs?: number }, + ): Promise { + assertNoStaticBaoToken(raw); + const baoEnabled = resolveBaoEnabled(raw); + const background = opts?.background ?? (role === 'api' || role === 'worker'); + + if (!baoEnabled) { + return new RuntimeSecretsStore({ + role, + baoEnabled: false, + refreshIntervalMs: 15_000, + reactiveCooldownMs: opts?.reactiveCooldownMs, + background: false, + initialSnapshot: snapshotFromEnv(raw), + }); + } + + const first = (...vals: unknown[]): string | undefined => { + for (const v of vals) { + if (typeof v === 'string' && v.trim().length > 0) + return v.trim(); + } + return undefined; + }; + const addr = first(raw.BAO_ADDR); + if (!addr) { + throw new Error('BAO_ADDR is required when BAO_ENABLED=true'); + } + const authMethod = + first(raw.BAO_AUTH_METHOD) === 'approle' ? 'approle' : 'cert'; + const certRole = + first(raw.BAO_CERT_ROLE, raw.BAO_AUTH_ROLE) ?? defaultRoleName(role); + const secretPath = + first(raw.BAO_SECRET_PATH) ?? defaultSecretPath(role); + const timeoutMs = Number(raw.BAO_TIMEOUT_MS) || 5000; + const refreshIntervalMs = Number(raw.BAO_REFRESH_INTERVAL_MS) || 15_000; + const startupRetries = Math.max( + 1, + Math.min(30, Number(raw.BAO_STARTUP_RETRIES) || 5), + ); + + const client: OpenBaoClientLike = + clientOverride ?? + new OpenBaoClient({ + addr, + authMethod, + certRole, + roleIdFile: first(raw.BAO_ROLE_ID_FILE), + secretIdFile: first(raw.BAO_SECRET_ID_FILE), + wrappedSecretIdFile: first(raw.BAO_WRAPPED_SECRET_ID_FILE), + timeoutMs, + tlsProvider: () => { + const ca = tlsMaterial.baoCa; + if (!ca) { + throw new Error( + 'CA certificate is required to connect to OpenBao', + ); + } + return { + ca, + cert: tlsMaterial.clientCert, + key: tlsMaterial.clientKey, + }; + }, + }); + + let auth: OpenBaoLoginResult | undefined; + let secret: OpenBaoSecretResult | undefined; + let lastError: unknown; + for (let attempt = 1; attempt <= startupRetries; attempt += 1) { + try { + auth = await client.login(); + secret = await client.readKvV2(auth.clientToken, secretPath); + break; + } catch (error) { + lastError = error; + if (attempt < startupRetries) { + const delay = Math.min(attempt * 1000, 5000); + await sleep(delay); + } + } + } + if (!auth || !secret) { + const status = + lastError instanceof OpenBaoHttpError + ? `HTTP ${lastError.statusCode}` + : lastError instanceof Error + ? lastError.name + : 'unknown'; + throw new Error(`OpenBao unavailable at startup (${status})`); + } + + appLogger.event( + 'INFO', + 'security.openbao_bootstrapped', + `OpenBao secrets loaded for ${role}`, + { + role, + kv_version: secret.version, + ttl_seconds: auth.leaseDuration, + }, + ); + + return new RuntimeSecretsStore({ + role, + baoEnabled: true, + client, + secretPath, + refreshIntervalMs, + reactiveCooldownMs: opts?.reactiveCooldownMs, + background, + initialSnapshot: snapshotFromKv(secret), + initialAuth: auth, + }); + } + + static fromEnvOnly( + role: SecretRole = 'api', + raw: Record = process.env as Record, + ): RuntimeSecretsStore { + return new RuntimeSecretsStore({ + role, + baoEnabled: false, + refreshIntervalMs: 15_000, + background: false, + initialSnapshot: snapshotFromEnv(raw), + }); + } + + get baoEnabled(): boolean { + return this.options.baoEnabled; + } + + get kvVersion(): number { + return this.snapshot.kvVersion; + } + + get isDegraded(): boolean { + return this.degraded; + } + + getDbCredentials(): DbCredentials | undefined { + return this.snapshot.db; + } + + getRedisCredentials(): RedisCredentials | undefined { + return this.snapshot.redis; + } + + getS3Credentials(): S3Credentials { + if (!this.snapshot.s3) { + throw new Error('S3 credentials are not available in RuntimeSecretsStore'); + } + return this.snapshot.s3; + } + + getBrokerCredentials(): BrokerCredentials | undefined { + return this.snapshot.broker; + } + + getMetricsToken(): string | undefined { + return this.snapshot.metricsToken; + } + + toJSON(): string { + return '[REDACTED RuntimeSecretsStore]'; + } + + async refreshNow(reason: string): Promise { + if (!this.options.baoEnabled || !this.options.client || !this.options.secretPath) { + return false; + } + if (this.closed) return false; + + const isReactive = + reason !== 'poll' && reason !== 'sighup' && reason !== 'reauth'; + if (isReactive) { + const now = Date.now(); + if (now - this.lastReactiveRefreshAt < this.reactiveCooldownMs) { + return false; + } + this.lastReactiveRefreshAt = now; + } + + if (this.refreshInFlight) return this.refreshInFlight; + + this.refreshInFlight = this.doRefresh(reason).finally(() => { + this.refreshInFlight = undefined; + }); + return this.refreshInFlight; + } + + async renewTokenNow(): Promise { + if (!this.options.baoEnabled || !this.options.client || this.closed) { + return false; + } + try { + if (!this.token || !this.renewable) { + await this.reauthenticate(); + return true; + } + const renewed = await this.options.client.renewSelf(this.token); + this.leaseDurationSec = renewed.leaseDuration; + this.renewable = renewed.renewable; + this.markRecovered(); + appLogger.event( + 'INFO', + 'security.openbao_token_renewed', + 'OpenBao service token renewed', + { ttl_seconds: renewed.leaseDuration }, + ); + return true; + } catch (error) { + if (error instanceof OpenBaoHttpError && error.statusCode === 403) { + try { + await this.reauthenticate(); + return true; + } catch (reauthError) { + this.markDegraded('reauth', reauthError); + return false; + } + } + this.markDegraded('renew', error); + return false; + } + } + + close(): void { + this.closed = true; + if (this.renewTimer) { + clearTimeout(this.renewTimer); + this.renewTimer = undefined; + } + if (this.pollTimer) { + clearInterval(this.pollTimer); + this.pollTimer = undefined; + } + this.token = undefined; + } + + onModuleDestroy(): void { + this.close(); + } + + private async doRefresh(reason: string): Promise { + const client = this.options.client!; + const secretPath = this.options.secretPath!; + try { + if (!this.token) { + await this.reauthenticate(); + } + let fetched: OpenBaoSecretResult; + try { + fetched = await client.readKvV2(this.token!, secretPath); + } catch (error) { + if (error instanceof OpenBaoHttpError && error.statusCode === 403) { + await this.reauthenticate(); + fetched = await client.readKvV2(this.token!, secretPath); + } else { + throw error; + } + } + this.markRecovered(); + return this.applySnapshot(snapshotFromKv(fetched), reason); + } catch (error) { + this.markDegraded('refresh', error); + return false; + } + } + + private async reauthenticate(): Promise { + if (this.reauthInFlight) return this.reauthInFlight; + const client = this.options.client!; + this.reauthInFlight = (async () => { + const auth = await client.login(); + this.token = auth.clientToken; + this.leaseDurationSec = auth.leaseDuration; + this.renewable = auth.renewable; + this.markRecovered(); + appLogger.event( + 'INFO', + 'security.openbao_reauthenticated', + 'OpenBao service re-authenticated', + { ttl_seconds: auth.leaseDuration }, + ); + })().finally(() => { + this.reauthInFlight = undefined; + }); + return this.reauthInFlight; + } + + private applySnapshot(next: SecretSnapshot, reason: string): boolean { + const prev = this.snapshot; + const changedScopes: Array<'db' | 'redis' | 's3' | 'broker' | 'metrics'> = + []; + + if (fingerprint(prev.db) !== fingerprint(next.db) && next.db) + changedScopes.push('db'); + if (fingerprint(prev.redis) !== fingerprint(next.redis) && next.redis) + changedScopes.push('redis'); + if (fingerprint(prev.s3) !== fingerprint(next.s3) && next.s3) + changedScopes.push('s3'); + if (fingerprint(prev.broker) !== fingerprint(next.broker) && next.broker) + changedScopes.push('broker'); + if ( + fingerprint(prev.metricsToken) !== fingerprint(next.metricsToken) && + next.metricsToken + ) + changedScopes.push('metrics'); + + this.snapshot = next; + for (const scope of changedScopes) { + appLogger.event( + 'INFO', + 'security.secret_rotated', + `Secret rotated for scope ${scope}`, + { + scope, + kv_version: next.kvVersion, + reason, + }, + ); + this.emit(`rotated:${scope}`); + } + return changedScopes.length > 0; + } + + private scheduleNextRenewal(overrideDelayMs?: number): void { + if (this.closed) return; + if (this.renewTimer) clearTimeout(this.renewTimer); + const delayMs = + overrideDelayMs ?? + Math.max(5_000, Math.floor(this.leaseDurationSec * 1000 * 0.66)); + this.renewTimer = setTimeout(() => { + this.renewTimer = undefined; + void this.renewTokenNow().then((ok) => { + if (this.closed) return; + if (ok) { + this.scheduleNextRenewal(); + } else { + const retryMs = this.degradedBackoffMs; + this.degradedBackoffMs = Math.min( + this.degradedBackoffMs * 2, + MAX_DEGRADED_BACKOFF_MS, + ); + this.scheduleNextRenewal(retryMs); + } + }); + }, delayMs); + this.renewTimer.unref(); + } + + private startPolling(): void { + if (this.closed || this.pollTimer || this.options.refreshIntervalMs <= 0) + return; + this.pollTimer = setInterval(() => { + void this.refreshNow('poll'); + }, this.options.refreshIntervalMs); + this.pollTimer.unref(); + } + + private markDegraded(op: string, error: unknown): void { + this.degraded = true; + const now = Date.now(); + if (now - this.lastWarnAt >= WARN_THROTTLE_MS) { + this.lastWarnAt = now; + const status = + error instanceof OpenBaoHttpError ? error.statusCode : undefined; + const sealed = + error instanceof OpenBaoHttpError ? error.sealed : false; + appLogger.event( + 'WARN', + 'security.openbao_unavailable', + `OpenBao ${op} failed; continuing in bounded degraded mode with cached credentials`, + { + op, + status_code: status, + sealed, + error_name: + error instanceof Error ? error.name : 'UnknownError', + }, + ); + } + } + + private markRecovered(): void { + if (!this.degraded) return; + this.degraded = false; + this.degradedBackoffMs = INITIAL_DEGRADED_BACKOFF_MS; + appLogger.event( + 'INFO', + 'security.openbao_recovered', + 'OpenBao connectivity recovered', + ); + } +} diff --git a/app/src/redis/redis.client.ts b/app/src/redis/redis.client.ts index 220a6fb..9059358 100644 --- a/app/src/redis/redis.client.ts +++ b/app/src/redis/redis.client.ts @@ -1,65 +1,120 @@ import { + Inject, Injectable, Logger, OnModuleDestroy, OnModuleInit, + Optional, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; +import { URL } from 'node:url'; import { createClient, type RedisClientType } from 'redis'; import type { AppConfig } from '../config/app-config.schema.js'; import { MetricsService } from '../metrics/metrics.service.js'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from '../security/tls-material.js'; const UNLOCK_SCRIPT = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end'; type Client = RedisClientType; +function isRedisAuthError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + return ( + error.message.includes('WRONGPASS') || error.message.includes('NOAUTH') + ); +} + +function parseRedisUrl(urlString: string | undefined): { + host?: string; + port?: number; + username?: string; + password?: string; + tls?: boolean; +} { + if (!urlString) return {}; + try { + const parsed = new URL(urlString); + return { + host: parsed.hostname || undefined, + port: parsed.port ? Number(parsed.port) : undefined, + username: parsed.username + ? decodeURIComponent(parsed.username) + : undefined, + password: parsed.password + ? decodeURIComponent(parsed.password) + : undefined, + tls: parsed.protocol === 'rediss:', + }; + } catch { + return {}; + } +} + @Injectable() export class RedisClient implements OnModuleInit, OnModuleDestroy { - readonly client: Client; + private activeClient: Client; private readonly logger = new Logger(RedisClient.name); + private readonly onRotateRedis: () => void; + private readonly onTlsReload: () => void; + private rotating: Promise | undefined; + private initialized = false; + private destroyed = false; constructor( private readonly config: ConfigService, private readonly metrics: MetricsService, + @Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager, + @Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore, ) { - this.client = createClient({ - url: this.config.getOrThrow('REDIS_URL'), - disableOfflineQueue: true, - socket: { - reconnectStrategy: (attempt) => - Math.min(1000 + attempt * 250, 5000), - connectTimeout: 5000, - }, - }) as Client; - // Reconnect failures must be visible; the readiness probe pings Redis. - this.client.on('error', (error: Error) => { - this.metrics.increment('redis.error'); - this.logger.warn(`Redis error: ${error.message}`); - }); + this.activeClient = this.buildClient(); + this.onRotateRedis = () => { + void this.rotateClient('secret_rotated'); + }; + this.onTlsReload = () => { + void this.rotateClient('tls_reloaded'); + }; + this.secrets?.on('rotated:redis', this.onRotateRedis); + this.tls?.on('reloaded', this.onTlsReload); + } + + get client(): Client { + return this.activeClient; } async onModuleInit(): Promise { - await this.client.connect(); + this.initialized = true; + await this.activeClient.connect(); } async onModuleDestroy(): Promise { - if (this.client.isOpen) await this.client.quit(); + this.destroyed = true; + this.secrets?.off('rotated:redis', this.onRotateRedis); + this.tls?.off('reloaded', this.onTlsReload); + if (this.activeClient.isOpen) await this.activeClient.quit(); } async health(): Promise { this.metrics.increment('redis.ping'); - // AbortSignal.timeout ограничивает именно пробу: обычные GET/SET остаются - // без командного таймаута, а замороженный Redis проваливает готовность - // в бюджет, который короче timeout check балансировщика. const timeout = AbortSignal.timeout( this.config.getOrThrow('HEALTH_TIMEOUT_MS'), ); - await this.client.withAbortSignal(timeout).ping(); + try { + await this.activeClient.withAbortSignal(timeout).ping(); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async get(key: string): Promise { this.metrics.increment('redis.get'); - return this.client.get(key); + try { + return await this.activeClient.get(key); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async set( @@ -68,7 +123,12 @@ export class RedisClient implements OnModuleInit, OnModuleDestroy { options?: { EX?: number; PX?: number; NX?: boolean }, ): Promise { this.metrics.increment('redis.set'); - return this.client.set(key, value, options); + try { + return await this.activeClient.set(key, value, options); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async setNxEx( @@ -77,10 +137,17 @@ export class RedisClient implements OnModuleInit, OnModuleDestroy { seconds: number, ): Promise { this.metrics.increment('redis.set'); - return ( - (await this.client.set(key, value, { NX: true, EX: seconds })) === - 'OK' - ); + try { + return ( + (await this.activeClient.set(key, value, { + NX: true, + EX: seconds, + })) === 'OK' + ); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async setNxPx( @@ -89,27 +156,47 @@ export class RedisClient implements OnModuleInit, OnModuleDestroy { milliseconds: number, ): Promise { this.metrics.increment('redis.set'); - return ( - (await this.client.set(key, value, { - NX: true, - PX: milliseconds, - })) === 'OK' - ); + try { + return ( + (await this.activeClient.set(key, value, { + NX: true, + PX: milliseconds, + })) === 'OK' + ); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async del(key: string): Promise { this.metrics.increment('redis.del'); - return this.client.del(key); + try { + return await this.activeClient.del(key); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async incr(key: string): Promise { this.metrics.increment('redis.incr'); - return this.client.incr(key); + try { + return await this.activeClient.incr(key); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async expire(key: string, seconds: number): Promise { this.metrics.increment('redis.expire'); - return (await this.client.expire(key, seconds)) === 1; + try { + return (await this.activeClient.expire(key, seconds)) === 1; + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async scan( @@ -118,28 +205,166 @@ export class RedisClient implements OnModuleInit, OnModuleDestroy { count = 100, ): Promise<{ cursor: number; keys: string[] }> { this.metrics.increment('redis.scan'); - const result = await this.client.scan(String(cursor), { - MATCH: pattern, - COUNT: count, - }); - return { cursor: Number(result.cursor), keys: result.keys }; + try { + const result = await this.activeClient.scan(String(cursor), { + MATCH: pattern, + COUNT: count, + }); + return { cursor: Number(result.cursor), keys: result.keys }; + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } + } + + async eval( + script: string, + keys: string[], + args: string[], + ): Promise { + this.metrics.increment('redis.eval'); + try { + return await this.activeClient.eval(script, { + keys, + arguments: args, + }); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } async unlock(key: string, owner: string): Promise { this.metrics.increment('redis.unlock'); - return Number( - await this.client.eval(UNLOCK_SCRIPT, { - keys: [key], - arguments: [owner], - }), - ); + try { + return Number( + await this.activeClient.eval(UNLOCK_SCRIPT, { + keys: [key], + arguments: [owner], + }), + ); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } } - pipeline(commands: Array<[string, ...string[]]>): Promise { + async pipeline(commands: Array<[string, ...string[]]>): Promise { this.metrics.increment('redis.pipeline'); - const multi = this.client.multi(); - for (const [command, ...args] of commands) - multi.addCommand([command, ...args]); - return multi.exec(); + try { + const multi = this.activeClient.multi(); + for (const [command, ...args] of commands) + multi.addCommand([command, ...args]); + return await multi.exec(); + } catch (error) { + this.maybeRefreshOnAuthError(error); + throw error; + } + } + + private buildClient(): Client { + const getOpt = (key: K): AppConfig[K] | undefined => + typeof this.config.get === 'function' ? this.config.get(key) : undefined; + const parsed = parseRedisUrl(getOpt('REDIS_URL')); + const host = getOpt('REDIS_HOST') ?? parsed.host ?? 'redis'; + const port = getOpt('REDIS_PORT') ?? parsed.port ?? 6379; + const creds = this.secrets?.getRedisCredentials(); + const username = creds?.user ?? getOpt('REDIS_USER') ?? parsed.username; + const password = + creds?.password ?? getOpt('REDIS_PASSWORD') ?? parsed.password; + + const tlsEnabled = + (this.tls?.enabled ?? Boolean(getOpt('TLS_ENABLED'))) || + Boolean(parsed.tls); + const redisMtls = getOpt('REDIS_TLS_MTLS') ?? true; + const reconnectStrategy = (attempt: number) => + Math.min(1000 + attempt * 250, 5000); + + let client: Client; + if (tlsEnabled) { + if (!this.tls?.ca) { + throw new Error('Redis TLS requires CA certificate (TLS_CA_FILE)'); + } + if (redisMtls && (!this.tls.clientCert || !this.tls.clientKey)) { + throw new Error( + 'Redis mTLS requires client certificate and key (TLS_CLIENT_CERT_FILE/TLS_CLIENT_KEY_FILE)', + ); + } + client = createClient({ + ...(username ? { username } : {}), + ...(password ? { password } : {}), + disableOfflineQueue: true, + socket: { + host, + port, + tls: true, + ca: this.tls.ca, + servername: host, + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + ...(redisMtls && this.tls.clientCert && this.tls.clientKey + ? { cert: this.tls.clientCert, key: this.tls.clientKey } + : {}), + reconnectStrategy, + connectTimeout: 5000, + }, + }) as Client; + } else { + client = createClient({ + ...(username ? { username } : {}), + ...(password ? { password } : {}), + disableOfflineQueue: true, + socket: { + host, + port, + reconnectStrategy, + connectTimeout: 5000, + }, + }) as Client; + } + + client.on('error', (error: Error) => { + this.metrics.increment('redis.error'); + this.maybeRefreshOnAuthError(error); + this.logger.warn(`Redis error: ${error.message}`); + }); + return client; + } + + private async rotateClient(reason: string): Promise { + if (!this.initialized || this.destroyed) return; + if (this.rotating) { + await this.rotating; + return; + } + this.rotating = (async () => { + let next: Client | undefined; + try { + next = this.buildClient(); + await next.connect(); + const previous = this.activeClient; + this.activeClient = next; + this.logger.log(`Swapped Redis client (${reason})`); + if (previous.isOpen) { + void previous.quit().catch(() => previous.destroy()); + } + } catch (error) { + if (next?.isOpen) { + void next.quit().catch(() => next?.destroy()); + } + this.logger.warn( + `Redis client swap failed (${reason}): ${error instanceof Error ? error.name : 'unknown error'}`, + ); + } + })().finally(() => { + this.rotating = undefined; + }); + await this.rotating; + } + + private maybeRefreshOnAuthError(error: unknown): void { + if (isRedisAuthError(error)) { + void this.secrets?.refreshNow('redis_auth_error'); + } } } diff --git a/app/src/redis/redis.module.ts b/app/src/redis/redis.module.ts index 74464f5..5065e31 100644 --- a/app/src/redis/redis.module.ts +++ b/app/src/redis/redis.module.ts @@ -1,7 +1,8 @@ -import { Module } from '@nestjs/common'; +import { Global, Module } from '@nestjs/common'; import { MetricsModule } from '../metrics/metrics.module.js'; import { RedisClient } from './redis.client.js'; +@Global() @Module({ imports: [MetricsModule], providers: [RedisClient], diff --git a/app/src/security/security.module.ts b/app/src/security/security.module.ts new file mode 100644 index 0000000..f3c84f8 --- /dev/null +++ b/app/src/security/security.module.ts @@ -0,0 +1,41 @@ +import { Global, Module } from '@nestjs/common'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from './tls-material.js'; + +let bootstrappedTls: TlsMaterialManager | undefined; +let bootstrappedSecrets: RuntimeSecretsStore | undefined; + +export function registerBootstrappedSecurity( + tlsMaterial: TlsMaterialManager, + secretsStore: RuntimeSecretsStore, +): void { + bootstrappedTls = tlsMaterial; + bootstrappedSecrets = secretsStore; +} + +export function clearBootstrappedSecurity(): void { + bootstrappedTls = undefined; + bootstrappedSecrets = undefined; +} + +@Global() +@Module({ + providers: [ + { + provide: TlsMaterialManager, + useFactory: () => + bootstrappedTls ?? + TlsMaterialManager.initFromEnv('api', { + ...process.env, + TLS_ENABLED: process.env.TLS_ENABLED ?? 'false', + }), + }, + { + provide: RuntimeSecretsStore, + useFactory: () => + bootstrappedSecrets ?? RuntimeSecretsStore.fromEnvOnly('api'), + }, + ], + exports: [TlsMaterialManager, RuntimeSecretsStore], +}) +export class SecurityModule {} diff --git a/app/src/security/tls-material.spec.ts b/app/src/security/tls-material.spec.ts new file mode 100644 index 0000000..0c37ca0 --- /dev/null +++ b/app/src/security/tls-material.spec.ts @@ -0,0 +1,322 @@ +import { execFileSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import https from 'node:https'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type tls from 'node:tls'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + normalizeSerial, + parseCrlRevokedSerials, + TlsMaterialManager, +} from './tls-material.js'; + +function runOpenSsl(args: string[], cwd: string): void { + execFileSync('openssl', args, { cwd, stdio: 'pipe' }); +} + +function makeTempPki() { + const dir = mkdtempSync(join(tmpdir(), 'lab7-tls-test-')); + mkdirSync(join(dir, 'newcerts')); + writeFileSync(join(dir, 'index.txt'), ''); + writeFileSync(join(dir, 'serial'), '1000\n'); + writeFileSync(join(dir, 'crlnumber'), '01\n'); + + const caConf = ` +[ca] +default_ca = lab7_ca + +[lab7_ca] +dir = ${dir} +database = $dir/index.txt +new_certs_dir = $dir/newcerts +certificate = $dir/ca.crt +private_key = $dir/ca.key +serial = $dir/serial +crlnumber = $dir/crlnumber +default_days = 30 +default_crl_days = 7 +default_md = sha256 +policy = policy_loose +copy_extensions = copy +unique_subject = no + +[policy_loose] +commonName = supplied +`; + writeFileSync(join(dir, 'ca.cnf'), caConf); + + // Root CA + runOpenSsl( + [ + 'ecparam', + '-name', + 'prime256v1', + '-genkey', + '-noout', + '-out', + 'ca.key', + ], + dir, + ); + runOpenSsl( + [ + 'req', + '-x509', + '-new', + '-key', + 'ca.key', + '-sha256', + '-days', + '30', + '-subj', + '/CN=lab7-test-ca', + '-out', + 'ca.crt', + ], + dir, + ); + + const issue = ( + name: string, + cn: string, + san: string, + eku: 'serverAuth' | 'clientAuth', + ) => { + runOpenSsl( + [ + 'ecparam', + '-name', + 'prime256v1', + '-genkey', + '-noout', + '-out', + `${name}.key`, + ], + dir, + ); + const extFile = join(dir, `${name}.ext`); + writeFileSync( + extFile, + `basicConstraints=CA:FALSE\nextendedKeyUsage=${eku}\nsubjectAltName=${san}\n`, + ); + runOpenSsl( + [ + 'req', + '-new', + '-key', + `${name}.key`, + '-subj', + `/CN=${cn}`, + '-out', + `${name}.csr`, + ], + dir, + ); + runOpenSsl( + [ + 'ca', + '-batch', + '-config', + 'ca.cnf', + '-in', + `${name}.csr`, + '-out', + `${name}.crt`, + '-extfile', + extFile, + ], + dir, + ); + return { + cert: join(dir, `${name}.crt`), + key: join(dir, `${name}.key`), + x509: new crypto.X509Certificate(readFileSync(join(dir, `${name}.crt`))), + }; + }; + + const genCrl = () => { + runOpenSsl( + ['ca', '-config', 'ca.cnf', '-gencrl', '-out', 'ca.crl'], + dir, + ); + }; + + const revoke = (certPath: string) => { + runOpenSsl(['ca', '-config', 'ca.cnf', '-revoke', certPath], dir); + genCrl(); + }; + + genCrl(); + return { dir, caCert: join(dir, 'ca.crt'), crlFile: join(dir, 'ca.crl'), issue, revoke }; +} + +describe('TlsMaterialManager', () => { + let pki: ReturnType; + let server1: ReturnType['issue']>; + let server2: ReturnType['issue']>; + let lbClient: ReturnType['issue']>; + let workerClient: ReturnType['issue']>; + let lookalikeClient: ReturnType['issue']>; + + beforeAll(() => { + pki = makeTempPki(); + server1 = pki.issue('server1', 'localhost', 'DNS:localhost,DNS:api', 'serverAuth'); + server2 = pki.issue('server2', 'localhost', 'DNS:localhost,DNS:api', 'serverAuth'); + lbClient = pki.issue('lb', 'haproxy-lb-g1', 'DNS:haproxy-lb', 'clientAuth'); + workerClient = pki.issue( + 'worker', + 'messenger-worker-g1', + 'DNS:messenger-worker', + 'clientAuth', + ); + lookalikeClient = pki.issue( + 'evil', + 'evil-lb', + 'DNS:evil-haproxy-lb', + 'clientAuth', + ); + }); + + afterAll(() => { + rmSync(pki.dir, { recursive: true, force: true }); + }); + + it('enforces exact DNS SAN allowlist and rejects wrong or lookalike identities', () => { + const manager = new TlsMaterialManager({ + enabled: true, + requireServerCert: true, + requireClientCert: true, + caFile: pki.caCert, + crlFile: pki.crlFile, + serverCertFile: server1.cert, + serverKeyFile: server1.key, + clientCertFile: lbClient.cert, + clientKeyFile: lbClient.key, + allowedClientSans: ['haproxy-lb'], + reloadIntervalMs: 0, + }); + + expect(manager.verifyPeerCertificate(lbClient.x509)).toMatchObject({ + allowed: true, + cn: 'haproxy-lb-g1', + }); + expect(manager.verifyPeerCertificate(workerClient.x509)).toMatchObject({ + allowed: false, + reason: 'identity_denied', + }); + expect(manager.verifyPeerCertificate(lookalikeClient.x509)).toMatchObject({ + allowed: false, + reason: 'identity_denied', + }); + expect(manager.verifyPeerCertificate(undefined)).toMatchObject({ + allowed: false, + reason: 'missing_cert', + }); + }); + + it('hot-reloads rotated server cert, parses revoked serials from ca.crl, and rejects revoked certs on new & active connections', async () => { + const activeCert = join(pki.dir, 'active-server.crt'); + const activeKey = join(pki.dir, 'active-server.key'); + writeFileSync(activeCert, readFileSync(server1.cert)); + writeFileSync(activeKey, readFileSync(server1.key)); + + const manager = new TlsMaterialManager({ + enabled: true, + requireServerCert: true, + requireClientCert: true, + caFile: pki.caCert, + crlFile: pki.crlFile, + serverCertFile: activeCert, + serverKeyFile: activeKey, + clientCertFile: lbClient.cert, + clientKeyFile: lbClient.key, + allowedClientSans: ['haproxy-lb'], + reloadIntervalMs: 0, + }); + + const server = https.createServer(manager.serverOptions(), (_req, res) => { + res.writeHead(200); + res.end('ok'); + }); + manager.trackServer(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const port = (server.address() as { port: number }).port; + + const fetchServerSerial = ( + certFile: string, + keyFile: string, + ): Promise => + new Promise((resolve, reject) => { + const req = https.request( + { + host: '127.0.0.1', + port, + servername: 'localhost', + ca: readFileSync(pki.caCert), + cert: readFileSync(certFile), + key: readFileSync(keyFile), + agent: false, + }, + (res) => { + const peer = (res.socket as tls.TLSSocket).getPeerX509Certificate(); + res.resume(); + res.on('end', () => + resolve(normalizeSerial(peer?.serialNumber ?? '')), + ); + }, + ); + req.on('error', reject); + req.end(); + }); + + try { + // Initial server cert serial matches server1. + expect(await fetchServerSerial(lbClient.cert, lbClient.key)).toBe( + normalizeSerial(server1.x509.serialNumber), + ); + + // Corrupt reload must preserve previous good snapshot. + writeFileSync(activeCert, 'not-a-valid-pem'); + expect(manager.reload('sighup')).toBe(false); + expect(await fetchServerSerial(lbClient.cert, lbClient.key)).toBe( + normalizeSerial(server1.x509.serialNumber), + ); + + // Live rotate to server2 without restarting the server. + writeFileSync(activeCert, readFileSync(server2.cert)); + writeFileSync(activeKey, readFileSync(server2.key)); + expect(manager.reload('sighup')).toBe(true); + expect(await fetchServerSerial(lbClient.cert, lbClient.key)).toBe( + normalizeSerial(server2.x509.serialNumber), + ); + + // Revoke lbClient in CRL and reload -> both CRL parser and TLS handshake reject it. + pki.revoke(lbClient.cert); + const parsedSerials = parseCrlRevokedSerials(readFileSync(pki.crlFile)); + expect(parsedSerials.has(normalizeSerial(lbClient.x509.serialNumber))).toBe( + true, + ); + + expect(manager.reload('sighup')).toBe(true); + expect(manager.verifyPeerCertificate(lbClient.x509)).toMatchObject({ + allowed: false, + reason: 'revoked', + }); + + await expect( + fetchServerSerial(lbClient.cert, lbClient.key), + ).rejects.toThrow(); + } finally { + manager.onModuleDestroy(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); +}); diff --git a/app/src/security/tls-material.ts b/app/src/security/tls-material.ts new file mode 100644 index 0000000..324f740 --- /dev/null +++ b/app/src/security/tls-material.ts @@ -0,0 +1,623 @@ +import { OnModuleDestroy } from '@nestjs/common'; +import crypto from 'node:crypto'; +import { EventEmitter } from 'node:events'; +import { existsSync, readFileSync } from 'node:fs'; +import type https from 'node:https'; +import tls from 'node:tls'; +import { resolveTlsEnabled } from '../config/app-config.schema.js'; +import { appLogger } from '../telemetry/logger.js'; + +export type X509Info = { + readonly serial: string; + readonly cn?: string; + readonly dnsSans: readonly string[]; + readonly uriSans: readonly string[]; + readonly fingerprint256: string; + readonly validFrom: string; + readonly validTo: string; +}; + +export type PeerVerificationResult = + | { + readonly allowed: true; + readonly serial: string; + readonly cn?: string; + readonly sans: readonly string[]; + } + | { + readonly allowed: false; + readonly reason: 'missing_cert' | 'revoked' | 'identity_denied'; + readonly serial?: string; + readonly cn?: string; + readonly sans: readonly string[]; + }; + +export type TlsSnapshot = { + readonly enabled: boolean; + readonly ca?: Buffer; + readonly baoCa?: Buffer; + readonly crl?: Buffer; + readonly serverCert?: Buffer; + readonly serverKey?: Buffer; + readonly serverCertInfo?: X509Info; + readonly clientCert?: Buffer; + readonly clientKey?: Buffer; + readonly clientCertInfo?: X509Info; + readonly allowedClientSans: ReadonlySet; + readonly revokedSerials: ReadonlySet; + readonly contentHash: string; +}; + +export type TlsMaterialPaths = { + readonly enabled: boolean; + readonly requireServerCert: boolean; + readonly requireClientCert: boolean; + readonly caFile?: string; + readonly baoCaFile?: string; + readonly crlFile?: string; + readonly serverCertFile?: string; + readonly serverKeyFile?: string; + readonly clientCertFile?: string; + readonly clientKeyFile?: string; + readonly allowedClientSans: readonly string[]; + readonly revokedSerialsFile?: string; + readonly reloadIntervalMs: number; +}; + +export function normalizeSerial(serial: string): string { + const cleaned = serial.replace(/[^0-9a-fA-F]/gu, '').toUpperCase(); + if (cleaned.length === 0) return ''; + const stripped = cleaned.replace(/^0+/u, ''); + return stripped.length > 0 ? stripped : '0'; +} + +export function parseX509Sans(subjectAltName: string | undefined): { + dns: string[]; + uri: string[]; + all: string[]; +} { + const dns: string[] = []; + const uri: string[] = []; + if (!subjectAltName) return { dns, uri, all: [] }; + for (const rawEntry of subjectAltName.split(',')) { + const entry = rawEntry.trim(); + if (entry.startsWith('DNS:')) { + const value = entry.slice(4).trim().toLowerCase(); + if (value.length > 0) dns.push(value); + } else if (entry.startsWith('URI:')) { + const value = entry.slice(4).trim(); + if (value.length > 0) uri.push(value); + } + } + return { dns, uri, all: [...dns, ...uri] }; +} + +export function parseX509CommonName(subject: string | undefined): string | undefined { + if (!subject) return undefined; + for (const line of subject.split(/\r?\n/u)) { + const trimmed = line.trim(); + if (trimmed.startsWith('CN=')) { + const value = trimmed.slice(3).trim(); + if (value.length > 0) return value; + } + } + return undefined; +} + +export function normalizeAllowedSanEntry(raw: string): string { + const trimmed = raw.trim(); + if (/^DNS:/iu.test(trimmed)) return trimmed.slice(4).trim().toLowerCase(); + if (/^URI:/iu.test(trimmed)) return trimmed.slice(4).trim(); + return trimmed.toLowerCase(); +} + +type DerElement = { + readonly tag: number; + readonly contentStart: number; + readonly contentEnd: number; + readonly nextOffset: number; +}; + +function readDerElement(buf: Buffer, offset: number): DerElement | undefined { + if (offset + 2 > buf.length) return undefined; + const tag = buf[offset]; + const firstLen = buf[offset + 1]; + let length = 0; + let contentStart = offset + 2; + if ((firstLen & 0x80) === 0) { + length = firstLen; + } else { + const numBytes = firstLen & 0x7f; + if (numBytes === 0 || numBytes > 4 || offset + 2 + numBytes > buf.length) + return undefined; + for (let i = 0; i < numBytes; i += 1) { + length = (length << 8) | buf[offset + 2 + i]; + } + contentStart = offset + 2 + numBytes; + } + const contentEnd = contentStart + length; + if (contentEnd > buf.length) return undefined; + return { tag, contentStart, contentEnd, nextOffset: contentEnd }; +} + +/** + * Extracts revoked certificate serial numbers directly from PEM-encoded X.509 CRL(s). + * Keeps active-socket eviction in sync with `ca.crl` without needing a separate list file. + */ +export function parseCrlRevokedSerials(crlPem: Buffer): Set { + const serials = new Set(); + const text = crlPem.toString('ascii'); + const blocks = text.match( + /-----BEGIN X509 CRL-----[\s\S]*?-----END X509 CRL-----/gu, + ); + if (!blocks) return serials; + + for (const block of blocks) { + const b64 = block + .replace(/-----BEGIN X509 CRL-----/u, '') + .replace(/-----END X509 CRL-----/u, '') + .replace(/\s+/gu, ''); + const der = Buffer.from(b64, 'base64'); + // CertificateList ::= SEQUENCE { tbsCertList SEQUENCE, ... } + const root = readDerElement(der, 0); + if (!root || root.tag !== 0x30) continue; + const tbs = readDerElement(der, root.contentStart); + if (!tbs || tbs.tag !== 0x30) continue; + + // Inside TBSCertList: + // [optional version INTEGER(0x02)], signature SEQUENCE(0x30), issuer SEQUENCE(0x30), + // thisUpdate UTCTime(0x17)/GenTime(0x18), [optional nextUpdate 0x17/0x18], + // [optional revokedCertificates SEQUENCE(0x30)], [optional crlExtensions [0](0xA0)] + let cursor = tbs.contentStart; + let elem = readDerElement(der, cursor); + if (!elem) continue; + if (elem.tag === 0x02) { + cursor = elem.nextOffset; + elem = readDerElement(der, cursor); + } + // signature SEQUENCE + if (!elem || elem.tag !== 0x30) continue; + cursor = elem.nextOffset; + // issuer SEQUENCE + elem = readDerElement(der, cursor); + if (!elem || elem.tag !== 0x30) continue; + cursor = elem.nextOffset; + // thisUpdate + elem = readDerElement(der, cursor); + if (!elem || (elem.tag !== 0x17 && elem.tag !== 0x18)) continue; + cursor = elem.nextOffset; + // optional nextUpdate + if (cursor < tbs.contentEnd) { + elem = readDerElement(der, cursor); + if (elem && (elem.tag === 0x17 || elem.tag === 0x18)) { + cursor = elem.nextOffset; + } + } + // optional revokedCertificates SEQUENCE OF SEQUENCE { userCertificate INTEGER, ... } + if (cursor >= tbs.contentEnd) continue; + const revokedSeq = readDerElement(der, cursor); + if (!revokedSeq || revokedSeq.tag !== 0x30) continue; + + let entryCursor = revokedSeq.contentStart; + while (entryCursor < revokedSeq.contentEnd) { + const entry = readDerElement(der, entryCursor); + if (!entry || entry.tag !== 0x30) break; + const serialElem = readDerElement(der, entry.contentStart); + if (serialElem && serialElem.tag === 0x02) { + const hex = der + .subarray(serialElem.contentStart, serialElem.contentEnd) + .toString('hex'); + const normalized = normalizeSerial(hex); + if (normalized) serials.add(normalized); + } + entryCursor = entry.nextOffset; + } + } + return serials; +} + +function inspectCert(certPem: Buffer): X509Info { + const x509 = new crypto.X509Certificate(certPem); + const sans = parseX509Sans(x509.subjectAltName); + return { + serial: normalizeSerial(x509.serialNumber), + cn: parseX509CommonName(x509.subject), + dnsSans: sans.dns, + uriSans: sans.uri, + fingerprint256: x509.fingerprint256, + validFrom: x509.validFrom, + validTo: x509.validTo, + }; +} + +function readOptionalFile(path: string | undefined): Buffer | undefined { + if (!path || !existsSync(path)) return undefined; + const data = readFileSync(path); + return data.length > 0 ? data : undefined; +} + +export class TlsMaterialManager extends EventEmitter implements OnModuleDestroy { + private snapshot: TlsSnapshot; + private pollTimer: NodeJS.Timeout | undefined; + private readonly trackedServers = new Set(); + private readonly activeSockets = new Set(); + + constructor(private readonly paths: TlsMaterialPaths) { + super(); + this.snapshot = this.loadSnapshot(); + } + + static initFromEnv( + role: 'api' | 'worker' | 'migrator' | 'cli' = 'api', + raw: Record = process.env as Record, + ): TlsMaterialManager { + const enabled = resolveTlsEnabled(raw); + const first = (...vals: unknown[]): string | undefined => { + for (const v of vals) { + if (typeof v === 'string' && v.trim().length > 0) + return v.trim(); + } + return undefined; + }; + const allowedRaw = + first(raw.TLS_ALLOWED_CLIENT_SANS) ?? 'haproxy-lb'; + const allowedClientSans = allowedRaw + .split(',') + .map((s) => normalizeAllowedSanEntry(s)) + .filter((s) => s.length > 0); + const intervalRaw = Number(raw.TLS_RELOAD_INTERVAL_MS); + const reloadIntervalMs = + Number.isInteger(intervalRaw) && intervalRaw >= 0 + ? intervalRaw + : 5000; + + const caFile = first(raw.TLS_CA_FILE); + const manager = new TlsMaterialManager({ + enabled, + requireServerCert: enabled && role === 'api', + requireClientCert: enabled, + caFile, + baoCaFile: first(raw.BAO_CACERT, caFile), + crlFile: first(raw.TLS_CRL_FILE), + serverCertFile: first(raw.TLS_SERVER_CERT_FILE, raw.TLS_CERT_FILE), + serverKeyFile: first(raw.TLS_SERVER_KEY_FILE, raw.TLS_KEY_FILE), + clientCertFile: first(raw.TLS_CLIENT_CERT_FILE, raw.TLS_CERT_FILE), + clientKeyFile: first(raw.TLS_CLIENT_KEY_FILE, raw.TLS_KEY_FILE), + allowedClientSans, + revokedSerialsFile: first(raw.TLS_REVOKED_SERIALS_FILE), + reloadIntervalMs, + }); + if (enabled && (role === 'api' || role === 'worker')) { + manager.startPolling(); + } + return manager; + } + + get enabled(): boolean { + return this.snapshot.enabled; + } + + get current(): TlsSnapshot { + return this.snapshot; + } + + get ca(): Buffer | undefined { + return this.snapshot.ca; + } + + get baoCa(): Buffer | undefined { + return this.snapshot.baoCa ?? this.snapshot.ca; + } + + get crl(): Buffer | undefined { + return this.snapshot.crl; + } + + get serverCert(): Buffer | undefined { + return this.snapshot.serverCert; + } + + get serverKey(): Buffer | undefined { + return this.snapshot.serverKey; + } + + get clientCert(): Buffer | undefined { + return this.snapshot.clientCert; + } + + get clientKey(): Buffer | undefined { + return this.snapshot.clientKey; + } + + get allowedClientSans(): ReadonlySet { + return this.snapshot.allowedClientSans; + } + + get revokedSerials(): ReadonlySet { + return this.snapshot.revokedSerials; + } + + /** + * Builds Fastify/Node HTTPS server options with mandatory mTLS and + * session resumption disabled so revoked certs cannot reuse prior sessions. + */ + serverOptions(): tls.TlsOptions { + const snap = this.snapshot; + if (!snap.enabled || !snap.ca || !snap.serverCert || !snap.serverKey) { + throw new Error( + 'TLS server material is not loaded (TLS_CA_FILE, TLS_SERVER_CERT_FILE, TLS_SERVER_KEY_FILE)', + ); + } + return { + ca: snap.ca, + cert: snap.serverCert, + key: snap.serverKey, + ...(snap.crl ? { crl: snap.crl } : {}), + requestCert: true, + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + secureOptions: crypto.constants.SSL_OP_NO_TICKET, + sessionTimeout: 0, + }; + } + + /** + * Registers an HTTPS server so live reloads update its TLS SecureContext + * and evict any active keep-alive sockets whose peer certs were revoked. + */ + trackServer(server: https.Server): void { + if (this.trackedServers.has(server)) return; + this.trackedServers.add(server); + server.on('secureConnection', (socket: tls.TLSSocket) => { + this.activeSockets.add(socket); + socket.once('close', () => { + this.activeSockets.delete(socket); + }); + }); + } + + verifyPeerCertificate( + peer: crypto.X509Certificate | undefined, + ): PeerVerificationResult { + if (!peer) { + return { allowed: false, reason: 'missing_cert', sans: [] }; + } + const serial = normalizeSerial(peer.serialNumber); + const cn = parseX509CommonName(peer.subject); + const sans = parseX509Sans(peer.subjectAltName); + if (serial && this.snapshot.revokedSerials.has(serial)) { + return { + allowed: false, + reason: 'revoked', + serial, + cn, + sans: sans.all, + }; + } + const matched = sans.all.some((san) => + this.snapshot.allowedClientSans.has(san), + ); + if (!matched) { + return { + allowed: false, + reason: 'identity_denied', + serial, + cn, + sans: sans.all, + }; + } + return { allowed: true, serial, cn, sans: sans.all }; + } + + reload(reason: string): boolean { + if (!this.paths.enabled) return false; + let next: TlsSnapshot; + try { + next = this.loadSnapshot(); + } catch (error) { + appLogger.event( + 'WARN', + 'security.tls_reload_failed', + `TLS material reload failed (${reason}): ${error instanceof Error ? error.name : 'unknown error'}`, + { reason }, + ); + return false; + } + if (reason === 'poll' && next.contentHash === this.snapshot.contentHash) { + return false; + } + const changed = next.contentHash !== this.snapshot.contentHash; + this.snapshot = next; + + for (const server of this.trackedServers) { + if (next.ca && next.serverCert && next.serverKey) { + try { + server.setSecureContext({ + ca: next.ca, + cert: next.serverCert, + key: next.serverKey, + ...(next.crl ? { crl: next.crl } : {}), + minVersion: 'TLSv1.2', + secureOptions: crypto.constants.SSL_OP_NO_TICKET, + sessionTimeout: 0, + }); + } catch (error) { + appLogger.event( + 'WARN', + 'security.tls_context_swap_failed', + `Failed to update HTTPS SecureContext: ${error instanceof Error ? error.name : 'unknown error'}`, + { reason }, + ); + } + } + } + + // Evict any open keep-alive TLS sockets whose peer cert is now revoked or disallowed. + let evicted = 0; + for (const socket of this.activeSockets) { + if (socket.destroyed) { + this.activeSockets.delete(socket); + continue; + } + const peer = + typeof socket.getPeerX509Certificate === 'function' + ? socket.getPeerX509Certificate() + : undefined; + const verdict = this.verifyPeerCertificate(peer); + if (!verdict.allowed) { + evicted += 1; + socket.destroy(); + this.activeSockets.delete(socket); + } + } + + if (changed || reason !== 'poll') { + appLogger.event( + 'INFO', + 'security.tls_reloaded', + `TLS material reloaded (${reason})`, + { + reason, + changed, + evicted_sockets: evicted, + server_serial: next.serverCertInfo?.serial, + client_serial: next.clientCertInfo?.serial, + crl_revoked_count: next.revokedSerials.size, + }, + ); + this.emit('reloaded', next); + } + return changed; + } + + startPolling(): void { + if (!this.paths.enabled || this.paths.reloadIntervalMs <= 0) return; + if (this.pollTimer) return; + this.pollTimer = setInterval(() => { + this.reload('poll'); + }, this.paths.reloadIntervalMs); + this.pollTimer.unref(); + } + + stopPolling(): void { + if (this.pollTimer) { + clearInterval(this.pollTimer); + this.pollTimer = undefined; + } + } + + onModuleDestroy(): void { + this.stopPolling(); + this.trackedServers.clear(); + this.activeSockets.clear(); + } + + private loadSnapshot(): TlsSnapshot { + const allowedClientSans = new Set(this.paths.allowedClientSans); + if (!this.paths.enabled) { + return { + enabled: false, + allowedClientSans, + revokedSerials: new Set(), + contentHash: 'disabled', + }; + } + + if (!this.paths.caFile) { + throw new Error('TLS_CA_FILE is required when TLS_ENABLED=true'); + } + const ca = readFileSync(this.paths.caFile); + const baoCa = + this.paths.baoCaFile && this.paths.baoCaFile !== this.paths.caFile + ? readFileSync(this.paths.baoCaFile) + : ca; + const crl = readOptionalFile(this.paths.crlFile); + + let serverCert: Buffer | undefined; + let serverKey: Buffer | undefined; + let serverCertInfo: X509Info | undefined; + if (this.paths.serverCertFile && this.paths.serverKeyFile) { + serverCert = readFileSync(this.paths.serverCertFile); + serverKey = readFileSync(this.paths.serverKeyFile); + serverCertInfo = inspectCert(serverCert); + // Pre-validate key/cert/CA/CRL pair before accepting reload. + tls.createSecureContext({ + ca, + cert: serverCert, + key: serverKey, + ...(crl ? { crl } : {}), + minVersion: 'TLSv1.2', + }); + } else if (this.paths.requireServerCert) { + throw new Error( + 'TLS_SERVER_CERT_FILE and TLS_SERVER_KEY_FILE are required when TLS_ENABLED=true', + ); + } + + let clientCert: Buffer | undefined; + let clientKey: Buffer | undefined; + let clientCertInfo: X509Info | undefined; + if (this.paths.clientCertFile && this.paths.clientKeyFile) { + clientCert = readFileSync(this.paths.clientCertFile); + clientKey = readFileSync(this.paths.clientKeyFile); + clientCertInfo = inspectCert(clientCert); + tls.createSecureContext({ + ca, + cert: clientCert, + key: clientKey, + minVersion: 'TLSv1.2', + }); + } else if (this.paths.requireClientCert) { + throw new Error( + 'TLS_CLIENT_CERT_FILE and TLS_CLIENT_KEY_FILE are required when TLS_ENABLED=true', + ); + } + + const revokedSerials = new Set(); + if (crl) { + for (const serial of parseCrlRevokedSerials(crl)) { + revokedSerials.add(serial); + } + } + const revokedListRaw = readOptionalFile(this.paths.revokedSerialsFile); + if (revokedListRaw) { + for (const line of revokedListRaw.toString('utf8').split(/\r?\n/u)) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + const normalized = normalizeSerial(trimmed); + if (normalized) revokedSerials.add(normalized); + } + } + + const hash = crypto.createHash('sha256'); + for (const part of [ + ca, + baoCa, + crl, + serverCert, + serverKey, + clientCert, + clientKey, + revokedListRaw, + ]) { + hash.update(part ?? ''); + hash.update('\0'); + } + + return { + enabled: true, + ca, + baoCa, + crl, + serverCert, + serverKey, + serverCertInfo, + clientCert, + clientKey, + clientCertInfo, + allowedClientSans, + revokedSerials, + contentHash: hash.digest('hex'), + }; + } +} diff --git a/app/src/storage/object-storage.ts b/app/src/storage/object-storage.ts index b9275fe..ebd4e02 100644 --- a/app/src/storage/object-storage.ts +++ b/app/src/storage/object-storage.ts @@ -9,14 +9,20 @@ import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import { NodeHttpHandler } from '@smithy/node-http-handler'; import { SpanKind } from '@opentelemetry/api'; import { + Inject, Injectable, Logger, + OnModuleDestroy, + Optional, ServiceUnavailableException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import http from 'node:http'; +import https from 'node:https'; import { Readable } from 'node:stream'; import type { AppConfig } from '../config/app-config.schema.js'; +import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js'; +import { TlsMaterialManager } from '../security/tls-material.js'; import { withChildSpan } from '../telemetry/tracing.js'; export class ObjectStorageUnavailableError extends ServiceUnavailableException { @@ -44,71 +50,69 @@ function isMissingKey(error: unknown): boolean { ); } +function isS3AuthError(error: unknown): boolean { + const candidate = error as { + name?: string; + Code?: string; + $metadata?: { httpStatusCode?: number }; + }; + const code = candidate?.Code ?? candidate?.name ?? ''; + return ( + code === 'InvalidAccessKeyId' || + code === 'SignatureDoesNotMatch' || + code === 'AccessDenied' || + code === 'ExpiredToken' || + candidate?.$metadata?.httpStatusCode === 403 + ); +} + @Injectable() -export class ObjectStorage { +export class ObjectStorage implements OnModuleDestroy { private readonly logger = new Logger(ObjectStorage.name); private readonly bucket: string; - private readonly internal: S3Client; - private readonly presign: S3Client; + private readonly endpoint: string; + private readonly publicEndpoint: string | undefined; + private readonly region: string; + private readonly connectTimeoutMs: number; private readonly requestTimeoutMs: number; + private internal: S3Client; + private presign: S3Client | undefined; + private agent: http.Agent | https.Agent; + private readonly onTlsReload: () => void; - constructor(config: ConfigService) { + constructor( + private readonly config: ConfigService, + @Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager, + @Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore, + ) { this.bucket = config.getOrThrow('S3_BUCKET'); + this.endpoint = config.getOrThrow('S3_ENDPOINT'); + this.publicEndpoint = + typeof config.get === 'function' + ? config.get('S3_PUBLIC_ENDPOINT') + : undefined; + this.region = config.getOrThrow('S3_REGION'); + this.connectTimeoutMs = config.getOrThrow('S3_CONNECT_TIMEOUT_MS'); this.requestTimeoutMs = config.getOrThrow('S3_REQUEST_TIMEOUT_MS'); - const common = { - region: config.getOrThrow('S3_REGION'), - forcePathStyle: true, - credentials: { - accessKeyId: config.getOrThrow('S3_ACCESS_KEY_ID'), - secretAccessKey: config.getOrThrow('S3_SECRET_ACCESS_KEY'), - }, - // Поток нельзя повторить: повтор — решение клиента API. - maxAttempts: 1, - requestChecksumCalculation: 'WHEN_REQUIRED' as const, - responseChecksumValidation: 'WHEN_REQUIRED' as const, - // requestTimeout bounds a request until its response arrives and, - // with throwOnRequestTimeout, actually fails it (otherwise smithy - // only logs a warning); socketTimeout bounds a stalled body read. - // A hung S3 therefore costs at most S3_REQUEST_TIMEOUT_MS per call. - requestHandler: new NodeHttpHandler({ - connectionTimeout: config.getOrThrow('S3_CONNECT_TIMEOUT_MS'), - requestTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'), - throwOnRequestTimeout: true, - socketTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'), - httpAgent: new http.Agent({ keepAlive: true, maxSockets: 64 }), - }), - }; - this.internal = new S3Client({ - ...common, - endpoint: config.getOrThrow('S3_ENDPOINT'), - }); - // One CLIENT span per S3 call (S3.PutObject, S3.GetObject, …), only - // inside a traced request or job. Object keys contain attachment ids - // and are deliberately not recorded. - this.internal.middlewareStack.add( - (next, handlerContext) => async (args) => { - const operation = String( - handlerContext.commandName ?? 'Unknown', - ).replace(/Command$/u, ''); - return withChildSpan( - `S3.${operation}`, - SpanKind.CLIENT, - { - 'rpc.system': 'aws-api', - 'rpc.service': 'S3', - 'rpc.method': operation, - 'aws.s3.bucket': this.bucket, - }, - () => next(args), - ); - }, - { step: 'initialize', name: 'messengerTelemetry' }, - ); - // Сеть не использует: только подпись URL для клиента. - this.presign = new S3Client({ - ...common, - endpoint: config.getOrThrow('S3_PUBLIC_ENDPOINT'), - }); + + if (this.tls?.enabled && !this.endpoint.startsWith('https://')) { + throw new Error('S3_ENDPOINT must use https:// when TLS_ENABLED=true'); + } + + const built = this.createClients(); + this.internal = built.internal; + this.presign = built.presign; + this.agent = built.agent; + + this.onTlsReload = () => this.rebuildClients(); + this.tls?.on('reloaded', this.onTlsReload); + } + + onModuleDestroy(): void { + this.tls?.off('reloaded', this.onTlsReload); + this.internal.destroy(); + this.presign?.destroy(); + this.agent.destroy(); } objectKey(attachmentId: string): string { @@ -126,8 +130,6 @@ export class ObjectStorage { extension: 'jpg' | 'webp', attempt = 1, ): string { - // The attempt suffix makes a stale worker's write harmless: the DB - // points at the key of the attempt that won the lease fence. return `attachments/${attachmentId}/v${pipelineVersion}/${variant}-a${attempt}.${extension}`; } @@ -147,9 +149,6 @@ export class ObjectStorage { ContentLength: contentLength, ContentType: contentType, }), - // The upload deadline (UPLOAD_TIMEOUT_MS, via `signal`) bounds the - // PUT: it lasts as long as the client sends, not S3_REQUEST_TIMEOUT_MS. - // A worker buffer has no client deadline, so it uses the SDK timeout. signal ? { abortSignal: signal, requestTimeout: 0 } : { requestTimeout: this.requestTimeoutMs }, @@ -228,6 +227,11 @@ export class ObjectStorage { } async presignPut(key: string, options: PresignPutOptions): Promise { + if (!this.presign) { + throw new Error( + 'S3_PUBLIC_ENDPOINT is not configured for presigned uploads', + ); + } return getSignedUrl( this.presign, new PutObjectCommand({ @@ -249,7 +253,105 @@ export class ObjectStorage { ); } + private createClients(): { + internal: S3Client; + presign: S3Client | undefined; + agent: http.Agent | https.Agent; + } { + const useHttps = this.endpoint.startsWith('https://'); + const agent = useHttps + ? new https.Agent({ + keepAlive: true, + maxSockets: 64, + ...(this.tls?.ca ? { ca: this.tls.ca } : {}), + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + }) + : new http.Agent({ keepAlive: true, maxSockets: 64 }); + + const credentials = this.secrets + ? async () => this.secrets!.getS3Credentials() + : { + accessKeyId: this.config.getOrThrow('S3_ACCESS_KEY_ID')!, + secretAccessKey: this.config.getOrThrow('S3_SECRET_ACCESS_KEY')!, + }; + + const common = { + region: this.region, + forcePathStyle: true, + credentials, + maxAttempts: 1, + requestChecksumCalculation: 'WHEN_REQUIRED' as const, + responseChecksumValidation: 'WHEN_REQUIRED' as const, + requestHandler: new NodeHttpHandler({ + connectionTimeout: this.connectTimeoutMs, + requestTimeout: this.requestTimeoutMs, + throwOnRequestTimeout: true, + socketTimeout: this.requestTimeoutMs, + ...(useHttps + ? { httpsAgent: agent as https.Agent } + : { httpAgent: agent as http.Agent }), + }), + }; + + const internal = new S3Client({ + ...common, + endpoint: this.endpoint, + }); + internal.middlewareStack.add( + (next, handlerContext) => async (args) => { + const operation = String( + handlerContext.commandName ?? 'Unknown', + ).replace(/Command$/u, ''); + return withChildSpan( + `S3.${operation}`, + SpanKind.CLIENT, + { + 'rpc.system': 'aws-api', + 'rpc.service': 'S3', + 'rpc.method': operation, + 'aws.s3.bucket': this.bucket, + }, + () => next(args), + ); + }, + { step: 'initialize', name: 'messengerTelemetry' }, + ); + + const presign = this.publicEndpoint + ? new S3Client({ + ...common, + endpoint: this.publicEndpoint, + }) + : undefined; + + return { internal, presign, agent }; + } + + private rebuildClients(): void { + try { + const next = this.createClients(); + const oldInternal = this.internal; + const oldPresign = this.presign; + const oldAgent = this.agent; + this.internal = next.internal; + this.presign = next.presign; + this.agent = next.agent; + oldInternal.destroy(); + oldPresign?.destroy(); + oldAgent.destroy(); + this.logger.log('Rebuilt S3 clients with updated TLS material'); + } catch (error) { + this.logger.warn( + `S3 client rebuild failed: ${error instanceof Error ? error.name : 'unknown error'}`, + ); + } + } + private fail(operation: string, error: unknown): Error { + if (isS3AuthError(error)) { + void this.secrets?.refreshNow('s3_auth_error'); + } const name = (error as { name?: string })?.name ?? 'UnknownError'; this.logger.warn(`S3 ${operation} failed: ${name}`); return new ObjectStorageUnavailableError(); diff --git a/app/src/telemetry/http.ts b/app/src/telemetry/http.ts index d869c4f..5062908 100644 --- a/app/src/telemetry/http.ts +++ b/app/src/telemetry/http.ts @@ -115,7 +115,8 @@ export function installHttpTelemetry(fastify: FastifyInstance): void { attributes: { 'http.request.method': method, 'http.route': route, - 'url.scheme': 'http', + 'url.scheme': + request.protocol === 'https' ? 'https' : 'http', 'network.protocol.version': request.raw.httpVersion, }, }, diff --git a/app/src/telemetry/identity.ts b/app/src/telemetry/identity.ts index 3ec0de5..157c682 100644 --- a/app/src/telemetry/identity.ts +++ b/app/src/telemetry/identity.ts @@ -1,4 +1,4 @@ -import os from 'node:os'; +import { getProcessInstanceId } from '../config/instance-id.js'; export type ServiceIdentity = { readonly serviceName: string; @@ -7,16 +7,12 @@ export type ServiceIdentity = { }; function fromEnv(defaultServiceName: string): ServiceIdentity { + const serviceName = process.env.OTEL_SERVICE_NAME?.trim() || defaultServiceName; + const prefix = serviceName.toLowerCase().includes('worker') ? 'wrk' : 'rep'; return { - serviceName: process.env.OTEL_SERVICE_NAME?.trim() || defaultServiceName, + serviceName, serviceVersion: process.env.SERVICE_VERSION?.trim() || 'dev', - // В compose у реплик API нет INSTANCE_ID, но HOSTNAME — id контейнера, - // уникальный для каждой реплики: так service.instance.id различает - // api-1 и api-2 во всех трёх сигналах. - instanceId: - process.env.INSTANCE_ID?.trim() || - process.env.HOSTNAME?.trim() || - os.hostname(), + instanceId: getProcessInstanceId(prefix), }; } diff --git a/app/src/telemetry/redact.spec.ts b/app/src/telemetry/redact.spec.ts index 0ee534d..62a5308 100644 --- a/app/src/telemetry/redact.spec.ts +++ b/app/src/telemetry/redact.spec.ts @@ -14,6 +14,12 @@ describe('redact', () => { expect( redact('postgresql://messenger:s3cret@postgres:5432/messenger'), ).toBe('postgresql://[REDACTED]@postgres:5432/messenger'); + expect( + redact('rediss://messenger_api:r3d1sPass@redis:6379'), + ).toBe('rediss://[REDACTED]@redis:6379'); + expect( + redact('amqps://messenger_api:br0kerPass@broker:5671/messenger'), + ).toBe('amqps://[REDACTED]@broker:5671/messenger'); }); it('masks presigned URL credentials and signatures', () => { @@ -24,9 +30,36 @@ describe('redact', () => { expect(out).not.toContain('deadbeef'); }); - it('masks password-like fields', () => { + it('masks OpenBao tokens, vault headers, PHC hashes, and secret fields', () => { + const baoOut = redact( + 'header X-Vault-Token: hvs.CAESIFakeTokenValue1234567890 and s.LegacyBaoToken1234567890', + ); + expect(baoOut).not.toContain('CAESIFakeTokenValue1234567890'); + expect(baoOut).not.toContain('LegacyBaoToken1234567890'); + + const hashOut = redact( + 'stored=$argon2id$v=19$m=32768,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNo legacy=$scrypt$ln=14,r=8,p=1$c2FsdA==$aGFzaA==', + ); + expect(hashOut).not.toContain('c2FsdHNhbHRzYWx0'); + expect(hashOut).not.toContain('aGFzaGhhc2hoYXNo'); + expect(hashOut).not.toContain('c2FsdA=='); + + const kvOut = redact( + '{"secret_id":"sec-999","role_id":"role-111","metrics_token":"mtr-777","password_hash":"ph-555","secret_access_key":"s3-sec-888"}', + ); + expect(kvOut).not.toContain('sec-999'); + expect(kvOut).not.toContain('role-111'); + expect(kvOut).not.toContain('mtr-777'); + expect(kvOut).not.toContain('ph-555'); + expect(kvOut).not.toContain('s3-sec-888'); + }); + + it('masks password-like fields and private keys', () => { expect(redact('{"password":"hunter2"}')).not.toContain('hunter2'); expect(redact('password=hunter2&x=1')).not.toContain('hunter2'); + const pem = + '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIA==\n-----END EC PRIVATE KEY-----'; + expect(redact(pem)).toBe('[REDACTED PRIVATE KEY]'); }); it('keeps ordinary diagnostic text intact', () => { diff --git a/app/src/telemetry/redact.ts b/app/src/telemetry/redact.ts index 3e64812..9361920 100644 --- a/app/src/telemetry/redact.ts +++ b/app/src/telemetry/redact.ts @@ -12,7 +12,13 @@ const RULES: ReadonlyArray = [ '$1=[REDACTED]', ], [ - /((?:password|passwd|secret|token|authorization|cookie)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;&}]+)/giu, + /\b(X-(?:Vault|Bao)-Token)\s*[:=]\s*[^\s,"';}]+/giu, + '$1: [REDACTED]', + ], + [/\b(?:hvs|hvb|hvr|s)\.[A-Za-z0-9_-]{16,}\b/gu, '[REDACTED_BAO_TOKEN]'], + [/\$(?:argon2(?:id|i|d)|scrypt)\$[^\s"'`]+/gu, '[REDACTED_HASH]'], + [ + /((?:password|passwd|password_hash|secret|secret_id|role_id|wrapping_token|unseal_key|client_token|access_key|access_key_id|secret_key|secret_access_key|metrics_token|private_key|passphrase|session_token|token|authorization|cookie)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;&}]+)/giu, '$1[REDACTED]', ], [ diff --git a/app/src/telemetry/sdk.ts b/app/src/telemetry/sdk.ts index 58c948a..99f07c7 100644 --- a/app/src/telemetry/sdk.ts +++ b/app/src/telemetry/sdk.ts @@ -23,6 +23,9 @@ import { TraceIdRatioBasedSampler, } from '@opentelemetry/sdk-trace-base'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; +import { existsSync, readFileSync } from 'node:fs'; +import type https from 'node:https'; +import type { TlsMaterialManager } from '../security/tls-material.js'; import { countingExporter } from './export-counter.js'; import { resolveServiceIdentity } from './identity.js'; import { redact } from './redact.js'; @@ -32,6 +35,7 @@ type Providers = { readonly tracer: NodeTracerProvider; readonly meter: MeterProvider; readonly logger: LoggerProvider; + readonly exporters: readonly unknown[]; }; let providers: Providers | undefined; @@ -57,6 +61,97 @@ function ratioFromEnv(name: string, fallback: number): number { return Number.isFinite(value) && value >= 0 && value <= 1 ? value : fallback; } +function firstExistingFile(...paths: Array): Buffer | undefined { + for (const candidate of paths) { + const trimmed = candidate?.trim(); + if (trimmed && existsSync(trimmed)) { + try { + const data = readFileSync(trimmed); + if (data.length > 0) return data; + } catch { + // Continue to next fallback path; OTel degrades gracefully. + } + } + } + return undefined; +} + +function buildOtlpAgentOptionsFromEnv(): https.AgentOptions | undefined { + const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim() ?? ''; + const ca = firstExistingFile( + process.env.OTEL_EXPORTER_OTLP_CERTIFICATE, + process.env.TLS_CA_FILE, + ); + const cert = firstExistingFile( + process.env.OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE, + process.env.TLS_CLIENT_CERT_FILE, + process.env.TLS_CERT_FILE, + ); + const key = firstExistingFile( + process.env.OTEL_EXPORTER_OTLP_CLIENT_KEY, + process.env.TLS_CLIENT_KEY_FILE, + process.env.TLS_KEY_FILE, + ); + if (!endpoint.startsWith('https://') && !ca && !cert) return undefined; + return { + keepAlive: true, + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + maxCachedSessions: 0, + ...(ca ? { ca } : {}), + ...(cert && key ? { cert, key } : {}), + }; +} + +function swapExporterTlsOptions( + exporter: unknown, + agentOptions: https.AgentOptions, +): void { + try { + const delegate = (exporter as { _delegate?: unknown })?._delegate ?? exporter; + const transport = ( + delegate as { + _transport?: { + _parameters?: { agentOptions?: https.AgentOptions }; + _utils?: { agent?: { destroy?: () => void } } | null; + }; + } + )?._transport; + if (!transport || !transport._parameters) return; + transport._parameters.agentOptions = agentOptions; + transport._utils?.agent?.destroy?.(); + transport._utils = null; + } catch { + // Best-effort live swap; telemetry must never throw into app lifecycle. + } +} + +/** + * Connects TlsMaterialManager reload events to the OTLP exporters so leaf cert + * and CA rotations on SIGHUP/poll also update outbound OTLP mTLS connections. + */ +export function attachTelemetryTls(tlsMaterial: TlsMaterialManager): void { + if (!tlsMaterial.enabled) return; + const apply = (): void => { + if (!providers || !tlsMaterial.ca) return; + const nextOptions: https.AgentOptions = { + keepAlive: true, + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + maxCachedSessions: 0, + ca: tlsMaterial.ca, + ...(tlsMaterial.clientCert && tlsMaterial.clientKey + ? { cert: tlsMaterial.clientCert, key: tlsMaterial.clientKey } + : {}), + }; + for (const exporter of providers.exporters) { + swapExporterTlsOptions(exporter, nextOptions); + } + }; + apply(); + tlsMaterial.on('reloaded', apply); +} + /** OTEL_RESOURCE_ATTRIBUTES: `k=v,k2=v2`, значения percent-encoded. */ export function parseResourceAttributes( raw: string | undefined, @@ -82,16 +177,6 @@ export function telemetryEnabled(): boolean { return (process.env.OTEL_SDK_DISABLED ?? '').trim().toLowerCase() !== 'true'; } -/** - * Явная настройка SDK без auto-instrumentation: приложение — ESM (авто- - * инструментации понадобился бы loader hook), а явные span дают полный - * контроль над атрибутами: SQL-текст, URL и тела не попадают в телеметрию. - * - * Экспорт асинхронный и ограниченный: очереди BatchProcessor фиксированного - * размера, таймаут экспорта 5 с. Недоступный Collector оборачивается потерей - * телеметрии (счётчик messenger.telemetry.export.items{outcome="failed"}), а не - * ростом latency или памяти API. - */ export function startTelemetry(defaultServiceName: string): void { if (providers) return; const identity = resolveServiceIdentity(defaultServiceName); @@ -114,6 +199,20 @@ export function startTelemetry(defaultServiceName: string): void { 100, 60_000, ); + const httpAgentOptions = buildOtlpAgentOptionsFromEnv(); + + const traceExporter = new OTLPTraceExporter({ + timeoutMillis: exportTimeout, + ...(httpAgentOptions ? { httpAgentOptions: { ...httpAgentOptions } } : {}), + }); + const metricExporter = new OTLPMetricExporter({ + timeoutMillis: exportTimeout, + ...(httpAgentOptions ? { httpAgentOptions: { ...httpAgentOptions } } : {}), + }); + const logExporter = new OTLPLogExporter({ + timeoutMillis: exportTimeout, + ...(httpAgentOptions ? { httpAgentOptions: { ...httpAgentOptions } } : {}), + }); const tracer = new NodeTracerProvider({ resource, @@ -124,10 +223,7 @@ export function startTelemetry(defaultServiceName: string): void { }), spanProcessors: [ new BatchSpanProcessor( - countingExporter( - 'traces', - new OTLPTraceExporter({ timeoutMillis: exportTimeout }), - ), + countingExporter('traces', traceExporter), { maxQueueSize: intFromEnv('OTEL_BSP_MAX_QUEUE_SIZE', 2048, 1, 100_000), maxExportBatchSize: intFromEnv( @@ -147,8 +243,6 @@ export function startTelemetry(defaultServiceName: string): void { ), ], }); - // Регистрирует глобальный TracerProvider, AsyncLocalStorage context manager и - // W3C TraceContext + Baggage propagator. tracer.register(); const interval = intFromEnv( @@ -161,7 +255,7 @@ export function startTelemetry(defaultServiceName: string): void { resource, readers: [ new PeriodicExportingMetricReader({ - exporter: new OTLPMetricExporter({ timeoutMillis: exportTimeout }), + exporter: metricExporter, exportIntervalMillis: interval, exportTimeoutMillis: Math.min(exportTimeout, interval), }), @@ -173,10 +267,7 @@ export function startTelemetry(defaultServiceName: string): void { resource, processors: [ new BatchLogRecordProcessor( - countingExporter( - 'logs', - new OTLPLogExporter({ timeoutMillis: exportTimeout }), - ), + countingExporter('logs', logExporter), { maxQueueSize: intFromEnv( 'OTEL_BLRP_MAX_QUEUE_SIZE', @@ -203,14 +294,15 @@ export function startTelemetry(defaultServiceName: string): void { }); logs.setGlobalLoggerProvider(logger); - providers = { tracer, meter, logger }; + providers = { + tracer, + meter, + logger, + exporters: [traceExporter, metricExporter, logExporter], + }; startRuntimeMetrics(); } -/** - * Сбрасывает буферы при остановке. Ограничено по времени: недоступный - * Collector не должен задерживать graceful shutdown сервиса. - */ export async function shutdownTelemetry(timeoutMs = 3000): Promise { const current = providers; if (!current) return; @@ -229,10 +321,6 @@ export async function shutdownTelemetry(timeoutMs = 3000): Promise { if (timer) clearTimeout(timer); } -/** - * Ошибки экспорта при недоступном Collector повторяются каждую секунду по - * каждому сигналу; одинаковые сообщения печатаем не чаще раза в 30 с. - */ class ThrottledDiagLogger implements DiagLogger { private readonly lastWritten = new Map(); diff --git a/app/src/users/users.controller.ts b/app/src/users/users.controller.ts index 1ab8c77..c23be1c 100644 --- a/app/src/users/users.controller.ts +++ b/app/src/users/users.controller.ts @@ -1,4 +1,16 @@ -import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common'; +import { + Body, + Controller, + Get, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import type { FastifyRequest } from 'fastify'; +import { + extractClientIp, + LoginRateLimiterService, +} from '../auth/login-rate-limiter.service.js'; import { CurrentUser } from '../common/auth/current-user.decorator.js'; import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; import type { User } from './user.js'; @@ -7,10 +19,15 @@ import { UsersService } from './users.service.js'; @Controller('api/v1/users') export class UsersController { - constructor(private readonly usersService: UsersService) {} + constructor( + private readonly usersService: UsersService, + private readonly rateLimiter: LoginRateLimiterService, + ) {} @Post() - create(@Body() body: CreateUserDTO) { + async create(@Body() body: CreateUserDTO, @Req() request: FastifyRequest) { + const clientIp = extractClientIp(request.headers, request.ip); + await this.rateLimiter.consumeRegister(clientIp); return this.usersService.create(body); } diff --git a/app/src/users/users.module.ts b/app/src/users/users.module.ts index 55a7328..035cdb1 100644 --- a/app/src/users/users.module.ts +++ b/app/src/users/users.module.ts @@ -1,16 +1,34 @@ import { Module } from '@nestjs/common'; +import { LoginRateLimiterService } from '../auth/login-rate-limiter.service.js'; +import { PasswordHasherService } from '../auth/password-hasher.service.js'; +import { SessionRepository } from '../auth/session.repository.js'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import { DatabaseModule } from '../database/database.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { RedisModule } from '../redis/redis.module.js'; import { UsersController } from './users.controller.js'; import { UsersRepository } from './users.repository.js'; import { UsersService } from './users.service.js'; -import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; -import { RedisModule } from '../redis/redis.module.js'; -import { MetricsModule } from '../metrics/metrics.module.js'; -import { DatabaseModule } from '../database/database.module.js'; @Module({ imports: [DatabaseModule, RedisModule, MetricsModule], controllers: [UsersController], - providers: [UsersRepository, UsersService, CurrentUserGuard], - exports: [UsersService, CurrentUserGuard, RedisModule, MetricsModule], + providers: [ + UsersRepository, + UsersService, + PasswordHasherService, + LoginRateLimiterService, + SessionRepository, + CurrentUserGuard, + ], + exports: [ + UsersService, + PasswordHasherService, + LoginRateLimiterService, + SessionRepository, + CurrentUserGuard, + RedisModule, + MetricsModule, + ], }) export class UsersModule {} diff --git a/app/src/users/users.repository.ts b/app/src/users/users.repository.ts index 4fbbe86..fd42e04 100644 --- a/app/src/users/users.repository.ts +++ b/app/src/users/users.repository.ts @@ -2,15 +2,18 @@ import { ConflictException, Injectable } from '@nestjs/common'; import { DatabaseClient } from '../database/database.client.js'; import type { User } from './user.js'; -type UserRow = { +type PublicUserRow = { id: string; username: string; display_name: string; - password_hash: string; created_at: Date | string; }; -function toUser(row: UserRow): User { +type UserWithHashRow = PublicUserRow & { + password_hash: string; +}; + +function toUser(row: PublicUserRow): User { return { id: row.id, username: row.username, @@ -24,9 +27,9 @@ export class UsersRepository { constructor(private readonly database: DatabaseClient) {} async findById(id: string): Promise { - const result = await this.database.query( + const result = await this.database.query( 'users.findById', - 'SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1', + 'SELECT id, username, display_name, created_at FROM users WHERE id = $1', [id], ); const row = result.rows[0]; @@ -36,7 +39,7 @@ export class UsersRepository { async findByUsername( username: string, ): Promise<(User & { password_hash: string }) | undefined> { - const result = await this.database.query( + const result = await this.database.query( 'users.findByUsername', 'SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1', [username], @@ -54,11 +57,11 @@ export class UsersRepository { password_hash: string; }): Promise { try { - const result = await this.database.query( + const result = await this.database.query( 'users.insert', `INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, $2, $3, $4) - RETURNING id, username, display_name, password_hash, created_at`, + RETURNING id, username, display_name, created_at`, [user.id, user.username, user.display_name, user.password_hash], ); return toUser(result.rows[0]); @@ -68,4 +71,12 @@ export class UsersRepository { throw error; } } + + async updatePasswordHash(id: string, passwordHash: string): Promise { + await this.database.query( + 'users.updatePasswordHash', + 'UPDATE users SET password_hash = $2 WHERE id = $1', + [id, passwordHash], + ); + } } diff --git a/app/src/users/users.service.ts b/app/src/users/users.service.ts index e4ac35d..59a1388 100644 --- a/app/src/users/users.service.ts +++ b/app/src/users/users.service.ts @@ -1,18 +1,19 @@ import { Injectable } from '@nestjs/common'; -import argon2 from 'argon2'; import { randomUUID } from 'node:crypto'; +import { PasswordHasherService } from '../auth/password-hasher.service.js'; import { CreateUserDTO } from './dto/create-user.dto.js'; import { User } from './user.js'; import { UsersRepository } from './users.repository.js'; @Injectable() export class UsersService { - constructor(private readonly usersRepository: UsersRepository) {} + constructor( + private readonly usersRepository: UsersRepository, + private readonly hasher: PasswordHasherService, + ) {} async create(input: CreateUserDTO): Promise { - const passwordHash = await argon2.hash(input.password, { - type: argon2.argon2id, - }); + const passwordHash = await this.hasher.hash(input.password); return this.usersRepository.create({ id: randomUUID(), username: input.username, @@ -28,4 +29,8 @@ export class UsersService { findByUsername(username: string) { return this.usersRepository.findByUsername(username); } + + updatePasswordHash(id: string, passwordHash: string): Promise { + return this.usersRepository.updatePasswordHash(id, passwordHash); + } } diff --git a/app/src/worker.main.ts b/app/src/worker.main.ts index 085c13a..dce5b54 100644 --- a/app/src/worker.main.ts +++ b/app/src/worker.main.ts @@ -5,24 +5,35 @@ import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import http from 'node:http'; import type { AppConfig } from './config/app-config.schema.js'; +import { resolveInstanceId } from './config/instance-id.js'; import { BrokerClient } from './jobs/broker.client.js'; +import { RuntimeSecretsStore } from './openbao/runtime-secrets.service.js'; +import { registerBootstrappedSecurity } from './security/security.module.js'; +import { TlsMaterialManager } from './security/tls-material.js'; +import { appLogger } from './telemetry/logger.js'; +import { attachTelemetryTls, shutdownTelemetry } from './telemetry/sdk.js'; import { JobProcessor } from './worker/job-processor.service.js'; import { WorkerModule } from './worker/worker.module.js'; -import { appLogger } from './telemetry/logger.js'; -import { shutdownTelemetry } from './telemetry/sdk.js'; const DRAIN_MS = 30_000; async function bootstrap(): Promise { + const tlsMaterial = TlsMaterialManager.initFromEnv('worker'); + attachTelemetryTls(tlsMaterial); + const secretsStore = await RuntimeSecretsStore.bootstrap( + 'worker', + tlsMaterial, + ); + registerBootstrappedSecurity(tlsMaterial, secretsStore); + const app = await NestFactory.createApplicationContext(WorkerModule, { - // Verbosity comes from LOG_LEVEL (default INFO, the former - // error/warn/log set). logger: appLogger, }); const config = app.get(ConfigService); const broker = app.get(BrokerClient); const processor = app.get(JobProcessor); const logger = new Logger('worker'); + const workerId = resolveInstanceId(config, 'wrk'); const server = http.createServer((request, response) => { if (request.method === 'GET' && request.url === '/health') { @@ -47,9 +58,13 @@ async function bootstrap(): Promise { resolve, ), ); - logger.log( - `worker ready: id=${process.env.INSTANCE_ID ?? process.env.HOSTNAME ?? 'worker'}`, - ); + logger.log(`worker ready: id=${workerId}`); + + // Live reload client certificates, CRL, and OpenBao secrets on SIGHUP. + process.on('SIGHUP', () => { + tlsMaterial.reload('sighup'); + void secretsStore.refreshNow('sighup'); + }); let shuttingDown = false; const shutdown = async (signal: string): Promise => { diff --git a/app/src/worker/job-processor.service.ts b/app/src/worker/job-processor.service.ts index f1914eb..2d9752c 100644 --- a/app/src/worker/job-processor.service.ts +++ b/app/src/worker/job-processor.service.ts @@ -1,4 +1,10 @@ -import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common'; +import { + Inject, + Injectable, + Logger, + OnApplicationBootstrap, + Optional, +} from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { Channel, ConsumeMessage } from 'amqplib'; import { @@ -9,9 +15,9 @@ import { type Span, } from '@opentelemetry/api'; import { createHash } from 'node:crypto'; -import os from 'node:os'; import type { AttachmentRow } from '../attachments/attachment.js'; import type { AppConfig } from '../config/app-config.schema.js'; +import { resolveInstanceId } from '../config/instance-id.js'; import { ObjectStorage } from '../storage/object-storage.js'; import { retryDelayMs } from '../jobs/backoff.js'; import { BrokerClient } from '../jobs/broker.client.js'; @@ -91,7 +97,7 @@ function sha256(data: Buffer): string { @Injectable() export class JobProcessor implements OnApplicationBootstrap { private readonly logger = new Logger(JobProcessor.name); - private readonly workerId = process.env.INSTANCE_ID ?? os.hostname(); + private readonly workerId: string; private readonly maxPixels: number; private readonly timeoutSeconds: number; private readonly leaseSeconds: number; @@ -105,11 +111,12 @@ export class JobProcessor implements OnApplicationBootstrap { private readonly config: ConfigService, private readonly broker: BrokerClient, private readonly jobs: JobsRepository, - private readonly relay: OutboxRelay, + @Optional() @Inject(OutboxRelay) private readonly relay: OutboxRelay | undefined, private readonly faults: FaultInjector, private readonly storage: ObjectStorage, private readonly metrics: MetricsService, ) { + this.workerId = resolveInstanceId(config, 'wrk'); this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS'); this.timeoutSeconds = config.getOrThrow('JOB_TIMEOUT_SECONDS'); this.leaseSeconds = config.getOrThrow('JOB_LEASE_SECONDS'); @@ -432,7 +439,7 @@ export class JobProcessor implements OnApplicationBootstrap { delay, ); this.metrics.increment(`worker.jobs.${outcome}`); - if (outcome === 'retry') this.relay.kick(); + if (outcome === 'retry') this.relay?.kick(); this.safeAck(channel, message); if (outcome === 'retry' || outcome === 'failed') await this.cleanupAttemptObjects(job, null); diff --git a/app/src/worker/lease-reaper.service.ts b/app/src/worker/lease-reaper.service.ts index 5531188..2775ee8 100644 --- a/app/src/worker/lease-reaper.service.ts +++ b/app/src/worker/lease-reaper.service.ts @@ -1,8 +1,10 @@ import { + Inject, Injectable, Logger, OnModuleDestroy, OnModuleInit, + Optional, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { AppConfig } from '../config/app-config.schema.js'; @@ -34,7 +36,7 @@ export class LeaseReaper implements OnModuleInit, OnModuleDestroy { private readonly config: ConfigService, private readonly jobs: JobsRepository, private readonly broker: BrokerClient, - private readonly relay: OutboxRelay, + @Optional() @Inject(OutboxRelay) private readonly relay: OutboxRelay | undefined, private readonly metrics: MetricsService, ) { this.retryBaseMs = config.getOrThrow('JOB_RETRY_BASE_MS'); @@ -76,7 +78,7 @@ export class LeaseReaper implements OnModuleInit, OnModuleDestroy { ); if (reaped > 0) { this.metrics.add('worker.leases.reaped', reaped); - this.relay.kick(); + this.relay?.kick(); } // A normal backlog also has queued jobs with a published outbox row. // Re-emitting them would multiply broker messages; only reconcile when @@ -94,7 +96,7 @@ export class LeaseReaper implements OnModuleInit, OnModuleDestroy { ); if (reconciled > 0) { this.metrics.add('worker.jobs.reconciled', reconciled); - this.relay.kick(); + this.relay?.kick(); } } } diff --git a/app/src/worker/worker.module.spec.ts b/app/src/worker/worker.module.spec.ts new file mode 100644 index 0000000..8edbc52 --- /dev/null +++ b/app/src/worker/worker.module.spec.ts @@ -0,0 +1,51 @@ +import 'reflect-metadata'; +import { MODULE_METADATA } from '@nestjs/common/constants.js'; +import { afterEach, describe, expect, it } from 'vitest'; +import { JobsModule } from '../jobs/jobs.module.js'; +import { OutboxRelay } from '../jobs/outbox-relay.service.js'; +import { RedisModule } from '../redis/redis.module.js'; + +describe('WorkerModule least-privilege isolation', () => { + const savedEnv = { ...process.env }; + + afterEach(() => { + for (const key of Object.keys(process.env)) { + if (!(key in savedEnv)) delete process.env[key]; + } + Object.assign(process.env, savedEnv); + }); + + it('excludes RedisModule and OutboxRelay and loads without Redis or S3_PUBLIC_ENDPOINT env', async () => { + // Provide worker-only env: explicitly NO REDIS_* and NO S3_PUBLIC_ENDPOINT. + delete process.env.REDIS_URL; + delete process.env.REDIS_HOST; + delete process.env.S3_PUBLIC_ENDPOINT; + process.env.TLS_ENABLED = 'false'; + process.env.BAO_ENABLED = 'false'; + process.env.DATABASE_URL = 'postgresql://worker:pass@postgres:5432/messenger'; + process.env.BROKER_URL = 'amqp://broker:5672/messenger'; + process.env.S3_ENDPOINT = 'http://s3:9000'; + process.env.S3_BUCKET = 'messenger-attachments'; + process.env.S3_ACCESS_KEY_ID = 'worker-key'; + process.env.S3_SECRET_ACCESS_KEY = 'worker-secret'; + + const { WorkerModule } = await import('./worker.module.js'); + + const workerImports = (Reflect.getMetadata( + MODULE_METADATA.IMPORTS, + WorkerModule, + ) ?? []) as unknown[]; + const workerProviders = (Reflect.getMetadata( + MODULE_METADATA.PROVIDERS, + WorkerModule, + ) ?? []) as unknown[]; + const jobsImports = (Reflect.getMetadata( + MODULE_METADATA.IMPORTS, + JobsModule, + ) ?? []) as unknown[]; + + expect(workerImports).not.toContain(RedisModule); + expect(workerProviders).not.toContain(OutboxRelay); + expect(jobsImports).not.toContain(RedisModule); + }); +}); diff --git a/app/src/worker/worker.module.ts b/app/src/worker/worker.module.ts index 8f409fd..38cfc5a 100644 --- a/app/src/worker/worker.module.ts +++ b/app/src/worker/worker.module.ts @@ -1,10 +1,9 @@ import { Module } from '@nestjs/common'; -import { AppConfigModule } from '../config/app-config.module.js'; +import { WorkerConfigModule } from '../config/worker-config.module.js'; import { DatabaseModule } from '../database/database.module.js'; import { JobsModule } from '../jobs/jobs.module.js'; -import { OutboxRelay } from '../jobs/outbox-relay.service.js'; import { MetricsModule } from '../metrics/metrics.module.js'; -import { RedisModule } from '../redis/redis.module.js'; +import { SecurityModule } from '../security/security.module.js'; import { StorageModule } from '../storage/storage.module.js'; import { JobProcessor } from './job-processor.service.js'; import { LeaseReaper } from './lease-reaper.service.js'; @@ -12,15 +11,16 @@ import { StagingCleaner } from './staging-cleaner.service.js'; @Module({ imports: [ - AppConfigModule, + WorkerConfigModule, + SecurityModule, DatabaseModule, - RedisModule, MetricsModule, StorageModule, JobsModule, ], - // The worker publishes retry and lease-expiry outbox rows itself; the same - // relay also runs in the API process. SKIP LOCKED makes that safe. - providers: [JobProcessor, LeaseReaper, StagingCleaner, OutboxRelay], + // Lab 7 least privilege: Worker has ZERO Redis access and does NOT run + // OutboxRelay (API replicas poll job_outbox every 500ms and publish with + // producer credentials; worker only consumes attachments.process). + providers: [JobProcessor, LeaseReaper, StagingCleaner], }) export class WorkerModule {}