-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 NEFARIOUSPLAN-CANONICAL-V1 {"body_md":"## The handler is one expression\n\nLibreChat is a self-hostable ChatGPT-style UI. Users register accounts on whatever instance they signed up for, then enter their own API keys for upstream providers: OpenAI, Anthropic, Google, others. The keys are stored encrypted, scoped per-user, and read back when the user makes a chat request. The endpoint that writes a user's stored key is `PUT /api/keys`. The CVE record for the bug in that handler is CVE-2026-31942. Pre-patch, the entire handler is four lines.\n\n```js\nrouter.put('/', requireJwtAuth, async (req, res) => {\n await updateUserKey({ userId: req.user.id, ...req.body });\n res.status(201).send();\n});\n```\n\n`requireJwtAuth` is the authentication middleware. It validates the bearer token and sets `req.user`. By the time the handler body runs, `req.user.id` is the MongoDB ObjectId of the caller, signed and verified.\n\nThe author wrote `userId: req.user.id` first. Read in source order, the intent is unambiguous: the userId we are about to store under is the authenticated caller. Then the author wrote `...req.body`. Read in source order, the intent is to merge in whatever `name`, `value`, and `expiresAt` the caller provided.\n\nObject spread in a literal does not honor the author's intent. It honors the runtime semantics of the operator. Later keys overwrite earlier keys.\n\n```js\nconst merged = { userId: 'server-pinned', ...{ userId: 'attacker-controlled', name: 'openAI' } };\n// merged.userId === 'attacker-controlled'\n```\n\nThat is the bug. There is no race. There is no timing window. There is no chain. There is one expression, evaluated left-to-right, and the right side overrides the left.\n\n## The exploit primitive is one request\n\nThe attacker registers an account on the LibreChat instance. They authenticate normally. They obtain a valid JWT, signed by the instance for their own user.\n\nThey then send:\n\n```http\nPUT /api/keys HTTP/1.1\nHost: librechat.example.com\nAuthorization: Bearer \nContent-Type: application/json\n\n{\n \"userId\": \"\",\n \"name\": \"openAI\",\n \"value\": \"sk-attacker-controlled-key\",\n \"expiresAt\": \"2099-12-31\"\n}\n```\n\n`requireJwtAuth` validates the attacker's token. `req.user.id` is the attacker's own ObjectId. The handler runs. The object literal evaluates to:\n\n```js\n{\n userId: '', // the body's userId wins\n name: 'openAI',\n value: 'sk-attacker-controlled-key',\n expiresAt: '2099-12-31'\n}\n```\n\n`updateUserKey` destructures the four expected fields from its argument. It encrypts the value with the server's static AES key. It upserts on `{ userId, name }`, replacing the victim's stored OpenAI key with the attacker's.\n\nThe next time the victim opens LibreChat and sends a message to OpenAI, the LibreChat server fetches the stored key for `(victim, openAI)`, decrypts it with `CREDS_KEY`, and uses it to authenticate to OpenAI. The decrypted key is the attacker's. The victim's prompt and the model's completion are now traffic on the attacker's OpenAI account.\n\nThe victim sees a working chat. The attacker sees a dashboard.\n\n## The CVSS scored the wrong asset\n\nThe CVE record assigns CVE-2026-31942 the vector `CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:L`. No confidentiality impact, high integrity impact, low availability impact. The reasoning is that the stored key value is encrypted at rest with `CREDS_KEY`, a server-wide environment secret, and the attacker cannot read the existing ciphertext.\n\nThe reasoning is correct about the stored credential. It is not the credential that gets compromised. The asset that gets compromised is every prompt the victim sends after the overwrite, because the attacker's upstream provider account now sits in the middle of the victim's chats. `C:N` is the score for \"we cannot read the victim's prior key.\" It is not the score for \"we cannot read the victim's traffic after the overwrite.\"\n\nThe integrity reading the score does name is the rest of the menu. The attacker can write garbage as the value, breaking the victim's chat entirely until the victim notices and re-enters their key. The attacker can backdate `expiresAt`, silently expiring the victim's working key. The attacker can iterate through every provider name the victim might have keys for and do this to all of them at once.\n\nMongoDB ObjectIds are enumerable. The first four bytes are a Unix timestamp; the next five are per-process randomness that stays stable across a deployment; the last three are an incrementing counter. An attacker on a registration-open instance can register their own account, read the issued ObjectId from their own session, and grind from there. There is no entropy gate on userId. The route hands the merge whatever userId the body says, and the body is in the attacker's hand.\n\n## The fix is to stop spreading\n\nThe patch (commit `b8c31e73`, merged 2026-02-12, shipped in v0.8.3-rc1) is six lines.\n\n```diff\n router.put('/', requireJwtAuth, async (req, res) => {\n- await updateUserKey({ userId: req.user.id, ...req.body });\n+ if (req.body == null || typeof req.body !== 'object') {\n+ return res.status(400).send({ error: 'Invalid request body.' });\n+ }\n+ const { name, value, expiresAt } = req.body;\n+ await updateUserKey({ userId: req.user.id, name, value, expiresAt });\n res.status(201).send();\n });\n```\n\nThe fix does not add a security check. The fix removes the spread.\n\nThe destructure enumerates the three fields the handler accepts from the body: `name`, `value`, `expiresAt`. Everything else in `req.body` is dropped on the floor of the function. `userId` is no longer reachable from the body because the handler no longer reads it from the body. The pin holds because there is nothing left to overwrite it.\n\nThe same commit added a test file. One of its tests is named, verbatim:\n\n```js\nit('should not allow userId override via request body (IDOR prevention)', async () => {\n updateUserKey.mockResolvedValue({});\n const response = await request(app).put('/api/keys').send({\n userId: 'attacker-injected-id',\n name: 'openAI',\n value: 'sk-attacker-key',\n });\n expect(response.status).toBe(201);\n expect(updateUserKey).toHaveBeenCalledWith({\n userId: 'test-user-123',\n name: 'openAI',\n value: 'sk-attacker-key',\n expiresAt: undefined,\n });\n});\n```\n\nThe test exists because the maintainer understood what the bug was. The maintainer's commit title also understood: `🔱 chore: Harden API Routes Against IDOR and DoS Attacks`. The CVE record for CVE-2026-31942 says IDOR. The CWE assigned is 639, Authorization Bypass Through User-Controlled Key.\n\nNone of those labels describe what actually happened in this code. The user-controlled key was not in the URL. It was in the request body. The route's own code put it there.\n\n## Pin then spread\n\nMass assignment is a thirty-year-old bug class. Rails introduced `attr_protected` in 2005 and `strong_params` in 2013 because every framework that lets attacker-controlled JSON merge directly into a server model lets the attacker write any attribute they can name. Express, which LibreChat uses, has no equivalent gate. The default Express request body is a plain object, and the default JavaScript way to combine it with another object is the spread operator.\n\nThe bug recurs because the spread operator reads as assignment. `{ userId: req.user.id, ...req.body }` reads, to a hurried reviewer, as \"set userId from auth, then add whatever else the body has.\" It evaluates to \"left-to-right, last key wins, and `req.body.userId` is a key like any other.\" There is no warning. The TypeScript signature on `updateUserKey` says `userId: string`. Both the pin and the override satisfy `string`. The type system is silent.\n\nThe same codebase contains the correct ordering in `api/server/routes/messages.js`. The handler that saves a chat message writes:\n\n```js\nconst message = { ...req.body, conversationId: req.params.conversationId };\n// ...\nconst savedMessage = await db.saveMessage(\n reqCtx,\n { ...message, user: req.user.id },\n { context: 'POST /api/messages/:conversationId' },\n);\n```\n\nSpread first, pin last. `conversationId` overrides anything in the body called `conversationId`. `user` overrides anything in `message` called `user`. The pin survives because the pin runs last. The author of these lines understood the rule.\n\nThe author of `keys.js` understood it too, or thought they did, and put the pin where it reads first instead of where it runs last. Three keystrokes of source-order separate one route from the other. The maintainer's patch fixed the route the CVE named. The pattern survives wherever the next handler builds an `updateX` payload by spreading `req.body` after a pin instead of before.\n\nThe pattern this CVE belongs to is **pin-then-spread**: a handler pins a server-derived authoritative field at the head of an object literal and immediately spreads attacker-controlled input over the same object. The pin reads to code review as enforcement. The runtime applies it as a default.\n\nPoC: [@offseq on infosec.exchange](https://infosec.exchange/@offseq/116684647649200501)","closing_line":"The pin came first. The spread came last. Last wins.","hook_md":"LibreChat's `PUT /api/keys` handler is one expression of business logic. It pins `userId: req.user.id`, the identifier the JWT middleware extracted from the bearer token, then it spreads `...req.body` over the pin. JavaScript's object literal does not care which key the author intended to win. It cares which key was written last. The spread comes after the pin; the spread overrides it.\n\nCVE-2026-31942 is one line of code. The line is `await updateUserKey({ userId: req.user.id, ...req.body });`.","post_id":545,"slug":"librechat-cve-2026-31942-spread-overrode-the-pinned-userid","title":"CVE-2026-31942: LibreChat's Keys Route Pinned the User ID. The Spread on the Same Line Overrode It.","type":"initial","unreadable_sentence":"The pin reads to code review as enforcement. The runtime applies it as a default."} -----BEGIN PGP SIGNATURE----- iHUEARYIAB0WIQRf0htP5+SjynlxywneZjl4jgkQJgUCap8iyAAKCRDeZjl4jgkQ Jt0TAQDzIY7Zij+S/AvUfu28EfApC6vqQkDWM6qZ74yyfZy14QEA9cexdLnCyYek Y3krDvWGrdeHXsVFnU1VeEzAotSTqQs= =/avh -----END PGP SIGNATURE-----