Skip to content

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

feat: review changes

=75737b493a42
diff --git a/backend/src/server/routes/v1/auth-router.ts b/backend/src/server/routes/v1/auth-router.ts
index a9092a90f8..3477a55d59 100644
--- a/backend/src/server/routes/v1/auth-router.ts
+++ b/backend/src/server/routes/v1/auth-router.ts
@@ -121,13 +121,11 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
}
let newRefreshToken: string | undefined;
- let sessionForAccessToken = tokenVersion;
if (!isGraceHit) {
// Normal rotation: issue new refresh token and invalidate the old one
const rotation = await server.services.authToken.rotateRefreshToken(decodedToken, tokenVersion);
newRefreshToken = rotation.newRefreshToken;
- sessionForAccessToken = rotation.updatedSession;
}
let expiresIn: string | number = appCfg.JWT_AUTH_LIFETIME;
@@ -150,8 +148,8 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
authMethod: decodedToken.authMethod,
authTokenType: AuthTokenType.ACCESS_TOKEN,
userId: decodedToken.userId,
- tokenVersionId: sessionForAccessToken.id,
- accessVersion: sessionForAccessToken.accessVersion,
+ tokenVersionId: tokenVersion.id,
+ accessVersion: tokenVersion.accessVersion,
organizationId: decodedToken.organizationId,
...(decodedToken.subOrganizationId && { subOrganizationId: decodedToken.subOrganizationId }),
isMfaVerified: decodedToken.isMfaVerified,
diff --git a/backend/src/services/auth-token/auth-token-dal.ts b/backend/src/services/auth-token/auth-token-dal.ts
index 968bf9ad8b..65b5fba827 100644
--- a/backend/src/services/auth-token/auth-token-dal.ts
+++ b/backend/src/services/auth-token/auth-token-dal.ts
@@ -100,13 +100,13 @@ export const tokenDALFactory = (db: TDbClient) => {
sessionId: string,
userId: string,
tx?: Knex
- ): Promise<TAuthTokenSessions | undefined> => {
+ ): Promise<{ refreshVersion: number; id: string } | undefined> => {
try {
const [session] = await (tx || db)(TableName.AuthTokenSession)
.where({ id: sessionId, userId })
.increment("refreshVersion", 1)
.update({ lastUsed: new Date() })
- .returning("*");
+ .returning(["refreshVersion", "id"]);
return session;
} catch (error) {
throw new DatabaseError({ error, name: "IncrementRefreshVersion" });
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index 37c91f3987..a99cc7624f 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -12,6 +12,7 @@ import { TOrgDALFactory } from "../org/org-dal";
import { TUserDALFactory } from "../user/user-dal";
import { TTokenDALFactory } from "./auth-token-dal";
import { TCreateTokenForUserDTO, TIssueAuthTokenDTO, TokenType, TValidateTokenForUserDTO } from "./auth-token-types";
+import { logger } from "@app/lib/logger";
type TAuthTokenServiceFactoryDep = {
tokenDAL: TTokenDALFactory;
@@ -138,11 +139,11 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
const isValidToken = await crypto.hashing().compareHash(code, hashToCompare);
// Now perform the logical checks *after* the constant-time work is done.
- if (!token) throw new Error("Failed to find token");
+ if (!token) throw new Error("Invalid token");
- if (token.expiresAt && new Date(token.expiresAt) < new Date()) {
+ if (!token.expiresAt || new Date(token.expiresAt) < new Date()) {
await tokenDAL.delete({ type, userId, orgId });
- throw new Error("Token expired. Please try again");
+ throw new Error("Invalid token");
}
if (!isValidToken) {
@@ -188,7 +189,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
if (!refreshToken)
throw new NotFoundError({
name: "AuthTokenNotFound",
- message: "Failed to find refresh token"
+ message: "Invalid token"
});
const decodedToken = crypto.jwt().verify(refreshToken, appCfg.AUTH_SECRET) as AuthModeRefreshJwtTokenPayload;
@@ -203,7 +204,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
if (!tokenVersion)
throw new UnauthorizedError({
- message: "Valid token version not found",
+ message: "Invalid token",
name: "InvalidToken"
});
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index ff40f4e13f..62013d1bfb 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -28,6 +28,8 @@ type TAuthSignupDep = {
loginService: Pick<TAuthLoginFactory, "generateUserTokens">;
};
+const DUMMY_USER_ID = "00000000-0000-0000-0000-000000000000";
+
export type TAuthSignupFactory = ReturnType<typeof authSignupServiceFactory>;
export const authSignupServiceFactory = ({
authDAL,
@@ -100,7 +102,6 @@ export const authSignupServiceFactory = ({
// Always call validateTokenForUser so the response time includes
// the bcrypt cost regardless of whether the user exists.
// Use a dummy userId when there's no valid user.
- const DUMMY_USER_ID = "00000000-0000-0000-0000-000000000000";
const shouldReject = !user || user.isAccepted;
try {
@@ -145,14 +146,13 @@ export const authSignupServiceFactory = ({
*/
const completeAccount = async (dto: TCompleteAccountDTO) => {
const appCfg = getConfig();
- const DUMMY_USER_ID = "00000000-0000-0000-0000-000000000000";
// Step 1: Extract and validate the signup token
const tokenValue = extractBearerToken(dto.authorization);
const decodedToken = crypto.jwt().verify(tokenValue, appCfg.AUTH_SECRET) as AuthModeSignUpTokenPayload;
if (decodedToken.authTokenType !== AuthTokenType.SIGNUP_TOKEN) {
- throw new UnauthorizedError({ message: "Invalid token type" });
+ throw new UnauthorizedError({ message: "Invalid token" });
}
// Step 2: Find the user
@@ -172,7 +172,7 @@ export const authSignupServiceFactory = ({
const hashedPassword = await crypto.hashing().createHash(dto.password, appCfg.SALT_ROUNDS);
if (shouldReject) {
- throw new BadRequestError({ message: "Invalid or expired verification code" });
+ throw new BadRequestError({ message: "Invalid token" });
}
const updatedUser = await authDAL.transaction(async (tx) => {
@@ -210,12 +210,13 @@ export const authSignupServiceFactory = ({
authMethod = AuthMethod.EMAIL;
} else {
// Alias verification
- const userAlias = decodedToken.aliasId
- ? await userAliasDAL.findOne({
- id: decodedToken.aliasId,
- userId: user?.id ?? DUMMY_USER_ID
- })
- : null;
+ const userAlias =
+ decodedToken.aliasId && user?.id
+ ? await userAliasDAL.findOne({
+ id: decodedToken.aliasId,
+ userId: user?.id
+ })
+ : null;
// Determine rejection before token validation, but don't throw yet
const shouldReject = !user || !decodedToken.aliasId || !userAlias;
@@ -229,11 +230,11 @@ export const authSignupServiceFactory = ({
code: dto.code
});
} catch {
- throw new BadRequestError({ message: "Invalid or expired verification code" });
+ throw new BadRequestError({ message: "Invalid token" });
}
if (shouldReject) {
- throw new BadRequestError({ message: "Invalid or expired verification code" });
+ throw new BadRequestError({ message: "Invalid token" });
}
// Mark alias as verified
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 29dad6dfc4..3951d41482 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -4,6 +4,7 @@ import { Knex } from "knex";
import { AccessScope, OrganizationActionScope } from "@app/db/schemas";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -58,7 +59,9 @@ export const userServiceFactory = ({
userAliasDAL
}: TUserServiceFactoryDep) => {
const sendEmailVerificationCode = async (token: string) => {
- const { authType, aliasId, username, authTokenType } = crypto.jwt().decode(token) as {
+ const config = getConfig();
+
+ const { authType, aliasId, username, authTokenType } = crypto.jwt().verify(token, config.AUTH_SECRET) as {
authType: string;
aliasId?: string;
username: string;
@@ -67,7 +70,7 @@ export const userServiceFactory = ({
if (authTokenType !== AuthTokenType.SIGNUP_TOKEN) throw new BadRequestError({ name: "Invalid auth token type" });
const user = await userDAL.findOne({ username });
- if (!user) throw new NotFoundError({ name: `User with username '${username}' not found` });
+ if (!user) throw new BadRequestError({ message: "Invalid token" });
let { isEmailVerified } = user;
if (aliasId) {
@@ -76,10 +79,8 @@ export const userServiceFactory = ({
isEmailVerified = userAlias.isEmailVerified;
}
- if (!user.email)
- throw new BadRequestError({ name: "Failed to send email verification code due to no email on user" });
- if (isEmailVerified)
- throw new BadRequestError({ name: "Failed to send email verification code due to email already verified" });
+ if (!user.email) throw new BadRequestError({ message: "Invalid token" });
+ if (isEmailVerified) throw new BadRequestError({ name: "Invalid token" });
const userToken = await tokenService.createTokenForUser({
type: TokenType.TOKEN_EMAIL_VERIFICATION,
@@ -219,14 +220,11 @@ export const userServiceFactory = ({
}: TUpdateUserEmailDTO & { otpCode: string }) => {
const newEmail = sanitizeEmail(unsanitizedEmail);
validateEmail(newEmail);
+
const changedUser = await userDAL.transaction(async (tx) => {
const user = await userDAL.findById(userId, tx);
if (!user) throw new NotFoundError({ message: `User with ID '${userId}' not found`, name: "UpdateUserEmail" });
- if (user.authMethods?.includes(AuthMethod.LDAP)) {
- throw new BadRequestError({ message: "Cannot update email for LDAP users", name: "UpdateUserEmail" });
- }
-
const hasScimRestriction = await checkUserScimRestriction(userId, tx);
if (hasScimRestriction) {
throw new BadRequestError({