pangolin/server/lib/requestAuthState.ts
Owen c5c4880342
Only trust cached org membership that belongs to the caller
Access middlewares cache the caller's org link on req.userOrg and
req.apiKeyOrg and skip their membership query when it is already set.
A value inherited from a polluted Object.prototype passed that check.

- Give every request its own undefined copy of the cached auth fields
  (userOrg, apiKeyOrg, userOrgRoleIds, userOrgId, userOrgIds,
  orgPolicyAllowed) before any route runs, on the API, integration,
  internal and AI gateway servers.
- Add ownUserOrg/ownApiKeyOrg, which return a cached value only if it is
  an own property for the signed-in user or calling key.
- Every user and API key access middleware now uses them and refuses
  when the cached org does not match the org of the object being
  accessed. verifyApiKeySiteAccess and verifyApiKeySiteResourceAccess
  had no org comparison at all once req.apiKeyOrg was set.

Defence in depth for PAN-1814 / GHSA-5fhj.
2026-11-25 18:38:16 -05:00

55 lines
1.8 KiB
TypeScript

import type { Request } from "express";
import type { ApiKeyOrg, UserOrg } from "@server/db";
// Request fields that access middlewares use as a per-request cache. A value
// for any of these that does not live on the request itself (for example one
// inherited from a polluted Object.prototype) must never be trusted.
const AUTH_STATE_KEYS = [
"userOrg",
"apiKeyOrg",
"userOrgRoleIds",
"userOrgId",
"userOrgIds",
"orgPolicyAllowed"
] as const;
// Give the request its own (undefined) copy of every cached auth field so a
// read can never fall through to the prototype chain.
export function initRequestAuthState(req: Request): void {
for (const key of AUTH_STATE_KEYS) {
if (!Object.hasOwn(req, key)) {
Object.defineProperty(req, key, {
value: undefined,
writable: true,
enumerable: true,
configurable: true
});
}
}
}
// The cached org membership for the signed-in user, or undefined if there is
// none or it belongs to someone else.
export function ownUserOrg(req: Request): UserOrg | undefined {
if (!Object.hasOwn(req, "userOrg")) {
return undefined;
}
const userOrg = req.userOrg;
if (!userOrg || !req.user || userOrg.userId !== req.user.userId) {
return undefined;
}
return userOrg;
}
// The cached org link for the calling API key, or undefined if there is none
// or it belongs to a different key.
export function ownApiKeyOrg(req: Request): ApiKeyOrg | undefined {
if (!Object.hasOwn(req, "apiKeyOrg")) {
return undefined;
}
const keyOrg = req.apiKeyOrg;
if (!keyOrg || !req.apiKey || keyOrg.apiKeyId !== req.apiKey.apiKeyId) {
return undefined;
}
return keyOrg;
}