mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-07 11:27:32 +00:00
Fix case where user can get stuck in a deleted organization if they were prev logged into it
This commit is contained in:
Generated
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
"@fastify/etag": "^5.1.0",
|
"@fastify/etag": "^5.1.0",
|
||||||
"@fastify/formbody": "^7.4.0",
|
"@fastify/formbody": "^7.4.0",
|
||||||
"@fastify/helmet": "^11.1.1",
|
"@fastify/helmet": "^11.1.1",
|
||||||
"@fastify/multipart": "8.3.1",
|
"@fastify/multipart": "^8.3.1",
|
||||||
"@fastify/passport": "^2.4.0",
|
"@fastify/passport": "^2.4.0",
|
||||||
"@fastify/rate-limit": "^9.0.0",
|
"@fastify/rate-limit": "^9.0.0",
|
||||||
"@fastify/request-context": "^5.1.0",
|
"@fastify/request-context": "^5.1.0",
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { getConfig } from "@app/lib/config/env";
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { NotFoundError, UnauthorizedError } from "@app/lib/errors";
|
|
||||||
import { authRateLimit, writeLimit } from "@app/server/config/rateLimiter";
|
import { authRateLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
import { AuthMode, AuthModeRefreshJwtTokenPayload, AuthTokenType } from "@app/services/auth/auth-type";
|
import { AuthMode, AuthTokenType } from "@app/services/auth/auth-type";
|
||||||
|
|
||||||
export const registerAuthRoutes = async (server: FastifyZodProvider) => {
|
export const registerAuthRoutes = async (server: FastifyZodProvider) => {
|
||||||
server.route({
|
server.route({
|
||||||
@@ -21,18 +19,19 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
|
|
||||||
handler: async (req, res) => {
|
handler: async (req, res) => {
|
||||||
|
const { decodedToken } = await server.services.authToken.validateRefreshToken(req.cookies.jid);
|
||||||
const appCfg = getConfig();
|
const appCfg = getConfig();
|
||||||
if (req.auth.authMode === AuthMode.JWT) {
|
|
||||||
await server.services.login.logout(req.permission.id, req.auth.tokenVersionId);
|
await server.services.login.logout(decodedToken.userId, decodedToken.tokenVersionId);
|
||||||
}
|
|
||||||
void res.cookie("jid", "", {
|
void res.cookie("jid", "", {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
path: "/",
|
path: "/",
|
||||||
sameSite: "strict",
|
sameSite: "strict",
|
||||||
secure: appCfg.HTTPS_ENABLED
|
secure: appCfg.HTTPS_ENABLED
|
||||||
});
|
});
|
||||||
|
|
||||||
return { message: "Successfully logged out" };
|
return { message: "Successfully logged out" };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -69,37 +68,8 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
handler: async (req) => {
|
handler: async (req) => {
|
||||||
const refreshToken = req.cookies.jid;
|
const { decodedToken, tokenVersion } = await server.services.authToken.validateRefreshToken(req.cookies.jid);
|
||||||
const appCfg = getConfig();
|
const appCfg = getConfig();
|
||||||
if (!refreshToken)
|
|
||||||
throw new NotFoundError({
|
|
||||||
name: "AuthTokenNotFound",
|
|
||||||
message: "Failed to find refresh token"
|
|
||||||
});
|
|
||||||
|
|
||||||
const decodedToken = jwt.verify(refreshToken, appCfg.AUTH_SECRET) as AuthModeRefreshJwtTokenPayload;
|
|
||||||
if (decodedToken.authTokenType !== AuthTokenType.REFRESH_TOKEN)
|
|
||||||
throw new UnauthorizedError({
|
|
||||||
message: "The token provided is not a refresh token",
|
|
||||||
name: "InvalidToken"
|
|
||||||
});
|
|
||||||
|
|
||||||
const tokenVersion = await server.services.authToken.getUserTokenSessionById(
|
|
||||||
decodedToken.tokenVersionId,
|
|
||||||
decodedToken.userId
|
|
||||||
);
|
|
||||||
if (!tokenVersion)
|
|
||||||
throw new UnauthorizedError({
|
|
||||||
message: "Valid token version not found",
|
|
||||||
name: "InvalidToken"
|
|
||||||
});
|
|
||||||
|
|
||||||
if (decodedToken.refreshVersion !== tokenVersion.refreshVersion) {
|
|
||||||
throw new UnauthorizedError({
|
|
||||||
message: "Token version mismatch",
|
|
||||||
name: "InvalidToken"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = jwt.sign(
|
const token = jwt.sign(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
|
import jwt from "jsonwebtoken";
|
||||||
|
|
||||||
import bcrypt from "bcrypt";
|
import bcrypt from "bcrypt";
|
||||||
import { Knex } from "knex";
|
import { Knex } from "knex";
|
||||||
@@ -8,7 +9,7 @@ import { getConfig } from "@app/lib/config/env";
|
|||||||
import { ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
|
import { ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
|
||||||
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
|
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
|
||||||
|
|
||||||
import { AuthModeJwtTokenPayload } from "../auth/auth-type";
|
import { AuthModeJwtTokenPayload, AuthModeRefreshJwtTokenPayload, AuthTokenType } from "../auth/auth-type";
|
||||||
import { TUserDALFactory } from "../user/user-dal";
|
import { TUserDALFactory } from "../user/user-dal";
|
||||||
import { TTokenDALFactory } from "./auth-token-dal";
|
import { TTokenDALFactory } from "./auth-token-dal";
|
||||||
import { TCreateTokenForUserDTO, TIssueAuthTokenDTO, TokenType, TValidateTokenForUserDTO } from "./auth-token-types";
|
import { TCreateTokenForUserDTO, TIssueAuthTokenDTO, TokenType, TValidateTokenForUserDTO } from "./auth-token-types";
|
||||||
@@ -100,6 +101,40 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgMembershipDAL }: TAu
|
|||||||
return token;
|
return token;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const validateRefreshToken = async (refreshToken?: string) => {
|
||||||
|
const appCfg = getConfig();
|
||||||
|
if (!refreshToken)
|
||||||
|
throw new NotFoundError({
|
||||||
|
name: "AuthTokenNotFound",
|
||||||
|
message: "Failed to find refresh token"
|
||||||
|
});
|
||||||
|
|
||||||
|
const decodedToken = jwt.verify(refreshToken, appCfg.AUTH_SECRET) as AuthModeRefreshJwtTokenPayload;
|
||||||
|
|
||||||
|
if (decodedToken.authTokenType !== AuthTokenType.REFRESH_TOKEN)
|
||||||
|
throw new UnauthorizedError({
|
||||||
|
message: "The token provided is not a refresh token",
|
||||||
|
name: "InvalidToken"
|
||||||
|
});
|
||||||
|
|
||||||
|
const tokenVersion = await getUserTokenSessionById(decodedToken.tokenVersionId, decodedToken.userId);
|
||||||
|
|
||||||
|
if (!tokenVersion)
|
||||||
|
throw new UnauthorizedError({
|
||||||
|
message: "Valid token version not found",
|
||||||
|
name: "InvalidToken"
|
||||||
|
});
|
||||||
|
|
||||||
|
if (decodedToken.refreshVersion !== tokenVersion.refreshVersion) {
|
||||||
|
throw new UnauthorizedError({
|
||||||
|
message: "Token version mismatch",
|
||||||
|
name: "InvalidToken"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { decodedToken, tokenVersion };
|
||||||
|
};
|
||||||
|
|
||||||
const validateTokenForUser = async ({
|
const validateTokenForUser = async ({
|
||||||
type,
|
type,
|
||||||
userId,
|
userId,
|
||||||
@@ -183,6 +218,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgMembershipDAL }: TAu
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
createTokenForUser,
|
createTokenForUser,
|
||||||
|
validateRefreshToken,
|
||||||
validateTokenForUser,
|
validateTokenForUser,
|
||||||
getUserTokenSession,
|
getUserTokenSession,
|
||||||
clearTokenSessionById,
|
clearTokenSessionById,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import jwt from "jsonwebtoken";
|
|||||||
|
|
||||||
import { getConfig } from "@app/lib/config/env";
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";
|
import { ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";
|
||||||
|
|
||||||
import { AuthModeProviderJwtTokenPayload, AuthModeProviderSignUpTokenPayload, AuthTokenType } from "./auth-type";
|
import { AuthModeProviderJwtTokenPayload, AuthModeProviderSignUpTokenPayload, AuthTokenType } from "./auth-type";
|
||||||
|
|
||||||
export const validateProviderAuthToken = (providerToken: string, username?: string) => {
|
export const validateProviderAuthToken = (providerToken: string, username?: string) => {
|
||||||
|
|||||||
@@ -24,10 +24,10 @@ import {
|
|||||||
User,
|
User,
|
||||||
UserEnc
|
UserEnc
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
import { queryClient } from "@app/hooks/api/reactQuery";
|
||||||
|
|
||||||
export const fetchUserDetails = async () => {
|
export const fetchUserDetails = async () => {
|
||||||
const { data } = await apiRequest.get<{ user: User & UserEnc }>("/api/v1/user");
|
const { data } = await apiRequest.get<{ user: User & UserEnc }>("/api/v1/user");
|
||||||
|
|
||||||
return data.user;
|
return data.user;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -278,30 +278,33 @@ export const useRegisterUserAction = () => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useLogoutUser = (keepQueryClient?: boolean) => {
|
export const logoutUser = async () => {
|
||||||
const queryClient = useQueryClient();
|
await apiRequest.post("/api/v1/auth/logout");
|
||||||
return useMutation({
|
};
|
||||||
mutationFn: async () => {
|
|
||||||
await apiRequest.post("/api/v1/auth/logout");
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
setAuthToken("");
|
|
||||||
// Delete the cookie by not setting a value; Alternatively clear the local storage
|
|
||||||
localStorage.removeItem("protectedKey");
|
|
||||||
localStorage.removeItem("protectedKeyIV");
|
|
||||||
localStorage.removeItem("protectedKeyTag");
|
|
||||||
localStorage.removeItem("publicKey");
|
|
||||||
localStorage.removeItem("encryptedPrivateKey");
|
|
||||||
localStorage.removeItem("iv");
|
|
||||||
localStorage.removeItem("tag");
|
|
||||||
localStorage.removeItem("PRIVATE_KEY");
|
|
||||||
localStorage.removeItem("orgData.id");
|
|
||||||
sessionStorage.removeItem(SessionStorageKeys.CLI_TERMINAL_TOKEN);
|
|
||||||
|
|
||||||
if (!keepQueryClient) {
|
// Utility function to clear session storage and query cache
|
||||||
queryClient.clear();
|
export const clearSession = (keepQueryClient?: boolean) => {
|
||||||
}
|
setAuthToken(""); // Clear authentication token
|
||||||
}
|
localStorage.removeItem("protectedKey");
|
||||||
|
localStorage.removeItem("protectedKeyIV");
|
||||||
|
localStorage.removeItem("protectedKeyTag");
|
||||||
|
localStorage.removeItem("publicKey");
|
||||||
|
localStorage.removeItem("encryptedPrivateKey");
|
||||||
|
localStorage.removeItem("iv");
|
||||||
|
localStorage.removeItem("tag");
|
||||||
|
localStorage.removeItem("PRIVATE_KEY");
|
||||||
|
localStorage.removeItem("orgData.id");
|
||||||
|
sessionStorage.removeItem(SessionStorageKeys.CLI_TERMINAL_TOKEN);
|
||||||
|
|
||||||
|
if (!keepQueryClient) {
|
||||||
|
queryClient.clear(); // Clear React Query cache
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useLogoutUser = (keepQueryClient?: boolean) => {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: logoutUser,
|
||||||
|
onSuccess: () => clearSession(keepQueryClient)
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ export const LoginPage = () => {
|
|||||||
console.log("Error - Not logged in yet");
|
console.log("Error - Not logged in yet");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isLoggedIn()) {
|
if (isLoggedIn()) {
|
||||||
handleRedirects();
|
handleRedirects();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -250,20 +250,24 @@ export const SignupInvitePage = () => {
|
|||||||
setStep(2);
|
setStep(2);
|
||||||
} else {
|
} else {
|
||||||
const redirectExistingUser = async () => {
|
const redirectExistingUser = async () => {
|
||||||
const { token: mfaToken, isMfaEnabled } = await selectOrganization({
|
try {
|
||||||
organizationId
|
const { token: mfaToken, isMfaEnabled } = await selectOrganization({
|
||||||
});
|
organizationId
|
||||||
|
});
|
||||||
|
|
||||||
if (isMfaEnabled) {
|
if (isMfaEnabled) {
|
||||||
SecurityClient.setMfaToken(mfaToken);
|
SecurityClient.setMfaToken(mfaToken);
|
||||||
toggleShowMfa.on();
|
toggleShowMfa.on();
|
||||||
setMfaSuccessCallback(() => redirectExistingUser);
|
setMfaSuccessCallback(() => redirectExistingUser);
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// user will be redirected to dashboard
|
||||||
|
// if not logged in gets kicked out to login
|
||||||
|
await navigateUserToOrg(navigate, organizationId);
|
||||||
|
} catch (err) {
|
||||||
|
navigate({ to: "/login" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// user will be redirected to dashboard
|
|
||||||
// if not logged in gets kicked out to login
|
|
||||||
await navigateUserToOrg(navigate, organizationId);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await redirectExistingUser();
|
await redirectExistingUser();
|
||||||
|
|||||||
@@ -5,12 +5,15 @@ import { ROUTE_PATHS } from "@app/const/routes";
|
|||||||
import { userKeys } from "@app/hooks/api";
|
import { userKeys } from "@app/hooks/api";
|
||||||
import { authKeys, fetchAuthToken } from "@app/hooks/api/auth/queries";
|
import { authKeys, fetchAuthToken } from "@app/hooks/api/auth/queries";
|
||||||
import { fetchUserDetails } from "@app/hooks/api/users/queries";
|
import { fetchUserDetails } from "@app/hooks/api/users/queries";
|
||||||
|
import { AxiosError } from "axios";
|
||||||
|
import { clearSession, logoutUser } from "@app/hooks/api/users/queries";
|
||||||
|
|
||||||
export const Route = createFileRoute("/_authenticate")({
|
export const Route = createFileRoute("/_authenticate")({
|
||||||
beforeLoad: async ({ context, location }) => {
|
beforeLoad: async ({ context, location }) => {
|
||||||
if (!context.serverConfig.initialized) {
|
if (!context.serverConfig.initialized) {
|
||||||
throw redirect({ to: "/admin/signup" });
|
throw redirect({ to: "/admin/signup" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await context.queryClient
|
const data = await context.queryClient
|
||||||
.ensureQueryData({
|
.ensureQueryData({
|
||||||
queryKey: authKeys.getAuthToken,
|
queryKey: authKeys.getAuthToken,
|
||||||
@@ -27,14 +30,31 @@ export const Route = createFileRoute("/_authenticate")({
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!data.organizationId && location.pathname !== ROUTE_PATHS.Auth.PasswordSetupPage.path && location.pathname !== "/organization/none") {
|
if (
|
||||||
|
!data.organizationId &&
|
||||||
|
location.pathname !== ROUTE_PATHS.Auth.PasswordSetupPage.path &&
|
||||||
|
location.pathname !== "/organization/none"
|
||||||
|
) {
|
||||||
throw redirect({ to: "/login/select-organization" });
|
throw redirect({ to: "/login/select-organization" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await context.queryClient.ensureQueryData({
|
const user = await context.queryClient
|
||||||
queryKey: userKeys.getUser,
|
.ensureQueryData({
|
||||||
queryFn: fetchUserDetails
|
queryKey: userKeys.getUser,
|
||||||
});
|
queryFn: fetchUserDetails
|
||||||
|
})
|
||||||
|
.catch(async (error) => {
|
||||||
|
const err = error as AxiosError;
|
||||||
|
if (err.response?.status === 403) {
|
||||||
|
// (dangtony98): this edge-case can occur if the user's token corresponds to an organization
|
||||||
|
// that has been deleted for which we must clear the refresh token in http-only cookie
|
||||||
|
clearSession(true);
|
||||||
|
await logoutUser();
|
||||||
|
throw redirect({
|
||||||
|
to: "/login"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return { organizationId: data.organizationId as string, isAuthenticated: true, user };
|
return { organizationId: data.organizationId as string, isAuthenticated: true, user };
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user