Skip to content

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

misc: address self-review

Sheen Capadngan15e5398c4cd3
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index a84371659a..92d2bf799a 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -9,21 +9,19 @@ import {
ProjectPermissionPamAccountActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
-import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
-import { crypto } from "@app/lib/crypto";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType, MfaMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
-import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
-import { MfaSessionStatus, TMfaSession } from "@app/services/mfa-session/mfa-session-types";
+import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
+import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
+import { TSmtpService } from "@app/services/smtp/smtp-service";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";
@@ -48,6 +46,7 @@ type TPamAccountServiceFactoryDep = {
pamSessionDAL: TPamSessionDALFactory;
pamAccountDAL: TPamAccountDALFactory;
pamFolderDAL: TPamFolderDALFactory;
+ mfaSessionService: TMfaSessionServiceFactory;
projectDAL: TProjectDALFactory;
orgDAL: TOrgDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
@@ -59,7 +58,6 @@ type TPamAccountServiceFactoryDep = {
>;
userDAL: TUserDALFactory;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "deleteItem">;
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser" | "validateTokenForUser">;
smtpService: Pick<TSmtpService, "sendMail">;
};
@@ -71,6 +69,7 @@ export const pamAccountServiceFactory = ({
pamResourceDAL,
pamSessionDAL,
pamAccountDAL,
+ mfaSessionService,
pamFolderDAL,
projectDAL,
orgDAL,
@@ -79,47 +78,8 @@ export const pamAccountServiceFactory = ({
licenseService,
kmsService,
gatewayV2Service,
- auditLogService,
- keyStore,
- tokenService,
- smtpService
+ auditLogService
}: TPamAccountServiceFactoryDep) => {
- const createMfaSession = async (userId: string, accountId: string, mfaMethod: MfaMethod): Promise<string> => {
- const mfaSessionId = crypto.randomBytes(32).toString("hex");
- const mfaSession: TMfaSession = {
- sessionId: mfaSessionId,
- userId,
- resourceId: accountId,
- status: MfaSessionStatus.PENDING,
- mfaMethod
- };
-
- await keyStore.setItemWithExpiry(
- KeyStorePrefixes.MfaSession(mfaSessionId),
- KeyStoreTtls.MfaSessionInSeconds,
- JSON.stringify(mfaSession)
- );
-
- return mfaSessionId;
- };
-
- // Helper function to send MFA code via email
- const sendMfaCode = async (userId: string, email: string) => {
- const code = await tokenService.createTokenForUser({
- type: TokenType.TOKEN_EMAIL_MFA,
- userId
- });
-
- await smtpService.sendMail({
- template: SmtpTemplates.EmailMfa,
- subjectLine: "Infisical PAM Access MFA code",
- recipients: [email],
- substitutions: {
- code
- }
- });
- };
-
const create = async (
{
credentials,
@@ -595,8 +555,6 @@ export const pamAccountServiceFactory = ({
})
);
- // MFA is required for all PAM account access (as per user requirement)
- // Get user to check MFA configuration
const actorUser = await userDAL.findById(actor.id);
if (!actorUser) throw new NotFoundError({ message: `User with ID '${actor.id}' not found` });
@@ -617,11 +575,11 @@ export const pamAccountServiceFactory = ({
const mfaMethod = (orgMfaMethod ?? userMfaMethod ?? MfaMethod.EMAIL) as MfaMethod;
// Create MFA session
- const newMfaSessionId = await createMfaSession(actorUser.id, accountId, mfaMethod);
+ const newMfaSessionId = await mfaSessionService.createMfaSession(actorUser.id, accountId, mfaMethod);
// If MFA method is email, send the code immediately
if (mfaMethod === MfaMethod.EMAIL && actorUser.email) {
- await sendMfaCode(actorUser.id, actorUser.email);
+ await mfaSessionService.sendMfaCode(actorUser.id, actorUser.email);
}
// Throw an error with the mfaSessionId to signal that MFA is required
@@ -636,21 +594,16 @@ export const pamAccountServiceFactory = ({
}
if (mfaSessionId && account.requireMfa) {
- // If mfaSessionId is provided, verify it
- const mfaSessionKey = KeyStorePrefixes.MfaSession(mfaSessionId);
- const mfaSessionData = await keyStore.getItem(mfaSessionKey);
-
- if (!mfaSessionData) {
+ const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
+ if (!mfaSession) {
throw new BadRequestError({
message: "MFA session not found or expired"
});
}
- const mfaSession = JSON.parse(mfaSessionData) as TMfaSession;
-
// Verify the session belongs to the current user
if (mfaSession.userId !== actor.id) {
- throw new ForbiddenRequestError({
+ throw new BadRequestError({
message: "MFA session does not belong to current user"
});
}
@@ -670,7 +623,7 @@ export const pamAccountServiceFactory = ({
}
// MFA verified successfully, delete the session and proceed with access
- await keyStore.deleteItem(mfaSessionKey);
+ await mfaSessionService.deleteMfaSession(mfaSessionId);
}
const session = await pamSessionDAL.create({
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index e1a74078a0..5995fe9bce 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2391,7 +2391,7 @@ export const registerRoutes = async (
orgDAL,
userDAL,
auditLogService,
- keyStore,
+ mfaSessionService,
tokenService,
smtpService
});
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index 9be6cbe4d2..28344c0e22 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -444,13 +444,13 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
server.route({
method: "PATCH",
- url: "/me/webauthn/:credentialId",
+ url: "/me/webauthn/:id",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- credentialId: z.string()
+ id: z.string()
}),
body: z.object({
name: z.string().optional()
@@ -467,7 +467,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
return server.services.webAuthn.updateWebAuthnCredential({
userId: req.permission.id,
- credentialId: req.params.credentialId,
+ id: req.params.id,
name: req.body.name
});
}
@@ -475,13 +475,13 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
server.route({
method: "DELETE",
- url: "/me/webauthn/:credentialId",
+ url: "/me/webauthn/:id",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- credentialId: z.string()
+ id: z.string()
}),
response: {
200: z.object({
@@ -493,7 +493,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
await server.services.webAuthn.deleteWebAuthnCredential({
userId: req.permission.id,
- credentialId: req.params.credentialId
+ id: req.params.id
});
return { success: true };
}
diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.ts
index c255b88a84..7b58426aee 100644
--- a/backend/src/services/mfa-session/mfa-session-service.ts
+++ b/backend/src/services/mfa-session/mfa-session-service.ts
@@ -1,4 +1,5 @@
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { MfaMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
@@ -134,9 +135,35 @@ export const mfaSessionServiceFactory = ({
};
};
+ const createMfaSession = async (userId: string, resourceId: string, mfaMethod: MfaMethod): Promise<string> => {
+ const mfaSessionId = crypto.randomBytes(32).toString("hex");
+ const mfaSession: TMfaSession = {
+ sessionId: mfaSessionId,
+ userId,
+ resourceId,
+ status: MfaSessionStatus.PENDING,
+ mfaMethod
+ };
+
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.MfaSession(mfaSessionId),
+ KeyStoreTtls.MfaSessionInSeconds,
+ JSON.stringify(mfaSession)
+ );
+
+ return mfaSessionId;
+ };
+
+ const deleteMfaSession = async (mfaSessionId: string) => {
+ await keyStore.deleteItem(KeyStorePrefixes.MfaSession(mfaSessionId));
+ };
+
return {
+ createMfaSession,
verifyMfaSession,
getMfaSessionStatus,
- sendMfaCode
+ sendMfaCode,
+ getMfaSession,
+ deleteMfaSession
};
};
diff --git a/backend/src/services/webauthn/webauthn-fns.ts b/backend/src/services/webauthn/webauthn-fns.ts
index f3c364b146..b563b79131 100644
--- a/backend/src/services/webauthn/webauthn-fns.ts
+++ b/backend/src/services/webauthn/webauthn-fns.ts
@@ -1,7 +1,3 @@
-/**
- * Helper functions for WebAuthn operations
- */
-
/**
* Verify that a credential ID belongs to a user
*/
diff --git a/backend/src/services/webauthn/webauthn-service.ts b/backend/src/services/webauthn/webauthn-service.ts
index 6b204149bf..49dd99ad2c 100644
--- a/backend/src/services/webauthn/webauthn-service.ts
+++ b/backend/src/services/webauthn/webauthn-service.ts
@@ -324,8 +324,8 @@ export const webAuthnServiceFactory = ({
/**
* Delete a WebAuthn credential
*/
- const deleteWebAuthnCredential = async ({ userId, credentialId }: TDeleteWebAuthnCredentialDTO) => {
- const credential = await webAuthnCredentialDAL.findOne({ credentialId });
+ const deleteWebAuthnCredential = async ({ userId, id }: TDeleteWebAuthnCredentialDTO) => {
+ const credential = await webAuthnCredentialDAL.findById(id);
if (!credential) {
throw new NotFoundError({
@@ -349,8 +349,8 @@ export const webAuthnServiceFactory = ({
/**
* Update a WebAuthn credential (e.g., rename it)
*/
- const updateWebAuthnCredential = async ({ userId, credentialId, name }: TUpdateWebAuthnCredentialDTO) => {
- const credential = await webAuthnCredentialDAL.findOne({ credentialId });
+ const updateWebAuthnCredential = async ({ userId, id, name }: TUpdateWebAuthnCredentialDTO) => {
+ const credential = await webAuthnCredentialDAL.findById(id);
if (!credential) {
throw new NotFoundError({
diff --git a/backend/src/services/webauthn/webauthn-types.ts b/backend/src/services/webauthn/webauthn-types.ts
index aacd4eaa35..28aa5ac44a 100644
--- a/backend/src/services/webauthn/webauthn-types.ts
+++ b/backend/src/services/webauthn/webauthn-types.ts
@@ -25,11 +25,11 @@ export type TGetUserWebAuthnCredentialsDTO = {
export type TDeleteWebAuthnCredentialDTO = {
userId: string;
- credentialId: string;
+ id: string;
};
export type TUpdateWebAuthnCredentialDTO = {
userId: string;
- credentialId: string;
+ id: string;
name?: string;
};
diff --git a/frontend/src/hooks/api/webauthn/mutations.tsx b/frontend/src/hooks/api/webauthn/mutations.tsx
index 79b379ae00..3477c35060 100644
--- a/frontend/src/hooks/api/webauthn/mutations.tsx
+++ b/frontend/src/hooks/api/webauthn/mutations.tsx
@@ -65,9 +65,9 @@ export const useDeleteWebAuthnCredential = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ credentialId }: TDeleteWebAuthnCredentialDTO) => {
+ mutationFn: async ({ id }: TDeleteWebAuthnCredentialDTO) => {
const { data } = await apiRequest.delete<{ success: boolean }>(
- `/api/v1/user/me/webauthn/${credentialId}`
+ `/api/v1/user/me/webauthn/${id}`
);
return data;
},
@@ -81,12 +81,12 @@ export const useUpdateWebAuthnCredential = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ credentialId, name }: TUpdateWebAuthnCredentialDTO) => {
+ mutationFn: async ({ id, name }: TUpdateWebAuthnCredentialDTO) => {
const { data } = await apiRequest.patch<{
id: string;
credentialId: string;
name?: string | null;
- }>(`/api/v1/user/me/webauthn/${credentialId}`, { name });
+ }>(`/api/v1/user/me/webauthn/${id}`, { name });
return data;
},
onSuccess: () => {
diff --git a/frontend/src/hooks/api/webauthn/types.ts b/frontend/src/hooks/api/webauthn/types.ts
index 76da73909c..a19710ac4c 100644
--- a/frontend/src/hooks/api/webauthn/types.ts
+++ b/frontend/src/hooks/api/webauthn/types.ts
@@ -28,10 +28,10 @@ export type TVerifyAuthenticationDTO = {
};
export type TUpdateWebAuthnCredentialDTO = {
- credentialId: string;
+ id: string;
name?: string;
};
export type TDeleteWebAuthnCredentialDTO = {
- credentialId: string;
+ id: string;
};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
index ef4fbe9551..04a6e74f29 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
@@ -202,7 +202,7 @@ export const MFASection = () => {
const handleDeleteWebAuthnCredential = async () => {
try {
- await deleteWebAuthnCredential({ credentialId: selectedCredentialId });
+ await deleteWebAuthnCredential({ id: selectedCredentialId });
createNotification({
text: "Successfully deleted passkey",
@@ -222,7 +222,7 @@ export const MFASection = () => {
const handleRenameWebAuthnCredential = async () => {
try {
await updateWebAuthnCredential({
- credentialId: selectedCredentialId,
+ id: selectedCredentialId,
name: credentialName
});
@@ -358,8 +358,6 @@ export const MFASection = () => {
updates.selectedMfaMethod = formData.selectedMfaMethod;
}
- console.log("updates", updates, formData.selectedMfaMethod, user.selectedMfaMethod);
-
if (Object.keys(updates).length > 0) {
await mutateAsync(updates);
@@ -769,7 +767,7 @@ export const MFASection = () => {
colorSchema="secondary"
variant="outline_bg"
onClick={() => {
- setSelectedCredentialId(credential.credentialId);
+ setSelectedCredentialId(credential.id);
setCredentialName(credential.name || "");
handlePopUpOpen("renameWebAuthnCredential");
}}
@@ -781,7 +779,7 @@ export const MFASection = () => {
colorSchema="danger"
variant="outline_bg"
onClick={() => {
- setSelectedCredentialId(credential.credentialId);
+ setSelectedCredentialId(credential.id);
handlePopUpOpen("deleteWebAuthnCredential");
}}
>