Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

test(auth-token): enhance tests for sub-org token access and membership status handling

Victor Hugo dos Santos25f404492168
diff --git a/backend/e2e-test/routes/v1/auth-token-org-scope.spec.ts b/backend/e2e-test/routes/v1/auth-token-org-scope.spec.ts
index 209ce513a9..9f55903567 100644
--- a/backend/e2e-test/routes/v1/auth-token-org-scope.spec.ts
+++ b/backend/e2e-test/routes/v1/auth-token-org-scope.spec.ts
@@ -292,6 +292,38 @@ describe("Org scope of user tokens after root membership deactivation", () => {
expect(refreshRes.payload).toContain("no longer exists");
});
+ // SCIM provisions the root membership as Invited, and selecting a sub-org never promotes it.
+ test("a still-Invited but active root member can use and refresh a sub-org token", async () => {
+ const member = await makeMember();
+ await testDb(TableName.Membership)
+ .where({ id: member.rootMembershipId })
+ .update({ status: OrgMembershipStatus.Invited });
+
+ expect((await readOrgMembers(accessToken(member, subScope(member)), member.subOrgId)).statusCode).toBe(200);
+ expect((await refresh(refreshToken(member, subScope(member)))).statusCode).toBe(200);
+
+ await setMembershipActive(member.rootMembershipId, false);
+ expect((await readOrgMembers(accessToken(member, subScope(member)), member.subOrgId)).statusCode).toBe(403);
+ });
+
+ test("tokens scoped to a deleted sub-org are refused with 401, not a 400", async () => {
+ const member = await makeMember();
+ await testDb(TableName.MembershipRole).where({ membershipId: member.subMembershipId }).del();
+ await testDb(TableName.Membership).where({ id: member.subMembershipId }).del();
+ await testDb(TableName.Organization).where({ id: member.subOrgId }).del();
+
+ const accessRes = await testServer.inject({
+ method: "GET",
+ url: "/api/v1/user",
+ headers: { authorization: `Bearer ${accessToken(member, subScope(member))}` }
+ });
+ expect(accessRes.statusCode).toBe(401);
+
+ const refreshRes = await refresh(refreshToken(member, subScope(member)));
+ expect(refreshRes.statusCode).toBe(401);
+ expect(refreshRes.payload).toContain("no longer exists");
+ });
+
test("claim shapes no issuer produces are refused", async () => {
const member = await makeMember();
diff --git a/backend/src/services/auth-token/auth-token-service.test.ts b/backend/src/services/auth-token/auth-token-service.test.ts
index e2e6dbf63e..503fbdbee2 100644
--- a/backend/src/services/auth-token/auth-token-service.test.ts
+++ b/backend/src/services/auth-token/auth-token-service.test.ts
@@ -255,12 +255,22 @@ describe("tokenServiceFactory — org scope of user tokens", () => {
const build = ({
user = { id: USER_ID, isAccepted: true, isLocked: false, temporaryLockDateEnd: null as Date | null },
- memberships = { [ROOT]: true, [SUB]: true } as Record<string, boolean | undefined>
+ memberships = { [ROOT]: true, [SUB]: true } as Record<
+ string,
+ boolean | { isActive: boolean; status: string } | undefined
+ >
} = {}) => {
const orgDAL = {
findOne: vi.fn(async ({ id }: { id: string }) => orgs[id]),
- findEffectiveOrgMembership: vi.fn(async ({ orgId }: { orgId: string }) =>
- memberships[orgId] === undefined ? null : { isActive: memberships[orgId] }
+ // Mirrors the DAL: a status filter hides rows in any other status unless acceptAnyStatus is set.
+ findEffectiveOrgMembership: vi.fn(
+ async ({ orgId, status, acceptAnyStatus }: { orgId: string; status?: string; acceptAnyStatus?: boolean }) => {
+ const entry = memberships[orgId];
+ if (entry === undefined) return null;
+ const row = typeof entry === "boolean" ? { isActive: entry, status: "accepted" } : entry;
+ if (!acceptAnyStatus && status && row.status !== status) return null;
+ return row;
+ }
)
};
const service = tokenServiceFactory({
@@ -349,6 +359,43 @@ describe("tokenServiceFactory — org scope of user tokens", () => {
expect(err.message).toContain("deleted-org");
});
+ // selectOrganization issues a sub-org token to a still-Invited root member and only promotes on root selection.
+ test("a sub-org token is accepted while the root membership is still Invited but active", async () => {
+ const { service } = build({ memberships: { [ROOT]: { isActive: true, status: "invited" }, [SUB]: true } });
+ await expect(
+ service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: SUB }))
+ ).resolves.toMatchObject({ orgId: SUB });
+ await expect(
+ service.validateRefreshTokenAccess(refreshToken({ organizationId: ROOT, subOrganizationId: SUB }))
+ ).resolves.toBeUndefined();
+ });
+
+ test("a sub-org token is refused when the Invited root membership is deactivated", async () => {
+ const { service } = build({ memberships: { [ROOT]: { isActive: false, status: "invited" }, [SUB]: true } });
+ await expectRejected(
+ service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: SUB })),
+ ForbiddenRequestError
+ );
+ });
+
+ test("a root-scoped token still requires an Accepted root membership", async () => {
+ const { service } = build({ memberships: { [ROOT]: { isActive: true, status: "invited" } } });
+ await expectRejected(service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT })), ForbiddenRequestError);
+ });
+
+ test("a token for a sub-org that no longer exists is refused with 401, not a 400", async () => {
+ const { service } = build();
+ const err = await expectRejected(
+ service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: "deleted-sub" })),
+ UnauthorizedError
+ );
+ expect(err.message).toContain("deleted-sub");
+ await expectRejected(
+ service.validateRefreshTokenAccess(refreshToken({ organizationId: ROOT, subOrganizationId: "deleted-sub" })),
+ UnauthorizedError
+ );
+ });
+
describe("validateRefreshTokenAccess", () => {
test("allows an active, unlocked member", async () => {
const { service } = build();
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index 636d8bd9ac..ea38caa07b 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -4,7 +4,7 @@ import { OrgMembershipStatus, TAuthTokens, TAuthTokenSessions, TUsers } from "@a
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
+import { ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { chunkArray } from "@app/lib/fn/array";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
@@ -389,12 +389,12 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
return { user };
};
- const assertActiveOrgMembership = async (userId: string, orgId: string) => {
+ const assertActiveOrgMembership = async (userId: string, orgId: string, { acceptAnyStatus = false } = {}) => {
const orgMembership = await orgDAL.findEffectiveOrgMembership({
actorType: ActorType.USER,
actorId: userId,
orgId,
- status: OrgMembershipStatus.Accepted
+ ...(acceptAnyStatus ? { acceptAnyStatus } : { status: OrgMembershipStatus.Accepted })
});
if (!orgMembership) {
@@ -439,12 +439,18 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
}
const subOrganization = await orgDAL.findOne({ id: subOrganizationId });
- if (!subOrganization) throw new BadRequestError({ message: `Sub organization ${subOrganizationId} not found` });
+ if (!subOrganization) {
+ throw new UnauthorizedError({
+ message: `The sub-organization with ID '${subOrganizationId}' no longer exists. Log in again.`
+ });
+ }
if (subOrganization.rootOrgId !== organizationId || subOrganization.id === organizationId) {
throw new ForbiddenRequestError({ message: "Sub-organization does not belong to the token's organization" });
}
- await assertActiveOrgMembership(userId, organizationId);
+ // Mirrors selectOrganization, which lets a still-Invited root member into a sub-org: selecting a sub-org
+ // never promotes the root membership, so only deactivation is a reason to refuse here.
+ await assertActiveOrgMembership(userId, organizationId, { acceptAnyStatus: true });
await assertActiveOrgMembership(userId, subOrganization.id);
return {