Compare commits

...

35 Commits

Author SHA1 Message Date
c01ea048ce Merge pull request #2638 from scott-ray-wilson/fix-region-display
Fix: refine check of when to display region select
2024-10-22 23:58:15 -04:00
7e7d9a2bd5 fix: refine check of when to display region select 2024-10-22 20:56:10 -07:00
8497ac831f Merge pull request #2635 from Infisical/feat/allow-approvers-to-bypass-secret-change-requests
feat: allow approvers to bypass secret change requests
2024-10-22 22:28:52 +04:00
e5821122d5 Merge pull request #2597 from Infisical/feat/moved-mfa-to-org-level
feat: moved mfa to org level
2024-10-22 14:14:48 -04:00
340693cfcd feat: allow approvers to bypass secret change requests 2024-10-23 01:54:40 +08:00
014b9585e0 Merge pull request #2634 from Infisical/azure-permission-docs
Add permission note for Azure Key Vault (KV) integration documentation
2024-10-22 09:48:25 -07:00
67373b0883 Add permission note for azure kv integration 2024-10-22 09:43:36 -07:00
2101040a77 misc: updated e2e 2024-10-23 00:13:10 +08:00
2e2fea304b Merge remote-tracking branch 'origin/main' into feat/moved-mfa-to-org-level 2024-10-23 00:04:09 +08:00
571709370d misc: addressed ux issues 2024-10-23 00:00:15 +08:00
4c2ed1cc8b Merge pull request #2631 from scott-ray-wilson/fix-uw-secret-overview-overflow
Fix: cap width for tw container size on uw monitors
2024-10-22 00:48:48 -04:00
067b0f4232 fix: cap width for tw container size on uw monitors 2024-10-21 20:58:28 -07:00
6ed786e6d0 Merge pull request #2627 from Infisical/daniel/go-sdk-docs-update
docs: go SDK refreshing docs
2024-10-21 19:23:00 -04:00
d187cc3d4d Merge pull request #2622 from Infisical/daniel/error-context
feat: more contextual not found errors
2024-10-21 19:09:12 -04:00
764446a2d9 update small missing ' 2024-10-21 19:06:02 -04:00
614e4934a2 Merge pull request #2630 from scott-ray-wilson/incorrect-import-value-display-fix
Fix: Correct Secret Value Override Display on Overview Table
2024-10-21 14:18:43 -04:00
14e92f895a fix: only override secret value/id by key if same environment 2024-10-21 10:55:39 -07:00
0a38374a73 Merge pull request #2629 from Infisical/daniel/cli-snapshot-update
fix: cli snapshot test error message change
2024-10-21 21:29:34 +04:00
ec3b94a335 fix: snapshot error message change 2024-10-21 21:27:16 +04:00
ca0241bb51 improvement: improve empty table labeling for org group/users 2024-10-21 10:20:43 -07:00
7403385e7c fix: fix select all rows checkbox being checked if no folders/secrets 2024-10-21 09:45:56 -07:00
2cd1141a65 Merge pull request #2610 from scott-ray-wilson/group-tables-fixes/improvements
Fix: Group Tables/Pagination Fixes and Improvements
2024-10-21 09:39:00 -07:00
256627b2cc Update go.mdx 2024-10-21 20:38:32 +04:00
fd7e196f8b Merge pull request #2628 from Infisical/misc/export-org-data-feature
feat: add migration script to migrate org
2024-10-21 10:16:41 -04:00
9ca8da152b Update go.mdx 2024-10-21 12:08:33 +04:00
c6f66226c8 feat: more contextual not found errors 2024-10-19 05:00:14 +04:00
d677654311 improvement: org user groups tables search fixed and col sort added and group add users pagination fixed and search improved to include first and last name 2024-10-18 13:20:17 -07:00
5debeb421d Merge remote-tracking branch 'origin/main' into feat/moved-mfa-to-org-level 2024-10-18 20:07:59 +08:00
25b30e441a misc: added missing enforcement checks 2024-10-18 19:51:31 +08:00
8eb668cd72 misc: removed remaining mfa handling 2024-10-18 03:26:48 +08:00
bb079b3e46 misc: updated cli interactive to support mfa in org select 2024-10-18 01:59:24 +08:00
7a77dc7343 feat: added mfa popup for all select org 2024-10-17 22:29:38 +08:00
bd1ed2614e feat: added enforceMfa toggle for orgs 2024-10-17 03:02:26 +08:00
9192c5caa2 feat: created reusable mfa flow 2024-10-17 02:01:22 +08:00
8da2213bf1 misc: removed mfa from existing login 2024-10-16 22:44:04 +08:00
135 changed files with 2067 additions and 1339 deletions

View File

@ -39,8 +39,6 @@ describe("Login V1 Router", async () => {
}); });
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(200);
const payload = JSON.parse(res.payload); const payload = JSON.parse(res.payload);
expect(payload).toHaveProperty("mfaEnabled");
expect(payload).toHaveProperty("token"); expect(payload).toHaveProperty("token");
expect(payload.mfaEnabled).toBeFalsy();
}); });
}); });

View File

@ -0,0 +1,19 @@
import { Knex } from "knex";
import { TableName } from "../schemas";
export async function up(knex: Knex): Promise<void> {
if (!(await knex.schema.hasColumn(TableName.Organization, "enforceMfa"))) {
await knex.schema.alterTable(TableName.Organization, (tb) => {
tb.boolean("enforceMfa").defaultTo(false).notNullable();
});
}
}
export async function down(knex: Knex): Promise<void> {
if (await knex.schema.hasColumn(TableName.Organization, "enforceMfa")) {
await knex.schema.alterTable(TableName.Organization, (t) => {
t.dropColumn("enforceMfa");
});
}
}

View File

@ -20,7 +20,8 @@ export const OrganizationsSchema = z.object({
scimEnabled: z.boolean().default(false).nullable().optional(), scimEnabled: z.boolean().default(false).nullable().optional(),
kmsDefaultKeyId: z.string().uuid().nullable().optional(), kmsDefaultKeyId: z.string().uuid().nullable().optional(),
kmsEncryptedDataKey: zodBuffer.nullable().optional(), kmsEncryptedDataKey: zodBuffer.nullable().optional(),
defaultMembershipRole: z.string().default("member") defaultMembershipRole: z.string().default("member"),
enforceMfa: z.boolean().default(false)
}); });
export type TOrganizations = z.infer<typeof OrganizationsSchema>; export type TOrganizations = z.infer<typeof OrganizationsSchema>;

View File

@ -165,7 +165,8 @@ export const registerGroupRouter = async (server: FastifyZodProvider) => {
querystring: z.object({ querystring: z.object({
offset: z.coerce.number().min(0).max(100).default(0).describe(GROUPS.LIST_USERS.offset), offset: z.coerce.number().min(0).max(100).default(0).describe(GROUPS.LIST_USERS.offset),
limit: z.coerce.number().min(1).max(100).default(10).describe(GROUPS.LIST_USERS.limit), limit: z.coerce.number().min(1).max(100).default(10).describe(GROUPS.LIST_USERS.limit),
username: z.string().optional().describe(GROUPS.LIST_USERS.username) username: z.string().trim().optional().describe(GROUPS.LIST_USERS.username),
search: z.string().trim().optional().describe(GROUPS.LIST_USERS.search)
}), }),
response: { response: {
200: z.object({ 200: z.object({

View File

@ -58,7 +58,7 @@ export const accessApprovalPolicyServiceFactory = ({
enforcementLevel enforcementLevel
}: TCreateAccessApprovalPolicy) => { }: TCreateAccessApprovalPolicy) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
// If there is a group approver people might be added to the group later to meet the approvers quota // If there is a group approver people might be added to the group later to meet the approvers quota
const groupApprovers = approvers const groupApprovers = approvers
@ -89,7 +89,7 @@ export const accessApprovalPolicyServiceFactory = ({
ProjectPermissionSub.SecretApproval ProjectPermissionSub.SecretApproval
); );
const env = await projectEnvDAL.findOne({ slug: environment, projectId: project.id }); const env = await projectEnvDAL.findOne({ slug: environment, projectId: project.id });
if (!env) throw new NotFoundError({ message: "Environment not found" }); if (!env) throw new NotFoundError({ message: `Environment with slug '${environment}' not found` });
let approverUserIds = userApprovers; let approverUserIds = userApprovers;
if (userApproverNames.length) { if (userApproverNames.length) {
@ -124,7 +124,9 @@ export const accessApprovalPolicyServiceFactory = ({
const verifyAllApprovers = [...approverUserIds]; const verifyAllApprovers = [...approverUserIds];
for (const groupId of groupApprovers) { for (const groupId of groupApprovers) {
usersPromises.push(groupDAL.findAllGroupPossibleMembers({ orgId: actorOrgId, groupId, offset: 0 })); usersPromises.push(
groupDAL.findAllGroupPossibleMembers({ orgId: actorOrgId, groupId, offset: 0 }).then((group) => group.members)
);
} }
const verifyGroupApprovers = (await Promise.all(usersPromises)) const verifyGroupApprovers = (await Promise.all(usersPromises))
.flat() .flat()
@ -192,7 +194,7 @@ export const accessApprovalPolicyServiceFactory = ({
projectSlug projectSlug
}: TListAccessApprovalPoliciesDTO) => { }: TListAccessApprovalPoliciesDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
// Anyone in the project should be able to get the policies. // Anyone in the project should be able to get the policies.
/* const { permission } = */ await permissionService.getProjectPermission( /* const { permission } = */ await permissionService.getProjectPermission(
@ -243,7 +245,9 @@ export const accessApprovalPolicyServiceFactory = ({
throw new BadRequestError({ message: "Approvals cannot be greater than approvers" }); throw new BadRequestError({ message: "Approvals cannot be greater than approvers" });
} }
if (!accessApprovalPolicy) throw new NotFoundError({ message: "Secret approval policy not found" }); if (!accessApprovalPolicy) {
throw new NotFoundError({ message: `Secret approval policy with ID '${policyId}' not found` });
}
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
actorId, actorId,
@ -327,7 +331,11 @@ export const accessApprovalPolicyServiceFactory = ({
>[] = []; >[] = [];
for (const groupId of groupApprovers) { for (const groupId of groupApprovers) {
usersPromises.push(groupDAL.findAllGroupPossibleMembers({ orgId: actorOrgId, groupId, offset: 0 })); usersPromises.push(
groupDAL
.findAllGroupPossibleMembers({ orgId: actorOrgId, groupId, offset: 0 })
.then((group) => group.members)
);
} }
const verifyGroupApprovers = (await Promise.all(usersPromises)) const verifyGroupApprovers = (await Promise.all(usersPromises))
.flat() .flat()
@ -376,7 +384,7 @@ export const accessApprovalPolicyServiceFactory = ({
actorOrgId actorOrgId
}: TDeleteAccessApprovalPolicy) => { }: TDeleteAccessApprovalPolicy) => {
const policy = await accessApprovalPolicyDAL.findById(policyId); const policy = await accessApprovalPolicyDAL.findById(policyId);
if (!policy) throw new NotFoundError({ message: "Secret approval policy not found" }); if (!policy) throw new NotFoundError({ message: `Secret approval policy with ID '${policyId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -404,7 +412,7 @@ export const accessApprovalPolicyServiceFactory = ({
}: TGetAccessPolicyCountByEnvironmentDTO) => { }: TGetAccessPolicyCountByEnvironmentDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const { membership } = await permissionService.getProjectPermission( const { membership } = await permissionService.getProjectPermission(
actor, actor,
@ -418,10 +426,10 @@ export const accessApprovalPolicyServiceFactory = ({
} }
const environment = await projectEnvDAL.findOne({ projectId: project.id, slug: envSlug }); const environment = await projectEnvDAL.findOne({ projectId: project.id, slug: envSlug });
if (!environment) throw new NotFoundError({ message: "Environment not found" }); if (!environment) throw new NotFoundError({ message: `Environment with slug '${envSlug}' not found` });
const policies = await accessApprovalPolicyDAL.find({ envId: environment.id, projectId: project.id }); const policies = await accessApprovalPolicyDAL.find({ envId: environment.id, projectId: project.id });
if (!policies) throw new NotFoundError({ message: "No policies found" }); if (!policies) throw new NotFoundError({ message: `No policies found in environment with slug '${envSlug}'` });
return { count: policies.length }; return { count: policies.length };
}; };
@ -437,7 +445,7 @@ export const accessApprovalPolicyServiceFactory = ({
if (!policy) { if (!policy) {
throw new NotFoundError({ throw new NotFoundError({
message: "Cannot find access approval policy" message: `Cannot find access approval policy with ID ${policyId}`
}); });
} }

View File

@ -99,7 +99,7 @@ export const accessApprovalRequestServiceFactory = ({
}: TCreateAccessApprovalRequestDTO) => { }: TCreateAccessApprovalRequestDTO) => {
const cfg = getConfig(); const cfg = getConfig();
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
// Anyone can create an access approval request. // Anyone can create an access approval request.
const { membership } = await permissionService.getProjectPermission( const { membership } = await permissionService.getProjectPermission(
@ -121,13 +121,17 @@ export const accessApprovalRequestServiceFactory = ({
const { envSlug, secretPath, accessTypes } = verifyRequestedPermissions({ permissions: requestedPermissions }); const { envSlug, secretPath, accessTypes } = verifyRequestedPermissions({ permissions: requestedPermissions });
const environment = await projectEnvDAL.findOne({ projectId: project.id, slug: envSlug }); const environment = await projectEnvDAL.findOne({ projectId: project.id, slug: envSlug });
if (!environment) throw new NotFoundError({ message: "Environment not found" }); if (!environment) throw new NotFoundError({ message: `Environment with slug '${envSlug}' not found` });
const policy = await accessApprovalPolicyDAL.findOne({ const policy = await accessApprovalPolicyDAL.findOne({
envId: environment.id, envId: environment.id,
secretPath secretPath
}); });
if (!policy) throw new NotFoundError({ message: "No policy matching criteria was found." }); if (!policy) {
throw new NotFoundError({
message: `No policy in environment with slug '${environment.slug}' and with secret path '${secretPath}' was found.`
});
}
const approverIds: string[] = []; const approverIds: string[] = [];
const approverGroupIds: string[] = []; const approverGroupIds: string[] = [];
@ -147,10 +151,12 @@ export const accessApprovalRequestServiceFactory = ({
const groupUsers = ( const groupUsers = (
await Promise.all( await Promise.all(
approverGroupIds.map((groupApproverId) => approverGroupIds.map((groupApproverId) =>
groupDAL.findAllGroupPossibleMembers({ groupDAL
.findAllGroupPossibleMembers({
orgId: actorOrgId, orgId: actorOrgId,
groupId: groupApproverId groupId: groupApproverId
}) })
.then((group) => group.members)
) )
) )
).flat(); ).flat();
@ -264,7 +270,7 @@ export const accessApprovalRequestServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TListApprovalRequestsDTO) => { }: TListApprovalRequestsDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const { membership } = await permissionService.getProjectPermission( const { membership } = await permissionService.getProjectPermission(
actor, actor,
@ -300,7 +306,9 @@ export const accessApprovalRequestServiceFactory = ({
actorOrgId actorOrgId
}: TReviewAccessRequestDTO) => { }: TReviewAccessRequestDTO) => {
const accessApprovalRequest = await accessApprovalRequestDAL.findById(requestId); const accessApprovalRequest = await accessApprovalRequestDAL.findById(requestId);
if (!accessApprovalRequest) throw new NotFoundError({ message: "Secret approval request not found" }); if (!accessApprovalRequest) {
throw new NotFoundError({ message: `Secret approval request with ID '${requestId}' not found` });
}
const { policy } = accessApprovalRequest; const { policy } = accessApprovalRequest;
const { membership, hasRole } = await permissionService.getProjectPermission( const { membership, hasRole } = await permissionService.getProjectPermission(
@ -421,7 +429,7 @@ export const accessApprovalRequestServiceFactory = ({
const getCount = async ({ projectSlug, actor, actorAuthMethod, actorId, actorOrgId }: TGetAccessRequestCountDTO) => { const getCount = async ({ projectSlug, actor, actorAuthMethod, actorId, actorOrgId }: TGetAccessRequestCountDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const { membership } = await permissionService.getProjectPermission( const { membership } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -130,7 +130,7 @@ export const auditLogStreamServiceFactory = ({
}); });
const logStream = await auditLogStreamDAL.findById(id); const logStream = await auditLogStreamDAL.findById(id);
if (!logStream) throw new NotFoundError({ message: "Audit log stream not found" }); if (!logStream) throw new NotFoundError({ message: `Audit log stream with ID '${id}' not found` });
const { orgId } = logStream; const { orgId } = logStream;
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId); const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
@ -182,7 +182,7 @@ export const auditLogStreamServiceFactory = ({
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID attached to authentication token" }); if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID attached to authentication token" });
const logStream = await auditLogStreamDAL.findById(id); const logStream = await auditLogStreamDAL.findById(id);
if (!logStream) throw new NotFoundError({ message: "Audit log stream not found" }); if (!logStream) throw new NotFoundError({ message: `Audit log stream with ID '${id}' not found` });
const { orgId } = logStream; const { orgId } = logStream;
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId); const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
@ -194,7 +194,7 @@ export const auditLogStreamServiceFactory = ({
const getById = async ({ id, actor, actorId, actorOrgId, actorAuthMethod }: TGetDetailsAuditLogStreamDTO) => { const getById = async ({ id, actor, actorId, actorOrgId, actorAuthMethod }: TGetDetailsAuditLogStreamDTO) => {
const logStream = await auditLogStreamDAL.findById(id); const logStream = await auditLogStreamDAL.findById(id);
if (!logStream) throw new NotFoundError({ message: "Audit log stream not found" }); if (!logStream) throw new NotFoundError({ message: `Audit log stream with ID '${id}' not found` });
const { orgId } = logStream; const { orgId } = logStream;
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId); const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);

View File

@ -34,7 +34,7 @@ export const certificateAuthorityCrlServiceFactory = ({
*/ */
const getCrlById = async (crlId: TGetCrlById) => { const getCrlById = async (crlId: TGetCrlById) => {
const caCrl = await certificateAuthorityCrlDAL.findById(crlId); const caCrl = await certificateAuthorityCrlDAL.findById(crlId);
if (!caCrl) throw new NotFoundError({ message: "CRL not found" }); if (!caCrl) throw new NotFoundError({ message: `CRL with ID '${crlId}' not found` });
const ca = await certificateAuthorityDAL.findById(caCrl.caId); const ca = await certificateAuthorityDAL.findById(caCrl.caId);
@ -64,7 +64,7 @@ export const certificateAuthorityCrlServiceFactory = ({
*/ */
const getCaCrls = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCrlsDTO) => { const getCaCrls = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCrlsDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -211,7 +211,7 @@ export const certificateEstServiceFactory = ({
const certTemplate = await certificateTemplateDAL.findById(certificateTemplateId); const certTemplate = await certificateTemplateDAL.findById(certificateTemplateId);
if (!certTemplate) { if (!certTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found" message: `Certificate template with ID '${certificateTemplateId}' not found`
}); });
} }
@ -236,7 +236,7 @@ export const certificateEstServiceFactory = ({
const ca = await certificateAuthorityDAL.findById(certTemplate.caId); const ca = await certificateAuthorityDAL.findById(certTemplate.caId);
if (!ca) { if (!ca) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate Authority not found" message: `Certificate Authority with ID '${certTemplate.caId}' not found`
}); });
} }

View File

@ -61,7 +61,7 @@ export const dynamicSecretLeaseServiceFactory = ({
}: TCreateDynamicSecretLeaseDTO) => { }: TCreateDynamicSecretLeaseDTO) => {
const appCfg = getConfig(); const appCfg = getConfig();
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -84,10 +84,16 @@ export const dynamicSecretLeaseServiceFactory = ({
} }
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${path}' in environment with slug '${environmentSlug}' not found`
});
const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id }); const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id });
if (!dynamicSecretCfg) throw new NotFoundError({ message: "Dynamic secret not found" }); if (!dynamicSecretCfg)
throw new NotFoundError({
message: `Dynamic secret with name '${name}' in folder with path '${path}' not found`
});
const totalLeasesTaken = await dynamicSecretLeaseDAL.countLeasesForDynamicSecret(dynamicSecretCfg.id); const totalLeasesTaken = await dynamicSecretLeaseDAL.countLeasesForDynamicSecret(dynamicSecretCfg.id);
if (totalLeasesTaken >= appCfg.MAX_LEASE_LIMIT) if (totalLeasesTaken >= appCfg.MAX_LEASE_LIMIT)
@ -134,7 +140,7 @@ export const dynamicSecretLeaseServiceFactory = ({
leaseId leaseId
}: TRenewDynamicSecretLeaseDTO) => { }: TRenewDynamicSecretLeaseDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -157,10 +163,15 @@ export const dynamicSecretLeaseServiceFactory = ({
} }
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${path}' in environment with slug '${environmentSlug}' not found`
});
const dynamicSecretLease = await dynamicSecretLeaseDAL.findById(leaseId); const dynamicSecretLease = await dynamicSecretLeaseDAL.findById(leaseId);
if (!dynamicSecretLease) throw new NotFoundError({ message: "Dynamic secret lease not found" }); if (!dynamicSecretLease) {
throw new NotFoundError({ message: `Dynamic secret lease with ID '${leaseId}' not found` });
}
const dynamicSecretCfg = dynamicSecretLease.dynamicSecret; const dynamicSecretCfg = dynamicSecretLease.dynamicSecret;
const selectedProvider = dynamicSecretProviders[dynamicSecretCfg.type as DynamicSecretProviders]; const selectedProvider = dynamicSecretProviders[dynamicSecretCfg.type as DynamicSecretProviders];
@ -208,7 +219,7 @@ export const dynamicSecretLeaseServiceFactory = ({
isForced isForced
}: TDeleteDynamicSecretLeaseDTO) => { }: TDeleteDynamicSecretLeaseDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -224,10 +235,14 @@ export const dynamicSecretLeaseServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${path}' in environment with slug '${environmentSlug}' not found`
});
const dynamicSecretLease = await dynamicSecretLeaseDAL.findById(leaseId); const dynamicSecretLease = await dynamicSecretLeaseDAL.findById(leaseId);
if (!dynamicSecretLease) throw new NotFoundError({ message: "Dynamic secret lease not found" }); if (!dynamicSecretLease)
throw new NotFoundError({ message: `Dynamic secret lease with ID '${leaseId}' not found` });
const dynamicSecretCfg = dynamicSecretLease.dynamicSecret; const dynamicSecretCfg = dynamicSecretLease.dynamicSecret;
const selectedProvider = dynamicSecretProviders[dynamicSecretCfg.type as DynamicSecretProviders]; const selectedProvider = dynamicSecretProviders[dynamicSecretCfg.type as DynamicSecretProviders];
@ -273,7 +288,7 @@ export const dynamicSecretLeaseServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TListDynamicSecretLeasesDTO) => { }: TListDynamicSecretLeasesDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -289,10 +304,16 @@ export const dynamicSecretLeaseServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${path}' in environment with slug '${environmentSlug}' not found`
});
const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id }); const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id });
if (!dynamicSecretCfg) throw new NotFoundError({ message: "Dynamic secret not found" }); if (!dynamicSecretCfg)
throw new NotFoundError({
message: `Dynamic secret with name '${name}' in folder with path '${path}' not found`
});
const dynamicSecretLeases = await dynamicSecretLeaseDAL.find({ dynamicSecretId: dynamicSecretCfg.id }); const dynamicSecretLeases = await dynamicSecretLeaseDAL.find({ dynamicSecretId: dynamicSecretCfg.id });
return dynamicSecretLeases; return dynamicSecretLeases;
@ -309,7 +330,7 @@ export const dynamicSecretLeaseServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TDetailsDynamicSecretLeaseDTO) => { }: TDetailsDynamicSecretLeaseDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -325,10 +346,11 @@ export const dynamicSecretLeaseServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) throw new NotFoundError({ message: `Folder with path '${path}' not found` });
const dynamicSecretLease = await dynamicSecretLeaseDAL.findById(leaseId); const dynamicSecretLease = await dynamicSecretLeaseDAL.findById(leaseId);
if (!dynamicSecretLease) throw new NotFoundError({ message: "Dynamic secret lease not found" }); if (!dynamicSecretLease)
throw new NotFoundError({ message: `Dynamic secret lease with ID '${leaseId}' not found` });
return dynamicSecretLease; return dynamicSecretLease;
}; };

View File

@ -66,7 +66,7 @@ export const dynamicSecretServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TCreateDynamicSecretDTO) => { }: TCreateDynamicSecretDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -89,7 +89,9 @@ export const dynamicSecretServiceFactory = ({
} }
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) {
throw new NotFoundError({ message: `Folder with path '${path}' in environment '${environmentSlug}' not found` });
}
const existingDynamicSecret = await dynamicSecretDAL.findOne({ name, folderId: folder.id }); const existingDynamicSecret = await dynamicSecretDAL.findOne({ name, folderId: folder.id });
if (existingDynamicSecret) if (existingDynamicSecret)
@ -134,7 +136,7 @@ export const dynamicSecretServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TUpdateDynamicSecretDTO) => { }: TUpdateDynamicSecretDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
@ -158,11 +160,15 @@ export const dynamicSecretServiceFactory = ({
} }
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({ message: `Folder with path '${path}' in environment '${environmentSlug}' not found` });
const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id }); const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id });
if (!dynamicSecretCfg) throw new NotFoundError({ message: "Dynamic secret not found" }); if (!dynamicSecretCfg) {
throw new NotFoundError({
message: `Dynamic secret with name '${name}' in folder '${folder.path}' not found`
});
}
if (newName) { if (newName) {
const existingDynamicSecret = await dynamicSecretDAL.findOne({ name: newName, folderId: folder.id }); const existingDynamicSecret = await dynamicSecretDAL.findOne({ name: newName, folderId: folder.id });
if (existingDynamicSecret) if (existingDynamicSecret)
@ -213,7 +219,7 @@ export const dynamicSecretServiceFactory = ({
isForced isForced
}: TDeleteDynamicSecretDTO) => { }: TDeleteDynamicSecretDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
@ -230,10 +236,13 @@ export const dynamicSecretServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({ message: `Folder with path '${path}' in environment '${environmentSlug}' not found` });
const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id }); const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id });
if (!dynamicSecretCfg) throw new BadRequestError({ message: "Dynamic secret not found" }); if (!dynamicSecretCfg) {
throw new NotFoundError({ message: `Dynamic secret with name '${name}' in folder '${folder.path}' not found` });
}
const leases = await dynamicSecretLeaseDAL.find({ dynamicSecretId: dynamicSecretCfg.id }); const leases = await dynamicSecretLeaseDAL.find({ dynamicSecretId: dynamicSecretCfg.id });
// when not forced we check with the external system to first remove the things // when not forced we check with the external system to first remove the things
@ -271,7 +280,7 @@ export const dynamicSecretServiceFactory = ({
actor actor
}: TDetailsDynamicSecretDTO) => { }: TDetailsDynamicSecretDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -287,10 +296,13 @@ export const dynamicSecretServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({ message: `Folder with path '${path}' in environment '${environmentSlug}' not found` });
const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id }); const dynamicSecretCfg = await dynamicSecretDAL.findOne({ name, folderId: folder.id });
if (!dynamicSecretCfg) throw new NotFoundError({ message: "Dynamic secret not found" }); if (!dynamicSecretCfg) {
throw new NotFoundError({ message: `Dynamic secret with name '${name} in folder '${path}' not found` });
}
const decryptedStoredInput = JSON.parse( const decryptedStoredInput = JSON.parse(
infisicalSymmetricDecrypt({ infisicalSymmetricDecrypt({
keyEncoding: dynamicSecretCfg.keyEncoding as SecretKeyEncoding, keyEncoding: dynamicSecretCfg.keyEncoding as SecretKeyEncoding,
@ -335,7 +347,11 @@ export const dynamicSecretServiceFactory = ({
} }
const folders = await folderDAL.findBySecretPathMultiEnv(projectId, environmentSlugs, path); const folders = await folderDAL.findBySecretPathMultiEnv(projectId, environmentSlugs, path);
if (!folders.length) throw new NotFoundError({ message: "Folders not found" }); if (!folders.length) {
throw new NotFoundError({
message: `Folders with path '${path}' in environments with slugs '${environmentSlugs.join(", ")}' not found`
});
}
const dynamicSecretCfg = await dynamicSecretDAL.find( const dynamicSecretCfg = await dynamicSecretDAL.find(
{ $in: { folderId: folders.map((folder) => folder.id) }, $search: search ? { name: `%${search}%` } : undefined }, { $in: { folderId: folders.map((folder) => folder.id) }, $search: search ? { name: `%${search}%` } : undefined },
@ -369,7 +385,9 @@ export const dynamicSecretServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) {
throw new NotFoundError({ message: `Folder with path '${path}' in environment '${environmentSlug}' not found` });
}
const dynamicSecretCfg = await dynamicSecretDAL.find( const dynamicSecretCfg = await dynamicSecretDAL.find(
{ folderId: folder.id, $search: search ? { name: `%${search}%` } : undefined }, { folderId: folder.id, $search: search ? { name: `%${search}%` } : undefined },
@ -398,7 +416,7 @@ export const dynamicSecretServiceFactory = ({
if (!projectId) { if (!projectId) {
if (!projectSlug) throw new BadRequestError({ message: "Project ID or slug required" }); if (!projectSlug) throw new BadRequestError({ message: "Project ID or slug required" });
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
projectId = project.id; projectId = project.id;
} }
@ -415,7 +433,8 @@ export const dynamicSecretServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path); const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({ message: `Folder with path '${path}' in environment '${environmentSlug}' not found` });
const dynamicSecretCfg = await dynamicSecretDAL.find( const dynamicSecretCfg = await dynamicSecretDAL.find(
{ folderId: folder.id, $search: search ? { name: `%${search}%` } : undefined }, { folderId: folder.id, $search: search ? { name: `%${search}%` } : undefined },
@ -459,7 +478,10 @@ export const dynamicSecretServiceFactory = ({
} }
const folders = await folderDAL.findBySecretPathMultiEnv(projectId, environmentSlugs, path); const folders = await folderDAL.findBySecretPathMultiEnv(projectId, environmentSlugs, path);
if (!folders.length) throw new NotFoundError({ message: "Folders not found" }); if (!folders.length)
throw new NotFoundError({
message: `Folders with path '${path} in environments with slugs '${environmentSlugs.join(", ")}' not found`
});
const dynamicSecretCfg = await dynamicSecretDAL.listDynamicSecretsByFolderIds({ const dynamicSecretCfg = await dynamicSecretDAL.listDynamicSecretsByFolderIds({
folderIds: folders.map((folder) => folder.id), folderIds: folders.map((folder) => folder.id),

View File

@ -145,7 +145,7 @@ export const externalKmsServiceFactory = ({
const kmsName = name ? slugify(name) : undefined; const kmsName = name ? slugify(name) : undefined;
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id }); const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
if (!externalKmsDoc) throw new NotFoundError({ message: "External kms not found" }); if (!externalKmsDoc) throw new NotFoundError({ message: `External KMS with ID '${kmsId}' not found` });
let sanitizedProviderInput = ""; let sanitizedProviderInput = "";
const { encryptor: orgDataKeyEncryptor, decryptor: orgDataKeyDecryptor } = const { encryptor: orgDataKeyEncryptor, decryptor: orgDataKeyDecryptor } =
@ -220,7 +220,7 @@ export const externalKmsServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Kms); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Kms);
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id }); const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
if (!externalKmsDoc) throw new NotFoundError({ message: "External kms not found" }); if (!externalKmsDoc) throw new NotFoundError({ message: `External KMS with ID '${kmsId}' not found` });
const externalKms = await externalKmsDAL.transaction(async (tx) => { const externalKms = await externalKmsDAL.transaction(async (tx) => {
const kms = await kmsDAL.deleteById(kmsDoc.id, tx); const kms = await kmsDAL.deleteById(kmsDoc.id, tx);
@ -258,7 +258,7 @@ export const externalKmsServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms);
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id }); const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
if (!externalKmsDoc) throw new NotFoundError({ message: "External kms not found" }); if (!externalKmsDoc) throw new NotFoundError({ message: `External KMS with ID '${kmsId}' not found` });
const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({ const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization, type: KmsDataKey.Organization,
@ -298,7 +298,7 @@ export const externalKmsServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms);
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id }); const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
if (!externalKmsDoc) throw new NotFoundError({ message: "External kms not found" }); if (!externalKmsDoc) throw new NotFoundError({ message: `External KMS with ID '${kmsDoc.id}' not found` });
const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({ const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization, type: KmsDataKey.Organization,

View File

@ -65,16 +65,18 @@ export const groupDALFactory = (db: TDbClient) => {
groupId, groupId,
offset = 0, offset = 0,
limit, limit,
username username, // depreciated in favor of search
search
}: { }: {
orgId: string; orgId: string;
groupId: string; groupId: string;
offset?: number; offset?: number;
limit?: number; limit?: number;
username?: string; username?: string;
search?: string;
}) => { }) => {
try { try {
let query = db const query = db
.replicaNode()(TableName.OrgMembership) .replicaNode()(TableName.OrgMembership)
.where(`${TableName.OrgMembership}.orgId`, orgId) .where(`${TableName.OrgMembership}.orgId`, orgId)
.join(TableName.Users, `${TableName.OrgMembership}.userId`, `${TableName.Users}.id`) .join(TableName.Users, `${TableName.OrgMembership}.userId`, `${TableName.Users}.id`)
@ -92,22 +94,27 @@ export const groupDALFactory = (db: TDbClient) => {
db.ref("username").withSchema(TableName.Users), db.ref("username").withSchema(TableName.Users),
db.ref("firstName").withSchema(TableName.Users), db.ref("firstName").withSchema(TableName.Users),
db.ref("lastName").withSchema(TableName.Users), db.ref("lastName").withSchema(TableName.Users),
db.ref("id").withSchema(TableName.Users).as("userId") db.ref("id").withSchema(TableName.Users).as("userId"),
db.raw(`count(*) OVER() as total_count`)
) )
.where({ isGhost: false }) .where({ isGhost: false })
.offset(offset); .offset(offset)
.orderBy("firstName", "asc");
if (limit) { if (limit) {
query = query.limit(limit); void query.limit(limit);
} }
if (username) { if (search) {
query = query.andWhere(`${TableName.Users}.username`, "ilike", `%${username}%`); void query.andWhereRaw(`CONCAT_WS(' ', "firstName", "lastName", "username") ilike '%${search}%'`);
} else if (username) {
void query.andWhere(`${TableName.Users}.username`, "ilike", `%${username}%`);
} }
const members = await query; const members = await query;
return members.map( return {
members: members.map(
({ email, username: memberUsername, firstName, lastName, userId, groupId: memberGroupId }) => ({ ({ email, username: memberUsername, firstName, lastName, userId, groupId: memberGroupId }) => ({
id: userId, id: userId,
email, email,
@ -116,7 +123,10 @@ export const groupDALFactory = (db: TDbClient) => {
lastName, lastName,
isPartOfGroup: !!memberGroupId isPartOfGroup: !!memberGroupId
}) })
); ),
// @ts-expect-error col select is raw and not strongly typed
totalCount: Number(members?.[0]?.total_count ?? 0)
};
} catch (error) { } catch (error) {
throw new DatabaseError({ error, name: "Find all org members" }); throw new DatabaseError({ error, name: "Find all org members" });
} }

View File

@ -74,7 +74,7 @@ const addAcceptedUsersToGroup = async ({
if (!ghostUser) { if (!ghostUser) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project owner" message: `Failed to find project owner of project with ID '${projectId}'`
}); });
} }
@ -82,7 +82,7 @@ const addAcceptedUsersToGroup = async ({
if (!ghostUserLatestKey) { if (!ghostUserLatestKey) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project owner's latest key" message: `Failed to find project owner's latest key in project with ID '${projectId}'`
}); });
} }
@ -90,7 +90,7 @@ const addAcceptedUsersToGroup = async ({
if (!bot) { if (!bot) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project bot" message: `Failed to find project bot in project with ID '${projectId}'`
}); });
} }

View File

@ -221,7 +221,8 @@ export const groupServiceFactory = ({
actor, actor,
actorId, actorId,
actorAuthMethod, actorAuthMethod,
actorOrgId actorOrgId,
search
}: TListGroupUsersDTO) => { }: TListGroupUsersDTO) => {
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" }); if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
@ -244,17 +245,16 @@ export const groupServiceFactory = ({
message: `Failed to find group with ID ${id}` message: `Failed to find group with ID ${id}`
}); });
const users = await groupDAL.findAllGroupPossibleMembers({ const { members, totalCount } = await groupDAL.findAllGroupPossibleMembers({
orgId: group.orgId, orgId: group.orgId,
groupId: group.id, groupId: group.id,
offset, offset,
limit, limit,
username username,
search
}); });
const count = await orgDAL.countAllOrgMembers(group.orgId); return { users: members, totalCount };
return { users, totalCount: count };
}; };
const addUserToGroup = async ({ id, username, actor, actorId, actorAuthMethod, actorOrgId }: TAddUserToGroupDTO) => { const addUserToGroup = async ({ id, username, actor, actorId, actorAuthMethod, actorOrgId }: TAddUserToGroupDTO) => {

View File

@ -38,6 +38,7 @@ export type TListGroupUsersDTO = {
offset: number; offset: number;
limit: number; limit: number;
username?: string; username?: string;
search?: string;
} & TGenericPermission; } & TGenericPermission;
export type TAddUserToGroupDTO = { export type TAddUserToGroupDTO = {

View File

@ -65,7 +65,7 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
...dto ...dto
}: TCreateIdentityPrivilegeDTO) => { }: TCreateIdentityPrivilegeDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId }); const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
@ -137,7 +137,7 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TUpdateIdentityPrivilegeDTO) => { }: TUpdateIdentityPrivilegeDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId }); const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
@ -167,7 +167,11 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
slug, slug,
projectMembershipId: identityProjectMembership.id projectMembershipId: identityProjectMembership.id
}); });
if (!identityPrivilege) throw new NotFoundError({ message: "Identity additional privilege not found" }); if (!identityPrivilege) {
throw new NotFoundError({
message: `Identity additional privilege with slug '${slug}' not found for the specified identity with ID '${identityProjectMembership.identityId}'`
});
}
if (data?.slug) { if (data?.slug) {
const existingSlug = await identityProjectAdditionalPrivilegeDAL.findOne({ const existingSlug = await identityProjectAdditionalPrivilegeDAL.findOne({
slug: data.slug, slug: data.slug,
@ -218,7 +222,7 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TDeleteIdentityPrivilegeDTO) => { }: TDeleteIdentityPrivilegeDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId }); const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
@ -248,7 +252,11 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
slug, slug,
projectMembershipId: identityProjectMembership.id projectMembershipId: identityProjectMembership.id
}); });
if (!identityPrivilege) throw new NotFoundError({ message: "Identity additional privilege not found" }); if (!identityPrivilege) {
throw new NotFoundError({
message: `Identity additional privilege with slug '${slug}' not found for the specified identity with ID '${identityProjectMembership.identityId}'`
});
}
const deletedPrivilege = await identityProjectAdditionalPrivilegeDAL.deleteById(identityPrivilege.id); const deletedPrivilege = await identityProjectAdditionalPrivilegeDAL.deleteById(identityPrivilege.id);
return { return {
@ -268,7 +276,7 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TGetIdentityPrivilegeDetailsDTO) => { }: TGetIdentityPrivilegeDetailsDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId }); const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
@ -287,8 +295,11 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
slug, slug,
projectMembershipId: identityProjectMembership.id projectMembershipId: identityProjectMembership.id
}); });
if (!identityPrivilege) throw new NotFoundError({ message: "Identity additional privilege not found" }); if (!identityPrivilege) {
throw new NotFoundError({
message: `Identity additional privilege with slug '${slug}' not found for the specified identity with ID '${identityProjectMembership.identityId}'`
});
}
return { return {
...identityPrivilege, ...identityPrivilege,
permissions: unpackPermissions(identityPrivilege.permissions) permissions: unpackPermissions(identityPrivilege.permissions)
@ -304,7 +315,7 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
projectSlug projectSlug
}: TListIdentityPrivilegesDTO) => { }: TListIdentityPrivilegesDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId }); const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });

View File

@ -247,7 +247,11 @@ export const ldapConfigServiceFactory = ({
}; };
const orgBot = await orgBotDAL.findOne({ orgId }); const orgBot = await orgBotDAL.findOne({ orgId });
if (!orgBot) throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); if (!orgBot)
throw new NotFoundError({
message: `Organization bot in organization with ID '${orgId}' not found`,
name: "OrgBotNotFound"
});
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
iv: orgBot.symmetricKeyIV, iv: orgBot.symmetricKeyIV,
@ -283,10 +287,19 @@ export const ldapConfigServiceFactory = ({
const getLdapCfg = async (filter: { orgId: string; isActive?: boolean; id?: string }) => { const getLdapCfg = async (filter: { orgId: string; isActive?: boolean; id?: string }) => {
const ldapConfig = await ldapConfigDAL.findOne(filter); const ldapConfig = await ldapConfigDAL.findOne(filter);
if (!ldapConfig) throw new NotFoundError({ message: "Failed to find organization LDAP data" }); if (!ldapConfig) {
throw new NotFoundError({
message: `Failed to find organization LDAP data in organization with ID '${filter.orgId}'`
});
}
const orgBot = await orgBotDAL.findOne({ orgId: ldapConfig.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: ldapConfig.orgId });
if (!orgBot) throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); if (!orgBot) {
throw new NotFoundError({
message: `Organization bot not found in organization with ID ${ldapConfig.orgId}`,
name: "OrgBotNotFound"
});
}
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
@ -369,7 +382,7 @@ export const ldapConfigServiceFactory = ({
const bootLdap = async (organizationSlug: string) => { const bootLdap = async (organizationSlug: string) => {
const organization = await orgDAL.findOne({ slug: organizationSlug }); const organization = await orgDAL.findOne({ slug: organizationSlug });
if (!organization) throw new NotFoundError({ message: "Organization not found" }); if (!organization) throw new NotFoundError({ message: `Organization with slug '${organizationSlug}' not found` });
const ldapConfig = await getLdapCfg({ const ldapConfig = await getLdapCfg({
orgId: organization.id, orgId: organization.id,
@ -426,7 +439,7 @@ export const ldapConfigServiceFactory = ({
}); });
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) throw new NotFoundError({ message: "Organization not found" }); if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
if (userAlias) { if (userAlias) {
await userDAL.transaction(async (tx) => { await userDAL.transaction(async (tx) => {
@ -700,7 +713,11 @@ export const ldapConfigServiceFactory = ({
orgId orgId
}); });
if (!ldapConfig) throw new NotFoundError({ message: "Failed to find organization LDAP data" }); if (!ldapConfig) {
throw new NotFoundError({
message: `Failed to find organization LDAP data with ID '${ldapConfigId}' in organization with ID ${orgId}`
});
}
const groupMaps = await ldapGroupMapDAL.findLdapGroupMapsByLdapConfigId(ldapConfigId); const groupMaps = await ldapGroupMapDAL.findLdapGroupMapsByLdapConfigId(ldapConfigId);
@ -747,7 +764,11 @@ export const ldapConfigServiceFactory = ({
} }
const group = await groupDAL.findOne({ slug: groupSlug, orgId }); const group = await groupDAL.findOne({ slug: groupSlug, orgId });
if (!group) throw new NotFoundError({ message: "Failed to find group" }); if (!group) {
throw new NotFoundError({
message: `Failed to find group with slug '${groupSlug}' in organization with ID '${orgId}'`
});
}
const groupMap = await ldapGroupMapDAL.create({ const groupMap = await ldapGroupMapDAL.create({
ldapConfigId, ldapConfigId,
@ -781,7 +802,11 @@ export const ldapConfigServiceFactory = ({
orgId orgId
}); });
if (!ldapConfig) throw new NotFoundError({ message: "Failed to find organization LDAP data" }); if (!ldapConfig) {
throw new NotFoundError({
message: `Failed to find organization LDAP data with ID '${ldapConfigId}' in organization with ID ${orgId}`
});
}
const [deletedGroupMap] = await ldapGroupMapDAL.delete({ const [deletedGroupMap] = await ldapGroupMapDAL.delete({
ldapConfigId: ldapConfig.id, ldapConfigId: ldapConfig.id,

View File

@ -46,7 +46,8 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
writeLimit: 200, writeLimit: 200,
secretsLimit: 40 secretsLimit: 40
}, },
pkiEst: false pkiEst: false,
enforceMfa: false
}); });
export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => { export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => {

View File

@ -145,7 +145,7 @@ export const licenseServiceFactory = ({
if (cachedPlan) return JSON.parse(cachedPlan) as TFeatureSet; if (cachedPlan) return JSON.parse(cachedPlan) as TFeatureSet;
const org = await orgDAL.findOrgById(orgId); const org = await orgDAL.findOrgById(orgId);
if (!org) throw new NotFoundError({ message: "Organization not found" }); if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
const { const {
data: { currentPlan } data: { currentPlan }
} = await licenseServerCloudApi.request.get<{ currentPlan: TFeatureSet }>( } = await licenseServerCloudApi.request.get<{ currentPlan: TFeatureSet }>(
@ -204,7 +204,7 @@ export const licenseServiceFactory = ({
const updateSubscriptionOrgMemberCount = async (orgId: string, tx?: Knex) => { const updateSubscriptionOrgMemberCount = async (orgId: string, tx?: Knex) => {
if (instanceType === InstanceType.Cloud) { if (instanceType === InstanceType.Cloud) {
const org = await orgDAL.findOrgById(orgId); const org = await orgDAL.findOrgById(orgId);
if (!org) throw new NotFoundError({ message: "Organization not found" }); if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
const quantity = await licenseDAL.countOfOrgMembers(orgId, tx); const quantity = await licenseDAL.countOfOrgMembers(orgId, tx);
const quantityIdentities = await licenseDAL.countOrgUsersAndIdentities(orgId, tx); const quantityIdentities = await licenseDAL.countOrgUsersAndIdentities(orgId, tx);
@ -267,7 +267,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
@ -341,7 +341,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
const { data } = await licenseServerCloudApi.request.get( const { data } = await licenseServerCloudApi.request.get(
@ -358,7 +358,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
const { data } = await licenseServerCloudApi.request.get( const { data } = await licenseServerCloudApi.request.get(
@ -374,7 +374,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
@ -399,7 +399,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
const { data } = await licenseServerCloudApi.request.patch( const { data } = await licenseServerCloudApi.request.patch(
@ -419,7 +419,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
@ -446,7 +446,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
const { const {
@ -475,7 +475,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
@ -492,7 +492,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
const { const {
@ -510,7 +510,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
@ -531,7 +531,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
@ -548,7 +548,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }
@ -565,7 +565,7 @@ export const licenseServiceFactory = ({
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with ID '${orgId}' not found`
}); });
} }

View File

@ -64,6 +64,7 @@ export type TFeatureSet = {
secretsLimit: number; secretsLimit: number;
}; };
pkiEst: boolean; pkiEst: boolean;
enforceMfa: boolean;
}; };
export type TOrgPlansTableDTO = { export type TOrgPlansTableDTO = {

View File

@ -79,7 +79,7 @@ export const oidcConfigServiceFactory = ({
const org = await orgDAL.findOne({ slug: dto.orgSlug }); const org = await orgDAL.findOne({ slug: dto.orgSlug });
if (!org) { if (!org) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found", message: `Organization with slug '${dto.orgSlug}' not found`,
name: "OrgNotFound" name: "OrgNotFound"
}); });
} }
@ -100,14 +100,17 @@ export const oidcConfigServiceFactory = ({
if (!oidcCfg) { if (!oidcCfg) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find organization OIDC configuration" message: `OIDC configuration for organization with slug '${dto.orgSlug}' not found`
}); });
} }
// decrypt and return cfg // decrypt and return cfg
const orgBot = await orgBotDAL.findOne({ orgId: oidcCfg.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: oidcCfg.orgId });
if (!orgBot) { if (!orgBot) {
throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); throw new NotFoundError({
message: `Organization bot for organization with ID '${oidcCfg.orgId}' not found`,
name: "OrgBotNotFound"
});
} }
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
@ -174,7 +177,7 @@ export const oidcConfigServiceFactory = ({
}); });
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) throw new NotFoundError({ message: "Organization not found" }); if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
let user: TUsers; let user: TUsers;
if (userAlias) { if (userAlias) {
@ -366,7 +369,7 @@ export const oidcConfigServiceFactory = ({
if (!org) { if (!org) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with slug '${orgSlug}' not found`
}); });
} }
@ -387,7 +390,11 @@ export const oidcConfigServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Sso); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Sso);
const orgBot = await orgBotDAL.findOne({ orgId: org.id }); const orgBot = await orgBotDAL.findOne({ orgId: org.id });
if (!orgBot) throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); if (!orgBot)
throw new NotFoundError({
message: `Organization bot for organization with ID '${org.id}' not found`,
name: "OrgBotNotFound"
});
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
iv: orgBot.symmetricKeyIV, iv: orgBot.symmetricKeyIV,
@ -455,7 +462,7 @@ export const oidcConfigServiceFactory = ({
}); });
if (!org) { if (!org) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found" message: `Organization with slug '${orgSlug}' not found`
}); });
} }
@ -561,7 +568,7 @@ export const oidcConfigServiceFactory = ({
if (!org) { if (!org) {
throw new NotFoundError({ throw new NotFoundError({
message: "Organization not found." message: `Organization with slug '${orgSlug}' not found`
}); });
} }

View File

@ -64,7 +64,7 @@ export const permissionServiceFactory = ({
permissions as PackRule<RawRuleOf<MongoAbility<OrgPermissionSet>>>[] permissions as PackRule<RawRuleOf<MongoAbility<OrgPermissionSet>>>[]
); );
default: default:
throw new NotFoundError({ name: "OrgRoleInvalid", message: "Organization role not found" }); throw new NotFoundError({ name: "OrgRoleInvalid", message: `Organization role '${role}' not found` });
} }
}) })
.reduce((curr, prev) => prev.concat(curr), []); .reduce((curr, prev) => prev.concat(curr), []);
@ -94,7 +94,7 @@ export const permissionServiceFactory = ({
default: default:
throw new NotFoundError({ throw new NotFoundError({
name: "ProjectRoleInvalid", name: "ProjectRoleInvalid",
message: "Project role not found" message: `Project role '${role}' not found`
}); });
} }
}) })
@ -145,7 +145,7 @@ export const permissionServiceFactory = ({
const membership = await permissionDAL.getOrgIdentityPermission(identityId, orgId); const membership = await permissionDAL.getOrgIdentityPermission(identityId, orgId);
if (!membership) throw new ForbiddenRequestError({ name: "Identity is not apart of this organization" }); if (!membership) throw new ForbiddenRequestError({ name: "Identity is not apart of this organization" });
if (membership.role === OrgMembershipRole.Custom && !membership.permissions) { if (membership.role === OrgMembershipRole.Custom && !membership.permissions) {
throw new NotFoundError({ name: "Custom organization permission not found" }); throw new NotFoundError({ name: `Custom organization permission not found for identity ${identityId}` });
} }
return { return {
permission: buildOrgPermission([{ role: membership.role, permissions: membership.permissions }]), permission: buildOrgPermission([{ role: membership.role, permissions: membership.permissions }]),
@ -179,7 +179,10 @@ export const permissionServiceFactory = ({
const isCustomRole = !Object.values(OrgMembershipRole).includes(role as OrgMembershipRole); const isCustomRole = !Object.values(OrgMembershipRole).includes(role as OrgMembershipRole);
if (isCustomRole) { if (isCustomRole) {
const orgRole = await orgRoleDAL.findOne({ slug: role, orgId }); const orgRole = await orgRoleDAL.findOne({ slug: role, orgId });
if (!orgRole) throw new NotFoundError({ message: "Specified role was not found" }); if (!orgRole)
throw new NotFoundError({
message: `Specified role '${role}' was not found in the organization with ID '${orgId}'`
});
return { return {
permission: buildOrgPermission([{ role: OrgMembershipRole.Custom, permissions: orgRole.permissions }]), permission: buildOrgPermission([{ role: OrgMembershipRole.Custom, permissions: orgRole.permissions }]),
role: orgRole role: orgRole
@ -264,7 +267,9 @@ export const permissionServiceFactory = ({
): Promise<TProjectPermissionRT<ActorType.IDENTITY>> => { ): Promise<TProjectPermissionRT<ActorType.IDENTITY>> => {
const identityProjectPermission = await permissionDAL.getProjectIdentityPermission(identityId, projectId); const identityProjectPermission = await permissionDAL.getProjectIdentityPermission(identityId, projectId);
if (!identityProjectPermission) if (!identityProjectPermission)
throw new ForbiddenRequestError({ name: "Identity is not a member of the specified project" }); throw new ForbiddenRequestError({
name: `Identity is not a member of the specified project with ID '${projectId}'`
});
if ( if (
identityProjectPermission.roles.some( identityProjectPermission.roles.some(
@ -326,7 +331,7 @@ export const permissionServiceFactory = ({
actorOrgId: string | undefined actorOrgId: string | undefined
) => { ) => {
const serviceToken = await serviceTokenDAL.findById(serviceTokenId); const serviceToken = await serviceTokenDAL.findById(serviceTokenId);
if (!serviceToken) throw new NotFoundError({ message: "Service token not found" }); if (!serviceToken) throw new NotFoundError({ message: `Service token with ID '${serviceTokenId}' not found` });
const serviceTokenProject = await projectDAL.findById(serviceToken.projectId); const serviceTokenProject = await projectDAL.findById(serviceToken.projectId);
@ -337,11 +342,15 @@ export const permissionServiceFactory = ({
} }
if (serviceToken.projectId !== projectId) { if (serviceToken.projectId !== projectId) {
throw new ForbiddenRequestError({ name: "Service token not a part of the specified project" }); throw new ForbiddenRequestError({
name: `Service token not a part of the specified project with ID ${projectId}`
});
} }
if (serviceTokenProject.orgId !== actorOrgId) { if (serviceTokenProject.orgId !== actorOrgId) {
throw new ForbiddenRequestError({ message: "Service token not a part of the specified organization" }); throw new ForbiddenRequestError({
message: `Service token not a part of the specified organization with ID ${actorOrgId}`
});
} }
const scopes = ServiceTokenScopes.parse(serviceToken.scopes || []); const scopes = ServiceTokenScopes.parse(serviceToken.scopes || []);

View File

@ -42,7 +42,8 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
...dto ...dto
}: TCreateUserPrivilegeDTO) => { }: TCreateUserPrivilegeDTO) => {
const projectMembership = await projectMembershipDAL.findById(projectMembershipId); const projectMembership = await projectMembershipDAL.findById(projectMembershipId);
if (!projectMembership) throw new NotFoundError({ message: "Project membership not found" }); if (!projectMembership)
throw new NotFoundError({ message: `Project membership with ID '${projectMembershipId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -94,14 +95,18 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
...dto ...dto
}: TUpdateUserPrivilegeDTO) => { }: TUpdateUserPrivilegeDTO) => {
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId); const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
if (!userPrivilege) throw new NotFoundError({ message: "User additional privilege not found" }); if (!userPrivilege)
throw new NotFoundError({ message: `User additional privilege with ID '${privilegeId}' not found` });
const projectMembership = await projectMembershipDAL.findOne({ const projectMembership = await projectMembershipDAL.findOne({
userId: userPrivilege.userId, userId: userPrivilege.userId,
projectId: userPrivilege.projectId projectId: userPrivilege.projectId
}); });
if (!projectMembership) throw new NotFoundError({ message: "Project membership not found" }); if (!projectMembership)
throw new NotFoundError({
message: `Project membership for user with ID '${userPrivilege.userId}' not found in project with ID '${userPrivilege.projectId}'`
});
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -147,13 +152,17 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
const deleteById = async ({ actorId, actor, actorOrgId, actorAuthMethod, privilegeId }: TDeleteUserPrivilegeDTO) => { const deleteById = async ({ actorId, actor, actorOrgId, actorAuthMethod, privilegeId }: TDeleteUserPrivilegeDTO) => {
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId); const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
if (!userPrivilege) throw new NotFoundError({ message: "User additional privilege not found" }); if (!userPrivilege)
throw new NotFoundError({ message: `User additional privilege with ID '${privilegeId}' not found` });
const projectMembership = await projectMembershipDAL.findOne({ const projectMembership = await projectMembershipDAL.findOne({
userId: userPrivilege.userId, userId: userPrivilege.userId,
projectId: userPrivilege.projectId projectId: userPrivilege.projectId
}); });
if (!projectMembership) throw new NotFoundError({ message: "Project membership not found" }); if (!projectMembership)
throw new NotFoundError({
message: `Project membership for user with ID '${userPrivilege.userId}' not found in project with ID '${userPrivilege.projectId}'`
});
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -176,13 +185,17 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TGetUserPrivilegeDetailsDTO) => { }: TGetUserPrivilegeDetailsDTO) => {
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId); const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
if (!userPrivilege) throw new NotFoundError({ message: "User additional privilege not found" }); if (!userPrivilege)
throw new NotFoundError({ message: `User additional privilege with ID '${privilegeId}' not found` });
const projectMembership = await projectMembershipDAL.findOne({ const projectMembership = await projectMembershipDAL.findOne({
userId: userPrivilege.userId, userId: userPrivilege.userId,
projectId: userPrivilege.projectId projectId: userPrivilege.projectId
}); });
if (!projectMembership) throw new NotFoundError({ message: "Project membership not found" }); if (!projectMembership)
throw new NotFoundError({
message: `Project membership for user with ID '${userPrivilege.userId}' not found in project with ID '${userPrivilege.projectId}'`
});
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -204,7 +217,8 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TListUserPrivilegesDTO) => { }: TListUserPrivilegesDTO) => {
const projectMembership = await projectMembershipDAL.findById(projectMembershipId); const projectMembership = await projectMembershipDAL.findById(projectMembershipId);
if (!projectMembership) throw new NotFoundError({ message: "Project membership not found" }); if (!projectMembership)
throw new NotFoundError({ message: `Project membership with ID '${projectMembershipId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -191,7 +191,11 @@ export const samlConfigServiceFactory = ({
const updateQuery: TSamlConfigsUpdate = { authProvider, isActive, lastUsed: null }; const updateQuery: TSamlConfigsUpdate = { authProvider, isActive, lastUsed: null };
const orgBot = await orgBotDAL.findOne({ orgId }); const orgBot = await orgBotDAL.findOne({ orgId });
if (!orgBot) throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); if (!orgBot)
throw new NotFoundError({
message: `Organization bot not found for organization with ID '${orgId}'`,
name: "OrgBotNotFound"
});
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
iv: orgBot.symmetricKeyIV, iv: orgBot.symmetricKeyIV,
@ -257,7 +261,7 @@ export const samlConfigServiceFactory = ({
ssoConfig = await samlConfigDAL.findById(id); ssoConfig = await samlConfigDAL.findById(id);
} }
if (!ssoConfig) throw new NotFoundError({ message: "Failed to find organization SSO data" }); if (!ssoConfig) throw new NotFoundError({ message: `Failed to find SSO data` });
// when dto is type id means it's internally used // when dto is type id means it's internally used
if (dto.type === "org") { if (dto.type === "org") {
@ -283,7 +287,11 @@ export const samlConfigServiceFactory = ({
} = ssoConfig; } = ssoConfig;
const orgBot = await orgBotDAL.findOne({ orgId: ssoConfig.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: ssoConfig.orgId });
if (!orgBot) throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); if (!orgBot)
throw new NotFoundError({
message: `Organization bot not found in organization with ID '${ssoConfig.orgId}'`,
name: "OrgBotNotFound"
});
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
iv: orgBot.symmetricKeyIV, iv: orgBot.symmetricKeyIV,
@ -355,7 +363,7 @@ export const samlConfigServiceFactory = ({
}); });
const organization = await orgDAL.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) throw new NotFoundError({ message: "Organization not found" }); if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
let user: TUsers; let user: TUsers;
if (userAlias) { if (userAlias) {

View File

@ -183,7 +183,7 @@ export const scimServiceFactory = ({
const deleteScimToken = async ({ scimTokenId, actor, actorId, actorAuthMethod, actorOrgId }: TDeleteScimTokenDTO) => { const deleteScimToken = async ({ scimTokenId, actor, actorId, actorAuthMethod, actorOrgId }: TDeleteScimTokenDTO) => {
let scimToken = await scimDAL.findById(scimTokenId); let scimToken = await scimDAL.findById(scimTokenId);
if (!scimToken) throw new NotFoundError({ message: "Failed to find SCIM token to delete" }); if (!scimToken) throw new NotFoundError({ message: `SCIM token with ID '${scimTokenId}' not found` });
const { permission } = await permissionService.getOrgPermission( const { permission } = await permissionService.getOrgPermission(
actor, actor,
@ -834,10 +834,12 @@ export const scimServiceFactory = ({
}); });
} }
const users = await groupDAL.findAllGroupPossibleMembers({ const users = await groupDAL
.findAllGroupPossibleMembers({
orgId: group.orgId, orgId: group.orgId,
groupId: group.id groupId: group.id
}); })
.then((g) => g.members);
const orgMemberships = await orgDAL.findMembership({ const orgMemberships = await orgDAL.findMembership({
[`${TableName.OrgMembership}.orgId` as "orgId"]: orgId, [`${TableName.OrgMembership}.orgId` as "orgId"]: orgId,

View File

@ -95,7 +95,10 @@ export const secretApprovalPolicyServiceFactory = ({
} }
const env = await projectEnvDAL.findOne({ slug: environment, projectId }); const env = await projectEnvDAL.findOne({ slug: environment, projectId });
if (!env) throw new NotFoundError({ message: "Environment not found" }); if (!env)
throw new NotFoundError({
message: `Environment with slug '${environment}' not found in project with ID ${projectId}`
});
const secretApproval = await secretApprovalPolicyDAL.transaction(async (tx) => { const secretApproval = await secretApprovalPolicyDAL.transaction(async (tx) => {
const doc = await secretApprovalPolicyDAL.create( const doc = await secretApprovalPolicyDAL.create(
@ -178,7 +181,11 @@ export const secretApprovalPolicyServiceFactory = ({
.filter(Boolean) as string[]; .filter(Boolean) as string[];
const secretApprovalPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId); const secretApprovalPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId);
if (!secretApprovalPolicy) throw new NotFoundError({ message: "Secret approval policy not found" }); if (!secretApprovalPolicy) {
throw new NotFoundError({
message: `Secret approval policy with ID '${secretPolicyId}' not found`
});
}
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -271,7 +278,8 @@ export const secretApprovalPolicyServiceFactory = ({
actorOrgId actorOrgId
}: TDeleteSapDTO) => { }: TDeleteSapDTO) => {
const sapPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId); const sapPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId);
if (!sapPolicy) throw new NotFoundError({ message: "Secret approval policy not found" }); if (!sapPolicy)
throw new NotFoundError({ message: `Secret approval policy with ID '${secretPolicyId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -320,7 +328,11 @@ export const secretApprovalPolicyServiceFactory = ({
const getSecretApprovalPolicy = async (projectId: string, environment: string, path: string) => { const getSecretApprovalPolicy = async (projectId: string, environment: string, path: string) => {
const secretPath = removeTrailingSlash(path); const secretPath = removeTrailingSlash(path);
const env = await projectEnvDAL.findOne({ slug: environment, projectId }); const env = await projectEnvDAL.findOne({ slug: environment, projectId });
if (!env) throw new NotFoundError({ message: "Environment not found" }); if (!env) {
throw new NotFoundError({
message: `Environment with slug '${environment}' not found in project with ID ${projectId}`
});
}
const policies = await secretApprovalPolicyDAL.find({ envId: env.id }); const policies = await secretApprovalPolicyDAL.find({ envId: env.id });
if (!policies.length) return; if (!policies.length) return;
@ -369,7 +381,7 @@ export const secretApprovalPolicyServiceFactory = ({
if (!sapPolicy) { if (!sapPolicy) {
throw new NotFoundError({ throw new NotFoundError({
message: "Cannot find secret approval policy" message: `Secret approval policy with ID '${sapId}' not found`
}); });
} }

View File

@ -204,7 +204,8 @@ export const secretApprovalRequestServiceFactory = ({
if (actor === ActorType.SERVICE) throw new BadRequestError({ message: "Cannot use service token" }); if (actor === ActorType.SERVICE) throw new BadRequestError({ message: "Cannot use service token" });
const secretApprovalRequest = await secretApprovalRequestDAL.findById(id); const secretApprovalRequest = await secretApprovalRequestDAL.findById(id);
if (!secretApprovalRequest) throw new NotFoundError({ message: "Secret approval request not found" }); if (!secretApprovalRequest)
throw new NotFoundError({ message: `Secret approval request with ID '${id}' not found` });
const { projectId } = secretApprovalRequest; const { projectId } = secretApprovalRequest;
const { botKey, shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId); const { botKey, shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);
@ -271,7 +272,7 @@ export const secretApprovalRequestServiceFactory = ({
: undefined : undefined
})); }));
} else { } else {
if (!botKey) throw new NotFoundError({ message: "Project bot key not found" }); if (!botKey) throw new NotFoundError({ message: `Project bot key not found`, name: "BotKeyNotFound" }); // CLI depends on this error message. TODO(daniel): Make API check for name BotKeyNotFound instead of message
const encrypedSecrets = await secretApprovalRequestSecretDAL.findByRequestId(secretApprovalRequest.id); const encrypedSecrets = await secretApprovalRequestSecretDAL.findByRequestId(secretApprovalRequest.id);
secrets = encrypedSecrets.map((el) => ({ secrets = encrypedSecrets.map((el) => ({
...el, ...el,
@ -307,7 +308,9 @@ export const secretApprovalRequestServiceFactory = ({
actorOrgId actorOrgId
}: TReviewRequestDTO) => { }: TReviewRequestDTO) => {
const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId); const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
if (!secretApprovalRequest) throw new NotFoundError({ message: "Secret approval request not found" }); if (!secretApprovalRequest) {
throw new NotFoundError({ message: `Secret approval request with ID '${approvalId}' not found` });
}
if (actor !== ActorType.USER) throw new BadRequestError({ message: "Must be a user" }); if (actor !== ActorType.USER) throw new BadRequestError({ message: "Must be a user" });
const plan = await licenseService.getPlan(actorOrgId); const plan = await licenseService.getPlan(actorOrgId);
@ -365,7 +368,9 @@ export const secretApprovalRequestServiceFactory = ({
actorAuthMethod actorAuthMethod
}: TStatusChangeDTO) => { }: TStatusChangeDTO) => {
const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId); const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
if (!secretApprovalRequest) throw new NotFoundError({ message: "Secret approval request not found" }); if (!secretApprovalRequest) {
throw new NotFoundError({ message: `Secret approval request with ID '${approvalId}' not found` });
}
if (actor !== ActorType.USER) throw new BadRequestError({ message: "Must be a user" }); if (actor !== ActorType.USER) throw new BadRequestError({ message: "Must be a user" });
const plan = await licenseService.getPlan(actorOrgId); const plan = await licenseService.getPlan(actorOrgId);
@ -414,7 +419,8 @@ export const secretApprovalRequestServiceFactory = ({
bypassReason bypassReason
}: TMergeSecretApprovalRequestDTO) => { }: TMergeSecretApprovalRequestDTO) => {
const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId); const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
if (!secretApprovalRequest) throw new NotFoundError({ message: "Secret approval request not found" }); if (!secretApprovalRequest)
throw new NotFoundError({ message: `Secret approval request with ID '${approvalId}' not found` });
if (actor !== ActorType.USER) throw new BadRequestError({ message: "Must be a user" }); if (actor !== ActorType.USER) throw new BadRequestError({ message: "Must be a user" });
const plan = await licenseService.getPlan(actorOrgId); const plan = await licenseService.getPlan(actorOrgId);
@ -462,7 +468,9 @@ export const secretApprovalRequestServiceFactory = ({
const secretApprovalSecrets = await secretApprovalRequestSecretDAL.findByRequestIdBridgeSecretV2( const secretApprovalSecrets = await secretApprovalRequestSecretDAL.findByRequestIdBridgeSecretV2(
secretApprovalRequest.id secretApprovalRequest.id
); );
if (!secretApprovalSecrets) throw new NotFoundError({ message: "No secrets found" }); if (!secretApprovalSecrets) {
throw new NotFoundError({ message: `No secrets found in secret change request with ID '${approvalId}'` });
}
const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({ const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.SecretManager, type: KmsDataKey.SecretManager,
@ -602,7 +610,9 @@ export const secretApprovalRequestServiceFactory = ({
}); });
} else { } else {
const secretApprovalSecrets = await secretApprovalRequestSecretDAL.findByRequestId(secretApprovalRequest.id); const secretApprovalSecrets = await secretApprovalRequestSecretDAL.findByRequestId(secretApprovalRequest.id);
if (!secretApprovalSecrets) throw new NotFoundError({ message: "No secrets found" }); if (!secretApprovalSecrets) {
throw new NotFoundError({ message: `No secrets found in secret change request with ID '${approvalId}'` });
}
const conflicts: Array<{ secretId: string; op: SecretOperations }> = []; const conflicts: Array<{ secretId: string; op: SecretOperations }> = [];
let secretCreationCommits = secretApprovalSecrets.filter(({ op }) => op === SecretOperations.Create); let secretCreationCommits = secretApprovalSecrets.filter(({ op }) => op === SecretOperations.Create);
@ -610,10 +620,10 @@ export const secretApprovalRequestServiceFactory = ({
const { secsGroupedByBlindIndex: conflictGroupByBlindIndex } = await fnSecretBlindIndexCheckV2({ const { secsGroupedByBlindIndex: conflictGroupByBlindIndex } = await fnSecretBlindIndexCheckV2({
folderId, folderId,
secretDAL, secretDAL,
inputSecrets: secretCreationCommits.map(({ secretBlindIndex }) => { inputSecrets: secretCreationCommits.map(({ secretBlindIndex, secret }) => {
if (!secretBlindIndex) { if (!secretBlindIndex) {
throw new NotFoundError({ throw new NotFoundError({
message: "Secret blind index not found" message: `Secret blind index not found on secret with ID '${secret.id}`
}); });
} }
return { secretBlindIndex }; return { secretBlindIndex };
@ -637,10 +647,10 @@ export const secretApprovalRequestServiceFactory = ({
userId: "", userId: "",
inputSecrets: secretUpdationCommits inputSecrets: secretUpdationCommits
.filter(({ secretBlindIndex, secret }) => secret && secret.secretBlindIndex !== secretBlindIndex) .filter(({ secretBlindIndex, secret }) => secret && secret.secretBlindIndex !== secretBlindIndex)
.map(({ secretBlindIndex }) => { .map(({ secretBlindIndex, secret }) => {
if (!secretBlindIndex) { if (!secretBlindIndex) {
throw new NotFoundError({ throw new NotFoundError({
message: "Secret blind index not found" message: `Secret blind index not found on secret with ID '${secret.id}`
}); });
} }
return { secretBlindIndex }; return { secretBlindIndex };
@ -760,10 +770,10 @@ export const secretApprovalRequestServiceFactory = ({
actorId: "", actorId: "",
secretDAL, secretDAL,
secretQueueService, secretQueueService,
inputSecrets: secretDeletionCommits.map(({ secretBlindIndex }) => { inputSecrets: secretDeletionCommits.map(({ secretBlindIndex, secret }) => {
if (!secretBlindIndex) { if (!secretBlindIndex) {
throw new NotFoundError({ throw new NotFoundError({
message: "Secret blind index not found" message: `Secret blind index not found on secret with ID '${secret.id}`
}); });
} }
return { secretBlindIndex, type: SecretType.Shared }; return { secretBlindIndex, type: SecretType.Shared };
@ -789,7 +799,9 @@ export const secretApprovalRequestServiceFactory = ({
await snapshotService.performSnapshot(folderId); await snapshotService.performSnapshot(folderId);
const [folder] = await folderDAL.findSecretPathByFolderIds(projectId, [folderId]); const [folder] = await folderDAL.findSecretPathByFolderIds(projectId, [folderId]);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) {
throw new NotFoundError({ message: `Folder with ID '${folderId}' not found in project with ID '${projectId}'` });
}
await secretQueueService.syncSecrets({ await secretQueueService.syncSecrets({
projectId, projectId,
secretPath: folder.path, secretPath: folder.path,
@ -861,14 +873,18 @@ export const secretApprovalRequestServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder not found for environment with slug '${environment}' & secret path '${secretPath}'`,
name: "GenSecretApproval" name: "GenSecretApproval"
}); });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) throw new NotFoundError({ message: "Blind index not found", name: "Update secret" }); if (!blindIndexCfg) {
throw new NotFoundError({
message: `Blind index not found for project with ID '${projectId}'`,
name: "Update secret"
});
}
const commits: Omit<TSecretApprovalRequestsSecretsInsert, "requestId">[] = []; const commits: Omit<TSecretApprovalRequestsSecretsInsert, "requestId">[] = [];
const commitTagIds: Record<string, string[]> = {}; const commitTagIds: Record<string, string[]> = {};
// for created secret approval change // for created secret approval change
@ -961,7 +977,9 @@ export const secretApprovalRequestServiceFactory = ({
secretDAL secretDAL
}); });
const secretsGroupedByBlindIndex = groupBy(secrets, (i) => { const secretsGroupedByBlindIndex = groupBy(secrets, (i) => {
if (!i.secretBlindIndex) throw new NotFoundError({ message: "Secret blind index not found" }); if (!i.secretBlindIndex) {
throw new NotFoundError({ message: `Secret blind index not found for secret with ID '${i.id}'` });
}
return i.secretBlindIndex; return i.secretBlindIndex;
}); });
const deletedSecretIds = deletedSecrets.map( const deletedSecretIds = deletedSecrets.map(
@ -972,7 +990,7 @@ export const secretApprovalRequestServiceFactory = ({
...deletedSecrets.map((el) => { ...deletedSecrets.map((el) => {
const secretId = secretsGroupedByBlindIndex[keyName2BlindIndex[el.secretName]][0].id; const secretId = secretsGroupedByBlindIndex[keyName2BlindIndex[el.secretName]][0].id;
if (!latestSecretVersions[secretId].secretBlindIndex) if (!latestSecretVersions[secretId].secretBlindIndex)
throw new NotFoundError({ message: "Secret blind index not found" }); throw new NotFoundError({ message: `Secret blind index not found for secret with ID '${secretId}'` });
return { return {
op: SecretOperations.Delete as const, op: SecretOperations.Delete as const,
...latestSecretVersions[secretId], ...latestSecretVersions[secretId],
@ -988,7 +1006,7 @@ export const secretApprovalRequestServiceFactory = ({
const tagIds = unique(Object.values(commitTagIds).flat()); const tagIds = unique(Object.values(commitTagIds).flat());
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tagIds.length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if (tagIds.length !== tags.length) throw new NotFoundError({ message: "One or more tags not found" });
const secretApprovalRequest = await secretApprovalRequestDAL.transaction(async (tx) => { const secretApprovalRequest = await secretApprovalRequestDAL.transaction(async (tx) => {
const doc = await secretApprovalRequestDAL.create( const doc = await secretApprovalRequestDAL.create(
@ -1054,7 +1072,7 @@ export const secretApprovalRequestServiceFactory = ({
const commitsGroupByBlindIndex = groupBy(approvalCommits, (i) => { const commitsGroupByBlindIndex = groupBy(approvalCommits, (i) => {
if (!i.secretBlindIndex) { if (!i.secretBlindIndex) {
throw new NotFoundError({ message: "Secret blind index not found" }); throw new NotFoundError({ message: `Secret blind index not found for secret with ID '${i.id}'` });
} }
return i.secretBlindIndex; return i.secretBlindIndex;
}); });
@ -1133,7 +1151,7 @@ export const secretApprovalRequestServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder not found for the environment slug '${environment}' & secret path '${secretPath}'`,
name: "GenSecretApproval" name: "GenSecretApproval"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -1291,7 +1309,7 @@ export const secretApprovalRequestServiceFactory = ({
const tagIds = unique(Object.values(commitTagIds).flat()); const tagIds = unique(Object.values(commitTagIds).flat());
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tagIds.length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if (tagIds.length !== tags.length) throw new NotFoundError({ message: "One or more tags not found" });
const secretApprovalRequest = await secretApprovalRequestDAL.transaction(async (tx) => { const secretApprovalRequest = await secretApprovalRequestDAL.transaction(async (tx) => {
const doc = await secretApprovalRequestDAL.create( const doc = await secretApprovalRequestDAL.create(

View File

@ -295,7 +295,10 @@ export const secretReplicationServiceFactory = ({
const [destinationFolder] = await folderDAL.findSecretPathByFolderIds(projectId, [ const [destinationFolder] = await folderDAL.findSecretPathByFolderIds(projectId, [
destinationSecretImport.folderId destinationSecretImport.folderId
]); ]);
if (!destinationFolder) throw new NotFoundError({ message: "Imported folder not found" }); if (!destinationFolder)
throw new NotFoundError({
message: `Imported folder with ID '${destinationSecretImport.folderId}' not found in project with ID ${projectId}`
});
let destinationReplicationFolder = await folderDAL.findOne({ let destinationReplicationFolder = await folderDAL.findOne({
parentId: destinationFolder.id, parentId: destinationFolder.id,
@ -506,7 +509,7 @@ export const secretReplicationServiceFactory = ({
return; return;
} }
if (!botKey) throw new NotFoundError({ message: "Project bot not found" }); if (!botKey) throw new NotFoundError({ message: `Bot key not found for project with ID ${projectId}` });
// these are the secrets to be added in replicated folders // these are the secrets to be added in replicated folders
const sourceLocalSecrets = await secretDAL.find({ folderId: folder.id, type: SecretType.Shared }); const sourceLocalSecrets = await secretDAL.find({ folderId: folder.id, type: SecretType.Shared });
const sourceSecretImports = await secretImportDAL.find({ folderId: folder.id }); const sourceSecretImports = await secretImportDAL.find({ folderId: folder.id });
@ -545,7 +548,11 @@ export const secretReplicationServiceFactory = ({
const [destinationFolder] = await folderDAL.findSecretPathByFolderIds(projectId, [ const [destinationFolder] = await folderDAL.findSecretPathByFolderIds(projectId, [
destinationSecretImport.folderId destinationSecretImport.folderId
]); ]);
if (!destinationFolder) throw new NotFoundError({ message: "Imported folder not found" }); if (!destinationFolder) {
throw new NotFoundError({
message: `Imported folder with ID '${destinationSecretImport.folderId}' not found in project with ID ${projectId}`
});
}
let destinationReplicationFolder = await folderDAL.findOne({ let destinationReplicationFolder = await folderDAL.findOne({
parentId: destinationFolder.id, parentId: destinationFolder.id,

View File

@ -332,7 +332,10 @@ export const secretRotationQueueFactory = ({
); );
}); });
} else { } else {
if (!botKey) throw new NotFoundError({ message: "Project bot not found" }); if (!botKey)
throw new NotFoundError({
message: `Project bot not found for project with ID '${secretRotation.projectId}'`
});
const encryptedSecrets = rotationOutputs.map(({ key: outputKey, secretId }) => ({ const encryptedSecrets = rotationOutputs.map(({ key: outputKey, secretId }) => ({
secretId, secretId,
value: encryptSymmetric128BitHexKeyUTF8( value: encryptSymmetric128BitHexKeyUTF8(
@ -372,7 +375,9 @@ export const secretRotationQueueFactory = ({
); );
await secretVersionDAL.insertMany( await secretVersionDAL.insertMany(
updatedSecrets.map(({ id, updatedAt, createdAt, ...el }) => { updatedSecrets.map(({ id, updatedAt, createdAt, ...el }) => {
if (!el.secretBlindIndex) throw new NotFoundError({ message: "Secret blind index not found" }); if (!el.secretBlindIndex) {
throw new NotFoundError({ message: `Secret blind index not found on secret with ID '${id}` });
}
return { return {
...el, ...el,
secretId: id, secretId: id,

View File

@ -94,7 +94,11 @@ export const secretRotationServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new NotFoundError({ message: "Secret path not found" }); if (!folder) {
throw new NotFoundError({
message: `Secret path with path '${secretPath}' not found in environment with slug '${environment}'`
});
}
ForbiddenError.from(permission).throwUnlessCan( ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionActions.Edit, ProjectPermissionActions.Edit,
subject(ProjectPermissionSub.Secrets, { environment, secretPath }) subject(ProjectPermissionSub.Secrets, { environment, secretPath })
@ -108,14 +112,14 @@ export const secretRotationServiceFactory = ({
$in: { id: Object.values(outputs) } $in: { id: Object.values(outputs) }
}); });
if (selectedSecrets.length !== Object.values(outputs).length) if (selectedSecrets.length !== Object.values(outputs).length)
throw new NotFoundError({ message: "Secrets not found" }); throw new NotFoundError({ message: `Secrets not found in folder with ID '${folder.id}'` });
} else { } else {
const selectedSecrets = await secretDAL.find({ const selectedSecrets = await secretDAL.find({
folderId: folder.id, folderId: folder.id,
$in: { id: Object.values(outputs) } $in: { id: Object.values(outputs) }
}); });
if (selectedSecrets.length !== Object.values(outputs).length) if (selectedSecrets.length !== Object.values(outputs).length)
throw new NotFoundError({ message: "Secrets not found" }); throw new NotFoundError({ message: `Secrets not found in folder with ID '${folder.id}'` });
} }
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
@ -125,7 +129,7 @@ export const secretRotationServiceFactory = ({
}); });
const selectedTemplate = rotationTemplates.find(({ name }) => name === provider); const selectedTemplate = rotationTemplates.find(({ name }) => name === provider);
if (!selectedTemplate) throw new NotFoundError({ message: "Provider not found" }); if (!selectedTemplate) throw new NotFoundError({ message: `Provider with name '${provider}' not found` });
const formattedInputs: Record<string, unknown> = {}; const formattedInputs: Record<string, unknown> = {};
Object.entries(inputs).forEach(([key, value]) => { Object.entries(inputs).forEach(([key, value]) => {
const { type } = selectedTemplate.template.inputs.properties[key]; const { type } = selectedTemplate.template.inputs.properties[key];
@ -198,7 +202,7 @@ export const secretRotationServiceFactory = ({
return docs; return docs;
} }
if (!botKey) throw new NotFoundError({ message: "Project bot not found" }); if (!botKey) throw new NotFoundError({ message: `Project bot not found for project with ID '${projectId}'` });
const docs = await secretRotationDAL.find({ projectId }); const docs = await secretRotationDAL.find({ projectId });
return docs.map((el) => ({ return docs.map((el) => ({
...el, ...el,
@ -220,7 +224,7 @@ export const secretRotationServiceFactory = ({
const restartById = async ({ actor, actorId, actorOrgId, actorAuthMethod, rotationId }: TRestartDTO) => { const restartById = async ({ actor, actorId, actorOrgId, actorAuthMethod, rotationId }: TRestartDTO) => {
const doc = await secretRotationDAL.findById(rotationId); const doc = await secretRotationDAL.findById(rotationId);
if (!doc) throw new NotFoundError({ message: "Rotation not found" }); if (!doc) throw new NotFoundError({ message: `Rotation with ID '${rotationId}' not found` });
const project = await projectDAL.findById(doc.projectId); const project = await projectDAL.findById(doc.projectId);
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
@ -244,7 +248,7 @@ export const secretRotationServiceFactory = ({
const deleteById = async ({ actor, actorId, actorOrgId, actorAuthMethod, rotationId }: TDeleteDTO) => { const deleteById = async ({ actor, actorId, actorOrgId, actorAuthMethod, rotationId }: TDeleteDTO) => {
const doc = await secretRotationDAL.findById(rotationId); const doc = await secretRotationDAL.findById(rotationId);
if (!doc) throw new NotFoundError({ message: "Rotation not found" }); if (!doc) throw new NotFoundError({ message: `Rotation with ID '${rotationId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -99,7 +99,11 @@ export const secretSnapshotServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) {
throw new NotFoundError({
message: `Folder with path '${path}' not found in environment with slug '${environment}'`
});
}
return snapshotDAL.countOfSnapshotsByFolderId(folder.id); return snapshotDAL.countOfSnapshotsByFolderId(folder.id);
}; };
@ -131,7 +135,10 @@ export const secretSnapshotServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${path}' not found in environment with slug '${environment}'`
});
const snapshots = await snapshotDAL.find({ folderId: folder.id }, { limit, offset, sort: [["createdAt", "desc"]] }); const snapshots = await snapshotDAL.find({ folderId: folder.id }, { limit, offset, sort: [["createdAt", "desc"]] });
return snapshots; return snapshots;
@ -139,7 +146,7 @@ export const secretSnapshotServiceFactory = ({
const getSnapshotData = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TGetSnapshotDataDTO) => { const getSnapshotData = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TGetSnapshotDataDTO) => {
const snapshot = await snapshotDAL.findById(id); const snapshot = await snapshotDAL.findById(id);
if (!snapshot) throw new NotFoundError({ message: "Snapshot not found" }); if (!snapshot) throw new NotFoundError({ message: `Snapshot with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
actorId, actorId,
@ -173,7 +180,8 @@ export const secretSnapshotServiceFactory = ({
} else { } else {
const encryptedSnapshotDetails = await snapshotDAL.findSecretSnapshotDataById(id); const encryptedSnapshotDetails = await snapshotDAL.findSecretSnapshotDataById(id);
const { botKey } = await projectBotService.getBotKey(snapshot.projectId); const { botKey } = await projectBotService.getBotKey(snapshot.projectId);
if (!botKey) throw new NotFoundError({ message: "Project bot not found" }); if (!botKey)
throw new NotFoundError({ message: `Project bot key not found for project with ID '${snapshot.projectId}'` });
snapshotDetails = { snapshotDetails = {
...encryptedSnapshotDetails, ...encryptedSnapshotDetails,
secretVersions: encryptedSnapshotDetails.secretVersions.map((el) => ({ secretVersions: encryptedSnapshotDetails.secretVersions.map((el) => ({
@ -225,7 +233,7 @@ export const secretSnapshotServiceFactory = ({
try { try {
if (!licenseService.isValidLicense) throw new InternalServerError({ message: "Invalid license" }); if (!licenseService.isValidLicense) throw new InternalServerError({ message: "Invalid license" });
const folder = await folderDAL.findById(folderId); const folder = await folderDAL.findById(folderId);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
const shouldUseSecretV2Bridge = folder.projectVersion === 3; const shouldUseSecretV2Bridge = folder.projectVersion === 3;
if (shouldUseSecretV2Bridge) { if (shouldUseSecretV2Bridge) {
@ -311,7 +319,7 @@ export const secretSnapshotServiceFactory = ({
actorOrgId actorOrgId
}: TRollbackSnapshotDTO) => { }: TRollbackSnapshotDTO) => {
const snapshot = await snapshotDAL.findById(snapshotId); const snapshot = await snapshotDAL.findById(snapshotId);
if (!snapshot) throw new NotFoundError({ message: "Snapshot not found" }); if (!snapshot) throw new NotFoundError({ message: `Snapshot with ID '${snapshotId}' not found` });
const shouldUseBridge = snapshot.projectVersion === 3; const shouldUseBridge = snapshot.projectVersion === 3;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(

View File

@ -18,7 +18,8 @@ export const GROUPS = {
id: "The id of the group to list users for", id: "The id of the group to list users for",
offset: "The offset to start from. If you enter 10, it will start from the 10th user.", offset: "The offset to start from. If you enter 10, it will start from the 10th user.",
limit: "The number of users to return.", limit: "The number of users to return.",
username: "The username to search for." username: "The username to search for.",
search: "The text string that user email or name will be filtered by."
}, },
ADD_USER: { ADD_USER: {
id: "The id of the group to add the user to.", id: "The id of the group to add the user to.",

View File

@ -18,6 +18,7 @@ export type TAuthMode =
user: TUsers; user: TUsers;
orgId: string; orgId: string;
authMethod: AuthMethod; authMethod: AuthMethod;
isMfaVerified?: boolean;
} }
| { | {
authMode: AuthMode.API_KEY; authMode: AuthMode.API_KEY;
@ -121,7 +122,8 @@ export const injectIdentity = fp(async (server: FastifyZodProvider) => {
tokenVersionId, tokenVersionId,
actor, actor,
orgId: orgId as string, orgId: orgId as string,
authMethod: token.authMethod authMethod: token.authMethod,
isMfaVerified: token.isMfaVerified
}; };
break; break;
} }

View File

@ -107,7 +107,8 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
userId: decodedToken.userId, userId: decodedToken.userId,
tokenVersionId: tokenVersion.id, tokenVersionId: tokenVersion.id,
accessVersion: tokenVersion.accessVersion, accessVersion: tokenVersion.accessVersion,
organizationId: decodedToken.organizationId organizationId: decodedToken.organizationId,
isMfaVerified: decodedToken.isMfaVerified
}, },
appCfg.AUTH_SECRET, appCfg.AUTH_SECRET,
{ expiresIn: appCfg.JWT_AUTH_LIFETIME } { expiresIn: appCfg.JWT_AUTH_LIFETIME }

View File

@ -258,7 +258,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
.refine((v) => slugify(v) === v, { .refine((v) => slugify(v) === v, {
message: "Membership role must be a valid slug" message: "Membership role must be a valid slug"
}) })
.optional() .optional(),
enforceMfa: z.boolean().optional()
}), }),
response: { response: {
200: z.object({ 200: z.object({

View File

@ -280,10 +280,6 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
providerAuthToken: req.body.providerAuthToken providerAuthToken: req.body.providerAuthToken
}); });
if (data.isMfaEnabled) {
return { mfaEnabled: true, token: data.token } as const; // for discriminated union
}
void res.setCookie("jid", data.token.refresh, { void res.setCookie("jid", data.token.refresh, {
httpOnly: true, httpOnly: true,
path: "/", path: "/",
@ -292,7 +288,6 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
}); });
return { return {
mfaEnabled: false,
encryptionVersion: data.user.encryptionVersion, encryptionVersion: data.user.encryptionVersion,
token: data.token.access, token: data.token.access,
publicKey: data.user.publicKey, publicKey: data.user.publicKey,

View File

@ -47,7 +47,8 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
}), }),
response: { response: {
200: z.object({ 200: z.object({
token: z.string() token: z.string(),
isMfaEnabled: z.boolean()
}) })
} }
}, },
@ -60,6 +61,13 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
ipAddress: req.realIp ipAddress: req.realIp
}); });
if (tokens.isMfaEnabled) {
return {
token: tokens.mfa as string,
isMfaEnabled: true
};
}
void res.setCookie("jid", tokens.refresh, { void res.setCookie("jid", tokens.refresh, {
httpOnly: true, httpOnly: true,
path: "/", path: "/",
@ -67,7 +75,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
secure: cfg.HTTPS_ENABLED secure: cfg.HTTPS_ENABLED
}); });
return { token: tokens.access }; return { token: tokens.access, isMfaEnabled: false };
} }
}); });
@ -86,10 +94,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
password: z.string().optional() password: z.string().optional()
}), }),
response: { response: {
200: z.discriminatedUnion("mfaEnabled", [ 200: z.object({
z.object({ mfaEnabled: z.literal(true), token: z.string() }),
z.object({
mfaEnabled: z.literal(false),
encryptionVersion: z.number().default(1).nullable().optional(), encryptionVersion: z.number().default(1).nullable().optional(),
protectedKey: z.string().nullable(), protectedKey: z.string().nullable(),
protectedKeyIV: z.string().nullable(), protectedKeyIV: z.string().nullable(),
@ -100,7 +105,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
tag: z.string(), tag: z.string(),
token: z.string() token: z.string()
}) })
])
} }
}, },
handler: async (req, res) => { handler: async (req, res) => {
@ -118,10 +122,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
password: req.body.password password: req.body.password
}); });
if (data.isMfaEnabled) {
return { mfaEnabled: true, token: data.token } as const; // for discriminated union
}
void res.setCookie("jid", data.token.refresh, { void res.setCookie("jid", data.token.refresh, {
httpOnly: true, httpOnly: true,
path: "/", path: "/",
@ -130,7 +130,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
}); });
return { return {
mfaEnabled: false,
encryptionVersion: data.user.encryptionVersion, encryptionVersion: data.user.encryptionVersion,
token: data.token.access, token: data.token.access,
publicKey: data.user.publicKey, publicKey: data.user.publicKey,

View File

@ -45,7 +45,7 @@ export const apiKeyServiceFactory = ({ apiKeyDAL, userDAL }: TApiKeyServiceFacto
const deleteApiKey = async (userId: string, apiKeyId: string) => { const deleteApiKey = async (userId: string, apiKeyId: string) => {
const [apiKeyData] = await apiKeyDAL.delete({ id: apiKeyId, userId }); const [apiKeyData] = await apiKeyDAL.delete({ id: apiKeyId, userId });
if (!apiKeyData) throw new NotFoundError({ message: "API key not found" }); if (!apiKeyData) throw new NotFoundError({ message: `API key with ID '${apiKeyId}' not found` });
return formatApiKey(apiKeyData); return formatApiKey(apiKeyData);
}; };

View File

@ -156,7 +156,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgMembershipDAL }: TAu
} }
const user = await userDAL.findById(session.userId); const user = await userDAL.findById(session.userId);
if (!user || !user.isAccepted) throw new NotFoundError({ message: "User not found" }); if (!user || !user.isAccepted) throw new NotFoundError({ message: `User with ID '${session.userId}' not found` });
if (token.organizationId) { if (token.organizationId) {
const orgMembership = await orgMembershipDAL.findOne({ const orgMembership = await orgMembershipDAL.findOne({

View File

@ -99,13 +99,15 @@ export const authLoginServiceFactory = ({
ip, ip,
userAgent, userAgent,
organizationId, organizationId,
authMethod authMethod,
isMfaVerified
}: { }: {
user: TUsers; user: TUsers;
ip: string; ip: string;
userAgent: string; userAgent: string;
organizationId?: string; organizationId?: string;
authMethod: AuthMethod; authMethod: AuthMethod;
isMfaVerified?: boolean;
}) => { }) => {
const cfg = getConfig(); const cfg = getConfig();
await updateUserDeviceSession(user, ip, userAgent); await updateUserDeviceSession(user, ip, userAgent);
@ -123,7 +125,8 @@ export const authLoginServiceFactory = ({
userId: user.id, userId: user.id,
tokenVersionId: tokenSession.id, tokenVersionId: tokenSession.id,
accessVersion: tokenSession.accessVersion, accessVersion: tokenSession.accessVersion,
organizationId organizationId,
isMfaVerified
}, },
cfg.AUTH_SECRET, cfg.AUTH_SECRET,
{ expiresIn: cfg.JWT_AUTH_LIFETIME } { expiresIn: cfg.JWT_AUTH_LIFETIME }
@ -136,7 +139,8 @@ export const authLoginServiceFactory = ({
userId: user.id, userId: user.id,
tokenVersionId: tokenSession.id, tokenVersionId: tokenSession.id,
refreshVersion: tokenSession.refreshVersion, refreshVersion: tokenSession.refreshVersion,
organizationId organizationId,
isMfaVerified
}, },
cfg.AUTH_SECRET, cfg.AUTH_SECRET,
{ expiresIn: cfg.JWT_REFRESH_LIFETIME } { expiresIn: cfg.JWT_REFRESH_LIFETIME }
@ -298,30 +302,6 @@ export const authLoginServiceFactory = ({
}); });
} }
// send multi factor auth token if they it enabled
if (userEnc.isMfaEnabled && userEnc.email) {
enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
const mfaToken = jwt.sign(
{
authMethod,
authTokenType: AuthTokenType.MFA_TOKEN,
userId: userEnc.userId
},
cfg.AUTH_SECRET,
{
expiresIn: cfg.JWT_MFA_LIFETIME
}
);
await sendUserMfaCode({
userId: userEnc.userId,
email: userEnc.email
});
return { isMfaEnabled: true, token: mfaToken } as const;
}
const token = await generateUserTokens({ const token = await generateUserTokens({
user: { user: {
...userEnc, ...userEnc,
@ -333,7 +313,7 @@ export const authLoginServiceFactory = ({
organizationId organizationId
}); });
return { token, isMfaEnabled: false, user: userEnc } as const; return { token, user: userEnc } as const;
}; };
const selectOrganization = async ({ const selectOrganization = async ({
@ -373,15 +353,43 @@ export const authLoginServiceFactory = ({
}); });
} }
// send multi factor auth token if they it enabled
if ((selectedOrg.enforceMfa || user.isMfaEnabled) && user.email && !decodedToken.isMfaVerified) {
enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
const mfaToken = jwt.sign(
{
authMethod: decodedToken.authMethod,
authTokenType: AuthTokenType.MFA_TOKEN,
userId: user.id
},
cfg.AUTH_SECRET,
{
expiresIn: cfg.JWT_MFA_LIFETIME
}
);
await sendUserMfaCode({
userId: user.id,
email: user.email
});
return { isMfaEnabled: true, mfa: mfaToken } as const;
}
const tokens = await generateUserTokens({ const tokens = await generateUserTokens({
authMethod: decodedToken.authMethod, authMethod: decodedToken.authMethod,
user, user,
userAgent, userAgent,
ip: ipAddress, ip: ipAddress,
organizationId organizationId,
isMfaVerified: decodedToken.isMfaVerified
}); });
return tokens; return {
...tokens,
isMfaEnabled: false
};
}; };
/* /*
@ -504,7 +512,8 @@ export const authLoginServiceFactory = ({
ip, ip,
userAgent, userAgent,
organizationId: orgId, organizationId: orgId,
authMethod: decodedToken.authMethod authMethod: decodedToken.authMethod,
isMfaVerified: true
}); });
return { token, user: userEnc }; return { token, user: userEnc };
@ -629,7 +638,6 @@ export const authLoginServiceFactory = ({
const oauth2TokenExchange = async ({ userAgent, ip, providerAuthToken, email }: TOauthTokenExchangeDTO) => { const oauth2TokenExchange = async ({ userAgent, ip, providerAuthToken, email }: TOauthTokenExchangeDTO) => {
const decodedProviderToken = validateProviderAuthToken(providerAuthToken, email); const decodedProviderToken = validateProviderAuthToken(providerAuthToken, email);
const appCfg = getConfig();
const { authMethod, userName } = decodedProviderToken; const { authMethod, userName } = decodedProviderToken;
if (!userName) throw new BadRequestError({ message: "Missing user name" }); if (!userName) throw new BadRequestError({ message: "Missing user name" });
const organizationId = const organizationId =
@ -644,29 +652,6 @@ export const authLoginServiceFactory = ({
if (!userEnc) throw new BadRequestError({ message: "Invalid token" }); if (!userEnc) throw new BadRequestError({ message: "Invalid token" });
if (!userEnc.serverEncryptedPrivateKey) if (!userEnc.serverEncryptedPrivateKey)
throw new BadRequestError({ message: "Key handoff incomplete. Please try logging in again." }); throw new BadRequestError({ message: "Key handoff incomplete. Please try logging in again." });
// send multi factor auth token if they it enabled
if (userEnc.isMfaEnabled && userEnc.email) {
enforceUserLockStatus(Boolean(userEnc.isLocked), userEnc.temporaryLockDateEnd);
const mfaToken = jwt.sign(
{
authMethod,
authTokenType: AuthTokenType.MFA_TOKEN,
userId: userEnc.userId
},
appCfg.AUTH_SECRET,
{
expiresIn: appCfg.JWT_MFA_LIFETIME
}
);
await sendUserMfaCode({
userId: userEnc.userId,
email: userEnc.email
});
return { isMfaEnabled: true, token: mfaToken } as const;
}
const token = await generateUserTokens({ const token = await generateUserTokens({
user: { ...userEnc, id: userEnc.userId }, user: { ...userEnc, id: userEnc.userId },

View File

@ -52,6 +52,7 @@ export type AuthModeJwtTokenPayload = {
tokenVersionId: string; tokenVersionId: string;
accessVersion: number; accessVersion: number;
organizationId?: string; organizationId?: string;
isMfaVerified?: boolean;
}; };
export type AuthModeMfaJwtTokenPayload = { export type AuthModeMfaJwtTokenPayload = {
@ -69,6 +70,7 @@ export type AuthModeRefreshJwtTokenPayload = {
tokenVersionId: string; tokenVersionId: string;
refreshVersion: number; refreshVersion: number;
organizationId?: string; organizationId?: string;
isMfaVerified?: boolean;
}; };
export type AuthModeProviderJwtTokenPayload = { export type AuthModeProviderJwtTokenPayload = {

View File

@ -113,10 +113,10 @@ export const getCaCredentials = async ({
kmsService kmsService
}: TGetCaCredentialsDTO) => { }: TGetCaCredentialsDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const caSecret = await certificateAuthoritySecretDAL.findOne({ caId }); const caSecret = await certificateAuthoritySecretDAL.findOne({ caId });
if (!caSecret) throw new NotFoundError({ message: "CA secret not found" }); if (!caSecret) throw new NotFoundError({ message: `CA secret for CA with ID '${caId}' not found` });
const keyId = await getProjectKmsCertificateKeyId({ const keyId = await getProjectKmsCertificateKeyId({
projectId: ca.projectId, projectId: ca.projectId,
@ -165,7 +165,7 @@ export const getCaCertChains = async ({
kmsService kmsService
}: TGetCaCertChainsDTO) => { }: TGetCaCertChainsDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const keyId = await getProjectKmsCertificateKeyId({ const keyId = await getProjectKmsCertificateKeyId({
projectId: ca.projectId, projectId: ca.projectId,
@ -256,7 +256,7 @@ export const rebuildCaCrl = async ({
kmsService kmsService
}: TRebuildCaCrlDTO) => { }: TRebuildCaCrlDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id }); const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id });

View File

@ -76,7 +76,7 @@ export const certificateAuthorityQueueFactory = ({
logger.info(`secretReminderQueue.process: [secretDocument=${caId}]`); logger.info(`secretReminderQueue.process: [secretDocument=${caId}]`);
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id }); const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id });

View File

@ -122,7 +122,7 @@ export const certificateAuthorityServiceFactory = ({
actorOrgId actorOrgId
}: TCreateCaDTO) => { }: TCreateCaDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -290,7 +290,7 @@ export const certificateAuthorityServiceFactory = ({
*/ */
const getCaById = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaDTO) => { const getCaById = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -321,7 +321,7 @@ export const certificateAuthorityServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateCaDTO) => { }: TUpdateCaDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -346,7 +346,7 @@ export const certificateAuthorityServiceFactory = ({
*/ */
const deleteCaById = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteCaDTO) => { const deleteCaById = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteCaDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -371,7 +371,7 @@ export const certificateAuthorityServiceFactory = ({
*/ */
const getCaCsr = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCsrDTO) => { const getCaCsr = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCsrDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -430,7 +430,7 @@ export const certificateAuthorityServiceFactory = ({
*/ */
const renewCaCert = async ({ caId, notAfter, actorId, actorAuthMethod, actor, actorOrgId }: TRenewCaCertDTO) => { const renewCaCert = async ({ caId, notAfter, actorId, actorAuthMethod, actor, actorOrgId }: TRenewCaCertDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
if (!ca.activeCaCertId) throw new BadRequestError({ message: "CA does not have a certificate installed" }); if (!ca.activeCaCertId) throw new BadRequestError({ message: "CA does not have a certificate installed" });
@ -702,7 +702,7 @@ export const certificateAuthorityServiceFactory = ({
const getCaCerts = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCertsDTO) => { const getCaCerts = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCertsDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -736,7 +736,7 @@ export const certificateAuthorityServiceFactory = ({
*/ */
const getCaCert = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCertDTO) => { const getCaCert = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCertDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
if (!ca.activeCaCertId) throw new BadRequestError({ message: "CA does not have a certificate installed" }); if (!ca.activeCaCertId) throw new BadRequestError({ message: "CA does not have a certificate installed" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -778,7 +778,7 @@ export const certificateAuthorityServiceFactory = ({
}); });
if (!caCert) { if (!caCert) {
throw new NotFoundError({ message: "CA certificate not found" }); throw new NotFoundError({ message: `Ca certificate with ID '${caCertId}' not found for CA with ID '${caId}'` });
} }
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
@ -963,7 +963,7 @@ export const certificateAuthorityServiceFactory = ({
certificateChain certificateChain
}: TImportCertToCaDTO) => { }: TImportCertToCaDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1115,7 +1115,7 @@ export const certificateAuthorityServiceFactory = ({
certificateTemplate = await certificateTemplateDAL.getById(certificateTemplateId); certificateTemplate = await certificateTemplateDAL.getById(certificateTemplateId);
if (!certificateTemplate) { if (!certificateTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found" message: `Certificate template with ID '${certificateTemplateId}' not found`
}); });
} }
@ -1124,7 +1124,7 @@ export const certificateAuthorityServiceFactory = ({
} }
if (!ca) { if (!ca) {
throw new NotFoundError({ message: "CA not found" }); throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
} }
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -1442,7 +1442,7 @@ export const certificateAuthorityServiceFactory = ({
certificateTemplate = await certificateTemplateDAL.getById(certificateTemplateId); certificateTemplate = await certificateTemplateDAL.getById(certificateTemplateId);
if (!certificateTemplate) { if (!certificateTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found" message: `Certificate template with ID '${certificateTemplateId}' not found`
}); });
} }
@ -1451,7 +1451,7 @@ export const certificateAuthorityServiceFactory = ({
} }
if (!ca) { if (!ca) {
throw new NotFoundError({ message: "CA not found" }); throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
} }
if (!dto.isInternal) { if (!dto.isInternal) {
@ -1484,7 +1484,7 @@ export const certificateAuthorityServiceFactory = ({
// check PKI collection // check PKI collection
if (pkiCollectionId) { if (pkiCollectionId) {
const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId); const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${pkiCollectionId}' not found` });
if (pkiCollection.projectId !== ca.projectId) throw new BadRequestError({ message: "Invalid PKI collection" }); if (pkiCollection.projectId !== ca.projectId) throw new BadRequestError({ message: "Invalid PKI collection" });
} }
@ -1810,7 +1810,7 @@ export const certificateAuthorityServiceFactory = ({
actorOrgId actorOrgId
}: TGetCaCertificateTemplatesDTO) => { }: TGetCaCertificateTemplatesDTO) => {
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -64,7 +64,7 @@ export const certificateTemplateServiceFactory = ({
const ca = await certificateAuthorityDAL.findById(caId); const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) { if (!ca) {
throw new NotFoundError({ throw new NotFoundError({
message: "CA not found" message: `CA with ID ${caId} not found`
}); });
} }
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -98,7 +98,7 @@ export const certificateTemplateServiceFactory = ({
const certificateTemplate = await certificateTemplateDAL.getById(id, tx); const certificateTemplate = await certificateTemplateDAL.getById(id, tx);
if (!certificateTemplate) { if (!certificateTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found" message: `Certificate template with ID ${id} not found`
}); });
} }
@ -124,7 +124,7 @@ export const certificateTemplateServiceFactory = ({
const certTemplate = await certificateTemplateDAL.getById(id); const certTemplate = await certificateTemplateDAL.getById(id);
if (!certTemplate) { if (!certTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found." message: `Certificate template with ID ${id} not found`
}); });
} }
@ -169,7 +169,7 @@ export const certificateTemplateServiceFactory = ({
const updatedTemplate = await certificateTemplateDAL.getById(id, tx); const updatedTemplate = await certificateTemplateDAL.getById(id, tx);
if (!updatedTemplate) { if (!updatedTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found" message: `Certificate template with ID ${id} not found`
}); });
} }
@ -181,7 +181,7 @@ export const certificateTemplateServiceFactory = ({
const certTemplate = await certificateTemplateDAL.getById(id); const certTemplate = await certificateTemplateDAL.getById(id);
if (!certTemplate) { if (!certTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found." message: `Certificate template with ID ${id} not found`
}); });
} }
@ -207,7 +207,7 @@ export const certificateTemplateServiceFactory = ({
const certTemplate = await certificateTemplateDAL.getById(id); const certTemplate = await certificateTemplateDAL.getById(id);
if (!certTemplate) { if (!certTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found." message: `Certificate template with ID ${id} not found`
}); });
} }
@ -247,7 +247,7 @@ export const certificateTemplateServiceFactory = ({
const certTemplate = await certificateTemplateDAL.getById(certificateTemplateId); const certTemplate = await certificateTemplateDAL.getById(certificateTemplateId);
if (!certTemplate) { if (!certTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found." message: `Certificate template with ID ${certificateTemplateId} not found`
}); });
} }
@ -324,7 +324,7 @@ export const certificateTemplateServiceFactory = ({
const certTemplate = await certificateTemplateDAL.getById(certificateTemplateId); const certTemplate = await certificateTemplateDAL.getById(certificateTemplateId);
if (!certTemplate) { if (!certTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found." message: `Certificate template with ID ${certificateTemplateId} not found`
}); });
} }
@ -347,7 +347,7 @@ export const certificateTemplateServiceFactory = ({
if (!originalCaEstConfig) { if (!originalCaEstConfig) {
throw new NotFoundError({ throw new NotFoundError({
message: "EST configuration not found" message: `EST configuration with certificate template ID ${certificateTemplateId} not found`
}); });
} }
@ -403,7 +403,7 @@ export const certificateTemplateServiceFactory = ({
const certTemplate = await certificateTemplateDAL.getById(certificateTemplateId); const certTemplate = await certificateTemplateDAL.getById(certificateTemplateId);
if (!certTemplate) { if (!certTemplate) {
throw new NotFoundError({ throw new NotFoundError({
message: "Certificate template not found." message: `Certificate template with ID ${certificateTemplateId} not found`
}); });
} }
@ -428,7 +428,7 @@ export const certificateTemplateServiceFactory = ({
if (!estConfig) { if (!estConfig) {
throw new NotFoundError({ throw new NotFoundError({
message: "EST configuration not found" message: `EST configuration with certificate template ID ${certificateTemplateId} not found`
}); });
} }

View File

@ -46,7 +46,7 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
const updateCmekById = async ({ keyId, ...data }: TUpdabteCmekByIdDTO, actor: FastifyRequest["permission"]) => { const updateCmekById = async ({ keyId, ...data }: TUpdabteCmekByIdDTO, actor: FastifyRequest["permission"]) => {
const key = await kmsDAL.findById(keyId); const key = await kmsDAL.findById(keyId);
if (!key) throw new NotFoundError({ message: "Key not found" }); if (!key) throw new NotFoundError({ message: `Key with ID ${keyId} not found` });
if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" }); if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" });
@ -68,7 +68,7 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
const deleteCmekById = async (keyId: string, actor: FastifyRequest["permission"]) => { const deleteCmekById = async (keyId: string, actor: FastifyRequest["permission"]) => {
const key = await kmsDAL.findById(keyId); const key = await kmsDAL.findById(keyId);
if (!key) throw new NotFoundError({ message: "Key not found" }); if (!key) throw new NotFoundError({ message: `Key with ID ${keyId} not found` });
if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" }); if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" });
@ -109,7 +109,7 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
const cmekEncrypt = async ({ keyId, plaintext }: TCmekEncryptDTO, actor: FastifyRequest["permission"]) => { const cmekEncrypt = async ({ keyId, plaintext }: TCmekEncryptDTO, actor: FastifyRequest["permission"]) => {
const key = await kmsDAL.findById(keyId); const key = await kmsDAL.findById(keyId);
if (!key) throw new NotFoundError({ message: "Key not found" }); if (!key) throw new NotFoundError({ message: `Key with ID ${keyId} not found` });
if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" }); if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" });
@ -135,7 +135,7 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
const cmekDecrypt = async ({ keyId, ciphertext }: TCmekDecryptDTO, actor: FastifyRequest["permission"]) => { const cmekDecrypt = async ({ keyId, ciphertext }: TCmekDecryptDTO, actor: FastifyRequest["permission"]) => {
const key = await kmsDAL.findById(keyId); const key = await kmsDAL.findById(keyId);
if (!key) throw new NotFoundError({ message: "Key not found" }); if (!key) throw new NotFoundError({ message: `Key with ID ${keyId} not found` });
if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" }); if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" });

View File

@ -169,7 +169,7 @@ export const groupProjectServiceFactory = ({
if (!ghostUser) { if (!ghostUser) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project owner" message: `Failed to find project owner of project with name ${project.name}`
}); });
} }
@ -177,7 +177,7 @@ export const groupProjectServiceFactory = ({
if (!ghostUserLatestKey) { if (!ghostUserLatestKey) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project owner's latest key" message: `Failed to find project owner's latest key in project with name ${project.name}`
}); });
} }
@ -185,7 +185,7 @@ export const groupProjectServiceFactory = ({
if (!bot) { if (!bot) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project bot" message: `Failed to find project bot in project with name ${project.name}`
}); });
} }
@ -425,7 +425,7 @@ export const groupProjectServiceFactory = ({
if (!groupMembership) { if (!groupMembership) {
throw new NotFoundError({ throw new NotFoundError({
message: "Cannot find group membership" message: `Group membership with ID ${groupId} not found in project with ID ${projectId}`
}); });
} }

View File

@ -154,7 +154,7 @@ export const identityAwsAuthServiceFactory = ({
actorOrgId actorOrgId
}: TAttachAwsAuthDTO) => { }: TAttachAwsAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to add AWS Auth to already configured identity" message: "Failed to add AWS Auth to already configured identity"
@ -233,7 +233,7 @@ export const identityAwsAuthServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateAwsAuthDTO) => { }: TUpdateAwsAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AWS_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AWS_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to update AWS Auth" message: "Failed to update AWS Auth"
@ -292,7 +292,7 @@ export const identityAwsAuthServiceFactory = ({
const getAwsAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetAwsAuthDTO) => { const getAwsAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetAwsAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AWS_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AWS_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have AWS Auth attached" message: "The identity does not have AWS Auth attached"
@ -319,7 +319,7 @@ export const identityAwsAuthServiceFactory = ({
actorOrgId actorOrgId
}: TRevokeAwsAuthDTO) => { }: TRevokeAwsAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AWS_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AWS_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have aws auth" message: "The identity does not have aws auth"

View File

@ -125,7 +125,7 @@ export const identityAzureAuthServiceFactory = ({
actorOrgId actorOrgId
}: TAttachAzureAuthDTO) => { }: TAttachAzureAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to add Azure Auth to already configured identity" message: "Failed to add Azure Auth to already configured identity"
@ -203,7 +203,7 @@ export const identityAzureAuthServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateAzureAuthDTO) => { }: TUpdateAzureAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AZURE_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AZURE_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to update Azure Auth" message: "Failed to update Azure Auth"
@ -265,7 +265,7 @@ export const identityAzureAuthServiceFactory = ({
const getAzureAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetAzureAuthDTO) => { const getAzureAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetAzureAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AZURE_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AZURE_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have Azure Auth attached" message: "The identity does not have Azure Auth attached"
@ -293,7 +293,7 @@ export const identityAzureAuthServiceFactory = ({
actorOrgId actorOrgId
}: TRevokeAzureAuthDTO) => { }: TRevokeAzureAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AZURE_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.AZURE_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have azure auth" message: "The identity does not have azure auth"

View File

@ -167,7 +167,7 @@ export const identityGcpAuthServiceFactory = ({
actorOrgId actorOrgId
}: TAttachGcpAuthDTO) => { }: TAttachGcpAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to add GCP Auth to already configured identity" message: "Failed to add GCP Auth to already configured identity"
@ -247,7 +247,7 @@ export const identityGcpAuthServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateGcpAuthDTO) => { }: TUpdateGcpAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.GCP_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.GCP_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to update GCP Auth" message: "Failed to update GCP Auth"
@ -310,7 +310,7 @@ export const identityGcpAuthServiceFactory = ({
const getGcpAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetGcpAuthDTO) => { const getGcpAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetGcpAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.GCP_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.GCP_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have GCP Auth attached" message: "The identity does not have GCP Auth attached"
@ -338,7 +338,7 @@ export const identityGcpAuthServiceFactory = ({
actorOrgId actorOrgId
}: TRevokeGcpAuthDTO) => { }: TRevokeGcpAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.GCP_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.GCP_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have gcp auth" message: "The identity does not have gcp auth"

View File

@ -72,10 +72,19 @@ export const identityKubernetesAuthServiceFactory = ({
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ const identityMembershipOrg = await identityOrgMembershipDAL.findOne({
identityId: identityKubernetesAuth.identityId identityId: identityKubernetesAuth.identityId
}); });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Identity organization membership not found" }); if (!identityMembershipOrg) {
throw new NotFoundError({
message: `Identity organization membership for identity with ID '${identityKubernetesAuth.identityId}' not found`
});
}
const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId });
if (!orgBot) throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); if (!orgBot) {
throw new NotFoundError({
message: `Organization bot not found for organization with ID ${identityMembershipOrg.orgId}`,
name: "OrgBotNotFound"
});
}
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
@ -250,7 +259,7 @@ export const identityKubernetesAuthServiceFactory = ({
actorOrgId actorOrgId
}: TAttachKubernetesAuthDTO) => { }: TAttachKubernetesAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to add Kubernetes Auth to already configured identity" message: "Failed to add Kubernetes Auth to already configured identity"
@ -394,7 +403,7 @@ export const identityKubernetesAuthServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateKubernetesAuthDTO) => { }: TUpdateKubernetesAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.KUBERNETES_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.KUBERNETES_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to update Kubernetes Auth" message: "Failed to update Kubernetes Auth"
@ -451,8 +460,12 @@ export const identityKubernetesAuthServiceFactory = ({
}; };
const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId });
if (!orgBot) throw new NotFoundError({ message: "Org bot not found", name: "OrgBotNotFound" }); if (!orgBot) {
throw new NotFoundError({
message: `Organization bot not found for organization with ID ${identityMembershipOrg.orgId}`,
name: "OrgBotNotFound"
});
}
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
iv: orgBot.symmetricKeyIV, iv: orgBot.symmetricKeyIV,
@ -518,7 +531,7 @@ export const identityKubernetesAuthServiceFactory = ({
actorOrgId actorOrgId
}: TGetKubernetesAuthDTO) => { }: TGetKubernetesAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.KUBERNETES_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.KUBERNETES_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have Kubernetes Auth attached" message: "The identity does not have Kubernetes Auth attached"
@ -536,7 +549,11 @@ export const identityKubernetesAuthServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Identity); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Identity);
const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId });
if (!orgBot) throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); if (!orgBot)
throw new NotFoundError({
message: `Organization bot not found for organization with ID ${identityMembershipOrg.orgId}`,
name: "OrgBotNotFound"
});
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
ciphertext: orgBot.encryptedSymmetricKey, ciphertext: orgBot.encryptedSymmetricKey,
@ -579,7 +596,7 @@ export const identityKubernetesAuthServiceFactory = ({
actorOrgId actorOrgId
}: TRevokeKubernetesAuthDTO) => { }: TRevokeKubernetesAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.KUBERNETES_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.KUBERNETES_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have kubernetes auth" message: "The identity does not have kubernetes auth"

View File

@ -68,12 +68,17 @@ export const identityOidcAuthServiceFactory = ({
identityId: identityOidcAuth.identityId identityId: identityOidcAuth.identityId
}); });
if (!identityMembershipOrg) { if (!identityMembershipOrg) {
throw new NotFoundError({ message: "Identity organization membership not found" }); throw new NotFoundError({
message: `Identity organization membership for identity with ID '${identityOidcAuth.identityId}' not found`
});
} }
const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId });
if (!orgBot) { if (!orgBot) {
throw new NotFoundError({ message: "Organization bot was not found", name: "OrgBotNotFound" }); throw new NotFoundError({
message: `Organization bot not found for organization with ID '${identityMembershipOrg.orgId}'`,
name: "OrgBotNotFound"
});
} }
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
@ -221,7 +226,7 @@ export const identityOidcAuthServiceFactory = ({
}: TAttachOidcAuthDTO) => { }: TAttachOidcAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) { if (!identityMembershipOrg) {
throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
} }
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
@ -360,7 +365,7 @@ export const identityOidcAuthServiceFactory = ({
}: TUpdateOidcAuthDTO) => { }: TUpdateOidcAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) { if (!identityMembershipOrg) {
throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
} }
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.OIDC_AUTH) { if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.OIDC_AUTH) {
@ -422,7 +427,10 @@ export const identityOidcAuthServiceFactory = ({
const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId });
if (!orgBot) { if (!orgBot) {
throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); throw new NotFoundError({
message: `Organization bot not found for organization with ID '${identityMembershipOrg.orgId}'`,
name: "OrgBotNotFound"
});
} }
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
@ -460,7 +468,7 @@ export const identityOidcAuthServiceFactory = ({
const getOidcAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetOidcAuthDTO) => { const getOidcAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetOidcAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) { if (!identityMembershipOrg) {
throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
} }
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.OIDC_AUTH) { if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.OIDC_AUTH) {
@ -482,7 +490,10 @@ export const identityOidcAuthServiceFactory = ({
const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: identityMembershipOrg.orgId });
if (!orgBot) { if (!orgBot) {
throw new NotFoundError({ message: "Organization bot not found", name: "OrgBotNotFound" }); throw new NotFoundError({
message: `Organization bot not found for organization with ID ${identityMembershipOrg.orgId}`,
name: "OrgBotNotFound"
});
} }
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({

View File

@ -66,7 +66,7 @@ export const identityProjectServiceFactory = ({
const existingIdentity = await identityProjectDAL.findOne({ identityId, projectId }); const existingIdentity = await identityProjectDAL.findOne({ identityId, projectId });
if (existingIdentity) if (existingIdentity)
throw new BadRequestError({ throw new BadRequestError({
message: `Identity with id ${identityId} already exists in project with id ${projectId}` message: `Identity with ID ${identityId} already exists in project with ID ${projectId}`
}); });
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
@ -76,7 +76,7 @@ export const identityProjectServiceFactory = ({
}); });
if (!identityOrgMembership) if (!identityOrgMembership)
throw new NotFoundError({ throw new NotFoundError({
message: `Failed to find identity with id ${identityId}` message: `Failed to find identity with ID ${identityId}`
}); });
for await (const { role: requestedRoleChange } of roles) { for await (const { role: requestedRoleChange } of roles) {
@ -104,7 +104,7 @@ export const identityProjectServiceFactory = ({
}) })
: []; : [];
if (customRoles.length !== customInputRoles.length) if (customRoles.length !== customInputRoles.length)
throw new NotFoundError({ message: "Custom project roles not found" }); throw new NotFoundError({ message: "One or more custom project roles not found" });
const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug); const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug);
const projectIdentity = await identityProjectDAL.transaction(async (tx) => { const projectIdentity = await identityProjectDAL.transaction(async (tx) => {
@ -166,7 +166,7 @@ export const identityProjectServiceFactory = ({
const projectIdentity = await identityProjectDAL.findOne({ identityId, projectId }); const projectIdentity = await identityProjectDAL.findOne({ identityId, projectId });
if (!projectIdentity) if (!projectIdentity)
throw new NotFoundError({ throw new NotFoundError({
message: `Identity with id ${identityId} doesn't exists in project with id ${projectId}` message: `Identity with ID ${identityId} doesn't exists in project with ID ${projectId}`
}); });
for await (const { role: requestedRoleChange } of roles) { for await (const { role: requestedRoleChange } of roles) {
@ -192,7 +192,7 @@ export const identityProjectServiceFactory = ({
}) })
: []; : [];
if (customRoles.length !== customInputRoles.length) if (customRoles.length !== customInputRoles.length)
throw new NotFoundError({ message: "Custom project roles not found" }); throw new NotFoundError({ message: "One or more custom project roles not found" });
const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug); const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug);
@ -237,8 +237,9 @@ export const identityProjectServiceFactory = ({
projectId projectId
}: TDeleteProjectIdentityDTO) => { }: TDeleteProjectIdentityDTO) => {
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId }); const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
if (!identityProjectMembership) if (!identityProjectMembership) {
throw new NotFoundError({ message: `Failed to find identity with id ${identityId}` }); throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
}
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -314,7 +315,10 @@ export const identityProjectServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Identity); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Identity);
const [identityMembership] = await identityProjectDAL.findByProjectId(projectId, { identityId }); const [identityMembership] = await identityProjectDAL.findByProjectId(projectId, { identityId });
if (!identityMembership) throw new NotFoundError({ message: `Membership not found for identity ${identityId}` }); if (!identityMembership)
throw new NotFoundError({
message: `Project membership for identity with ID '${identityId} in project with ID '${projectId}' not found`
});
return identityMembership; return identityMembership;
}; };

View File

@ -64,7 +64,7 @@ export const identityTokenAuthServiceFactory = ({
actorOrgId actorOrgId
}: TAttachTokenAuthDTO) => { }: TAttachTokenAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to add Token Auth to already configured identity" message: "Failed to add Token Auth to already configured identity"
@ -136,7 +136,7 @@ export const identityTokenAuthServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateTokenAuthDTO) => { }: TUpdateTokenAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to update Token Auth" message: "Failed to update Token Auth"
@ -196,7 +196,7 @@ export const identityTokenAuthServiceFactory = ({
const getTokenAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetTokenAuthDTO) => { const getTokenAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetTokenAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have Token Auth attached" message: "The identity does not have Token Auth attached"
@ -224,7 +224,7 @@ export const identityTokenAuthServiceFactory = ({
actorOrgId actorOrgId
}: TRevokeTokenAuthDTO) => { }: TRevokeTokenAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have Token Auth" message: "The identity does not have Token Auth"
@ -269,7 +269,7 @@ export const identityTokenAuthServiceFactory = ({
name name
}: TCreateTokenAuthTokenDTO) => { }: TCreateTokenAuthTokenDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have Token Auth" message: "The identity does not have Token Auth"
@ -343,7 +343,7 @@ export const identityTokenAuthServiceFactory = ({
actorOrgId actorOrgId
}: TGetTokenAuthTokensDTO) => { }: TGetTokenAuthTokensDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have Token Auth" message: "The identity does not have Token Auth"
@ -376,9 +376,11 @@ export const identityTokenAuthServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateTokenAuthTokenDTO) => { }: TUpdateTokenAuthTokenDTO) => {
const foundToken = await identityAccessTokenDAL.findById(tokenId); const foundToken = await identityAccessTokenDAL.findById(tokenId);
if (!foundToken) throw new NotFoundError({ message: "Failed to find token" }); if (!foundToken) throw new NotFoundError({ message: `Token with ID ${tokenId} not found` });
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId: foundToken.identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId: foundToken.identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) {
throw new NotFoundError({ message: `Failed to find identity with ID ${foundToken.identityId}` });
}
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.TOKEN_AUTH)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have Token Auth" message: "The identity does not have Token Auth"
@ -431,7 +433,7 @@ export const identityTokenAuthServiceFactory = ({
}); });
if (!identityAccessToken) if (!identityAccessToken)
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find token" message: `Token with ID ${tokenId} not found or already revoked`
}); });
const identityOrgMembership = await identityOrgMembershipDAL.findOne({ const identityOrgMembership = await identityOrgMembershipDAL.findOne({
@ -439,7 +441,7 @@ export const identityTokenAuthServiceFactory = ({
}); });
if (!identityOrgMembership) { if (!identityOrgMembership) {
throw new NotFoundError({ message: "No identity organization membership found" }); throw new NotFoundError({ message: `Failed to find identity with ID ${identityAccessToken.identityId}` });
} }
const { permission } = await permissionService.getOrgPermission( const { permission } = await permissionService.getOrgPermission(

View File

@ -155,7 +155,7 @@ export const identityUaServiceFactory = ({
actorOrgId actorOrgId
}: TAttachUaDTO) => { }: TAttachUaDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to add universal auth to already configured identity" message: "Failed to add universal auth to already configured identity"
@ -246,7 +246,7 @@ export const identityUaServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateUaDTO) => { }: TUpdateUaDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to updated universal auth" message: "Failed to updated universal auth"
@ -320,7 +320,7 @@ export const identityUaServiceFactory = ({
const getIdentityUniversalAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetUaDTO) => { const getIdentityUniversalAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetUaDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have universal auth" message: "The identity does not have universal auth"
@ -347,7 +347,7 @@ export const identityUaServiceFactory = ({
actorOrgId actorOrgId
}: TRevokeUaDTO) => { }: TRevokeUaDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have universal auth" message: "The identity does not have universal auth"
@ -392,7 +392,7 @@ export const identityUaServiceFactory = ({
numUsesLimit numUsesLimit
}: TCreateUaClientSecretDTO) => { }: TCreateUaClientSecretDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have universal auth" message: "The identity does not have universal auth"
@ -452,7 +452,7 @@ export const identityUaServiceFactory = ({
identityId identityId
}: TGetUaClientSecretsDTO) => { }: TGetUaClientSecretsDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have universal auth" message: "The identity does not have universal auth"
@ -499,7 +499,7 @@ export const identityUaServiceFactory = ({
clientSecretId clientSecretId
}: TGetUniversalAuthClientSecretByIdDTO) => { }: TGetUniversalAuthClientSecretByIdDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have universal auth" message: "The identity does not have universal auth"
@ -538,7 +538,7 @@ export const identityUaServiceFactory = ({
clientSecretId clientSecretId
}: TRevokeUaClientSecretDTO) => { }: TRevokeUaClientSecretDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
message: "The identity does not have universal auth" message: "The identity does not have universal auth"

View File

@ -1259,6 +1259,6 @@ export const getApps = async ({
}); });
default: default:
throw new NotFoundError({ message: "integration not found" }); throw new NotFoundError({ message: `Integration '${integration}' not found` });
} }
}; };

View File

@ -110,7 +110,7 @@ export const integrationAuthServiceFactory = ({
const getIntegrationAuth = async ({ actor, id, actorId, actorAuthMethod, actorOrgId }: TGetIntegrationAuthDTO) => { const getIntegrationAuth = async ({ actor, id, actorId, actorAuthMethod, actorOrgId }: TGetIntegrationAuthDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -195,7 +195,7 @@ export const integrationAuthServiceFactory = ({
updateDoc.encryptedAccess = accessToken; updateDoc.encryptedAccess = accessToken;
} }
} else { } else {
if (!botKey) throw new NotFoundError({ message: "Project bot key not found" }); if (!botKey) throw new NotFoundError({ message: `Project bot key for project with ID '${projectId}' not found` });
if (tokenExchange.refreshToken) { if (tokenExchange.refreshToken) {
const refreshEncToken = encryptSymmetric128BitHexKeyUTF8(tokenExchange.refreshToken, botKey); const refreshEncToken = encryptSymmetric128BitHexKeyUTF8(tokenExchange.refreshToken, botKey);
updateDoc.refreshIV = refreshEncToken.iv; updateDoc.refreshIV = refreshEncToken.iv;
@ -317,7 +317,7 @@ export const integrationAuthServiceFactory = ({
} }
} }
} else { } else {
if (!botKey) throw new NotFoundError({ message: "Project bot key not found" }); if (!botKey) throw new NotFoundError({ message: `Project bot key for project with ID '${projectId}' not found` });
if (refreshToken) { if (refreshToken) {
const tokenDetails = await exchangeRefresh( const tokenDetails = await exchangeRefresh(
integration, integration,
@ -496,7 +496,7 @@ export const integrationAuthServiceFactory = ({
workspaceSlug workspaceSlug
}: TIntegrationAuthAppsDTO) => { }: TIntegrationAuthAppsDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -530,7 +530,7 @@ export const integrationAuthServiceFactory = ({
id id
}: TIntegrationAuthTeamsDTO) => { }: TIntegrationAuthTeamsDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -560,7 +560,7 @@ export const integrationAuthServiceFactory = ({
actorOrgId actorOrgId
}: TIntegrationAuthVercelBranchesDTO) => { }: TIntegrationAuthVercelBranchesDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -601,7 +601,7 @@ export const integrationAuthServiceFactory = ({
accountId accountId
}: TIntegrationAuthChecklyGroupsDTO) => { }: TIntegrationAuthChecklyGroupsDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -629,7 +629,7 @@ export const integrationAuthServiceFactory = ({
const getGithubOrgs = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TIntegrationAuthGithubOrgsDTO) => { const getGithubOrgs = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TIntegrationAuthGithubOrgsDTO) => {
const appCfg = getConfig(); const appCfg = getConfig();
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -703,7 +703,7 @@ export const integrationAuthServiceFactory = ({
repoName repoName
}: TIntegrationAuthGithubEnvsDTO) => { }: TIntegrationAuthGithubEnvsDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -750,7 +750,7 @@ export const integrationAuthServiceFactory = ({
const getQoveryOrgs = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TIntegrationAuthQoveryOrgsDTO) => { const getQoveryOrgs = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TIntegrationAuthQoveryOrgsDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -784,7 +784,7 @@ export const integrationAuthServiceFactory = ({
region region
}: TIntegrationAuthAwsKmsKeyDTO) => { }: TIntegrationAuthAwsKmsKeyDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -842,7 +842,7 @@ export const integrationAuthServiceFactory = ({
orgId orgId
}: TIntegrationAuthQoveryProjectDTO) => { }: TIntegrationAuthQoveryProjectDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -878,7 +878,7 @@ export const integrationAuthServiceFactory = ({
actorOrgId actorOrgId
}: TIntegrationAuthQoveryEnvironmentsDTO) => { }: TIntegrationAuthQoveryEnvironmentsDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -919,7 +919,7 @@ export const integrationAuthServiceFactory = ({
environmentId environmentId
}: TIntegrationAuthQoveryScopesDTO) => { }: TIntegrationAuthQoveryScopesDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -959,7 +959,7 @@ export const integrationAuthServiceFactory = ({
environmentId environmentId
}: TIntegrationAuthQoveryScopesDTO) => { }: TIntegrationAuthQoveryScopesDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -999,7 +999,7 @@ export const integrationAuthServiceFactory = ({
environmentId environmentId
}: TIntegrationAuthQoveryScopesDTO) => { }: TIntegrationAuthQoveryScopesDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID ${id} not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1038,7 +1038,7 @@ export const integrationAuthServiceFactory = ({
actorOrgId actorOrgId
}: TIntegrationAuthHerokuPipelinesDTO) => { }: TIntegrationAuthHerokuPipelinesDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1078,7 +1078,7 @@ export const integrationAuthServiceFactory = ({
appId appId
}: TIntegrationAuthRailwayEnvDTO) => { }: TIntegrationAuthRailwayEnvDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1146,7 +1146,7 @@ export const integrationAuthServiceFactory = ({
appId appId
}: TIntegrationAuthRailwayServicesDTO) => { }: TIntegrationAuthRailwayServicesDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1220,7 +1220,7 @@ export const integrationAuthServiceFactory = ({
id id
}: TIntegrationAuthBitbucketWorkspaceDTO) => { }: TIntegrationAuthBitbucketWorkspaceDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1269,7 +1269,7 @@ export const integrationAuthServiceFactory = ({
appId appId
}: TIntegrationAuthNorthflankSecretGroupDTO) => { }: TIntegrationAuthNorthflankSecretGroupDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1337,7 +1337,7 @@ export const integrationAuthServiceFactory = ({
actor actor
}: TGetIntegrationAuthTeamCityBuildConfigDTO) => { }: TGetIntegrationAuthTeamCityBuildConfigDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1399,7 +1399,7 @@ export const integrationAuthServiceFactory = ({
actorOrgId actorOrgId
}: TDeleteIntegrationAuthByIdDTO) => { }: TDeleteIntegrationAuthByIdDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new NotFoundError({ message: "Failed to find integration" }); if (!integrationAuth) throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1412,7 +1412,7 @@ export const integrationAuthServiceFactory = ({
const delIntegrationAuth = await integrationAuthDAL.transaction(async (tx) => { const delIntegrationAuth = await integrationAuthDAL.transaction(async (tx) => {
const doc = await integrationAuthDAL.deleteById(integrationAuth.id, tx); const doc = await integrationAuthDAL.deleteById(integrationAuth.id, tx);
if (!doc) throw new NotFoundError({ message: "Faled to find integration" }); if (!doc) throw new NotFoundError({ message: `Integration auth with ID '${integrationAuth.id}' not found` });
await integrationDAL.delete({ integrationAuthId: doc.id }, tx); await integrationDAL.delete({ integrationAuthId: doc.id }, tx);
return doc; return doc;
}); });
@ -1431,7 +1431,7 @@ export const integrationAuthServiceFactory = ({
}: TDuplicateGithubIntegrationAuthDTO) => { }: TDuplicateGithubIntegrationAuthDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) { if (!integrationAuth) {
throw new NotFoundError({ message: "Failed to find integration" }); throw new NotFoundError({ message: `Integration auth with ID '${id}' not found` });
} }
const { permission: sourcePermission } = await permissionService.getProjectPermission( const { permission: sourcePermission } = await permissionService.getProjectPermission(

View File

@ -314,7 +314,7 @@ export const deleteIntegrationSecrets = async ({
if (!folder) { if (!folder) {
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found." message: `Folder with path '${integration.secretPath}' not found in environment with slug '${integration.environment.slug}'`
}); });
} }

View File

@ -76,7 +76,8 @@ export const integrationServiceFactory = ({
targetEnvironmentId targetEnvironmentId
}: TCreateIntegrationDTO) => { }: TCreateIntegrationDTO) => {
const integrationAuth = await integrationAuthDAL.findById(integrationAuthId); const integrationAuth = await integrationAuthDAL.findById(integrationAuthId);
if (!integrationAuth) throw new NotFoundError({ message: "Integration auth not found" }); if (!integrationAuth)
throw new NotFoundError({ message: `Integration auth with ID '${integrationAuthId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -93,7 +94,11 @@ export const integrationServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(integrationAuth.projectId, sourceEnvironment, secretPath); const folder = await folderDAL.findBySecretPath(integrationAuth.projectId, sourceEnvironment, secretPath);
if (!folder) throw new NotFoundError({ message: "Folder path not found" }); if (!folder) {
throw new NotFoundError({
message: `Folder with path '${secretPath}' not found in environment with slug'${sourceEnvironment}'`
});
}
const integration = await integrationDAL.create({ const integration = await integrationDAL.create({
envId: folder.envId, envId: folder.envId,
@ -145,7 +150,7 @@ export const integrationServiceFactory = ({
metadata metadata
}: TUpdateIntegrationDTO) => { }: TUpdateIntegrationDTO) => {
const integration = await integrationDAL.findById(id); const integration = await integrationDAL.findById(id);
if (!integration) throw new NotFoundError({ message: "Integration auth not found" }); if (!integration) throw new NotFoundError({ message: `Integration with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -167,7 +172,11 @@ export const integrationServiceFactory = ({
} }
const folder = await folderDAL.findBySecretPath(integration.projectId, newEnvironment, newSecretPath); const folder = await folderDAL.findBySecretPath(integration.projectId, newEnvironment, newSecretPath);
if (!folder) throw new NotFoundError({ message: "Folder path not found" }); if (!folder) {
throw new NotFoundError({
message: `Folder with path '${newSecretPath}' not found in environment with slug '${newEnvironment}'`
});
}
const updatedIntegration = await integrationDAL.updateById(id, { const updatedIntegration = await integrationDAL.updateById(id, {
envId: folder.envId, envId: folder.envId,
@ -200,7 +209,7 @@ export const integrationServiceFactory = ({
if (!integration) { if (!integration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Integration not found" message: `Integration with ID '${id}' not found`
}); });
} }
@ -215,7 +224,7 @@ export const integrationServiceFactory = ({
if (!integration) { if (!integration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Integration not found" message: `Integration with ID '${id}' not found`
}); });
} }
@ -231,7 +240,7 @@ export const integrationServiceFactory = ({
shouldDeleteIntegrationSecrets shouldDeleteIntegrationSecrets
}: TDeleteIntegrationDTO) => { }: TDeleteIntegrationDTO) => {
const integration = await integrationDAL.findById(id); const integration = await integrationDAL.findById(id);
if (!integration) throw new NotFoundError({ message: "Integration auth not found" }); if (!integration) throw new NotFoundError({ message: `Integration with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -285,7 +294,7 @@ export const integrationServiceFactory = ({
const syncIntegration = async ({ id, actorId, actor, actorOrgId, actorAuthMethod }: TSyncIntegrationDTO) => { const syncIntegration = async ({ id, actorId, actor, actorOrgId, actorAuthMethod }: TSyncIntegrationDTO) => {
const integration = await integrationDAL.findById(id); const integration = await integrationDAL.findById(id);
if (!integration) { if (!integration) {
throw new NotFoundError({ message: "Integration not found" }); throw new NotFoundError({ message: `Integration with ID '${id}' not found` });
} }
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(

View File

@ -164,7 +164,7 @@ export const kmsServiceFactory = ({
let org = await orgDAL.findById(orgId, trx); let org = await orgDAL.findById(orgId, trx);
if (!org) { if (!org) {
throw new NotFoundError({ message: "Org not found" }); throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
} }
if (!org.kmsDefaultKeyId) { if (!org.kmsDefaultKeyId) {
@ -247,7 +247,7 @@ export const kmsServiceFactory = ({
const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId, tx); const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId, tx);
if (!kmsDoc) { if (!kmsDoc) {
throw new NotFoundError({ message: "KMS ID not found" }); throw new NotFoundError({ message: `KMS with ID '${kmsId}' not found` });
} }
if (kmsDoc.externalKms) { if (kmsDoc.externalKms) {
@ -315,7 +315,7 @@ export const kmsServiceFactory = ({
const encryptWithKmsKey = async ({ kmsId }: Omit<TEncryptWithKmsDTO, "plainText">, tx?: Knex) => { const encryptWithKmsKey = async ({ kmsId }: Omit<TEncryptWithKmsDTO, "plainText">, tx?: Knex) => {
const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId, tx); const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId, tx);
if (!kmsDoc) { if (!kmsDoc) {
throw new NotFoundError({ message: "KMS ID not found" }); throw new NotFoundError({ message: `KMS with ID '${kmsId}' not found` });
} }
if (kmsDoc.externalKms) { if (kmsDoc.externalKms) {
@ -382,7 +382,7 @@ export const kmsServiceFactory = ({
let org = await orgDAL.findById(orgId, trx); let org = await orgDAL.findById(orgId, trx);
if (!org) { if (!org) {
throw new NotFoundError({ message: "Org not found" }); throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
} }
if (!org.kmsEncryptedDataKey) { if (!org.kmsEncryptedDataKey) {
@ -460,7 +460,7 @@ export const kmsServiceFactory = ({
const getProjectSecretManagerKmsKeyId = async (projectId: string, trx?: Knex) => { const getProjectSecretManagerKmsKeyId = async (projectId: string, trx?: Knex) => {
let project = await projectDAL.findById(projectId, trx); let project = await projectDAL.findById(projectId, trx);
if (!project) { if (!project) {
throw new NotFoundError({ message: "Project not found" }); throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
} }
if (!project.kmsSecretManagerKeyId) { if (!project.kmsSecretManagerKeyId) {
@ -650,12 +650,12 @@ export const kmsServiceFactory = ({
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found." message: `Project with ID '${projectId}' not found`
}); });
} }
const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId); const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId);
if (!kmsDoc) { if (!kmsDoc) {
throw new NotFoundError({ message: "KMS ID not found." }); throw new NotFoundError({ message: `KMS with ID '${kmsId}' not found` });
} }
if (kmsDoc.orgId !== project.orgId) { if (kmsDoc.orgId !== project.orgId) {
@ -702,7 +702,7 @@ export const kmsServiceFactory = ({
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found" message: `Project with ID '${projectId}' not found`
}); });
} }
@ -730,7 +730,7 @@ export const kmsServiceFactory = ({
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found" message: `Project with ID '${projectId}' not found`
}); });
} }
@ -785,7 +785,7 @@ export const kmsServiceFactory = ({
if (!kms.id) { if (!kms.id) {
throw new NotFoundError({ throw new NotFoundError({
message: "KMS not found" message: `KMS with ID '${kmsKeyId}' not found`
}); });
} }
const { id, name, orgId, isExternal } = kms; const { id, name, orgId, isExternal } = kms;

View File

@ -90,7 +90,7 @@ export const orgAdminServiceFactory = ({
); );
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
if (project.version === ProjectVersion.V1) { if (project.version === ProjectVersion.V1) {
throw new BadRequestError({ message: "Please upgrade your project on your dashboard" }); throw new BadRequestError({ message: "Please upgrade your project on your dashboard" });
@ -120,21 +120,21 @@ export const orgAdminServiceFactory = ({
const ghostUser = await projectDAL.findProjectGhostUser(projectId); const ghostUser = await projectDAL.findProjectGhostUser(projectId);
if (!ghostUser) { if (!ghostUser) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project owner" message: `Project owner of project with ID '${projectId}' not found`
}); });
} }
const ghostUserLatestKey = await projectKeyDAL.findLatestProjectKey(ghostUser.id, projectId); const ghostUserLatestKey = await projectKeyDAL.findLatestProjectKey(ghostUser.id, projectId);
if (!ghostUserLatestKey) { if (!ghostUserLatestKey) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project owner's latest key" message: `Project owner's latest key of project with ID '${projectId}' not found`
}); });
} }
const bot = await projectBotDAL.findOne({ projectId }); const bot = await projectBotDAL.findOne({ projectId });
if (!bot) { if (!bot) {
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find project bot" message: `Project bot for project with ID '${projectId}' not found`
}); });
} }
@ -146,7 +146,8 @@ export const orgAdminServiceFactory = ({
}); });
const userEncryptionKey = await userDAL.findUserEncKeyByUserId(actorId); const userEncryptionKey = await userDAL.findUserEncKeyByUserId(actorId);
if (!userEncryptionKey) throw new NotFoundError({ message: "User encryption key not found" }); if (!userEncryptionKey)
throw new NotFoundError({ message: `User encryption key for user with ID '${actorId}' not found` });
const [newWsMember] = assignWorkspaceKeysToMembers({ const [newWsMember] = assignWorkspaceKeysToMembers({
decryptKey: ghostUserLatestKey, decryptKey: ghostUserLatestKey,
userPrivateKey: botPrivateKey, userPrivateKey: botPrivateKey,

View File

@ -5,7 +5,7 @@ import { TOrgRoleDALFactory } from "@app/services/org/org-role-dal";
const RESERVED_ORG_ROLE_SLUGS = Object.values(OrgMembershipRole).filter((role) => role !== "custom"); const RESERVED_ORG_ROLE_SLUGS = Object.values(OrgMembershipRole).filter((role) => role !== "custom");
export const isCustomOrgRole = (roleSlug: string) => !RESERVED_ORG_ROLE_SLUGS.includes(roleSlug as OrgMembershipRole); export const isCustomOrgRole = (roleSlug: string) => !RESERVED_ORG_ROLE_SLUGS.find((r) => r === roleSlug);
// this is only for updating an org // this is only for updating an org
export const getDefaultOrgMembershipRoleForUpdateOrg = async ({ export const getDefaultOrgMembershipRoleForUpdateOrg = async ({
@ -27,7 +27,12 @@ export const getDefaultOrgMembershipRoleForUpdateOrg = async ({
}); });
const customRole = await orgRoleDAL.findOne({ slug: membershipRoleSlug, orgId }); const customRole = await orgRoleDAL.findOne({ slug: membershipRoleSlug, orgId });
if (!customRole) throw new NotFoundError({ name: "UpdateOrg", message: "Organization role not found" }); if (!customRole) {
throw new NotFoundError({
name: "UpdateOrg",
message: `Organization role with slug '${membershipRoleSlug}' not found`
});
}
// use ID for default role // use ID for default role
return customRole.id; return customRole.id;

View File

@ -100,7 +100,7 @@ export const orgRoleServiceFactory = ({
} }
default: { default: {
const role = await orgRoleDAL.findOne({ id: roleId, orgId }); const role = await orgRoleDAL.findOne({ id: roleId, orgId });
if (!role) throw new NotFoundError({ message: "Organization role not found" }); if (!role) throw new NotFoundError({ message: `Organization role with ID '${roleId}' not found` });
return role; return role;
} }
} }
@ -125,7 +125,7 @@ export const orgRoleServiceFactory = ({
{ id: roleId, orgId }, { id: roleId, orgId },
{ ...data, permissions: data.permissions ? JSON.stringify(data.permissions) : undefined } { ...data, permissions: data.permissions ? JSON.stringify(data.permissions) : undefined }
); );
if (!updatedRole) throw new NotFoundError({ message: "Organization role not found" }); if (!updatedRole) throw new NotFoundError({ message: `Organization role with ID '${roleId}' not found` });
return updatedRole; return updatedRole;
}; };
@ -143,7 +143,7 @@ export const orgRoleServiceFactory = ({
if (!org) if (!org)
throw new NotFoundError({ throw new NotFoundError({
message: "Failed to find organization" message: `Organization with ID '${orgId}' not found`
}); });
if (org.defaultMembershipRole === roleId) if (org.defaultMembershipRole === roleId)
@ -163,7 +163,8 @@ export const orgRoleServiceFactory = ({
}); });
const [deletedRole] = await orgRoleDAL.delete({ id: roleId, orgId }); const [deletedRole] = await orgRoleDAL.delete({ id: roleId, orgId });
if (!deletedRole) throw new NotFoundError({ message: "Organization role not found", name: "Update role" }); if (!deletedRole)
throw new NotFoundError({ message: `Organization role with ID '${roleId}' not found`, name: "UpdateRole" });
return deletedRole; return deletedRole;
}; };

View File

@ -138,7 +138,7 @@ export const orgServiceFactory = ({
) => { ) => {
await permissionService.getUserOrgPermission(userId, orgId, actorAuthMethod, actorOrgId); await permissionService.getUserOrgPermission(userId, orgId, actorAuthMethod, actorOrgId);
const org = await orgDAL.findOrgById(orgId); const org = await orgDAL.findOrgById(orgId);
if (!org) throw new NotFoundError({ message: "Organization not found" }); if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
return org; return org;
}; };
/* /*
@ -268,13 +268,28 @@ export const orgServiceFactory = ({
actorOrgId, actorOrgId,
actorAuthMethod, actorAuthMethod,
orgId, orgId,
data: { name, slug, authEnforced, scimEnabled, defaultMembershipRoleSlug } data: { name, slug, authEnforced, scimEnabled, defaultMembershipRoleSlug, enforceMfa }
}: TUpdateOrgDTO) => { }: TUpdateOrgDTO) => {
const appCfg = getConfig();
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId); const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
const plan = await licenseService.getPlan(orgId); const plan = await licenseService.getPlan(orgId);
if (enforceMfa !== undefined) {
if (!plan.enforceMfa) {
throw new BadRequestError({
message: "Failed to enforce user MFA due to plan restriction. Upgrade plan to enforce/un-enforce MFA."
});
}
if (!appCfg.isSmtpConfigured) {
throw new BadRequestError({
message: "Failed to enforce user MFA due to missing instance SMTP configuration."
});
}
}
if (authEnforced !== undefined) { if (authEnforced !== undefined) {
if (!plan?.samlSSO || !plan.oidcSSO) if (!plan?.samlSSO || !plan.oidcSSO)
throw new BadRequestError({ throw new BadRequestError({
@ -298,7 +313,7 @@ export const orgServiceFactory = ({
if (!samlCfg && !oidcCfg) if (!samlCfg && !oidcCfg)
throw new NotFoundError({ throw new NotFoundError({
message: "No enforceable SSO config found" message: `SAML or OIDC configuration for organization with ID '${orgId}' not found`
}); });
} }
@ -317,9 +332,10 @@ export const orgServiceFactory = ({
slug: slug ? slugify(slug) : undefined, slug: slug ? slugify(slug) : undefined,
authEnforced, authEnforced,
scimEnabled, scimEnabled,
defaultMembershipRole defaultMembershipRole,
enforceMfa
}); });
if (!org) throw new NotFoundError({ message: "Organization not found" }); if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
return org; return org;
}; };
/* /*
@ -433,7 +449,8 @@ export const orgServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Member); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Member);
const foundMembership = await orgMembershipDAL.findById(membershipId); const foundMembership = await orgMembershipDAL.findById(membershipId);
if (!foundMembership) throw new NotFoundError({ message: "Failed to find organization membership" }); if (!foundMembership)
throw new NotFoundError({ message: `Organization membership with ID ${membershipId} not found` });
if (foundMembership.orgId !== orgId) if (foundMembership.orgId !== orgId)
throw new UnauthorizedError({ message: "Updated org member doesn't belong to the organization" }); throw new UnauthorizedError({ message: "Updated org member doesn't belong to the organization" });
if (foundMembership.userId === userId) if (foundMembership.userId === userId)
@ -629,8 +646,12 @@ export const orgServiceFactory = ({
const orgRole = isCustomOrgRole ? OrgMembershipRole.Custom : organizationRoleSlug; const orgRole = isCustomOrgRole ? OrgMembershipRole.Custom : organizationRoleSlug;
if (isCustomOrgRole) { if (isCustomOrgRole) {
const customRole = await orgRoleDAL.findOne({ slug: organizationRoleSlug, orgId }); const customRole = await orgRoleDAL.findOne({ slug: organizationRoleSlug, orgId });
if (!customRole) if (!customRole) {
throw new NotFoundError({ name: "InviteUser", message: "Custom organization role not found" }); throw new NotFoundError({
name: "InviteUser",
message: `Custom organization role with slug '${orgRole}' not found`
});
}
roleId = customRole.id; roleId = customRole.id;
} }
@ -788,7 +809,7 @@ export const orgServiceFactory = ({
if (!bot) { if (!bot) {
throw new NotFoundError({ throw new NotFoundError({
name: "InviteUser", name: "InviteUser",
message: "Failed to find project bot" message: `Failed to find project bot for project with ID '${projectId}'`
}); });
} }
@ -796,7 +817,7 @@ export const orgServiceFactory = ({
if (!ghostUserLatestKey) { if (!ghostUserLatestKey) {
throw new NotFoundError({ throw new NotFoundError({
name: "InviteUser", name: "InviteUser",
message: "Failed to find project owner's latest key" message: `Failed to find project owner's latest key for project with ID '${projectId}'`
}); });
} }
@ -985,7 +1006,7 @@ export const orgServiceFactory = ({
const membership = await orgMembershipDAL.findOrgMembershipById(membershipId); const membership = await orgMembershipDAL.findOrgMembershipById(membershipId);
if (!membership) { if (!membership) {
throw new NotFoundError({ message: "Organization membership not found" }); throw new NotFoundError({ message: `Organization membership with ID '${membershipId}' not found` });
} }
if (membership.orgId !== orgId) { if (membership.orgId !== orgId) {
throw new ForbiddenRequestError({ message: "Membership does not belong to organization" }); throw new ForbiddenRequestError({ message: "Membership does not belong to organization" });
@ -1031,7 +1052,7 @@ export const orgServiceFactory = ({
const membership = await orgMembershipDAL.findOrgMembershipById(orgMembershipId); const membership = await orgMembershipDAL.findOrgMembershipById(orgMembershipId);
if (!membership) { if (!membership) {
throw new NotFoundError({ message: "Organization membership not found" }); throw new NotFoundError({ message: `Organization membership with ID '${orgMembershipId}' not found` });
} }
if (membership.orgId !== orgId) throw new NotFoundError({ message: "Failed to find organization membership" }); if (membership.orgId !== orgId) throw new NotFoundError({ message: "Failed to find organization membership" });

View File

@ -64,6 +64,7 @@ export type TUpdateOrgDTO = {
authEnforced: boolean; authEnforced: boolean;
scimEnabled: boolean; scimEnabled: boolean;
defaultMembershipRoleSlug: string; defaultMembershipRoleSlug: string;
enforceMfa: boolean;
}>; }>;
} & TOrgPermission; } & TOrgPermission;

View File

@ -84,7 +84,7 @@ export const pkiAlertServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts);
const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId); const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${pkiCollectionId}' not found` });
if (pkiCollection.projectId !== projectId) if (pkiCollection.projectId !== projectId)
throw new ForbiddenRequestError({ message: "PKI collection does not belong to the specified project." }); throw new ForbiddenRequestError({ message: "PKI collection does not belong to the specified project." });
@ -100,7 +100,7 @@ export const pkiAlertServiceFactory = ({
const getPkiAlertById = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TGetAlertByIdDTO) => { const getPkiAlertById = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TGetAlertByIdDTO) => {
const alert = await pkiAlertDAL.findById(alertId); const alert = await pkiAlertDAL.findById(alertId);
if (!alert) throw new NotFoundError({ message: "Alert not found" }); if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -126,7 +126,7 @@ export const pkiAlertServiceFactory = ({
actorOrgId actorOrgId
}: TUpdateAlertDTO) => { }: TUpdateAlertDTO) => {
let alert = await pkiAlertDAL.findById(alertId); let alert = await pkiAlertDAL.findById(alertId);
if (!alert) throw new NotFoundError({ message: "Alert not found" }); if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -140,7 +140,7 @@ export const pkiAlertServiceFactory = ({
if (pkiCollectionId) { if (pkiCollectionId) {
const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId); const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${pkiCollectionId}' not found` });
if (pkiCollection.projectId !== alert.projectId) { if (pkiCollection.projectId !== alert.projectId) {
throw new ForbiddenRequestError({ message: "PKI collection does not belong to the specified project." }); throw new ForbiddenRequestError({ message: "PKI collection does not belong to the specified project." });
} }
@ -158,7 +158,7 @@ export const pkiAlertServiceFactory = ({
const deletePkiAlert = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteAlertDTO) => { const deletePkiAlert = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteAlertDTO) => {
let alert = await pkiAlertDAL.findById(alertId); let alert = await pkiAlertDAL.findById(alertId);
if (!alert) throw new NotFoundError({ message: "Alert not found" }); if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -80,7 +80,7 @@ export const pkiCollectionServiceFactory = ({
actorOrgId actorOrgId
}: TGetPkiCollectionByIdDTO) => { }: TGetPkiCollectionByIdDTO) => {
const pkiCollection = await pkiCollectionDAL.findById(collectionId); const pkiCollection = await pkiCollectionDAL.findById(collectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${collectionId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -104,7 +104,7 @@ export const pkiCollectionServiceFactory = ({
actorOrgId actorOrgId
}: TUpdatePkiCollectionDTO) => { }: TUpdatePkiCollectionDTO) => {
let pkiCollection = await pkiCollectionDAL.findById(collectionId); let pkiCollection = await pkiCollectionDAL.findById(collectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${collectionId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -131,7 +131,7 @@ export const pkiCollectionServiceFactory = ({
actorOrgId actorOrgId
}: TDeletePkiCollectionDTO) => { }: TDeletePkiCollectionDTO) => {
let pkiCollection = await pkiCollectionDAL.findById(collectionId); let pkiCollection = await pkiCollectionDAL.findById(collectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${collectionId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -160,7 +160,7 @@ export const pkiCollectionServiceFactory = ({
actorOrgId actorOrgId
}: TGetPkiCollectionItems) => { }: TGetPkiCollectionItems) => {
const pkiCollection = await pkiCollectionDAL.findById(collectionId); const pkiCollection = await pkiCollectionDAL.findById(collectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${collectionId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -203,7 +203,7 @@ export const pkiCollectionServiceFactory = ({
itemId itemId
}: TAddItemToPkiCollectionDTO) => { }: TAddItemToPkiCollectionDTO) => {
const pkiCollection = await pkiCollectionDAL.findById(collectionId); const pkiCollection = await pkiCollectionDAL.findById(collectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${collectionId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -235,7 +235,7 @@ export const pkiCollectionServiceFactory = ({
projectId: pkiCollection.projectId projectId: pkiCollection.projectId
}); });
if (!ca) throw new NotFoundError({ message: "CA not found" }); if (!ca) throw new NotFoundError({ message: `CA with ID '${itemId}' not found` });
pkiCollectionItem = await pkiCollectionItemDAL.create({ pkiCollectionItem = await pkiCollectionItemDAL.create({
pkiCollectionId: collectionId, pkiCollectionId: collectionId,
@ -261,7 +261,7 @@ export const pkiCollectionServiceFactory = ({
}, },
id: itemId id: itemId
}); });
if (!certificate) throw new NotFoundError({ message: "Certificate not found" }); if (!certificate) throw new NotFoundError({ message: `Certificate with ID '${itemId}' not found` });
pkiCollectionItem = await pkiCollectionItemDAL.create({ pkiCollectionItem = await pkiCollectionItemDAL.create({
pkiCollectionId: collectionId, pkiCollectionId: collectionId,
@ -289,14 +289,14 @@ export const pkiCollectionServiceFactory = ({
itemId itemId
}: TRemoveItemFromPkiCollectionDTO) => { }: TRemoveItemFromPkiCollectionDTO) => {
const pkiCollection = await pkiCollectionDAL.findById(collectionId); const pkiCollection = await pkiCollectionDAL.findById(collectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); if (!pkiCollection) throw new NotFoundError({ message: `PKI collection with ID '${collectionId}' not found` });
let pkiCollectionItem = await pkiCollectionItemDAL.findOne({ let pkiCollectionItem = await pkiCollectionItemDAL.findOne({
pkiCollectionId: collectionId, pkiCollectionId: collectionId,
id: itemId id: itemId
}); });
if (!pkiCollectionItem) throw new NotFoundError({ message: "PKI collection item not found" }); if (!pkiCollectionItem) throw new NotFoundError({ message: `PKI collection item with ID '${itemId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -28,7 +28,7 @@ export const getBotKeyFnFactory = (
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) if (!project)
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found during bot lookup. Are you sure you are using the correct project ID?" message: `Project with ID '${projectId}' not found during bot lookup. Are you sure you are using the correct project ID?`
}); });
if (project.version === 3 && !shouldGetBotKey) { if (project.version === 3 && !shouldGetBotKey) {
@ -39,8 +39,11 @@ export const getBotKeyFnFactory = (
if (!bot || !bot.isActive || !bot.encryptedProjectKey || !bot.encryptedProjectKeyNonce) { if (!bot || !bot.isActive || !bot.encryptedProjectKey || !bot.encryptedProjectKeyNonce) {
// trying to set bot automatically // trying to set bot automatically
const projectV1Keys = await projectBotDAL.findProjectUserWorkspaceKey(projectId); const projectV1Keys = await projectBotDAL.findProjectUserWorkspaceKey(projectId);
if (!projectV1Keys) throw new NotFoundError({ message: "Bot not found. Please ask admin user to login" }); if (!projectV1Keys) {
throw new NotFoundError({
message: `Project bot not found for project with ID '${projectId}'. Please ask an administrator to log-in to the Infisical Console.`
});
}
let userPrivateKey = ""; let userPrivateKey = "";
if ( if (
projectV1Keys?.serverEncryptedPrivateKey && projectV1Keys?.serverEncryptedPrivateKey &&

View File

@ -91,7 +91,7 @@ export const projectBotServiceFactory = ({
const bot = await projectBotDAL.findProjectByBotId(botId); const bot = await projectBotDAL.findProjectByBotId(botId);
return bot; return bot;
} catch (e) { } catch (e) {
throw new NotFoundError({ message: "Failed to find bot by ID" }); throw new NotFoundError({ message: `Project bot with ID '${botId}' not found` });
} }
}; };
@ -105,7 +105,7 @@ export const projectBotServiceFactory = ({
isActive isActive
}: TSetActiveStateDTO) => { }: TSetActiveStateDTO) => {
const bot = await projectBotDAL.findById(botId); const bot = await projectBotDAL.findById(botId);
if (!bot) throw new NotFoundError({ message: "Bot not found" }); if (!bot) throw new NotFoundError({ message: `Project bot with ID '${botId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -119,7 +119,7 @@ export const projectBotServiceFactory = ({
const project = await projectBotDAL.findProjectByBotId(botId); const project = await projectBotDAL.findProjectByBotId(botId);
if (!project) { if (!project) {
throw new NotFoundError({ message: "Failed to find project by bot ID" }); throw new NotFoundError({ message: `Project not found for bot with ID '${botId}'` });
} }
if (project.version === ProjectVersion.V2) { if (project.version === ProjectVersion.V2) {
@ -128,7 +128,9 @@ export const projectBotServiceFactory = ({
if (isActive) { if (isActive) {
if (!botKey?.nonce || !botKey?.encryptedKey) { if (!botKey?.nonce || !botKey?.encryptedKey) {
throw new NotFoundError({ message: "Bot key not found, failed to set bot active" }); throw new NotFoundError({
message: `Bot key not found for bot in project with ID '${botId}'. Failed to set bot state to active.`
});
} }
const doc = await projectBotDAL.updateById(botId, { const doc = await projectBotDAL.updateById(botId, {
isActive: true, isActive: true,
@ -136,7 +138,8 @@ export const projectBotServiceFactory = ({
encryptedProjectKeyNonce: botKey.nonce, encryptedProjectKeyNonce: botKey.nonce,
senderId: actorId senderId: actorId
}); });
if (!doc) throw new BadRequestError({ message: "Failed to update bot active state" }); if (!doc)
throw new BadRequestError({ message: `Project bot with ID '${botId}' not found. Failed to update bot.` });
return doc; return doc;
} }
@ -145,7 +148,7 @@ export const projectBotServiceFactory = ({
encryptedProjectKey: null, encryptedProjectKey: null,
encryptedProjectKeyNonce: null encryptedProjectKeyNonce: null
}); });
if (!doc) throw new BadRequestError({ message: "Failed to update bot active state" }); if (!doc) throw new BadRequestError({ message: `Project bot with ID '${botId}' not found. Failed to update bot.` });
return doc; return doc;
}; };

View File

@ -153,8 +153,11 @@ export const projectEnvServiceFactory = ({
} }
const oldEnv = await projectEnvDAL.findOne({ id, projectId }); const oldEnv = await projectEnvDAL.findOne({ id, projectId });
if (!oldEnv) throw new NotFoundError({ message: "Environment not found", name: "UpdateEnvironment" }); if (!oldEnv) {
throw new NotFoundError({
message: `Environment with id '${id}' in project with ID '${projectId}' not found`
});
}
if (slug) { if (slug) {
const existingEnv = await projectEnvDAL.findOne({ slug, projectId }); const existingEnv = await projectEnvDAL.findOne({ slug, projectId });
if (existingEnv && existingEnv.id !== id) { if (existingEnv && existingEnv.id !== id) {
@ -216,7 +219,7 @@ export const projectEnvServiceFactory = ({
const [doc] = await projectEnvDAL.delete({ id, projectId }, tx); const [doc] = await projectEnvDAL.delete({ id, projectId }, tx);
if (!doc) if (!doc)
throw new NotFoundError({ throw new NotFoundError({
message: "Environment doesn't exist", message: `Environment with id '${id}' in project with ID '${projectId}' not found`,
name: "DeleteEnvironment" name: "DeleteEnvironment"
}); });
@ -240,7 +243,7 @@ export const projectEnvServiceFactory = ({
if (!environment) { if (!environment) {
throw new NotFoundError({ throw new NotFoundError({
message: "Environment does not exist" message: `Environment with ID '${id}' not found`
}); });
} }

View File

@ -129,7 +129,7 @@ export const projectMembershipServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Member); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Member);
const [membership] = await projectMembershipDAL.findAllProjectMembers(projectId, { username }); const [membership] = await projectMembershipDAL.findAllProjectMembers(projectId, { username });
if (!membership) throw new NotFoundError({ message: `Project membership not found for user ${username}` }); if (!membership) throw new NotFoundError({ message: `Project membership not found for user '${username}'` });
return membership; return membership;
}; };
@ -143,7 +143,7 @@ export const projectMembershipServiceFactory = ({
sendEmails = true sendEmails = true
}: TAddUsersToWorkspaceDTO) => { }: TAddUsersToWorkspaceDTO) => {
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -259,7 +259,7 @@ export const projectMembershipServiceFactory = ({
}) })
: []; : [];
if (customRoles.length !== customInputRoles.length) { if (customRoles.length !== customInputRoles.length) {
throw new NotFoundError({ message: "Custom project roles not found" }); throw new NotFoundError({ message: "One or more custom roles not found" });
} }
const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug); const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug);
@ -352,7 +352,7 @@ export const projectMembershipServiceFactory = ({
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found" message: `Project with ID '${projectId}' not found`
}); });
} }
@ -426,7 +426,7 @@ export const projectMembershipServiceFactory = ({
} }
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
if (project.version === ProjectVersion.V1) { if (project.version === ProjectVersion.V1) {
throw new BadRequestError({ throw new BadRequestError({
@ -437,7 +437,7 @@ export const projectMembershipServiceFactory = ({
const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId); const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
if (!projectMembers?.length) { if (!projectMembers?.length) {
throw new NotFoundError({ message: "Failed to find project members" }); throw new NotFoundError({ message: `Project members not found for project with ID '${projectId}'` });
} }
if (projectMembers.length < 2) { if (projectMembers.length < 2) {

View File

@ -43,7 +43,7 @@ export const projectRoleServiceFactory = ({
}: TProjectRoleServiceFactoryDep) => { }: TProjectRoleServiceFactoryDep) => {
const createRole = async ({ projectSlug, data, actor, actorId, actorAuthMethod, actorOrgId }: TCreateRoleDTO) => { const createRole = async ({ projectSlug, data, actor, actorId, actorAuthMethod, actorOrgId }: TCreateRoleDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -75,7 +75,7 @@ export const projectRoleServiceFactory = ({
roleSlug roleSlug
}: TGetRoleBySlugDTO) => { }: TGetRoleBySlugDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -92,7 +92,7 @@ export const projectRoleServiceFactory = ({
} }
const customRole = await projectRoleDAL.findOne({ slug: roleSlug, projectId }); const customRole = await projectRoleDAL.findOne({ slug: roleSlug, projectId });
if (!customRole) throw new NotFoundError({ message: "Project role not found" }); if (!customRole) throw new NotFoundError({ message: `Project role with slug '${roleSlug}' not found` });
return { ...customRole, permissions: unpackPermissions(customRole.permissions) }; return { ...customRole, permissions: unpackPermissions(customRole.permissions) };
}; };
@ -106,7 +106,7 @@ export const projectRoleServiceFactory = ({
data data
}: TUpdateRoleDTO) => { }: TUpdateRoleDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -131,13 +131,17 @@ export const projectRoleServiceFactory = ({
permissions: data.permissions ? data.permissions : undefined permissions: data.permissions ? data.permissions : undefined
} }
); );
if (!updatedRole) throw new NotFoundError({ message: "Project role not found", name: "Update role" }); if (!updatedRole) {
throw new NotFoundError({
message: `Project role with ID '${roleId}' in project with ID '${projectId}' not found`
});
}
return { ...updatedRole, permissions: unpackPermissions(updatedRole.permissions) }; return { ...updatedRole, permissions: unpackPermissions(updatedRole.permissions) };
}; };
const deleteRole = async ({ actor, actorId, actorAuthMethod, actorOrgId, projectSlug, roleId }: TDeleteRoleDTO) => { const deleteRole = async ({ actor, actorId, actorAuthMethod, actorOrgId, projectSlug, roleId }: TDeleteRoleDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
const projectId = project.id; const projectId = project.id;
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -166,7 +170,12 @@ export const projectRoleServiceFactory = ({
} }
const [deletedRole] = await projectRoleDAL.delete({ id: roleId, projectId }); const [deletedRole] = await projectRoleDAL.delete({ id: roleId, projectId });
if (!deletedRole) throw new NotFoundError({ message: "Project role not found", name: "Delete role" }); if (!deletedRole) {
throw new NotFoundError({
message: `Project role with ID '${roleId}' in project with ID '${projectId}' not found`,
name: "DeleteRole"
});
}
return { ...deletedRole, permissions: unpackPermissions(deletedRole.permissions) }; return { ...deletedRole, permissions: unpackPermissions(deletedRole.permissions) };
}; };

View File

@ -186,7 +186,7 @@ export const projectDALFactory = (db: TDbClient) => {
})?.[0]; })?.[0];
if (!project) { if (!project) {
throw new NotFoundError({ message: "Project not found" }); throw new NotFoundError({ message: `Project with ID '${id}' not found` });
} }
return project; return project;
@ -235,7 +235,7 @@ export const projectDALFactory = (db: TDbClient) => {
})?.[0]; })?.[0];
if (!project) { if (!project) {
throw new NotFoundError({ message: "Project not found" }); throw new NotFoundError({ message: `Project with slug '${slug}' not found` });
} }
return project; return project;
@ -295,7 +295,7 @@ export const projectDALFactory = (db: TDbClient) => {
.first(); .first();
if (!project) { if (!project) {
throw new NotFoundError({ message: "Project not found" }); throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
} }
return { return {

View File

@ -75,7 +75,7 @@ export const getProjectKmsCertificateKeyId = async ({
const keyId = await projectDAL.transaction(async (tx) => { const keyId = await projectDAL.transaction(async (tx) => {
const project = await projectDAL.findOne({ id: projectId }, tx); const project = await projectDAL.findOne({ id: projectId }, tx);
if (!project) { if (!project) {
throw new NotFoundError({ message: "Project not found" }); throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
} }
if (!project.kmsCertificateKeyId) { if (!project.kmsCertificateKeyId) {

View File

@ -327,7 +327,7 @@ export const projectServiceFactory = ({
// If identity org membership not found, throw error // If identity org membership not found, throw error
if (!identityOrgMembership) { if (!identityOrgMembership) {
throw new NotFoundError({ throw new NotFoundError({
message: `Failed to find identity with id ${actorId}` message: `Failed to find identity with id '${actorId}'`
}); });
} }
@ -496,7 +496,7 @@ export const projectServiceFactory = ({
const project = await projectDAL.findProjectBySlug(workspaceSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(workspaceSlug, actorOrgId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found" message: `Project with slug '${workspaceSlug}' not found`
}); });
} }
@ -527,7 +527,7 @@ export const projectServiceFactory = ({
const project = await projectDAL.findProjectBySlug(workspaceSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(workspaceSlug, actorOrgId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found." message: `Project with slug '${workspaceSlug}' not found`
}); });
} }
@ -634,7 +634,7 @@ export const projectServiceFactory = ({
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: `Project with id ${projectId} not found` message: `Project with ID '${projectId}' not found`
}); });
} }
@ -933,7 +933,7 @@ export const projectServiceFactory = ({
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found" message: `Project with ID '${projectId}' not found`
}); });
} }
@ -967,14 +967,21 @@ export const projectServiceFactory = ({
const project = await projectDAL.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found" message: `Project with ID '${projectId}' not found`
}); });
} }
const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(slackIntegrationId); const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(slackIntegrationId);
if (!slackIntegration) { if (!slackIntegration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Slack integration not found" message: `Slack integration with ID '${slackIntegrationId}' not found`
});
}
if (slackIntegration.orgId !== actorOrgId) {
throw new ForbiddenRequestError({
message: "Selected slack integration is not in the same organization"
}); });
} }

View File

@ -79,13 +79,15 @@ export const secretBlindIndexServiceFactory = ({
} }
const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) throw new NotFoundError({ message: "Blind index not found", name: "CreateSecret" }); if (!blindIndexCfg)
throw new NotFoundError({ message: `Blind index for project with ID '${projectId}' not found` });
const secrets = await secretBlindIndexDAL.findSecretsByProjectId( const secrets = await secretBlindIndexDAL.findSecretsByProjectId(
projectId, projectId,
secretsToUpdate.map(({ secretId }) => secretId) secretsToUpdate.map(({ secretId }) => secretId)
); );
if (secrets.length !== secretsToUpdate.length) throw new NotFoundError({ message: "Secret not found" }); if (secrets.length !== secretsToUpdate.length)
throw new NotFoundError({ message: "One or more secrets to update not found" });
const operations = await Promise.all( const operations = await Promise.all(
secretsToUpdate.map(async ({ secretName, secretId: id }) => { secretsToUpdate.map(async ({ secretName, secretId: id }) => {

View File

@ -76,7 +76,11 @@ export const secretFolderServiceFactory = ({
} }
const env = await projectEnvDAL.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) throw new NotFoundError({ message: "Environment not found", name: "Create folder" }); if (!env) {
throw new NotFoundError({
message: `Environment with slug '${environment}' in project with ID '${projectId}' not found`
});
}
const folder = await folderDAL.transaction(async (tx) => { const folder = await folderDAL.transaction(async (tx) => {
// the logic is simple we need to avoid creating same folder in same path multiple times // the logic is simple we need to avoid creating same folder in same path multiple times
@ -86,7 +90,11 @@ export const secretFolderServiceFactory = ({
const pathWithFolder = path.join(secretPath, name); const pathWithFolder = path.join(secretPath, name);
const parentFolder = await folderDAL.findClosestFolder(projectId, environment, pathWithFolder, tx); const parentFolder = await folderDAL.findClosestFolder(projectId, environment, pathWithFolder, tx);
// no folder found is not possible root should be their // no folder found is not possible root should be their
if (!parentFolder) throw new NotFoundError({ message: "Secret path not found" }); if (!parentFolder) {
throw new NotFoundError({
message: `Folder with path '${pathWithFolder}' in environment with slug '${environment}' not found`
});
}
// exact folder // exact folder
if (parentFolder.path === pathWithFolder) return parentFolder; if (parentFolder.path === pathWithFolder) return parentFolder;
@ -149,7 +157,7 @@ export const secretFolderServiceFactory = ({
}: TUpdateManyFoldersDTO) => { }: TUpdateManyFoldersDTO) => {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) { if (!project) {
throw new NotFoundError({ message: "Project not found" }); throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
} }
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@ -184,12 +192,18 @@ export const secretFolderServiceFactory = ({
const parentFolder = await folderDAL.findBySecretPath(project.id, environment, secretPath); const parentFolder = await folderDAL.findBySecretPath(project.id, environment, secretPath);
if (!parentFolder) { if (!parentFolder) {
throw new NotFoundError({ message: "Secret path not found", name: "Batch update folder" }); throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "UpdateManyFolders"
});
} }
const env = await projectEnvDAL.findOne({ projectId: project.id, slug: environment }); const env = await projectEnvDAL.findOne({ projectId: project.id, slug: environment });
if (!env) { if (!env) {
throw new NotFoundError({ message: "Environment not found", name: "Batch update folder" }); throw new NotFoundError({
message: `Environment with slug '${environment}' in project with ID '${project.id}' not found`,
name: "UpdateManyFolders"
});
} }
const folder = await folderDAL const folder = await folderDAL
.findOne({ envId: env.id, id, parentId: parentFolder.id }) .findOne({ envId: env.id, id, parentId: parentFolder.id })
@ -198,7 +212,10 @@ export const secretFolderServiceFactory = ({
.catch(() => folderDAL.findOne({ envId: env.id, name: id, parentId: parentFolder.id })); .catch(() => folderDAL.findOne({ envId: env.id, name: id, parentId: parentFolder.id }));
if (!folder) { if (!folder) {
throw new NotFoundError({ message: "Folder not found" }); throw new NotFoundError({
message: `Folder with id '${id}' in environment with slug '${env.slug}' not found`,
name: "UpdateManyFolders"
});
} }
if (name !== folder.name) { if (name !== folder.name) {
// ensure that new folder name is unique // ensure that new folder name is unique
@ -231,7 +248,10 @@ export const secretFolderServiceFactory = ({
tx tx
); );
if (!doc) { if (!doc) {
throw new NotFoundError({ message: "Folder not found", name: "Batch update folder" }); throw new NotFoundError({
message: `Failed to update folder with id '${id}', not found`,
name: "UpdateManyFolders"
});
} }
return { oldFolder: folder, newFolder: doc }; return { oldFolder: folder, newFolder: doc };
@ -283,17 +303,23 @@ export const secretFolderServiceFactory = ({
} }
const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!parentFolder) throw new NotFoundError({ message: "Secret path not found" }); if (!parentFolder)
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "UpdateFolder"
});
const env = await projectEnvDAL.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) throw new NotFoundError({ message: "Environment not found", name: "Update folder" }); if (!env) {
throw new NotFoundError({ message: `Environment with slug '${environment}' not found`, name: "UpdateFolder" });
}
const folder = await folderDAL const folder = await folderDAL
.findOne({ envId: env.id, id, parentId: parentFolder.id, isReserved: false }) .findOne({ envId: env.id, id, parentId: parentFolder.id, isReserved: false })
// now folder api accepts id based change // now folder api accepts id based change
// this is for cli backward compatiability and when cli removes this, we will remove this logic // this is for cli backward compatiability and when cli removes this, we will remove this logic
.catch(() => folderDAL.findOne({ envId: env.id, name: id, parentId: parentFolder.id })); .catch(() => folderDAL.findOne({ envId: env.id, name: id, parentId: parentFolder.id }));
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) throw new NotFoundError({ message: `Folder with ID '${id}' not found`, name: "UpdateFolder" });
if (name !== folder.name) { if (name !== folder.name) {
// ensure that new folder name is unique // ensure that new folder name is unique
const folderToCheck = await folderDAL.findOne({ const folderToCheck = await folderDAL.findOne({
@ -305,7 +331,7 @@ export const secretFolderServiceFactory = ({
if (folderToCheck) { if (folderToCheck) {
throw new BadRequestError({ throw new BadRequestError({
message: "Folder with specified name already exists", message: "Folder with specified name already exists",
name: "Update folder" name: "UpdateFolder"
}); });
} }
} }
@ -325,7 +351,7 @@ export const secretFolderServiceFactory = ({
}, },
tx tx
); );
if (!doc) throw new NotFoundError({ message: "Folder not found", name: "Update folder" }); if (!doc) throw new NotFoundError({ message: `Failed to update folder with ID '${id}'`, name: "UpdateFolder" });
return doc; return doc;
}); });
@ -367,11 +393,14 @@ export const secretFolderServiceFactory = ({
} }
const env = await projectEnvDAL.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) throw new NotFoundError({ message: "Environment not found", name: "Create folder" }); if (!env) throw new NotFoundError({ message: `Environment with slug '${environment}' not found` });
const folder = await folderDAL.transaction(async (tx) => { const folder = await folderDAL.transaction(async (tx) => {
const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath, tx); const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath, tx);
if (!parentFolder) throw new NotFoundError({ message: "Secret path not found" }); if (!parentFolder)
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
const [doc] = await folderDAL.delete( const [doc] = await folderDAL.delete(
{ {
@ -382,7 +411,7 @@ export const secretFolderServiceFactory = ({
}, },
tx tx
); );
if (!doc) throw new NotFoundError({ message: "Folder not found", name: "Delete folder" }); if (!doc) throw new NotFoundError({ message: `Failed to delete folder with ID '${idOrName}', not found` });
return doc; return doc;
}); });
@ -409,7 +438,7 @@ export const secretFolderServiceFactory = ({
await permissionService.getProjectPermission(actor, actorId, projectId, actorAuthMethod, actorOrgId); await permissionService.getProjectPermission(actor, actorId, projectId, actorAuthMethod, actorOrgId);
const env = await projectEnvDAL.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) throw new NotFoundError({ message: "Environment not found", name: "get folders" }); if (!env) throw new NotFoundError({ message: `Environment with slug '${environment}' not found` });
const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!parentFolder) return []; if (!parentFolder) return [];
@ -448,7 +477,10 @@ export const secretFolderServiceFactory = ({
const envs = await projectEnvDAL.findBySlugs(projectId, environments); const envs = await projectEnvDAL.findBySlugs(projectId, environments);
if (!envs.length) if (!envs.length)
throw new NotFoundError({ message: "Environment(s) not found", name: "get project folder count" }); throw new NotFoundError({
message: `Environments '${environments.join(", ")}' not found`,
name: "GetFoldersMultiEnv"
});
const parentFolders = await folderDAL.findBySecretPathMultiEnv(projectId, environments, secretPath); const parentFolders = await folderDAL.findBySecretPathMultiEnv(projectId, environments, secretPath);
if (!parentFolders.length) return []; if (!parentFolders.length) return [];
@ -479,8 +511,7 @@ export const secretFolderServiceFactory = ({
const envs = await projectEnvDAL.findBySlugs(projectId, environments); const envs = await projectEnvDAL.findBySlugs(projectId, environments);
if (!envs.length) if (!envs.length) throw new NotFoundError({ message: `Environments '${environments.join(", ")}' not found` });
throw new NotFoundError({ message: "Environment(s) not found", name: "get project folder count" });
const parentFolders = await folderDAL.findBySecretPathMultiEnv(projectId, environments, secretPath); const parentFolders = await folderDAL.findBySecretPathMultiEnv(projectId, environments, secretPath);
if (!parentFolders.length) return 0; if (!parentFolders.length) return 0;
@ -502,7 +533,7 @@ export const secretFolderServiceFactory = ({
const getFolderById = async ({ actor, actorId, actorOrgId, actorAuthMethod, id }: TGetFolderByIdDTO) => { const getFolderById = async ({ actor, actorId, actorOrgId, actorAuthMethod, id }: TGetFolderByIdDTO) => {
const folder = await folderDAL.findById(id); const folder = await folderDAL.findById(id);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) throw new NotFoundError({ message: `Folder with ID '${id}' not found` });
// folder list is allowed to be read by anyone // folder list is allowed to be read by anyone
// permission to check does user has access // permission to check does user has access
await permissionService.getProjectPermission(actor, actorId, folder.projectId, actorAuthMethod, actorOrgId); await permissionService.getProjectPermission(actor, actorId, folder.projectId, actorAuthMethod, actorOrgId);
@ -510,7 +541,9 @@ export const secretFolderServiceFactory = ({
const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(folder.projectId, [folder.id]); const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(folder.projectId, [folder.id]);
if (!folderWithPath) { if (!folderWithPath) {
throw new NotFoundError({ message: "Folder path not found" }); throw new NotFoundError({
message: `Folder with ID '${folder.id}' in project with ID '${folder.projectId}' not found`
});
} }
return { return {

View File

@ -107,10 +107,17 @@ export const secretImportServiceFactory = ({
await projectDAL.checkProjectUpgradeStatus(projectId); await projectDAL.checkProjectUpgradeStatus(projectId);
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new NotFoundError({ message: "Folder not found", name: "Create import" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
const [importEnv] = await projectEnvDAL.findBySlugs(projectId, [data.environment]); const [importEnv] = await projectEnvDAL.findBySlugs(projectId, [data.environment]);
if (!importEnv) throw new NotFoundError({ error: "Imported env not found", name: "Create import" }); if (!importEnv) {
throw new NotFoundError({
error: `Imported environment with slug '${data.environment}' in project with ID '${projectId}' not found`
});
}
const sourceFolder = await folderDAL.findBySecretPath(projectId, data.environment, data.path); const sourceFolder = await folderDAL.findBySecretPath(projectId, data.environment, data.path);
if (sourceFolder) { if (sourceFolder) {
@ -119,7 +126,7 @@ export const secretImportServiceFactory = ({
importEnv: folder.environment.id, importEnv: folder.environment.id,
importPath: secretPath importPath: secretPath
}); });
if (existingImport) throw new NotFoundError({ message: "Cyclic import not allowed" }); if (existingImport) throw new BadRequestError({ message: `Cyclic import not allowed` });
} }
const secImport = await secretImportDAL.transaction(async (tx) => { const secImport = await secretImportDAL.transaction(async (tx) => {
@ -195,7 +202,11 @@ export const secretImportServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new NotFoundError({ message: "Folder not found", name: "Update import" }); if (!folder) {
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
}
const secImpDoc = await secretImportDAL.findOne({ folderId: folder.id, id }); const secImpDoc = await secretImportDAL.findOne({ folderId: folder.id, id });
if (!secImpDoc) throw ERR_SEC_IMP_NOT_FOUND; if (!secImpDoc) throw ERR_SEC_IMP_NOT_FOUND;
@ -203,7 +214,11 @@ export const secretImportServiceFactory = ({
const importedEnv = data.environment // this is get env information of new one or old one const importedEnv = data.environment // this is get env information of new one or old one
? (await projectEnvDAL.findBySlugs(projectId, [data.environment]))?.[0] ? (await projectEnvDAL.findBySlugs(projectId, [data.environment]))?.[0]
: await projectEnvDAL.findById(secImpDoc.importEnv); : await projectEnvDAL.findById(secImpDoc.importEnv);
if (!importedEnv) throw new NotFoundError({ error: "Imported env not found", name: "Create import" }); if (!importedEnv) {
throw new NotFoundError({
error: `Imported environment with slug '${data.environment}' in project with ID '${projectId}' not found`
});
}
const sourceFolder = await folderDAL.findBySecretPath( const sourceFolder = await folderDAL.findBySecretPath(
projectId, projectId,
@ -216,7 +231,7 @@ export const secretImportServiceFactory = ({
importEnv: folder.environment.id, importEnv: folder.environment.id,
importPath: secretPath importPath: secretPath
}); });
if (existingImport) throw new NotFoundError({ message: "Cyclic import not allowed" }); if (existingImport) throw new BadRequestError({ message: "Cyclic import not allowed" });
} }
const updatedSecImport = await secretImportDAL.transaction(async (tx) => { const updatedSecImport = await secretImportDAL.transaction(async (tx) => {
@ -281,11 +296,14 @@ export const secretImportServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new NotFoundError({ message: "Folder not found", name: "Delete import" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
const secImport = await secretImportDAL.transaction(async (tx) => { const secImport = await secretImportDAL.transaction(async (tx) => {
const [doc] = await secretImportDAL.delete({ folderId: folder.id, id }, tx); const [doc] = await secretImportDAL.delete({ folderId: folder.id, id }, tx);
if (!doc) throw new NotFoundError({ message: "Secret import not found" }); if (!doc) throw new NotFoundError({ message: `Secret import with folder ID '${id}' not found` });
if (doc.isReplication) { if (doc.isReplication) {
const replicationFolderPath = path.join(secretPath, getReplicationFolderName(doc.id)); const replicationFolderPath = path.join(secretPath, getReplicationFolderName(doc.id));
const replicatedFolder = await folderDAL.findBySecretPath(projectId, environment, replicationFolderPath, tx); const replicatedFolder = await folderDAL.findBySecretPath(projectId, environment, replicationFolderPath, tx);
@ -307,7 +325,11 @@ export const secretImportServiceFactory = ({
} }
const importEnv = await projectEnvDAL.findById(doc.importEnv); const importEnv = await projectEnvDAL.findById(doc.importEnv);
if (!importEnv) throw new NotFoundError({ error: "Imported env not found" }); if (!importEnv) {
throw new NotFoundError({
error: `Imported environment with ID '${doc.importEnv}' in project with ID '${projectId}' not found`
});
}
return { ...doc, importEnv }; return { ...doc, importEnv };
}); });
@ -354,13 +376,18 @@ export const secretImportServiceFactory = ({
} }
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder) {
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
}
const [secretImportDoc] = await secretImportDAL.find({ const [secretImportDoc] = await secretImportDAL.find({
folderId: folder.id, folderId: folder.id,
[`${TableName.SecretImport}.id` as "id"]: secretImportDocId [`${TableName.SecretImport}.id` as "id"]: secretImportDocId
}); });
if (!secretImportDoc) throw new NotFoundError({ message: "Failed to find secret import" }); if (!secretImportDoc)
throw new NotFoundError({ message: `Secret import with ID '${secretImportDocId}' not found` });
if (!secretImportDoc.isReplication) throw new BadRequestError({ message: "Import is not in replication mode" }); if (!secretImportDoc.isReplication) throw new BadRequestError({ message: "Import is not in replication mode" });
@ -418,7 +445,10 @@ export const secretImportServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new NotFoundError({ message: "Folder not found", name: "Get imports" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
const count = await secretImportDAL.getProjectImportCount({ folderId: folder.id, search }); const count = await secretImportDAL.getProjectImportCount({ folderId: folder.id, search });
@ -450,7 +480,10 @@ export const secretImportServiceFactory = ({
); );
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new NotFoundError({ message: "Folder not found" }); if (!folder)
throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
const secImports = await secretImportDAL.find({ folderId: folder.id, search, limit, offset }); const secImports = await secretImportDAL.find({ folderId: folder.id, search, limit, offset });
return secImports; return secImports;
@ -466,18 +499,22 @@ export const secretImportServiceFactory = ({
const importDoc = await secretImportDAL.findById(importId); const importDoc = await secretImportDAL.findById(importId);
if (!importDoc) { if (!importDoc) {
throw new NotFoundError({ message: "Secret import not found" }); throw new NotFoundError({ message: `Secret import with ID '${importId}' not found` });
} }
// the folder to import into // the folder to import into
const folder = await folderDAL.findById(importDoc.folderId); const folder = await folderDAL.findById(importDoc.folderId);
if (!folder) throw new NotFoundError({ message: "Secret import folder not found" }); if (!folder) throw new NotFoundError({ message: `Secret import folder with ID '${importDoc.folderId}' not found` });
// the folder to import into, with path // the folder to import into, with path
const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(folder.projectId, [folder.id]); const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(folder.projectId, [folder.id]);
if (!folderWithPath) throw new NotFoundError({ message: "Folder path not found" }); if (!folderWithPath) {
throw new NotFoundError({
message: `Folder with ID '${folder.id}' in project with ID ${folder.projectId} not found`
});
}
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -500,7 +537,11 @@ export const secretImportServiceFactory = ({
slug: folder.environment.envSlug slug: folder.environment.envSlug
}); });
if (!importIntoEnv) throw new NotFoundError({ message: "Environment to import into not found" }); if (!importIntoEnv) {
throw new NotFoundError({
message: `Environment with slug '${folder.environment.envSlug}' in project with ID ${folder.projectId} not found`
});
}
return { return {
...importDoc, ...importDoc,
@ -606,7 +647,7 @@ export const secretImportServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot not found for project with ID '${projectId}'. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });

View File

@ -199,7 +199,7 @@ export const secretSharingServiceFactory = ({
if (!sharedSecret) if (!sharedSecret)
throw new NotFoundError({ throw new NotFoundError({
message: "Shared secret not found" message: `Shared secret with ID '${sharedSecretId}' not found`
}); });
const { accessType, expiresAt, expiresAfterViews } = sharedSecret; const { accessType, expiresAt, expiresAfterViews } = sharedSecret;

View File

@ -47,7 +47,7 @@ export const secretTagServiceFactory = ({ secretTagDAL, permissionService }: TSe
const updateTag = async ({ actorId, actor, actorOrgId, actorAuthMethod, id, color, slug }: TUpdateTagDTO) => { const updateTag = async ({ actorId, actor, actorOrgId, actorAuthMethod, id, color, slug }: TUpdateTagDTO) => {
const tag = await secretTagDAL.findById(id); const tag = await secretTagDAL.findById(id);
if (!tag) throw new NotFoundError({ message: "Tag not found" }); if (!tag) throw new NotFoundError({ message: `Tag with ID '${id}' not found` });
if (slug) { if (slug) {
const existingTag = await secretTagDAL.findOne({ slug, projectId: tag.projectId }); const existingTag = await secretTagDAL.findOne({ slug, projectId: tag.projectId });
@ -69,7 +69,7 @@ export const secretTagServiceFactory = ({ secretTagDAL, permissionService }: TSe
const deleteTag = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TDeleteTagDTO) => { const deleteTag = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TDeleteTagDTO) => {
const tag = await secretTagDAL.findById(id); const tag = await secretTagDAL.findById(id);
if (!tag) throw new NotFoundError({ message: "Tag not found" }); if (!tag) throw new NotFoundError({ message: `Tag with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -86,7 +86,7 @@ export const secretTagServiceFactory = ({ secretTagDAL, permissionService }: TSe
const getTagById = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TGetTagByIdDTO) => { const getTagById = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TGetTagByIdDTO) => {
const tag = await secretTagDAL.findById(id); const tag = await secretTagDAL.findById(id);
if (!tag) throw new NotFoundError({ message: "Tag not found" }); if (!tag) throw new NotFoundError({ message: `Tag with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -102,7 +102,7 @@ export const secretTagServiceFactory = ({ secretTagDAL, permissionService }: TSe
const getTagBySlug = async ({ actorId, actor, actorOrgId, actorAuthMethod, slug, projectId }: TGetTagBySlugDTO) => { const getTagBySlug = async ({ actorId, actor, actorOrgId, actorAuthMethod, slug, projectId }: TGetTagBySlugDTO) => {
const tag = await secretTagDAL.findOne({ projectId, slug }); const tag = await secretTagDAL.findOne({ projectId, slug });
if (!tag) throw new NotFoundError({ message: "Tag not found" }); if (!tag) throw new NotFoundError({ message: `Tag with slug '${slug}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -342,7 +342,9 @@ export const recursivelyGetSecretPaths = async ({
}); });
if (!env) { if (!env) {
throw new NotFoundError({ message: `'${environment}' environment not found in project with ID ${projectId}` }); throw new NotFoundError({
message: `Environment with slug '${environment}' in project with ID ${projectId} not found`
});
} }
// Fetch all folders in env once with a single query // Fetch all folders in env once with a single query

View File

@ -118,8 +118,8 @@ export const secretV2BridgeServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "CreateSecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -144,7 +144,8 @@ export const secretV2BridgeServiceFactory = ({
// validate tags // validate tags
// fetch all tags and if not same count throw error meaning one was invalid tags // fetch all tags and if not same count throw error meaning one was invalid tags
const tags = inputSecret.tagIds ? await secretTagDAL.find({ projectId, $in: { id: inputSecret.tagIds } }) : []; const tags = inputSecret.tagIds ? await secretTagDAL.find({ projectId, $in: { id: inputSecret.tagIds } }) : [];
if ((inputSecret.tagIds || []).length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if ((inputSecret.tagIds || []).length !== tags.length)
throw new NotFoundError({ message: "One or more tags not found" });
const { secretName, type, ...el } = inputSecret; const { secretName, type, ...el } = inputSecret;
const references = getAllNestedSecretReferences(inputSecret.secretValue); const references = getAllNestedSecretReferences(inputSecret.secretValue);
@ -240,7 +241,7 @@ export const secretV2BridgeServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "UpdateSecret" name: "UpdateSecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -262,7 +263,8 @@ export const secretV2BridgeServiceFactory = ({
folderId, folderId,
userId: actorId userId: actorId
}); });
if (!personalSecretToModify) throw new NotFoundError({ message: "Secret not found" }); if (!personalSecretToModify)
throw new NotFoundError({ message: `Personal secret with name ${inputSecret.secretName} not found` });
secretId = personalSecretToModify.id; secretId = personalSecretToModify.id;
secret = personalSecretToModify; secret = personalSecretToModify;
} else { } else {
@ -271,7 +273,8 @@ export const secretV2BridgeServiceFactory = ({
type: SecretType.Shared, type: SecretType.Shared,
folderId folderId
}); });
if (!sharedSecretToModify) throw new NotFoundError({ message: "Secret not found" }); if (!sharedSecretToModify)
throw new NotFoundError({ message: `Secret with name ${inputSecret.secretName} not found` });
secretId = sharedSecretToModify.id; secretId = sharedSecretToModify.id;
secret = sharedSecretToModify; secret = sharedSecretToModify;
} }
@ -288,7 +291,8 @@ export const secretV2BridgeServiceFactory = ({
// validate tags // validate tags
// fetch all tags and if not same count throw error meaning one was invalid tags // fetch all tags and if not same count throw error meaning one was invalid tags
const tags = inputSecret.tagIds ? await secretTagDAL.find({ projectId, $in: { id: inputSecret.tagIds } }) : []; const tags = inputSecret.tagIds ? await secretTagDAL.find({ projectId, $in: { id: inputSecret.tagIds } }) : [];
if ((inputSecret.tagIds || []).length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if ((inputSecret.tagIds || []).length !== tags.length)
throw new NotFoundError({ message: "One or more tags not found" });
const { secretName, secretValue } = inputSecret; const { secretName, secretValue } = inputSecret;
@ -394,8 +398,8 @@ export const secretV2BridgeServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "Delete secret" name: "DeleteSecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -413,7 +417,11 @@ export const secretV2BridgeServiceFactory = ({
userId: actorId userId: actorId
}) })
}); });
if (!secretToDelete) throw new NotFoundError({ message: "Secret not found" }); if (!secretToDelete)
throw new NotFoundError({
message: `Secret with name '${inputSecret.secretName}' not found`,
name: "DeleteSecret"
});
const deletedSecret = await secretDAL.transaction(async (tx) => const deletedSecret = await secretDAL.transaction(async (tx) =>
fnSecretBulkDelete({ fnSecretBulkDelete({
@ -800,8 +808,8 @@ export const secretV2BridgeServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "GetSecretByName"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -885,7 +893,7 @@ export const secretV2BridgeServiceFactory = ({
} }
} }
} }
if (!secret) throw new NotFoundError({ message: "Secret not found" }); if (!secret) throw new NotFoundError({ message: `Secret with name '${secretName}' not found` });
let secretValue = secret.encryptedValue let secretValue = secret.encryptedValue
? secretManagerDecryptor({ cipherTextBlob: secret.encryptedValue }).toString() ? secretManagerDecryptor({ cipherTextBlob: secret.encryptedValue }).toString()
@ -935,8 +943,8 @@ export const secretV2BridgeServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "CreateManySecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -953,7 +961,7 @@ export const secretV2BridgeServiceFactory = ({
// get all tags // get all tags
const sanitizedTagIds = inputSecrets.flatMap(({ tagIds = [] }) => tagIds); const sanitizedTagIds = inputSecrets.flatMap(({ tagIds = [] }) => tagIds);
const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds) : []; const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds) : [];
if (tags.length !== sanitizedTagIds.length) throw new NotFoundError({ message: "Tag not found" }); if (tags.length !== sanitizedTagIds.length) throw new NotFoundError({ message: "One or more tags not found" });
const { encryptor: secretManagerEncryptor, decryptor: secretManagerDecryptor } = const { encryptor: secretManagerEncryptor, decryptor: secretManagerDecryptor } =
await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId }); await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
@ -1040,8 +1048,8 @@ export const secretV2BridgeServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "Update secret" name: "UpdateManySecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -1076,7 +1084,7 @@ export const secretV2BridgeServiceFactory = ({
// get all tags // get all tags
const sanitizedTagIds = inputSecrets.flatMap(({ tagIds = [] }) => tagIds); const sanitizedTagIds = inputSecrets.flatMap(({ tagIds = [] }) => tagIds);
const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds) : []; const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds) : [];
if (tags.length !== sanitizedTagIds.length) throw new NotFoundError({ message: "Tag not found" }); if (tags.length !== sanitizedTagIds.length) throw new NotFoundError({ message: "One or more tags not found" });
const { encryptor: secretManagerEncryptor, decryptor: secretManagerDecryptor } = const { encryptor: secretManagerEncryptor, decryptor: secretManagerDecryptor } =
await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId }); await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
@ -1172,8 +1180,8 @@ export const secretV2BridgeServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "DeleteManySecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -1186,7 +1194,7 @@ export const secretV2BridgeServiceFactory = ({
); );
if (secretsToDelete.length !== inputSecrets.length) if (secretsToDelete.length !== inputSecrets.length)
throw new NotFoundError({ throw new NotFoundError({
message: `One or more secrets does not exist: ${secretsToDelete.map((el) => el.key).join(",")}` message: `One or more secrets does not exist: ${secretsToDelete.map((el) => el.key).join(", ")}`
}); });
const secretsDeleted = await secretDAL.transaction(async (tx) => const secretsDeleted = await secretDAL.transaction(async (tx) =>
@ -1236,10 +1244,10 @@ export const secretV2BridgeServiceFactory = ({
secretId secretId
}: TGetSecretVersionsDTO) => { }: TGetSecretVersionsDTO) => {
const secret = await secretDAL.findById(secretId); const secret = await secretDAL.findById(secretId);
if (!secret) throw new NotFoundError({ message: "Failed to find secret" }); if (!secret) throw new NotFoundError({ message: `Secret with ID '${secretId}' not found` });
const folder = await folderDAL.findById(secret.folderId); const folder = await folderDAL.findById(secret.folderId);
if (!folder) throw new NotFoundError({ message: "Failed to find secret" }); if (!folder) throw new NotFoundError({ message: `Folder with ID '${secret.folderId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -1345,7 +1353,7 @@ export const secretV2BridgeServiceFactory = ({
const sourceFolder = await folderDAL.findBySecretPath(projectId, sourceEnvironment, sourceSecretPath); const sourceFolder = await folderDAL.findBySecretPath(projectId, sourceEnvironment, sourceSecretPath);
if (!sourceFolder) { if (!sourceFolder) {
throw new NotFoundError({ throw new NotFoundError({
message: "Source path does not exist." message: `Source folder with path '${sourceSecretPath}' in environment with slug '${sourceEnvironment}' not found`
}); });
} }
@ -1357,7 +1365,7 @@ export const secretV2BridgeServiceFactory = ({
if (!destinationFolder) { if (!destinationFolder) {
throw new NotFoundError({ throw new NotFoundError({
message: "Destination path does not exist." message: `Destination folder with path '${destinationSecretPath}' in environment with slug '${destinationEnvironment}' not found`
}); });
} }

View File

@ -152,7 +152,9 @@ export const recursivelyGetSecretPaths = ({
}); });
if (!env) { if (!env) {
throw new NotFoundError({ message: `'${environment}' environment not found in project with ID ${projectId}` }); throw new NotFoundError({
message: `Environment with slug '${environment}' in project with ID '${projectId}' not found`
});
} }
// Fetch all folders in env once with a single query // Fetch all folders in env once with a single query
@ -758,7 +760,7 @@ export const createManySecretsRawFnFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' not found in environment with slug '${environment}'`,
name: "Create secret" name: "Create secret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -798,7 +800,7 @@ export const createManySecretsRawFnFactory = ({
// get all tags // get all tags
const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags); const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags);
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tags.length !== tagIds.length) throw new NotFoundError({ message: "Tag not found" }); if (tags.length !== tagIds.length) throw new NotFoundError({ message: "One or more tags not found" });
const newSecrets = await secretDAL.transaction(async (tx) => const newSecrets = await secretDAL.transaction(async (tx) =>
fnSecretV2BridgeBulkInsert({ fnSecretV2BridgeBulkInsert({
@ -834,7 +836,7 @@ export const createManySecretsRawFnFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot not found for project with ID '${projectId}'. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
const inputSecrets = secrets.map((secret) => { const inputSecrets = secrets.map((secret) => {
@ -865,7 +867,7 @@ export const createManySecretsRawFnFactory = ({
// get all tags // get all tags
const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags); const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags);
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tags.length !== tagIds.length) throw new NotFoundError({ message: "Tag not found" }); if (tags.length !== tagIds.length) throw new NotFoundError({ message: "One or more tags not found" });
const newSecrets = await secretDAL.transaction(async (tx) => const newSecrets = await secretDAL.transaction(async (tx) =>
fnSecretBulkInsert({ fnSecretBulkInsert({
@ -918,8 +920,8 @@ export const updateManySecretsRawFnFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${secretPath}' not found in environment with slug '${environment}'`,
name: "Update secret" name: "UpdateSecret"
}); });
const folderId = folder.id; const folderId = folder.id;
if (shouldUseSecretV2Bridge) { if (shouldUseSecretV2Bridge) {
@ -977,7 +979,7 @@ export const updateManySecretsRawFnFactory = ({
const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags); const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags);
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tagIds.length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if (tagIds.length !== tags.length) throw new NotFoundError({ message: "One or more tags not found" });
const updatedSecrets = await secretDAL.transaction(async (tx) => const updatedSecrets = await secretDAL.transaction(async (tx) =>
fnSecretV2BridgeBulkUpdate({ fnSecretV2BridgeBulkUpdate({
@ -999,7 +1001,7 @@ export const updateManySecretsRawFnFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot not found for project with ID '${projectId}'. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
@ -1046,7 +1048,7 @@ export const updateManySecretsRawFnFactory = ({
const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags); const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags);
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tagIds.length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if (tagIds.length !== tags.length) throw new NotFoundError({ message: "One or more tags not found" });
// now find any secret that needs to update its name // now find any secret that needs to update its name
// same process as above // same process as above

View File

@ -1048,7 +1048,7 @@ export const secretQueueFactory = ({
return; return;
} }
if (!botKey) throw new NotFoundError({ message: "Project bot not found" }); if (!botKey) throw new NotFoundError({ message: `Project bot not found for project ${projectId}` });
await projectDAL.updateById(projectId, { upgradeStatus: ProjectUpgradeStatus.InProgress }); await projectDAL.updateById(projectId, { upgradeStatus: ProjectUpgradeStatus.InProgress });
const { encryptor: secretManagerEncryptor } = await kmsService.createCipherPairWithDataKey({ const { encryptor: secretManagerEncryptor } = await kmsService.createCipherPairWithDataKey({

View File

@ -153,7 +153,12 @@ export const secretServiceFactory = ({
const appCfg = getConfig(); const appCfg = getConfig();
const secretBlindIndexDoc = await secretBlindIndexDAL.findOne({ projectId }); const secretBlindIndexDoc = await secretBlindIndexDAL.findOne({ projectId });
if (!secretBlindIndexDoc) throw new NotFoundError({ message: "Blind index not found", name: "Create secret" }); if (!secretBlindIndexDoc) {
throw new NotFoundError({
message: `Blind index for project with ID '${projectId}' not found`,
name: "CreateSecret"
});
}
const secretBlindIndex = await buildSecretBlindIndexFromName({ const secretBlindIndex = await buildSecretBlindIndexFromName({
secretName, secretName,
@ -164,7 +169,7 @@ export const secretServiceFactory = ({
ciphertext: secretBlindIndexDoc.encryptedSaltCipherText, ciphertext: secretBlindIndexDoc.encryptedSaltCipherText,
iv: secretBlindIndexDoc.saltIV iv: secretBlindIndexDoc.saltIV
}); });
if (!secretBlindIndex) throw new NotFoundError({ message: "Secret not found" }); if (!secretBlindIndex) throw new NotFoundError({ message: `Secret with name '${secretName}' not found` });
return secretBlindIndex; return secretBlindIndex;
}; };
@ -195,13 +200,18 @@ export const secretServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "CreateSecret"
}); });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) throw new NotFoundError({ message: "Blind index not found", name: "CreateSecret" }); if (!blindIndexCfg) {
throw new NotFoundError({
message: `Blind index for project with ID '${projectId}' not found`,
name: "CreateSecret"
});
}
if (ActorType.USER !== actor && inputSecret.type === SecretType.Personal) { if (ActorType.USER !== actor && inputSecret.type === SecretType.Personal) {
throw new BadRequestError({ message: "Must be user to create personal secret" }); throw new BadRequestError({ message: "Must be user to create personal secret" });
@ -232,7 +242,8 @@ export const secretServiceFactory = ({
// validate tags // validate tags
// fetch all tags and if not same count throw error meaning one was invalid tags // fetch all tags and if not same count throw error meaning one was invalid tags
const tags = inputSecret.tags ? await secretTagDAL.findManyTagsById(projectId, inputSecret.tags) : []; const tags = inputSecret.tags ? await secretTagDAL.findManyTagsById(projectId, inputSecret.tags) : [];
if ((inputSecret.tags || []).length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if ((inputSecret.tags || []).length !== tags.length)
throw new NotFoundError({ message: "One or more tags not found" });
const { secretName, type, ...el } = inputSecret; const { secretName, type, ...el } = inputSecret;
const references = await getSecretReference(projectId); const references = await getSecretReference(projectId);
@ -308,13 +319,17 @@ export const secretServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "CreateSecret"
}); });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) throw new NotFoundError({ message: "Blind index not found", name: "CreateSecret" }); if (!blindIndexCfg)
throw new NotFoundError({
message: `Blind index for project with ID '${projectId}' not found`,
name: "CreateSecret"
});
if (ActorType.USER !== actor && inputSecret.type === SecretType.Personal) { if (ActorType.USER !== actor && inputSecret.type === SecretType.Personal) {
throw new BadRequestError({ message: "Must be user to create personal secret" }); throw new BadRequestError({ message: "Must be user to create personal secret" });
@ -354,7 +369,8 @@ export const secretServiceFactory = ({
}); });
const tags = inputSecret.tags ? await secretTagDAL.findManyTagsById(projectId, inputSecret.tags) : []; const tags = inputSecret.tags ? await secretTagDAL.findManyTagsById(projectId, inputSecret.tags) : [];
if ((inputSecret.tags || []).length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if ((inputSecret.tags || []).length !== tags.length)
throw new NotFoundError({ message: "One or more tags not found" });
const { secretName, ...el } = inputSecret; const { secretName, ...el } = inputSecret;
@ -441,13 +457,17 @@ export const secretServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "DeleteSecret"
}); });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) throw new NotFoundError({ message: "Blind index not found", name: "CreateSecret" }); if (!blindIndexCfg)
throw new NotFoundError({
message: `Blind index for project with ID '${projectId}' not found`,
name: "DeleteSecret"
});
if (ActorType.USER !== actor && inputSecret.type === SecretType.Personal) { if (ActorType.USER !== actor && inputSecret.type === SecretType.Personal) {
throw new BadRequestError({ message: "Must be user to create personal secret" }); throw new BadRequestError({ message: "Must be user to create personal secret" });
@ -624,8 +644,8 @@ export const secretServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "GetSecretByName"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -694,7 +714,7 @@ export const secretServiceFactory = ({
} }
} }
} }
if (!secret) throw new NotFoundError({ message: "Secret not found" }); if (!secret) throw new NotFoundError({ message: `Secret with name '${secretName}' not found` });
return { ...secret, workspace: projectId, environment, secretPath: path }; return { ...secret, workspace: projectId, environment, secretPath: path };
}; };
@ -726,8 +746,8 @@ export const secretServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "CreateManySecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -745,7 +765,7 @@ export const secretServiceFactory = ({
// get all tags // get all tags
const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags); const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags);
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tags.length !== tagIds.length) throw new NotFoundError({ message: "Tag not found" }); if (tags.length !== tagIds.length) throw new NotFoundError({ message: "One or more tags not found" });
const references = await getSecretReference(projectId); const references = await getSecretReference(projectId);
const newSecrets = await secretDAL.transaction(async (tx) => const newSecrets = await secretDAL.transaction(async (tx) =>
@ -811,8 +831,8 @@ export const secretServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Update secret" name: "UpdateManySecret"
}); });
const folderId = folder.id; const folderId = folder.id;
@ -841,7 +861,7 @@ export const secretServiceFactory = ({
// get all tags // get all tags
const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags); const tagIds = inputSecrets.flatMap(({ tags = [] }) => tags);
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : []; const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
if (tagIds.length !== tags.length) throw new NotFoundError({ message: "Tag not found" }); if (tagIds.length !== tags.length) throw new NotFoundError({ message: "One or more tags not found" });
const references = await getSecretReference(projectId); const references = await getSecretReference(projectId);
const secrets = await secretDAL.transaction(async (tx) => const secrets = await secretDAL.transaction(async (tx) =>
@ -917,13 +937,17 @@ export const secretServiceFactory = ({
const folder = await folderDAL.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) if (!folder)
throw new NotFoundError({ throw new NotFoundError({
message: "Folder not found for the given environment slug & secret path", message: `Folder with path '${path}' in environment with slug '${environment}' not found`,
name: "Create secret" name: "DeleteManySecret"
}); });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) throw new NotFoundError({ message: "Blind index not found", name: "Update secret" }); if (!blindIndexCfg)
throw new NotFoundError({
message: `Blind index for project with ID '${projectId}' not found`,
name: "DeleteManySecret"
});
const { keyName2BlindIndex } = await fnSecretBlindIndexCheck({ const { keyName2BlindIndex } = await fnSecretBlindIndexCheck({
inputSecrets, inputSecrets,
@ -1110,7 +1134,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
@ -1274,7 +1298,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
const decryptedSecret = decryptSecretRaw(encryptedSecret, botKey); const decryptedSecret = decryptSecretRaw(encryptedSecret, botKey);
@ -1370,7 +1394,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secretName, botKey); const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secretName, botKey);
@ -1512,7 +1536,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
@ -1638,7 +1662,7 @@ export const secretServiceFactory = ({
} }
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
if (policy) { if (policy) {
@ -1694,7 +1718,7 @@ export const secretServiceFactory = ({
// pick either project slug or projectid // pick either project slug or projectid
if (!optionalProjectId && projectSlug) { if (!optionalProjectId && projectSlug) {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
projectId = project.id; projectId = project.id;
} }
@ -1742,7 +1766,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
const sanitizedSecrets = inputSecrets.map( const sanitizedSecrets = inputSecrets.map(
@ -1821,7 +1845,7 @@ export const secretServiceFactory = ({
let projectId = optionalProjectId as string; let projectId = optionalProjectId as string;
if (!optionalProjectId && projectSlug) { if (!optionalProjectId && projectSlug) {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
projectId = project.id; projectId = project.id;
} }
@ -1868,7 +1892,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
const sanitizedSecrets = inputSecrets.map( const sanitizedSecrets = inputSecrets.map(
@ -1959,7 +1983,7 @@ export const secretServiceFactory = ({
let projectId = optionalProjectId as string; let projectId = optionalProjectId as string;
if (!optionalProjectId && projectSlug) { if (!optionalProjectId && projectSlug) {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: "Project not found" }); if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
projectId = project.id; projectId = project.id;
} }
@ -2000,7 +2024,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
@ -2066,12 +2090,13 @@ export const secretServiceFactory = ({
if (secretVersionV2) return secretVersionV2; if (secretVersionV2) return secretVersionV2;
const secret = await secretDAL.findById(secretId); const secret = await secretDAL.findById(secretId);
if (!secret) throw new NotFoundError({ message: "Failed to find secret" }); if (!secret) throw new NotFoundError({ message: `Secret with ID '${secretId}' not found` });
const folder = await folderDAL.findById(secret.folderId); const folder = await folderDAL.findById(secret.folderId);
if (!folder) throw new NotFoundError({ message: "Failed to find secret" }); if (!folder) throw new NotFoundError({ message: `Folder with ID '${secret.folderId}' not found` });
const { botKey } = await projectBotService.getBotKey(folder.projectId); const { botKey } = await projectBotService.getBotKey(folder.projectId);
if (!botKey) throw new NotFoundError({ message: "Project bot not found" }); if (!botKey)
throw new NotFoundError({ message: `Project bot for project with ID '${folder.projectId}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -2136,12 +2161,14 @@ export const secretServiceFactory = ({
}); });
if (!secret) { if (!secret) {
throw new NotFoundError({ message: "Secret not found" }); throw new NotFoundError({ message: `Secret with name '${secretName}' not found` });
} }
const folder = await folderDAL.findBySecretPath(project.id, environment, secretPath); const folder = await folderDAL.findBySecretPath(project.id, environment, secretPath);
if (!folder) { if (!folder) {
throw new NotFoundError({ message: "Folder not found" }); throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
} }
const tags = await secretTagDAL.find({ const tags = await secretTagDAL.find({
@ -2238,12 +2265,14 @@ export const secretServiceFactory = ({
}); });
if (!secret) { if (!secret) {
throw new NotFoundError({ message: "Secret not found" }); throw new NotFoundError({ message: `Secret with name '${secretName}' not found` });
} }
const folder = await folderDAL.findBySecretPath(project.id, environment, secretPath); const folder = await folderDAL.findBySecretPath(project.id, environment, secretPath);
if (!folder) { if (!folder) {
throw new NotFoundError({ message: "Folder not found" }); throw new NotFoundError({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
} }
const tags = await secretTagDAL.find({ const tags = await secretTagDAL.find({
@ -2337,7 +2366,7 @@ export const secretServiceFactory = ({
if (!botKey) if (!botKey)
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${projectId}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
@ -2378,7 +2407,7 @@ export const secretServiceFactory = ({
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId); const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) { if (!project) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project not found." message: `Project with slug '${projectSlug}' not found`
}); });
} }
if (project.version === 3) { if (project.version === 3) {
@ -2423,7 +2452,7 @@ export const secretServiceFactory = ({
const { botKey } = await projectBotService.getBotKey(project.id); const { botKey } = await projectBotService.getBotKey(project.id);
if (!botKey) { if (!botKey) {
throw new NotFoundError({ throw new NotFoundError({
message: "Project bot not found. Please upgrade your project.", message: `Project bot for project with ID '${project.id}' not found. Please upgrade your project.`,
name: "bot_not_found_error" name: "bot_not_found_error"
}); });
} }
@ -2431,7 +2460,7 @@ export const secretServiceFactory = ({
const sourceFolder = await folderDAL.findBySecretPath(project.id, sourceEnvironment, sourceSecretPath); const sourceFolder = await folderDAL.findBySecretPath(project.id, sourceEnvironment, sourceSecretPath);
if (!sourceFolder) { if (!sourceFolder) {
throw new NotFoundError({ throw new NotFoundError({
message: "Source path does not exist." message: `Source folder with path '${sourceSecretPath}' in environment with slug '${sourceEnvironment}' not found`
}); });
} }
@ -2443,7 +2472,7 @@ export const secretServiceFactory = ({
if (!destinationFolder) { if (!destinationFolder) {
throw new NotFoundError({ throw new NotFoundError({
message: "Destination path does not exist." message: `Destination folder with path '${destinationSecretPath}' in environment with slug '${destinationEnvironment}' not found`
}); });
} }

View File

@ -72,7 +72,7 @@ export const secretVersionDALFactory = (db: TDbClient) => {
); );
if (existingSecretVersions.length !== data.length) { if (existingSecretVersions.length !== data.length) {
throw new NotFoundError({ message: "Some of the secret versions do not exist" }); throw new NotFoundError({ message: "One or more secret versions not found" });
} }
if (data.length === 0) return []; if (data.length === 0) return [];

View File

@ -75,7 +75,8 @@ export const serviceTokenServiceFactory = ({
// validates env // validates env
const scopeEnvs = [...new Set(scopes.map(({ environment }) => environment))]; const scopeEnvs = [...new Set(scopes.map(({ environment }) => environment))];
const inputEnvs = await projectEnvDAL.findBySlugs(projectId, scopeEnvs); const inputEnvs = await projectEnvDAL.findBySlugs(projectId, scopeEnvs);
if (inputEnvs.length !== scopeEnvs.length) throw new NotFoundError({ message: "Environment not found" }); if (inputEnvs.length !== scopeEnvs.length)
throw new NotFoundError({ message: `One or more selected environments not found` });
const secret = crypto.randomBytes(16).toString("hex"); const secret = crypto.randomBytes(16).toString("hex");
const secretHash = await bcrypt.hash(secret, appCfg.SALT_ROUNDS); const secretHash = await bcrypt.hash(secret, appCfg.SALT_ROUNDS);
@ -106,7 +107,7 @@ export const serviceTokenServiceFactory = ({
const deleteServiceToken = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TDeleteServiceTokenDTO) => { const deleteServiceToken = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TDeleteServiceTokenDTO) => {
const serviceToken = await serviceTokenDAL.findById(id); const serviceToken = await serviceTokenDAL.findById(id);
if (!serviceToken) throw new NotFoundError({ message: "Token not found" }); if (!serviceToken) throw new NotFoundError({ message: `Service token with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -122,13 +123,15 @@ export const serviceTokenServiceFactory = ({
}; };
const getServiceToken = async ({ actor, actorId }: TGetServiceTokenInfoDTO) => { const getServiceToken = async ({ actor, actorId }: TGetServiceTokenInfoDTO) => {
if (actor !== ActorType.SERVICE) throw new NotFoundError({ message: "Service token not found" }); if (actor !== ActorType.SERVICE)
throw new NotFoundError({ message: `Service token with ID '${actorId}' not found` });
const serviceToken = await serviceTokenDAL.findById(actorId); const serviceToken = await serviceTokenDAL.findById(actorId);
if (!serviceToken) throw new NotFoundError({ message: "Token not found" }); if (!serviceToken) throw new NotFoundError({ message: `Service token with ID '${actorId}' not found` });
const serviceTokenUser = await userDAL.findById(serviceToken.createdBy); const serviceTokenUser = await userDAL.findById(serviceToken.createdBy);
if (!serviceTokenUser) throw new NotFoundError({ message: "Service token user not found" }); if (!serviceTokenUser)
throw new NotFoundError({ message: `Service token with ID ${serviceToken.id} has no associated creator` });
return { serviceToken, user: serviceTokenUser }; return { serviceToken, user: serviceTokenUser };
}; };
@ -157,10 +160,10 @@ export const serviceTokenServiceFactory = ({
const [, tokenIdentifier, tokenSecret] = <[string, string, string]>token.split(".", 3); const [, tokenIdentifier, tokenSecret] = <[string, string, string]>token.split(".", 3);
const serviceToken = await serviceTokenDAL.findById(tokenIdentifier); const serviceToken = await serviceTokenDAL.findById(tokenIdentifier);
if (!serviceToken) throw new NotFoundError({ message: "Service token not found" }); if (!serviceToken) throw new NotFoundError({ message: `Service token with ID '${tokenIdentifier}' not found` });
const project = await projectDAL.findById(serviceToken.projectId); const project = await projectDAL.findById(serviceToken.projectId);
if (!project) throw new NotFoundError({ message: "Service token project not found" }); if (!project) throw new NotFoundError({ message: `Project with ID '${serviceToken.projectId}' not found` });
if (serviceToken.expiresAt && new Date(serviceToken.expiresAt) < new Date()) { if (serviceToken.expiresAt && new Date(serviceToken.expiresAt) < new Date()) {
await serviceTokenDAL.deleteById(serviceToken.id); await serviceTokenDAL.deleteById(serviceToken.id);

View File

@ -110,7 +110,7 @@ export const slackServiceFactory = ({
if (!slackIntegration) { if (!slackIntegration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Slack integration not found" message: `Slack integration with ID ${id} not found`
}); });
} }
@ -260,7 +260,7 @@ export const slackServiceFactory = ({
if (!slackIntegration) { if (!slackIntegration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Slack integration not found" message: `Slack integration with ID ${id} not found`
}); });
} }
@ -347,7 +347,7 @@ export const slackServiceFactory = ({
const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id); const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id);
if (!slackIntegration) { if (!slackIntegration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Slack integration not found." message: `Slack integration with ID ${id} not found`
}); });
} }
@ -385,7 +385,7 @@ export const slackServiceFactory = ({
const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id); const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id);
if (!slackIntegration) { if (!slackIntegration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Slack integration not found" message: `Slack integration with ID ${id} not found`
}); });
} }
@ -428,7 +428,7 @@ export const slackServiceFactory = ({
const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id); const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id);
if (!slackIntegration) { if (!slackIntegration) {
throw new NotFoundError({ throw new NotFoundError({
message: "Slack integration not found" message: `Slack integration with ID ${id} not found`
}); });
} }

View File

@ -260,7 +260,7 @@ export const superAdminServiceFactory = ({
const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID); const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);
if (!serverCfg) { if (!serverCfg) {
throw new NotFoundError({ name: "Admin config", message: "Admin config not found" }); throw new NotFoundError({ name: "AdminConfig", message: "Admin config not found" });
} }
let clientId = ""; let clientId = "";

View File

@ -55,7 +55,7 @@ export const userServiceFactory = ({
}: TUserServiceFactoryDep) => { }: TUserServiceFactoryDep) => {
const sendEmailVerificationCode = async (username: string) => { const sendEmailVerificationCode = async (username: string) => {
const user = await userDAL.findOne({ username }); const user = await userDAL.findOne({ username });
if (!user) throw new NotFoundError({ name: "Failed to find user" }); if (!user) throw new NotFoundError({ name: `User with username '${username}' not found` });
if (!user.email) if (!user.email)
throw new BadRequestError({ name: "Failed to send email verification code due to no email on user" }); throw new BadRequestError({ name: "Failed to send email verification code due to no email on user" });
if (user.isEmailVerified) if (user.isEmailVerified)
@ -78,7 +78,7 @@ export const userServiceFactory = ({
const verifyEmailVerificationCode = async (username: string, code: string) => { const verifyEmailVerificationCode = async (username: string, code: string) => {
const user = await userDAL.findOne({ username }); const user = await userDAL.findOne({ username });
if (!user) throw new NotFoundError({ name: "Failed to find user" }); if (!user) throw new NotFoundError({ name: `User with username '${username}' not found` });
if (!user.email) if (!user.email)
throw new BadRequestError({ name: "Failed to verify email verification code due to no email on user" }); throw new BadRequestError({ name: "Failed to verify email verification code due to no email on user" });
if (user.isEmailVerified) if (user.isEmailVerified)
@ -193,10 +193,10 @@ export const userServiceFactory = ({
const updateAuthMethods = async (userId: string, authMethods: AuthMethod[]) => { const updateAuthMethods = async (userId: string, authMethods: AuthMethod[]) => {
const user = await userDAL.findById(userId); const user = await userDAL.findById(userId);
if (!user) throw new NotFoundError({ message: "User not found" }); if (!user) throw new NotFoundError({ message: `User with ID '${userId}' not found`, name: "UpdateAuthMethods" });
if (user.authMethods?.includes(AuthMethod.LDAP) || authMethods.includes(AuthMethod.LDAP)) { if (user.authMethods?.includes(AuthMethod.LDAP) || authMethods.includes(AuthMethod.LDAP)) {
throw new BadRequestError({ message: "LDAP auth method cannot be updated", name: "Update auth methods" }); throw new BadRequestError({ message: "LDAP auth method cannot be updated", name: "UpdateAuthMethods" });
} }
const updatedUser = await userDAL.updateById(userId, { authMethods }); const updatedUser = await userDAL.updateById(userId, { authMethods });
@ -205,7 +205,7 @@ export const userServiceFactory = ({
const getMe = async (userId: string) => { const getMe = async (userId: string) => {
const user = await userDAL.findUserEncKeyByUserId(userId); const user = await userDAL.findUserEncKeyByUserId(userId);
if (!user) throw new NotFoundError({ message: "User not found" }); if (!user) throw new NotFoundError({ message: `User with ID '${userId}' not found`, name: "GetMe" });
return user; return user;
}; };
@ -246,7 +246,7 @@ export const userServiceFactory = ({
const getUserPrivateKey = async (userId: string) => { const getUserPrivateKey = async (userId: string) => {
const user = await userDAL.findUserEncKeyByUserId(userId); const user = await userDAL.findUserEncKeyByUserId(userId);
if (!user?.serverEncryptedPrivateKey || !user.serverEncryptedPrivateKeyIV || !user.serverEncryptedPrivateKeyTag) { if (!user?.serverEncryptedPrivateKey || !user.serverEncryptedPrivateKeyIV || !user.serverEncryptedPrivateKeyTag) {
throw new NotFoundError({ message: "Private key not found. Please login again" }); throw new NotFoundError({ message: `Private key for user with ID '${userId}' not found` });
} }
const privateKey = infisicalSymmetricDecrypt({ const privateKey = infisicalSymmetricDecrypt({
ciphertext: user.serverEncryptedPrivateKey, ciphertext: user.serverEncryptedPrivateKey,

View File

@ -172,7 +172,11 @@ export const fnTriggerWebhook = async ({
await webhookDAL.transaction(async (tx) => { await webhookDAL.transaction(async (tx) => {
const env = await projectEnvDAL.findOne({ projectId, slug: environment }, tx); const env = await projectEnvDAL.findOne({ projectId, slug: environment }, tx);
if (!env) throw new NotFoundError({ message: "Environment not found" }); if (!env) {
throw new NotFoundError({
message: `Environment with slug '${environment}' in project with ID '${projectId}' not found`
});
}
if (successWebhooks.length) { if (successWebhooks.length) {
await webhookDAL.update( await webhookDAL.update(
{ envId: env.id, $in: { id: successWebhooks } }, { envId: env.id, $in: { id: successWebhooks } },

View File

@ -54,7 +54,10 @@ export const webhookServiceFactory = ({
); );
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Webhooks); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Webhooks);
const env = await projectEnvDAL.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) throw new NotFoundError({ message: "Environment not found" }); if (!env)
throw new NotFoundError({
message: `Environment with slug '${environment}' in project with ID '${projectId}' not found`
});
const insertDoc: TWebhooksInsert = { const insertDoc: TWebhooksInsert = {
url: "", // deprecated - we are moving away from plaintext URLs url: "", // deprecated - we are moving away from plaintext URLs
@ -88,7 +91,7 @@ export const webhookServiceFactory = ({
const updateWebhook = async ({ actorId, actor, actorOrgId, actorAuthMethod, id, isDisabled }: TUpdateWebhookDTO) => { const updateWebhook = async ({ actorId, actor, actorOrgId, actorAuthMethod, id, isDisabled }: TUpdateWebhookDTO) => {
const webhook = await webhookDAL.findById(id); const webhook = await webhookDAL.findById(id);
if (!webhook) throw new NotFoundError({ message: "Webhook not found" }); if (!webhook) throw new NotFoundError({ message: `Webhook with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -105,7 +108,7 @@ export const webhookServiceFactory = ({
const deleteWebhook = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TDeleteWebhookDTO) => { const deleteWebhook = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TDeleteWebhookDTO) => {
const webhook = await webhookDAL.findById(id); const webhook = await webhookDAL.findById(id);
if (!webhook) throw new NotFoundError({ message: "Webhook not found" }); if (!webhook) throw new NotFoundError({ message: `Webhook with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@ -122,7 +125,7 @@ export const webhookServiceFactory = ({
const testWebhook = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TTestWebhookDTO) => { const testWebhook = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TTestWebhookDTO) => {
const webhook = await webhookDAL.findById(id); const webhook = await webhookDAL.findById(id);
if (!webhook) throw new NotFoundError({ message: "Webhook not found" }); if (!webhook) throw new NotFoundError({ message: `Webhook with ID '${id}' not found` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,

View File

@ -137,6 +137,7 @@ type GetOrganizationsResponse struct {
type SelectOrganizationResponse struct { type SelectOrganizationResponse struct {
Token string `json:"token"` Token string `json:"token"`
MfaEnabled bool `json:"isMfaEnabled"`
} }
type SelectOrganizationRequest struct { type SelectOrganizationRequest struct {

View File

@ -5,6 +5,7 @@ package cmd
import ( import (
"encoding/json" "encoding/json"
"fmt"
"github.com/Infisical/infisical-merge/packages/api" "github.com/Infisical/infisical-merge/packages/api"
"github.com/Infisical/infisical-merge/packages/models" "github.com/Infisical/infisical-merge/packages/models"
@ -75,6 +76,42 @@ var initCmd = &cobra.Command{
selectedOrganization := organizations[index] selectedOrganization := organizations[index]
tokenResponse, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID}) tokenResponse, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
if tokenResponse.MfaEnabled {
i := 1
for i < 6 {
mfaVerifyCode := askForMFACode()
httpClient := resty.New()
httpClient.SetAuthToken(tokenResponse.Token)
verifyMFAresponse, mfaErrorResponse, requestError := api.CallVerifyMfaToken(httpClient, api.VerifyMfaTokenRequest{
Email: userCreds.UserCredentials.Email,
MFAToken: mfaVerifyCode,
})
if requestError != nil {
util.HandleError(err)
break
} else if mfaErrorResponse != nil {
if mfaErrorResponse.Context.Code == "mfa_invalid" {
msg := fmt.Sprintf("Incorrect, verification code. You have %v attempts left", 5-i)
fmt.Println(msg)
if i == 5 {
util.PrintErrorMessageAndExit("No tries left, please try again in a bit")
break
}
}
if mfaErrorResponse.Context.Code == "mfa_expired" {
util.PrintErrorMessageAndExit("Your 2FA verification code has expired, please try logging in again")
break
}
i++
} else {
httpClient.SetAuthToken(verifyMFAresponse.Token)
tokenResponse, err = api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
break
}
}
}
if err != nil { if err != nil {
util.HandleError(err, "Unable to select organization") util.HandleError(err, "Unable to select organization")

View File

@ -479,7 +479,7 @@ func cliDefaultLogin(userCredentialsToBeStored *models.UserCredentials) {
util.PrintErrorMessageAndExit("We were unable to fetch required details to complete your login. Run with -d to see more info") util.PrintErrorMessageAndExit("We were unable to fetch required details to complete your login. Run with -d to see more info")
} }
// Login is successful so ask user to choose organization // Login is successful so ask user to choose organization
newJwtToken := GetJwtTokenWithOrganizationId(loginTwoResponse.Token) newJwtToken := GetJwtTokenWithOrganizationId(loginTwoResponse.Token, email)
//updating usercredentials //updating usercredentials
userCredentialsToBeStored.Email = email userCredentialsToBeStored.Email = email
@ -718,7 +718,7 @@ func getFreshUserCredentials(email string, password string) (*api.GetLoginOneV2R
return &loginOneResponseResult, &loginTwoResponseResult, nil return &loginOneResponseResult, &loginTwoResponseResult, nil
} }
func GetJwtTokenWithOrganizationId(oldJwtToken string) string { func GetJwtTokenWithOrganizationId(oldJwtToken string, email string) string {
log.Debug().Msg(fmt.Sprint("GetJwtTokenWithOrganizationId: ", "oldJwtToken", oldJwtToken)) log.Debug().Msg(fmt.Sprint("GetJwtTokenWithOrganizationId: ", "oldJwtToken", oldJwtToken))
httpClient := resty.New() httpClient := resty.New()
@ -747,11 +747,51 @@ func GetJwtTokenWithOrganizationId(oldJwtToken string) string {
selectedOrganization := organizations[index] selectedOrganization := organizations[index]
selectedOrgRes, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID}) selectedOrgRes, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
if err != nil { if err != nil {
util.HandleError(err) util.HandleError(err)
} }
if selectedOrgRes.MfaEnabled {
i := 1
for i < 6 {
mfaVerifyCode := askForMFACode()
httpClient := resty.New()
httpClient.SetAuthToken(selectedOrgRes.Token)
verifyMFAresponse, mfaErrorResponse, requestError := api.CallVerifyMfaToken(httpClient, api.VerifyMfaTokenRequest{
Email: email,
MFAToken: mfaVerifyCode,
})
if requestError != nil {
util.HandleError(err)
break
} else if mfaErrorResponse != nil {
if mfaErrorResponse.Context.Code == "mfa_invalid" {
msg := fmt.Sprintf("Incorrect, verification code. You have %v attempts left", 5-i)
fmt.Println(msg)
if i == 5 {
util.PrintErrorMessageAndExit("No tries left, please try again in a bit")
break
}
}
if mfaErrorResponse.Context.Code == "mfa_expired" {
util.PrintErrorMessageAndExit("Your 2FA verification code has expired, please try logging in again")
break
}
i++
} else {
httpClient.SetAuthToken(verifyMFAresponse.Token)
selectedOrgRes, err = api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
break
}
}
}
if err != nil {
util.HandleError(err, "Unable to select organization")
}
return selectedOrgRes.Token return selectedOrgRes.Token
} }

View File

@ -1,4 +1,4 @@
error: CallGetRawSecretsV3: Unsuccessful response [GET https://app.infisical.com/api/v3/secrets/raw?environment=invalid-env&include_imports=true&recursive=true&secretPath=%2F&workspaceId=bef697d4-849b-4a75-b284-0922f87f8ba2] [status-code=500] [response={"statusCode":500,"error":"Internal Server Error","message":"'invalid-env' environment not found in project with ID bef697d4-849b-4a75-b284-0922f87f8ba2"}] error: CallGetRawSecretsV3: Unsuccessful response [GET https://app.infisical.com/api/v3/secrets/raw?environment=invalid-env&expandSecretReferences=true&include_imports=true&recursive=true&secretPath=%2F&workspaceId=bef697d4-849b-4a75-b284-0922f87f8ba2] [status-code=404] [response={"statusCode":404,"message":"'invalid-env' environment not found in project with ID bef697d4-849b-4a75-b284-0922f87f8ba2","error":"NotFound"}]
If this issue continues, get support at https://infisical.com/slack If this issue continues, get support at https://infisical.com/slack

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 511 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 379 KiB

After

Width:  |  Height:  |  Size: 706 KiB

View File

@ -29,8 +29,15 @@ description: "How to sync secrets from Infisical to Azure Key Vault"
![integrations](../../images/integrations/azure-key-vault/integrations-azure-key-vault.png) ![integrations](../../images/integrations/azure-key-vault/integrations-azure-key-vault.png)
<Note>
The Azure Key Vault integration requires the following secrets permissions to be set on the user / service principal
for Infisical to sync secrets to Azure Key Vault: `secrets/list`, `secrets/get`, `secrets/set`, `secrets/recover`.
Any role with these permissions would work such as the **Key Vault Secrets Officer** role.
</Note>
</Step> </Step>
</Steps> </Steps>
</Tab> </Tab>
<Tab title="Self-Hosted Setup"> <Tab title="Self-Hosted Setup">
Using the Azure KV integration on a self-hosted instance of Infisical requires configuring an application in Azure Using the Azure KV integration on a self-hosted instance of Infisical requires configuring an application in Azure
@ -65,6 +72,6 @@ description: "How to sync secrets from Infisical to Azure Key Vault"
Once added, restart your Infisical instance and use the Azure KV integration. Once added, restart your Infisical instance and use the Azure KV integration.
</Step> </Step>
</Steps> </Steps>
</Tab> </Tab>
</Tabs> </Tabs>

Some files were not shown because too many files have changed in this diff Show More