pangolin/server/lib/requestAuthState.test.ts

95 lines
2.7 KiB
TypeScript

import { test } from "node:test";
import assert from "node:assert/strict";
import {
initRequestAuthState,
ownApiKeyOrg,
ownUserOrg
} from "./requestAuthState";
const proto = Object.prototype as any;
function withPollutedPrototype(fn: () => void) {
proto.userOrg = { userId: "victim", orgId: "victim-org" };
proto.apiKeyOrg = { apiKeyId: "victim-key", orgId: "victim-org" };
proto.userOrgRoleIds = [1];
proto.orgPolicyAllowed = true;
try {
fn();
} finally {
delete proto.userOrg;
delete proto.apiKeyOrg;
delete proto.userOrgRoleIds;
delete proto.orgPolicyAllowed;
}
}
test("inherited auth state", () => {
withPollutedPrototype(() => {
const req: any = {
user: { userId: "victim" },
apiKey: { apiKeyId: "victim-key" }
};
assert.equal(
ownUserOrg(req),
undefined,
"inherited userOrg is ignored"
);
assert.equal(
ownApiKeyOrg(req),
undefined,
"inherited apiKeyOrg is ignored"
);
initRequestAuthState(req);
assert.equal(req.userOrg, undefined, "init shadows userOrg");
assert.equal(req.apiKeyOrg, undefined, "init shadows apiKeyOrg");
assert.equal(
req.userOrgRoleIds,
undefined,
"init shadows userOrgRoleIds"
);
assert.equal(
req.orgPolicyAllowed,
undefined,
"init shadows orgPolicyAllowed"
);
});
});
test("init keeps own values", () => {
const userOrg = { userId: "u1", orgId: "o1" };
const req: any = { user: { userId: "u1" }, userOrg };
initRequestAuthState(req);
assert.equal(req.userOrg, userOrg, "own value is kept");
});
test("cached membership ownership", () => {
const userOrg = { userId: "u1", orgId: "o1" };
assert.equal(
ownUserOrg({ user: { userId: "u1" }, userOrg } as any),
userOrg,
"own userOrg for the caller is returned"
);
assert.equal(
ownUserOrg({ user: { userId: "u2" }, userOrg } as any),
undefined,
"userOrg for another user is rejected"
);
assert.equal(
ownUserOrg({ userOrg } as any),
undefined,
"userOrg without a signed-in user is rejected"
);
const apiKeyOrg = { apiKeyId: "k1", orgId: "o1" };
assert.equal(
ownApiKeyOrg({ apiKey: { apiKeyId: "k1" }, apiKeyOrg } as any),
apiKeyOrg,
"own apiKeyOrg for the caller is returned"
);
assert.equal(
ownApiKeyOrg({ apiKey: { apiKeyId: "k2" }, apiKeyOrg } as any),
undefined,
"apiKeyOrg for another key is rejected"
);
});