Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(auth): implement organization scope validation for refresh tokens
Victor Hugo dos Santosa9732ff2db91
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.tsnew file mode 100644index 0000000000..209ce513a9--- /dev/null+++ b/backend/e2e-test/routes/v1/auth-token-org-scope.spec.ts@@ -0,0 +1,366 @@+import crypto from "node:crypto";++import jwt from "jsonwebtoken";++import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "@app/db/schemas";+import { seedData1 } from "@app/db/seed-data";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { getConfig, initEnvConfig } from "@app/lib/config/env";+import { initLogger, logger } from "@app/lib/logger";+import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";+import { OauthGrantType } from "@app/services/oauth-client/oauth-client-types";++declare const testKeyStore: TKeyStoreFactory;++// SCIM and admin deactivation flip only the root membership row; sub-org memberships are separate rows+// that stay active. These pin that a root-org deactivation still cuts off tokens scoped below it, for+// access tokens, the refresh endpoint (including its grace window) and the OAuth refresh grant.+const ROOT_ORG_ID = seedData1.organization.id;+const REDIRECT_URI = "https://app.example.com/callback";++type TScope = { organizationId?: string; subOrganizationId?: string };+type TMember = {+ userId: string;+ subOrgId: string;+ rootMembershipId: string;+ subMembershipId: string;+ sessionId: string;+};++const createdUserIds: string[] = [];+const createdOrgIds: string[] = [];+const createdClientIds: string[] = [];++const addOrgMembership = async (userId: string, orgId: string) => {+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: orgId,+ actorUserId: userId,+ status: OrgMembershipStatus.Accepted,+ isActive: true+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: membership.id, role: OrgMembershipRole.Member });+ return membership.id;+};++const makeOrg = async (rootOrgId?: string) => {+ const [org] = await testDb(TableName.Organization)+ .insert({+ name: `scope-${crypto.randomUUID()}`,+ slug: `scope-${crypto.randomUUID()}`,+ rootOrgId: rootOrgId ?? null,+ parentOrgId: rootOrgId ?? null+ })+ .returning("*");+ createdOrgIds.push(org.id);+ return org.id;+};++// A member of the seed root org and of a fresh sub-org under it, with one session.+const makeMember = async (): Promise<TMember> => {+ const email = `scope-${crypto.randomUUID()}@auth-scope.example`;+ const [user] = await testDb(TableName.Users)+ .insert({ username: email, email, isAccepted: true, isGhost: false, authMethods: [AuthMethod.EMAIL] })+ .returning("*");+ createdUserIds.push(user.id);++ const subOrgId = await makeOrg(ROOT_ORG_ID);+ const rootMembershipId = await addOrgMembership(user.id, ROOT_ORG_ID);+ const subMembershipId = await addOrgMembership(user.id, subOrgId);++ const [session] = await testDb(TableName.AuthTokenSession)+ .insert({+ userId: user.id,+ ip: "127.0.0.1",+ userAgent: "e2e-auth-token-org-scope",+ accessVersion: 1,+ refreshVersion: 1,+ lastUsed: new Date()+ } as never)+ .returning("*");++ return { userId: user.id, subOrgId, rootMembershipId, subMembershipId, sessionId: session.id };+};++const accessToken = (member: TMember, scope: TScope) =>+ jwt.sign(+ {+ authTokenType: AuthTokenType.ACCESS_TOKEN,+ authMethod: AuthMethod.EMAIL,+ userId: member.userId,+ tokenVersionId: member.sessionId,+ accessVersion: 1,+ ...scope+ },+ getConfig().AUTH_SECRET,+ { expiresIn: 3600 }+ );++const refreshToken = (member: TMember, scope: TScope) =>+ jwt.sign(+ {+ authTokenType: AuthTokenType.REFRESH_TOKEN,+ authMethod: AuthMethod.EMAIL,+ userId: member.userId,+ tokenVersionId: member.sessionId,+ refreshVersion: 1,+ ...scope+ },+ getConfig().AUTH_SECRET,+ { expiresIn: 3600 }+ );++const subScope = (member: TMember): TScope => ({ organizationId: ROOT_ORG_ID, subOrganizationId: member.subOrgId });++const readOrgMembers = (token: string, orgId: string) =>+ testServer.inject({+ method: "GET",+ url: `/api/v2/organizations/${orgId}/memberships`,+ headers: { authorization: `Bearer ${token}` }+ });++const refresh = (jid: string) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/auth/token",+ cookies: { jid }+ });++const setMembershipActive = (membershipId: string, isActive: boolean) =>+ testDb(TableName.Membership).where({ id: membershipId }).update({ isActive });++const refreshVersionOf = async (sessionId: string) =>+ (await testDb(TableName.AuthTokenSession).where({ id: sessionId }).first())?.refreshVersion;++const clearsJidCookie = (res: Awaited<ReturnType<typeof refresh>>) => {+ const cookies = res.headers["set-cookie"];+ const list = Array.isArray(cookies) ? cookies : [cookies ?? ""];+ return list.some((c) => c.startsWith("jid=;") && /Max-Age=0/i.test(c));+};++const postOauthToken = (body: Record<string, string>) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/oauth/token",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ payload: new URLSearchParams(body).toString()+ });++describe("Org scope of user tokens after root membership deactivation", () => {+ beforeAll(async () => {+ initLogger();+ await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);+ });++ afterEach(async () => {+ await Promise.all(+ createdClientIds.splice(0).map((id) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/oauth/clients/${id}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ })+ )+ );+ if (createdUserIds.length) {+ const membershipIds = await testDb(TableName.Membership)+ .whereIn("actorUserId", createdUserIds)+ .select("id")+ .then((rows) => rows.map((r) => r.id));+ if (membershipIds.length) await testDb(TableName.MembershipRole).whereIn("membershipId", membershipIds).del();+ await testDb(TableName.Membership).whereIn("actorUserId", createdUserIds).del();+ await testDb(TableName.AuthTokenSession).whereIn("userId", createdUserIds).del();+ await testDb(TableName.Users).whereIn("id", createdUserIds).del();+ createdUserIds.length = 0;+ }+ if (createdOrgIds.length) {+ await testDb(TableName.Organization).whereIn("id", createdOrgIds).whereNotNull("rootOrgId").del();+ await testDb(TableName.Organization).whereIn("id", createdOrgIds).del();+ createdOrgIds.length = 0;+ }+ });++ test("baseline: an active member's sub-org token works and refreshes with its scope intact", async () => {+ const member = await makeMember();++ expect((await readOrgMembers(accessToken(member, subScope(member)), member.subOrgId)).statusCode).toBe(200);++ const res = await refresh(refreshToken(member, subScope(member)));+ expect(res.statusCode).toBe(200);+ const { token } = res.json<{ token: string }>();+ expect(jwt.decode(token)).toMatchObject({ organizationId: ROOT_ORG_ID, subOrganizationId: member.subOrgId });+ });++ test("a sub-org token is refused on any request once the root membership is inactive", async () => {+ const member = await makeMember();+ await setMembershipActive(member.rootMembershipId, false);++ const subRes = await readOrgMembers(accessToken(member, subScope(member)), member.subOrgId);+ expect(subRes.statusCode).toBe(403);+ expect(subRes.payload).toContain("inactive");++ const rootRes = await readOrgMembers(accessToken(member, { organizationId: ROOT_ORG_ID }), ROOT_ORG_ID);+ expect(rootRes.statusCode).toBe(403);++ const subRow = await testDb(TableName.Membership).where({ id: member.subMembershipId }).first();+ expect(subRow?.isActive).toBe(true);+ });++ test("a sub-org token is refused when only the sub-org membership is inactive", async () => {+ const member = await makeMember();+ await setMembershipActive(member.subMembershipId, false);++ expect((await readOrgMembers(accessToken(member, subScope(member)), member.subOrgId)).statusCode).toBe(403);+ expect((await readOrgMembers(accessToken(member, { organizationId: ROOT_ORG_ID }), ROOT_ORG_ID)).statusCode).toBe(+ 200+ );+ });++ test("a deprovisioned root member's refresh is refused, clears the cookie and does not rotate", async () => {+ const member = await makeMember();+ await setMembershipActive(member.rootMembershipId, false);++ const expectRefused = (res: Awaited<ReturnType<typeof refresh>>) => {+ expect(res.statusCode).toBe(403);+ expect(res.json()).not.toHaveProperty("token");+ expect(clearsJidCookie(res)).toBe(true);+ };+ expectRefused(await refresh(refreshToken(member, subScope(member))));+ expectRefused(await refresh(refreshToken(member, { organizationId: ROOT_ORG_ID })));+ expect(await refreshVersionOf(member.sessionId)).toBe(1);+ expect(await testKeyStore.getItem(KeyStorePrefixes.RefreshTokenGrace(member.sessionId))).toBeNull();+ });++ test("a grace-window refresh by a deprovisioned member is refused", async () => {+ const member = await makeMember();+ const original = refreshToken(member, subScope(member));++ expect((await refresh(original)).statusCode).toBe(200);+ await setMembershipActive(member.rootMembershipId, false);++ // The rotation parked the old refreshVersion as a grace entry, so replaying the original token now+ // takes the grace-hit branch rather than reuse detection.+ expect(await testKeyStore.getItem(KeyStorePrefixes.RefreshTokenGrace(member.sessionId))).toBe("1");++ const res = await refresh(original);+ expect(res.statusCode).toBe(403);+ expect(res.json()).not.toHaveProperty("token");+ });++ test("reactivating the root membership restores access and the unrotated refresh token", async () => {+ const member = await makeMember();+ await setMembershipActive(member.rootMembershipId, false);+ expect((await refresh(refreshToken(member, subScope(member)))).statusCode).toBe(403);++ await setMembershipActive(member.rootMembershipId, true);+ expect((await readOrgMembers(accessToken(member, subScope(member)), member.subOrgId)).statusCode).toBe(200);+ expect((await refresh(refreshToken(member, subScope(member)))).statusCode).toBe(200);+ });++ test.each([+ ["permanently locked", { isLocked: true }],+ ["temporarily locked", { temporaryLockDateEnd: new Date(Date.now() + 10 * 60 * 1000) }],+ ["not accepted", { isAccepted: false }]+ ])("a %s user's refresh is refused without rotating", async (_label, patch) => {+ const member = await makeMember();+ await testDb(TableName.Users).where({ id: member.userId }).update(patch);++ const res = await refresh(refreshToken(member, subScope(member)));+ expect(res.statusCode).toBe(401);+ expect(clearsJidCookie(res)).toBe(true);+ expect(await refreshVersionOf(member.sessionId)).toBe(1);+ });++ test("tokens scoped to a deleted org are refused with 401, not a 500", async () => {+ const member = await makeMember();+ const doomedOrgId = await makeOrg();+ await addOrgMembership(member.userId, doomedOrgId);+ await testDb(TableName.Membership).where({ scopeOrgId: doomedOrgId }).del();+ await testDb(TableName.Organization).where({ id: doomedOrgId }).del();++ const accessRes = await testServer.inject({+ method: "GET",+ url: "/api/v1/user",+ headers: { authorization: `Bearer ${accessToken(member, { organizationId: doomedOrgId })}` }+ });+ expect(accessRes.statusCode).toBe(401);++ const refreshRes = await refresh(refreshToken(member, { organizationId: doomedOrgId }));+ 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();++ const noRoot = await testServer.inject({+ method: "GET",+ url: "/api/v1/user",+ headers: { authorization: `Bearer ${accessToken(member, { subOrganizationId: member.subOrgId })}` }+ });+ expect(noRoot.statusCode).toBe(401);++ const subIsRoot = await readOrgMembers(+ accessToken(member, { organizationId: ROOT_ORG_ID, subOrganizationId: ROOT_ORG_ID }),+ ROOT_ORG_ID+ );+ expect(subIsRoot.statusCode).toBe(403);+ expect(subIsRoot.payload).toContain("does not belong");+ });++ test("the OAuth refresh grant is refused as invalid_grant once the root membership is inactive", async () => {+ const member = await makeMember();++ const created = await testServer.inject({+ method: "POST",+ url: "/api/v1/oauth/clients",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: {+ name: `e2e-org-scope-${crypto.randomUUID()}`,+ grantTypes: [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken],+ redirectUris: [REDIRECT_URI]+ }+ });+ expect(created.statusCode).toBe(200);+ const { client, clientSecret } = created.json<{ client: { id: string; clientId: string }; clientSecret: string }>();+ createdClientIds.push(client.id);++ const consented = await testServer.inject({+ method: "POST",+ url: "/api/v1/oauth/authorize/consent",+ headers: { authorization: `Bearer ${accessToken(member, { organizationId: ROOT_ORG_ID })}` },+ body: { client_id: client.clientId, redirect_uri: REDIRECT_URI }+ });+ expect(consented.statusCode).toBe(200);+ const { callbackUrl } = consented.json<{ callbackUrl: string }>();++ const issued = await postOauthToken({+ grant_type: OauthGrantType.AuthorizationCode,+ code: new URL(callbackUrl).searchParams.get("code") as string,+ redirect_uri: REDIRECT_URI,+ client_id: client.clientId,+ client_secret: clientSecret+ });+ expect(issued.statusCode).toBe(200);+ const firstRefresh = issued.json<{ refresh_token: string }>().refresh_token;++ const refreshBody = (token: string) => ({+ grant_type: OauthGrantType.RefreshToken,+ refresh_token: token,+ client_id: client.clientId,+ client_secret: clientSecret+ });++ const active = await postOauthToken(refreshBody(firstRefresh));+ expect(active.statusCode).toBe(200);+ const secondRefresh = active.json<{ refresh_token: string }>().refresh_token;++ await setMembershipActive(member.rootMembershipId, false);++ const refused = await postOauthToken(refreshBody(secondRefresh));+ expect(refused.statusCode).toBe(400);+ expect(refused.json()).toMatchObject({ error: "invalid_grant" });+ });+});diff --git a/backend/src/server/routes/v1/auth-router.ts b/backend/src/server/routes/v1/auth-router.tsindex 8a22cbce76..6a29ea1c9e 100644--- a/backend/src/server/routes/v1/auth-router.ts+++ b/backend/src/server/routes/v1/auth-router.ts@@ -107,11 +107,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {({ decodedToken, tokenVersion, isGraceHit } = await server.services.authToken.validateRefreshToken(req.cookies.jid));- await server.services.authToken.validateTokenOrgScope({- userId: decodedToken.userId,- organizationId: decodedToken.organizationId,- subOrganizationId: decodedToken.subOrganizationId- });+ await server.services.authToken.validateRefreshTokenAccess(decodedToken);} catch (err) {// Clear the expired/invalid jid cookie so it doesn't cause login loops// when the browser keeps sending the stale cookie on subsequent requests.diff --git a/backend/src/services/auth-token/auth-token-service.test.ts b/backend/src/services/auth-token/auth-token-service.test.tsindex 142525e64a..e2e6dbf63e 100644--- a/backend/src/services/auth-token/auth-token-service.test.ts+++ b/backend/src/services/auth-token/auth-token-service.test.ts@@ -4,7 +4,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, type Mockimport { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { crypto } from "@app/lib/crypto/cryptography";-import { UnauthorizedError } from "@app/lib/errors";+import { ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";import { tokenServiceFactory } from "./auth-token-service";import { TEmailSignupOtpPayload } from "./auth-token-types";@@ -239,3 +239,176 @@ describe("tokenServiceFactory — email signup OTP", () => {});});});++describe("tokenServiceFactory — org scope of user tokens", () => {+ const USER_ID = "user-1";+ const ROOT = "root-org";+ const SUB = "sub-org";+ const OTHER_ROOT = "other-root-org";+ const SESSION = { id: "session-1", userId: USER_ID, accessVersion: 1, refreshVersion: 1 };++ const orgs: Record<string, { id: string; name: string; rootOrgId: string | null; parentOrgId: string | null }> = {+ [ROOT]: { id: ROOT, name: "Root", rootOrgId: null, parentOrgId: null },+ [SUB]: { id: SUB, name: "Sub", rootOrgId: ROOT, parentOrgId: ROOT },+ [OTHER_ROOT]: { id: OTHER_ROOT, name: "Other", rootOrgId: null, parentOrgId: null }+ };++ 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>+ } = {}) => {+ 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] }+ )+ };+ const service = tokenServiceFactory({+ tokenDAL: { findOneTokenSession: vi.fn().mockResolvedValue(SESSION) } as never,+ userDAL: { findById: vi.fn().mockResolvedValue(user) } as never,+ orgDAL: orgDAL as never,+ membershipUserDAL: {} as never,+ keyStore: makeKeyStore() as never+ });+ return { service, orgDAL };+ };++ const accessToken = (claims: { organizationId?: string; subOrganizationId?: string }) =>+ ({ userId: USER_ID, tokenVersionId: SESSION.id, accessVersion: 1, ...claims }) as never;+ const refreshToken = (claims: { organizationId?: string; subOrganizationId?: string }) =>+ ({ userId: USER_ID, tokenVersionId: SESSION.id, refreshVersion: 1, ...claims }) as never;++ afterEach(() => vi.clearAllMocks());++ test("a sub-org token resolves to the sub-org when root and sub-org memberships are active", async () => {+ const { service } = build();+ const identity = await service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: SUB }));+ expect(identity).toMatchObject({ orgId: SUB, orgName: "Sub", rootOrgId: ROOT, parentOrgId: ROOT });+ });++ test("a sub-org token is refused when the root membership is inactive", async () => {+ const { service } = build({ memberships: { [ROOT]: false, [SUB]: true } });+ const err = await expectRejected(+ service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: SUB })),+ ForbiddenRequestError+ );+ expect(err.message).toContain("inactive");+ });++ test("a sub-org token is refused when the root membership is gone", async () => {+ const { service } = build({ memberships: { [SUB]: true } });+ await expectRejected(+ service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: SUB })),+ ForbiddenRequestError+ );+ });++ test("a sub-org token is refused when the sub-org membership is inactive", async () => {+ const { service } = build({ memberships: { [ROOT]: true, [SUB]: false } });+ await expectRejected(+ service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: SUB })),+ ForbiddenRequestError+ );+ });++ test("subOrganizationId equal to organizationId is refused", async () => {+ const { service, orgDAL } = build();+ await expectRejected(+ service.fnValidateJwtIdentity(accessToken({ organizationId: ROOT, subOrganizationId: ROOT })),+ ForbiddenRequestError+ );+ expect(orgDAL.findEffectiveOrgMembership).not.toHaveBeenCalled();+ });++ test("a sub-org under a different root is refused", async () => {+ const { service } = build();+ await expectRejected(+ service.fnValidateJwtIdentity(accessToken({ organizationId: OTHER_ROOT, subOrganizationId: SUB })),+ ForbiddenRequestError+ );+ });++ test("subOrganizationId without organizationId is refused", async () => {+ const { service } = build();+ await expectRejected(service.fnValidateJwtIdentity(accessToken({ subOrganizationId: SUB })), UnauthorizedError);+ });++ test("a token with no org claims stays valid and unscoped", async () => {+ const { service, orgDAL } = build();+ const identity = await service.fnValidateJwtIdentity(accessToken({}));+ expect(identity).toMatchObject({ orgId: "", rootOrgId: "" });+ expect(orgDAL.findOne).not.toHaveBeenCalled();+ });++ test("a token for an org that no longer exists is refused with 401, not a 500", async () => {+ const { service } = build();+ const err = await expectRejected(+ service.fnValidateJwtIdentity(accessToken({ organizationId: "deleted-org" })),+ UnauthorizedError+ );+ expect(err.message).toContain("deleted-org");+ });++ describe("validateRefreshTokenAccess", () => {+ test("allows an active, unlocked member", async () => {+ const { service } = build();+ await expect(+ service.validateRefreshTokenAccess(refreshToken({ organizationId: ROOT, subOrganizationId: SUB }))+ ).resolves.toBeUndefined();+ });++ test("refuses when the root membership is inactive", async () => {+ const { service } = build({ memberships: { [ROOT]: false, [SUB]: true } });+ await expectRejected(+ service.validateRefreshTokenAccess(refreshToken({ organizationId: ROOT, subOrganizationId: SUB })),+ ForbiddenRequestError+ );+ });++ test("refuses a permanently locked user, even without an org claim", async () => {+ const { service, orgDAL } = build({+ user: { id: USER_ID, isAccepted: true, isLocked: true, temporaryLockDateEnd: null }+ });+ const err = await expectRejected(service.validateRefreshTokenAccess(refreshToken({})), UnauthorizedError);+ expect(err.message).toBe("Account is locked");+ expect(orgDAL.findEffectiveOrgMembership).not.toHaveBeenCalled();+ });++ test("refuses a temporarily locked user until the lock expires", async () => {+ const lockedUntil = new Date(Date.now() + 60_000);+ const locked = build({+ user: { id: USER_ID, isAccepted: true, isLocked: false, temporaryLockDateEnd: lockedUntil }+ });+ await expectRejected(+ locked.service.validateRefreshTokenAccess(refreshToken({ organizationId: ROOT })),+ UnauthorizedError+ );++ const expired = build({+ user: { id: USER_ID, isAccepted: true, isLocked: false, temporaryLockDateEnd: new Date(Date.now() - 60_000) }+ });+ await expect(+ expired.service.validateRefreshTokenAccess(refreshToken({ organizationId: ROOT }))+ ).resolves.toBeUndefined();+ });++ // UnauthorizedError, not NotFoundError: the OAuth token endpoint maps NotFound to server_error.+ test("refuses a user who is not accepted with UnauthorizedError", async () => {+ const { service } = build({+ user: { id: USER_ID, isAccepted: false, isLocked: false, temporaryLockDateEnd: null }+ });+ await expectRejected(+ service.validateRefreshTokenAccess(refreshToken({ organizationId: ROOT })),+ UnauthorizedError+ );+ });++ test("refuses a refresh token scoped to an org that no longer exists with UnauthorizedError", async () => {+ const { service } = build();+ await expectRejected(+ service.validateRefreshTokenAccess(refreshToken({ organizationId: "deleted-org" })),+ UnauthorizedError+ );+ });+ });+});diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.tsindex 95bc04c6a1..636d8bd9ac 100644--- a/backend/src/services/auth-token/auth-token-service.ts+++ b/backend/src/services/auth-token/auth-token-service.ts@@ -1,6 +1,6 @@import { Knex } from "knex";-import { OrgMembershipStatus, TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";+import { OrgMembershipStatus, TAuthTokens, TAuthTokenSessions, TUsers } from "@app/db/schemas";import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto/cryptography";@@ -110,6 +110,9 @@ export const getTokenConfig = (tokenType: TokenType) => {}};+const isUserLocked = (user: Pick<TUsers, "isLocked" | "temporaryLockDateEnd">) =>+ Boolean(user.isLocked || (user.temporaryLockDateEnd && new Date() < user.temporaryLockDateEnd));+export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAuthTokenServiceFactoryDep) => {const createTokenForUser = async ({ type, userId, orgId, aliasId, payload }: TCreateTokenForUserDTO) => {const { token, ...tkCfg } = getTokenConfig(type);@@ -379,7 +382,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu);if (!user || !user.isAccepted) throw new NotFoundError({ message: `User with ID '${session.userId}' not found` });- if (user.isLocked || (user.temporaryLockDateEnd && new Date() < user.temporaryLockDateEnd)) {+ if (isUserLocked(user)) {throw new UnauthorizedError({ message: "Account is locked" });}@@ -419,6 +422,12 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAuif (!subOrganizationId) {const organization = await orgDAL.findOne({ id: organizationId });++ if (!organization) {+ throw new UnauthorizedError({+ message: `The organization with ID '${organizationId}' no longer exists. Log in again.`+ });+ }await assertActiveOrgMembership(userId, organizationId);return {@@ -462,6 +471,20 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAureturn { user, tokenVersionId: token.tokenVersionId, orgId, orgName, rootOrgId, parentOrgId };};+ const validateRefreshTokenAccess = async (decodedToken: AuthModeRefreshJwtTokenPayload) => {+ const user = await requestMemoize(requestMemoKeys.userFindById(decodedToken.userId), () =>+ userDAL.findById(decodedToken.userId)+ );+ if (!user || !user.isAccepted) throw new UnauthorizedError({ message: "Invalid token", name: "InvalidToken" });+ if (isUserLocked(user)) throw new UnauthorizedError({ message: "Account is locked" });++ await validateTokenOrgScope({+ userId: user.id,+ organizationId: decodedToken.organizationId,+ subOrganizationId: decodedToken.subOrganizationId+ });+ };+const createEmailSignupToken = async (emailHash: string): Promise<string> => {const appCfg = getConfig();const token = generateSixDigitToken();@@ -553,7 +576,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAuvalidateRefreshToken,rotateRefreshToken,validateUserSessionFreshness,- validateTokenOrgScope,+ validateRefreshTokenAccess,fnValidateJwtIdentity,getUserTokenSessionById,createEmailSignupToken,diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex 544f75c67c..6226feb8e7 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -61,6 +61,7 @@ type TOauthClientServiceFactoryDep = {| "getUserTokenSession"| "getUserTokenSessionById"| "validateRefreshToken"+ | "validateRefreshTokenAccess"| "rotateRefreshToken"| "revokeSessionsByUserAgent">;@@ -912,6 +913,8 @@ export const oauthClientServiceFactory = ({throw new UnauthorizedError({ message: "Invalid refresh token" });}+ await tokenService.validateRefreshTokenAccess(decodedToken);+const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(client,decodedToken.organizationId