feat(infisical-pg): changed all dal to DAL as said by maidul

This commit is contained in:
Akhil Mohan
2024-01-27 12:38:23 +05:30
parent 59c747cf72
commit 6bf9bc1d2c
96 changed files with 1268 additions and 1268 deletions
+2 -2
View File
@@ -39,7 +39,7 @@ import { TSecretImportServiceFactory } from "@app/services/secret-import/secret-
import { TSecretTagServiceFactory } from "@app/services/secret-tag/secret-tag-service"; import { TSecretTagServiceFactory } from "@app/services/secret-tag/secret-tag-service";
import { TServiceTokenServiceFactory } from "@app/services/service-token/service-token-service"; import { TServiceTokenServiceFactory } from "@app/services/service-token/service-token-service";
import { TSuperAdminServiceFactory } from "@app/services/super-admin/super-admin-service"; import { TSuperAdminServiceFactory } from "@app/services/super-admin/super-admin-service";
import { TUserDalFactory } from "@app/services/user/user-dal"; import { TUserDALFactory } from "@app/services/user/user-dal";
import { TUserServiceFactory } from "@app/services/user/user-service"; import { TUserServiceFactory } from "@app/services/user/user-service";
import { TWebhookServiceFactory } from "@app/services/webhook/webhook-service"; import { TWebhookServiceFactory } from "@app/services/webhook/webhook-service";
@@ -109,7 +109,7 @@ declare module "fastify" {
// this is exclusive use for middlewares in which we need to inject data // this is exclusive use for middlewares in which we need to inject data
// everywhere else access using service layer // everywhere else access using service layer
store: { store: {
user: Pick<TUserDalFactory, "findById">; user: Pick<TUserDALFactory, "findById">;
}; };
} }
} }
@@ -4,7 +4,7 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify, stripUndefinedInWhere } from "@app/lib/knex"; import { ormify, stripUndefinedInWhere } from "@app/lib/knex";
export type TAuditLogDalFactory = ReturnType<typeof auditLogDalFactory>; export type TAuditLogDALFactory = ReturnType<typeof auditLogDALFactory>;
type TFindQuery = { type TFindQuery = {
actor?: string; actor?: string;
@@ -18,7 +18,7 @@ type TFindQuery = {
offset?: number; offset?: number;
}; };
export const auditLogDalFactory = (db: TDbClient) => { export const auditLogDALFactory = (db: TDbClient) => {
const auditLogOrm = ormify(db, TableName.AuditLog); const auditLogOrm = ormify(db, TableName.AuditLog);
const find = async ( const find = async (
@@ -1,23 +1,23 @@
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TProjectDalFactory } from "@app/services/project/project-dal"; import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TLicenseServiceFactory } from "../license/license-service"; import { TLicenseServiceFactory } from "../license/license-service";
import { TAuditLogDalFactory } from "./audit-log-dal"; import { TAuditLogDALFactory } from "./audit-log-dal";
import { TCreateAuditLogDTO } from "./audit-log-types"; import { TCreateAuditLogDTO } from "./audit-log-types";
type TAuditLogQueueServiceFactoryDep = { type TAuditLogQueueServiceFactoryDep = {
auditLogDal: TAuditLogDalFactory; auditLogDAL: TAuditLogDALFactory;
queueService: TQueueServiceFactory; queueService: TQueueServiceFactory;
projectDal: Pick<TProjectDalFactory, "findById">; projectDAL: Pick<TProjectDALFactory, "findById">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
}; };
export type TAuditLogQueueServiceFactory = ReturnType<typeof auditLogQueueServiceFactory>; export type TAuditLogQueueServiceFactory = ReturnType<typeof auditLogQueueServiceFactory>;
export const auditLogQueueServiceFactory = ({ export const auditLogQueueServiceFactory = ({
auditLogDal, auditLogDAL,
queueService, queueService,
projectDal, projectDAL,
licenseService licenseService
}: TAuditLogQueueServiceFactoryDep) => { }: TAuditLogQueueServiceFactoryDep) => {
const pushToLog = async (data: TCreateAuditLogDTO) => { const pushToLog = async (data: TCreateAuditLogDTO) => {
@@ -37,13 +37,13 @@ export const auditLogQueueServiceFactory = ({
if (!orgId) { if (!orgId) {
// it will never be undefined for both org and project id // it will never be undefined for both org and project id
// TODO(akhilmhdh): use caching here in dal to avoid db calls // TODO(akhilmhdh): use caching here in dal to avoid db calls
const project = await projectDal.findById(projectId as string); const project = await projectDAL.findById(projectId as string);
orgId = project.orgId; orgId = project.orgId;
} }
const plan = await licenseService.getPlan(orgId); const plan = await licenseService.getPlan(orgId);
const ttl = plan.auditLogsRetentionDays * MS_IN_DAY; const ttl = plan.auditLogsRetentionDays * MS_IN_DAY;
await auditLogDal.create({ await auditLogDAL.create({
actor: actor.type, actor: actor.type,
actorMetadata: actor.metadata, actorMetadata: actor.metadata,
userAgent, userAgent,
@@ -4,12 +4,12 @@ import { BadRequestError } from "@app/lib/errors";
import { TPermissionServiceFactory } from "../permission/permission-service"; import { TPermissionServiceFactory } from "../permission/permission-service";
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission"; import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
import { TAuditLogDalFactory } from "./audit-log-dal"; import { TAuditLogDALFactory } from "./audit-log-dal";
import { TAuditLogQueueServiceFactory } from "./audit-log-queue"; import { TAuditLogQueueServiceFactory } from "./audit-log-queue";
import { EventType, TCreateAuditLogDTO, TListProjectAuditLogDTO } from "./audit-log-types"; import { EventType, TCreateAuditLogDTO, TListProjectAuditLogDTO } from "./audit-log-types";
type TAuditLogServiceFactoryDep = { type TAuditLogServiceFactoryDep = {
auditLogDal: TAuditLogDalFactory; auditLogDAL: TAuditLogDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
auditLogQueue: TAuditLogQueueServiceFactory; auditLogQueue: TAuditLogQueueServiceFactory;
}; };
@@ -17,7 +17,7 @@ type TAuditLogServiceFactoryDep = {
export type TAuditLogServiceFactory = ReturnType<typeof auditLogServiceFactory>; export type TAuditLogServiceFactory = ReturnType<typeof auditLogServiceFactory>;
export const auditLogServiceFactory = ({ export const auditLogServiceFactory = ({
auditLogDal, auditLogDAL,
auditLogQueue, auditLogQueue,
permissionService permissionService
}: TAuditLogServiceFactoryDep) => { }: TAuditLogServiceFactoryDep) => {
@@ -38,7 +38,7 @@ export const auditLogServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
ProjectPermissionSub.AuditLogs ProjectPermissionSub.AuditLogs
); );
const auditLogs = await auditLogDal.find({ const auditLogs = await auditLogDAL.find({
startDate, startDate,
endDate, endDate,
limit, limit,
@@ -4,9 +4,9 @@ import { TDbClient } from "@app/db";
import { OrgMembershipStatus, TableName } from "@app/db/schemas"; import { OrgMembershipStatus, TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
export type TLicenseDalFactory = ReturnType<typeof licenseDalFactory>; export type TLicenseDALFactory = ReturnType<typeof licenseDALFactory>;
export const licenseDalFactory = (db: TDbClient) => { export const licenseDALFactory = (db: TDbClient) => {
const countOfOrgMembers = async (orgId: string | null, tx?: Knex) => { const countOfOrgMembers = async (orgId: string | null, tx?: Knex) => {
try { try {
const doc = await (tx || db)(TableName.OrgMembership) const doc = await (tx || db)(TableName.OrgMembership)
@@ -4,12 +4,12 @@ import NodeCache from "node-cache";
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger"; import { logger } from "@app/lib/logger";
import { TOrgDalFactory } from "@app/services/org/org-dal"; import { TOrgDALFactory } from "@app/services/org/org-dal";
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission"; import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service"; import { TPermissionServiceFactory } from "../permission/permission-service";
import { getDefaultOnPremFeatures, setupLicenceRequestWithStore } from "./licence-fns"; import { getDefaultOnPremFeatures, setupLicenceRequestWithStore } from "./licence-fns";
import { TLicenseDalFactory } from "./license-dal"; import { TLicenseDALFactory } from "./license-dal";
import { import {
InstanceType, InstanceType,
TAddOrgPmtMethodDTO, TAddOrgPmtMethodDTO,
@@ -29,9 +29,9 @@ import {
} from "./license-types"; } from "./license-types";
type TLicenseServiceFactoryDep = { type TLicenseServiceFactoryDep = {
orgDal: Pick<TOrgDalFactory, "findOrgById">; orgDAL: Pick<TOrgDALFactory, "findOrgById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">; permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
licenseDal: TLicenseDalFactory; licenseDAL: TLicenseDALFactory;
}; };
export type TLicenseServiceFactory = ReturnType<typeof licenseServiceFactory>; export type TLicenseServiceFactory = ReturnType<typeof licenseServiceFactory>;
@@ -41,9 +41,9 @@ const LICENSE_SERVER_ON_PREM_LOGIN = "/api/auth/v1/licence-login";
const FEATURE_CACHE_KEY = (orgId: string, projectId?: string) => `${orgId}-${projectId || ""}`; const FEATURE_CACHE_KEY = (orgId: string, projectId?: string) => `${orgId}-${projectId || ""}`;
export const licenseServiceFactory = ({ export const licenseServiceFactory = ({
orgDal, orgDAL,
permissionService, permissionService,
licenseDal licenseDAL
}: TLicenseServiceFactoryDep) => { }: TLicenseServiceFactoryDep) => {
let isValidLicense = false; let isValidLicense = false;
let instanceType = InstanceType.OnPrem; let instanceType = InstanceType.OnPrem;
@@ -101,7 +101,7 @@ export const licenseServiceFactory = ({
const cachedPlan = featureStore.get<TFeatureSet>(FEATURE_CACHE_KEY(orgId, projectId)); const cachedPlan = featureStore.get<TFeatureSet>(FEATURE_CACHE_KEY(orgId, projectId));
if (cachedPlan) return cachedPlan; if (cachedPlan) return cachedPlan;
const org = await orgDal.findOrgById(orgId); const org = await orgDAL.findOrgById(orgId);
if (!org) throw new BadRequestError({ message: "Org not found" }); if (!org) throw new BadRequestError({ message: "Org not found" });
const { const {
data: { currentPlan } data: { currentPlan }
@@ -152,10 +152,10 @@ export const licenseServiceFactory = ({
const updateSubscriptionOrgMemberCount = async (orgId: string) => { const updateSubscriptionOrgMemberCount = async (orgId: string) => {
if (instanceType === InstanceType.Cloud) { if (instanceType === InstanceType.Cloud) {
const org = await orgDal.findOrgById(orgId); const org = await orgDAL.findOrgById(orgId);
if (!org) throw new BadRequestError({ message: "Org not found" }); if (!org) throw new BadRequestError({ message: "Org not found" });
const count = await licenseDal.countOfOrgMembers(orgId); const count = await licenseDAL.countOfOrgMembers(orgId);
if (org?.customerId) { if (org?.customerId) {
await licenseServerCloudApi.request.patch( await licenseServerCloudApi.request.patch(
`/api/license-server/v1/customers/${org.customerId}/cloud-plan`, `/api/license-server/v1/customers/${org.customerId}/cloud-plan`,
@@ -166,7 +166,7 @@ export const licenseServiceFactory = ({
} }
featureStore.del(orgId); featureStore.del(orgId);
} else if (instanceType === InstanceType.EnterpriseOnPrem) { } else if (instanceType === InstanceType.EnterpriseOnPrem) {
const usedSeats = await licenseDal.countOfOrgMembers(null); const usedSeats = await licenseDAL.countOfOrgMembers(null);
await licenseServerOnPremApi.request.patch(`/api/license/v1/license`, { usedSeats }); await licenseServerOnPremApi.request.patch(`/api/license/v1/license`, { usedSeats });
} }
await refreshPlan(orgId); await refreshPlan(orgId);
@@ -211,7 +211,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -235,7 +235,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -255,7 +255,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -274,7 +274,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -300,7 +300,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -323,7 +323,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -351,7 +351,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -376,7 +376,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -396,7 +396,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -417,7 +417,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -441,7 +441,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -461,7 +461,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -483,7 +483,7 @@ export const licenseServiceFactory = ({
OrgPermissionSubjects.Billing OrgPermissionSubjects.Billing
); );
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) { if (!organization) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to find organization" message: "Failed to find organization"
@@ -3,9 +3,9 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { selectAllTableCols } from "@app/lib/knex"; import { selectAllTableCols } from "@app/lib/knex";
export type TPermissionDalFactory = ReturnType<typeof permissionDalFactory>; export type TPermissionDALFactory = ReturnType<typeof permissionDALFactory>;
export const permissionDalFactory = (db: TDbClient) => { export const permissionDALFactory = (db: TDbClient) => {
const getOrgPermission = async (userId: string, orgId: string) => { const getOrgPermission = async (userId: string, orgId: string) => {
try { try {
const membership = await db(TableName.OrgMembership) const membership = await db(TableName.OrgMembership)
@@ -12,9 +12,9 @@ import {
import { conditionsMatcher } from "@app/lib/casl"; import { conditionsMatcher } from "@app/lib/casl";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors"; import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { ActorType } from "@app/services/auth/auth-type"; import { ActorType } from "@app/services/auth/auth-type";
import { TOrgRoleDalFactory } from "@app/services/org/org-role-dal"; import { TOrgRoleDALFactory } from "@app/services/org/org-role-dal";
import { TProjectRoleDalFactory } from "@app/services/project-role/project-role-dal"; import { TProjectRoleDALFactory } from "@app/services/project-role/project-role-dal";
import { TServiceTokenDalFactory } from "@app/services/service-token/service-token-dal"; import { TServiceTokenDALFactory } from "@app/services/service-token/service-token-dal";
import { import {
orgAdminPermissions, orgAdminPermissions,
@@ -22,7 +22,7 @@ import {
orgNoAccessPermissions, orgNoAccessPermissions,
OrgPermissionSet OrgPermissionSet
} from "./org-permission"; } from "./org-permission";
import { TPermissionDalFactory } from "./permission-dal"; import { TPermissionDALFactory } from "./permission-dal";
import { import {
buildServiceTokenProjectPermission, buildServiceTokenProjectPermission,
projectAdminPermissions, projectAdminPermissions,
@@ -33,19 +33,19 @@ import {
} from "./project-permission"; } from "./project-permission";
type TPermissionServiceFactoryDep = { type TPermissionServiceFactoryDep = {
orgRoleDal: Pick<TOrgRoleDalFactory, "findOne">; orgRoleDAL: Pick<TOrgRoleDALFactory, "findOne">;
projectRoleDal: Pick<TProjectRoleDalFactory, "findOne">; projectRoleDAL: Pick<TProjectRoleDALFactory, "findOne">;
serviceTokenDal: Pick<TServiceTokenDalFactory, "findById">; serviceTokenDAL: Pick<TServiceTokenDALFactory, "findById">;
permissionDal: TPermissionDalFactory; permissionDAL: TPermissionDALFactory;
}; };
export type TPermissionServiceFactory = ReturnType<typeof permissionServiceFactory>; export type TPermissionServiceFactory = ReturnType<typeof permissionServiceFactory>;
export const permissionServiceFactory = ({ export const permissionServiceFactory = ({
permissionDal, permissionDAL,
orgRoleDal, orgRoleDAL,
projectRoleDal, projectRoleDAL,
serviceTokenDal serviceTokenDAL
}: TPermissionServiceFactoryDep) => { }: TPermissionServiceFactoryDep) => {
const buildOrgPermission = (role: string, permission?: unknown) => { const buildOrgPermission = (role: string, permission?: unknown) => {
switch (role) { switch (role) {
@@ -100,7 +100,7 @@ export const permissionServiceFactory = ({
* Get user permission in an organization * Get user permission in an organization
* */ * */
const getUserOrgPermission = async (userId: string, orgId: string) => { const getUserOrgPermission = async (userId: string, orgId: string) => {
const membership = await permissionDal.getOrgPermission(userId, orgId); const membership = await permissionDAL.getOrgPermission(userId, orgId);
if (!membership) throw new UnauthorizedError({ name: "User not in org" }); if (!membership) throw new UnauthorizedError({ name: "User not in org" });
if (membership.role === OrgMembershipRole.Custom && !membership.permissions) { if (membership.role === OrgMembershipRole.Custom && !membership.permissions) {
throw new BadRequestError({ name: "Custom permission not found" }); throw new BadRequestError({ name: "Custom permission not found" });
@@ -109,7 +109,7 @@ export const permissionServiceFactory = ({
}; };
const getIdentityOrgPermission = async (identityId: string, orgId: string) => { const getIdentityOrgPermission = async (identityId: string, orgId: string) => {
const membership = await permissionDal.getOrgIdentityPermission(identityId, orgId); const membership = await permissionDAL.getOrgIdentityPermission(identityId, orgId);
if (!membership) throw new UnauthorizedError({ name: "Identity not in org" }); if (!membership) throw new UnauthorizedError({ name: "Identity not in org" });
if (membership.role === OrgMembershipRole.Custom && !membership.permissions) { if (membership.role === OrgMembershipRole.Custom && !membership.permissions) {
throw new BadRequestError({ name: "Custom permission not found" }); throw new BadRequestError({ name: "Custom permission not found" });
@@ -136,7 +136,7 @@ export const permissionServiceFactory = ({
const getOrgPermissionByRole = async (role: string, orgId: string) => { const getOrgPermissionByRole = async (role: string, orgId: string) => {
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 BadRequestError({ message: "Role not found" }); if (!orgRole) throw new BadRequestError({ message: "Role not found" });
return { return {
permission: buildOrgPermission(OrgMembershipRole.Custom, orgRole.permissions), permission: buildOrgPermission(OrgMembershipRole.Custom, orgRole.permissions),
@@ -148,7 +148,7 @@ export const permissionServiceFactory = ({
// user permission for a project in an organization // user permission for a project in an organization
const getUserProjectPermission = async (userId: string, projectId: string) => { const getUserProjectPermission = async (userId: string, projectId: string) => {
const membership = await permissionDal.getProjectPermission(userId, projectId); const membership = await permissionDAL.getProjectPermission(userId, projectId);
if (!membership) throw new UnauthorizedError({ name: "User not in org" }); if (!membership) throw new UnauthorizedError({ name: "User not in org" });
if (membership.role === ProjectMembershipRole.Custom && !membership.permissions) { if (membership.role === ProjectMembershipRole.Custom && !membership.permissions) {
throw new BadRequestError({ name: "Custom permission not found" }); throw new BadRequestError({ name: "Custom permission not found" });
@@ -160,7 +160,7 @@ export const permissionServiceFactory = ({
}; };
const getIdentityProjectPermission = async (identityId: string, projectId: string) => { const getIdentityProjectPermission = async (identityId: string, projectId: string) => {
const membership = await permissionDal.getProjectIdentityPermission(identityId, projectId); const membership = await permissionDAL.getProjectIdentityPermission(identityId, projectId);
if (!membership) throw new UnauthorizedError({ name: "Identity not in org" }); if (!membership) throw new UnauthorizedError({ name: "Identity not in org" });
if (membership.role === ProjectMembershipRole.Custom && !membership.permissions) { if (membership.role === ProjectMembershipRole.Custom && !membership.permissions) {
throw new BadRequestError({ name: "Custom permission not found" }); throw new BadRequestError({ name: "Custom permission not found" });
@@ -172,7 +172,7 @@ export const permissionServiceFactory = ({
}; };
const getServiceTokenProjectPermission = async (serviceTokenId: string, projectId: string) => { const getServiceTokenProjectPermission = async (serviceTokenId: string, projectId: string) => {
const serviceToken = await serviceTokenDal.findById(serviceTokenId); const serviceToken = await serviceTokenDAL.findById(serviceTokenId);
if (serviceToken.projectId !== projectId) if (serviceToken.projectId !== projectId)
throw new UnauthorizedError({ throw new UnauthorizedError({
message: "Failed to find service authorization for given project" message: "Failed to find service authorization for given project"
@@ -218,7 +218,7 @@ export const permissionServiceFactory = ({
role as ProjectMembershipRole role as ProjectMembershipRole
); );
if (isCustomRole) { if (isCustomRole) {
const projectRole = await projectRoleDal.findOne({ slug: role, projectId }); const projectRole = await projectRoleDAL.findOne({ slug: role, projectId });
if (!projectRole) throw new BadRequestError({ message: "Role not found" }); if (!projectRole) throw new BadRequestError({ message: "Role not found" });
return { return {
permission: buildProjectPermission(ProjectMembershipRole.Custom, projectRole.permissions), permission: buildProjectPermission(ProjectMembershipRole.Custom, projectRole.permissions),
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSamlConfigDalFactory = ReturnType<typeof samlConfigDalFactory>; export type TSamlConfigDALFactory = ReturnType<typeof samlConfigDALFactory>;
export const samlConfigDalFactory = (db: TDbClient) => { export const samlConfigDALFactory = (db: TDbClient) => {
const samlCfgOrm = ormify(db, TableName.SamlConfig); const samlCfgOrm = ormify(db, TableName.SamlConfig);
return samlCfgOrm; return samlCfgOrm;
}; };
@@ -16,14 +16,14 @@ import {
} from "@app/lib/crypto/encryption"; } from "@app/lib/crypto/encryption";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { AuthTokenType } from "@app/services/auth/auth-type"; import { AuthTokenType } from "@app/services/auth/auth-type";
import { TOrgBotDalFactory } from "@app/services/org/org-bot-dal"; import { TOrgBotDALFactory } from "@app/services/org/org-bot-dal";
import { TOrgDalFactory } from "@app/services/org/org-dal"; import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TUserDalFactory } from "@app/services/user/user-dal"; import { TUserDALFactory } from "@app/services/user/user-dal";
import { TLicenseServiceFactory } from "../license/license-service"; import { TLicenseServiceFactory } from "../license/license-service";
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission"; import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service"; import { TPermissionServiceFactory } from "../permission/permission-service";
import { TSamlConfigDalFactory } from "./saml-config-dal"; import { TSamlConfigDALFactory } from "./saml-config-dal";
import { import {
SamlProviders, SamlProviders,
TCreateSamlCfgDTO, TCreateSamlCfgDTO,
@@ -33,13 +33,13 @@ import {
} from "./saml-config-types"; } from "./saml-config-types";
type TSamlConfigServiceFactoryDep = { type TSamlConfigServiceFactoryDep = {
samlConfigDal: TSamlConfigDalFactory; samlConfigDAL: TSamlConfigDALFactory;
userDal: Pick<TUserDalFactory, "create" | "findUserByEmail" | "transaction" | "updateById">; userDAL: Pick<TUserDALFactory, "create" | "findUserByEmail" | "transaction" | "updateById">;
orgDal: Pick< orgDAL: Pick<
TOrgDalFactory, TOrgDALFactory,
"createMembership" | "updateMembershipById" | "findMembership" | "findOrgById" "createMembership" | "updateMembershipById" | "findMembership" | "findOrgById"
>; >;
orgBotDal: Pick<TOrgBotDalFactory, "findOne">; orgBotDAL: Pick<TOrgBotDALFactory, "findOne">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">; permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
}; };
@@ -47,10 +47,10 @@ type TSamlConfigServiceFactoryDep = {
export type TSamlConfigServiceFactory = ReturnType<typeof samlConfigServiceFactory>; export type TSamlConfigServiceFactory = ReturnType<typeof samlConfigServiceFactory>;
export const samlConfigServiceFactory = ({ export const samlConfigServiceFactory = ({
samlConfigDal, samlConfigDAL,
orgBotDal, orgBotDAL,
orgDal, orgDAL,
userDal, userDAL,
permissionService, permissionService,
licenseService licenseService
}: TSamlConfigServiceFactoryDep) => { }: TSamlConfigServiceFactoryDep) => {
@@ -77,7 +77,7 @@ export const samlConfigServiceFactory = ({
"Failed to update SAML SSO configuration due to plan restriction. Upgrade plan to update SSO configuration." "Failed to update SAML SSO configuration due to plan restriction. Upgrade plan to update SSO configuration."
}); });
const orgBot = await orgBotDal.findOne({ orgId }); const orgBot = await orgBotDAL.findOne({ orgId });
if (!orgBot) if (!orgBot)
throw new BadRequestError({ message: "Org bot not found", name: "OrgBotNotFound" }); throw new BadRequestError({ message: "Org bot not found", name: "OrgBotNotFound" });
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
@@ -99,7 +99,7 @@ export const samlConfigServiceFactory = ({
} = encryptSymmetric(issuer, key); } = encryptSymmetric(issuer, key);
const { ciphertext: encryptedCert, iv: certIV, tag: certTag } = encryptSymmetric(cert, key); const { ciphertext: encryptedCert, iv: certIV, tag: certTag } = encryptSymmetric(cert, key);
const samlConfig = await samlConfigDal.create({ const samlConfig = await samlConfigDAL.create({
orgId, orgId,
authProvider, authProvider,
isActive, isActive,
@@ -139,7 +139,7 @@ export const samlConfigServiceFactory = ({
}); });
const updateQuery: TSamlConfigsUpdate = { authProvider, isActive }; const updateQuery: TSamlConfigsUpdate = { authProvider, isActive };
const orgBot = await orgBotDal.findOne({ orgId }); const orgBot = await orgBotDAL.findOne({ orgId });
if (!orgBot) if (!orgBot)
throw new BadRequestError({ message: "Org bot not found", name: "OrgBotNotFound" }); throw new BadRequestError({ message: "Org bot not found", name: "OrgBotNotFound" });
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
@@ -175,17 +175,17 @@ export const samlConfigServiceFactory = ({
updateQuery.certIV = certIV; updateQuery.certIV = certIV;
updateQuery.certTag = certTag; updateQuery.certTag = certTag;
} }
const [ssoConfig] = await samlConfigDal.update({ orgId }, updateQuery); const [ssoConfig] = await samlConfigDAL.update({ orgId }, updateQuery);
return ssoConfig; return ssoConfig;
}; };
const getSaml = async (dto: TGetSamlCfgDTO) => { const getSaml = async (dto: TGetSamlCfgDTO) => {
let ssoConfig: TSamlConfigs | undefined; let ssoConfig: TSamlConfigs | undefined;
if (dto.type === "org") { if (dto.type === "org") {
ssoConfig = await samlConfigDal.findOne({ orgId: dto.orgId }); ssoConfig = await samlConfigDAL.findOne({ orgId: dto.orgId });
if (!ssoConfig) return; if (!ssoConfig) return;
} else if (dto.type === "ssoId") { } else if (dto.type === "ssoId") {
ssoConfig = await samlConfigDal.findById(dto.id); ssoConfig = await samlConfigDAL.findById(dto.id);
} }
if (!ssoConfig) throw new BadRequestError({ message: "Failed to find organization SSO data" }); if (!ssoConfig) throw new BadRequestError({ message: "Failed to find organization SSO data" });
@@ -213,7 +213,7 @@ export const samlConfigServiceFactory = ({
encryptedIssuer encryptedIssuer
} = ssoConfig; } = ssoConfig;
const orgBot = await orgBotDal.findOne({ orgId: ssoConfig.orgId }); const orgBot = await orgBotDAL.findOne({ orgId: ssoConfig.orgId });
if (!orgBot) if (!orgBot)
throw new BadRequestError({ message: "Org bot not found", name: "OrgBotNotFound" }); throw new BadRequestError({ message: "Org bot not found", name: "OrgBotNotFound" });
const key = infisicalSymmetricDecrypt({ const key = infisicalSymmetricDecrypt({
@@ -270,25 +270,25 @@ export const samlConfigServiceFactory = ({
isSignupAllowed isSignupAllowed
}: TSamlLoginDTO) => { }: TSamlLoginDTO) => {
const appCfg = getConfig(); const appCfg = getConfig();
let user = await userDal.findUserByEmail(email); let user = await userDAL.findUserByEmail(email);
const isSamlSignUpDisabled = !isSignupAllowed && !user; const isSamlSignUpDisabled = !isSignupAllowed && !user;
if (isSamlSignUpDisabled) if (isSamlSignUpDisabled)
throw new BadRequestError({ message: "User signup disabled", name: "Saml SSO login" }); throw new BadRequestError({ message: "User signup disabled", name: "Saml SSO login" });
const organization = await orgDal.findOrgById(orgId); const organization = await orgDAL.findOrgById(orgId);
if (!organization) throw new BadRequestError({ message: "Org not found" }); if (!organization) throw new BadRequestError({ message: "Org not found" });
if (user) { if (user) {
const hasSamlEnabled = (user.authMethods || []).some((method) => const hasSamlEnabled = (user.authMethods || []).some((method) =>
Object.values(SamlProviders).includes(method as SamlProviders) Object.values(SamlProviders).includes(method as SamlProviders)
); );
await userDal.transaction(async (tx) => { await userDAL.transaction(async (tx) => {
if (!hasSamlEnabled) { if (!hasSamlEnabled) {
await userDal.updateById(user.id, { authMethods: [authProvider] }, tx); await userDAL.updateById(user.id, { authMethods: [authProvider] }, tx);
} }
const [orgMembership] = await orgDal.findMembership({ userId: user.id, orgId }, { tx }); const [orgMembership] = await orgDAL.findMembership({ userId: user.id, orgId }, { tx });
if (!orgMembership) { if (!orgMembership) {
await orgDal.createMembership( await orgDAL.createMembership(
{ {
userId: user.id, userId: user.id,
orgId, orgId,
@@ -299,7 +299,7 @@ export const samlConfigServiceFactory = ({
tx tx
); );
} else if (orgMembership.status === OrgMembershipStatus.Invited) { } else if (orgMembership.status === OrgMembershipStatus.Invited) {
await orgDal.updateMembershipById( await orgDAL.updateMembershipById(
orgMembership.id, orgMembership.id,
{ {
status: OrgMembershipStatus.Accepted status: OrgMembershipStatus.Accepted
@@ -309,8 +309,8 @@ export const samlConfigServiceFactory = ({
} }
}); });
} else { } else {
user = await userDal.transaction(async (tx) => { user = await userDAL.transaction(async (tx) => {
const newUser = await userDal.create( const newUser = await userDAL.create(
{ {
email, email,
firstName, firstName,
@@ -319,7 +319,7 @@ export const samlConfigServiceFactory = ({
}, },
tx tx
); );
await orgDal.createMembership({ await orgDAL.createMembership({
inviteEmail: email, inviteEmail: email,
orgId, orgId,
role: OrgMembershipRole.Member, role: OrgMembershipRole.Member,
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSapApproverDalFactory = ReturnType<typeof sapApproverDalFactory>; export type TSapApproverDALFactory = ReturnType<typeof sapApproverDALFactory>;
export const sapApproverDalFactory = (db: TDbClient) => { export const sapApproverDALFactory = (db: TDbClient) => {
const sapApproverOrm = ormify(db, TableName.SapApprover); const sapApproverOrm = ormify(db, TableName.SapApprover);
return sapApproverOrm; return sapApproverOrm;
}; };
@@ -10,9 +10,9 @@ import {
selectAllTableCols, selectAllTableCols,
TFindFilter} from "@app/lib/knex"; TFindFilter} from "@app/lib/knex";
export type TSecretApprovalPolicyDalFactory = ReturnType<typeof secretApprovalPolicyDalFactory>; export type TSecretApprovalPolicyDALFactory = ReturnType<typeof secretApprovalPolicyDALFactory>;
export const secretApprovalPolicyDalFactory = (db: TDbClient) => { export const secretApprovalPolicyDALFactory = (db: TDbClient) => {
const secretApprovalPolicyOrm = ormify(db, TableName.SecretApprovalPolicy); const secretApprovalPolicyOrm = ormify(db, TableName.SecretApprovalPolicy);
const sapFindQuery = (tx: Knex, filter: TFindFilter<TSecretApprovalPolicies>) => const sapFindQuery = (tx: Knex, filter: TFindFilter<TSecretApprovalPolicies>) =>
@@ -8,11 +8,11 @@ import {
} from "@app/ee/services/permission/project-permission"; } from "@app/ee/services/permission/project-permission";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { containsGlobPatterns } from "@app/lib/picomatch"; import { containsGlobPatterns } from "@app/lib/picomatch";
import { TProjectEnvDalFactory } from "@app/services/project-env/project-env-dal"; import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
import { TProjectMembershipDalFactory } from "@app/services/project-membership/project-membership-dal"; import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
import { TSapApproverDalFactory } from "./sap-approver-dal"; import { TSapApproverDALFactory } from "./sap-approver-dal";
import { TSecretApprovalPolicyDalFactory } from "./secret-approval-policy-dal"; import { TSecretApprovalPolicyDALFactory } from "./secret-approval-policy-dal";
import { import {
TCreateSapDTO, TCreateSapDTO,
TDeleteSapDTO, TDeleteSapDTO,
@@ -28,10 +28,10 @@ const getPolicyScore = (policy: { secretPath?: string | null }) =>
type TSecretApprovalPolicyServiceFactoryDep = { type TSecretApprovalPolicyServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
secretApprovalPolicyDal: TSecretApprovalPolicyDalFactory; secretApprovalPolicyDAL: TSecretApprovalPolicyDALFactory;
projectEnvDal: Pick<TProjectEnvDalFactory, "findOne">; projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
sapApproverDal: TSapApproverDalFactory; sapApproverDAL: TSapApproverDALFactory;
projectMembershipDal: Pick<TProjectMembershipDalFactory, "find">; projectMembershipDAL: Pick<TProjectMembershipDALFactory, "find">;
}; };
export type TSecretApprovalPolicyServiceFactory = ReturnType< export type TSecretApprovalPolicyServiceFactory = ReturnType<
@@ -39,11 +39,11 @@ export type TSecretApprovalPolicyServiceFactory = ReturnType<
>; >;
export const secretApprovalPolicyServiceFactory = ({ export const secretApprovalPolicyServiceFactory = ({
secretApprovalPolicyDal, secretApprovalPolicyDAL,
permissionService, permissionService,
sapApproverDal, sapApproverDAL,
projectEnvDal, projectEnvDAL,
projectMembershipDal projectMembershipDAL
}: TSecretApprovalPolicyServiceFactoryDep) => { }: TSecretApprovalPolicyServiceFactoryDep) => {
const createSap = async ({ const createSap = async ({
name, name,
@@ -63,18 +63,18 @@ export const secretApprovalPolicyServiceFactory = ({
ProjectPermissionActions.Create, ProjectPermissionActions.Create,
ProjectPermissionSub.SecretApproval ProjectPermissionSub.SecretApproval
); );
const env = await projectEnvDal.findOne({ slug: environment, projectId }); const env = await projectEnvDAL.findOne({ slug: environment, projectId });
if (!env) throw new BadRequestError({ message: "Environment not found" }); if (!env) throw new BadRequestError({ message: "Environment not found" });
const secretApprovers = await projectMembershipDal.find({ const secretApprovers = await projectMembershipDAL.find({
projectId, projectId,
$in: { id: approvers } $in: { id: approvers }
}); });
if (secretApprovers.length !== approvers.length) if (secretApprovers.length !== approvers.length)
throw new BadRequestError({ message: "Approver not found in project" }); throw new BadRequestError({ message: "Approver not found in project" });
const secretApproval = await secretApprovalPolicyDal.transaction(async (tx) => { const secretApproval = await secretApprovalPolicyDAL.transaction(async (tx) => {
const doc = await secretApprovalPolicyDal.create( const doc = await secretApprovalPolicyDAL.create(
{ {
envId: env.id, envId: env.id,
approvals, approvals,
@@ -83,7 +83,7 @@ export const secretApprovalPolicyServiceFactory = ({
}, },
tx tx
); );
await sapApproverDal.insertMany( await sapApproverDAL.insertMany(
secretApprovers.map(({ id }) => ({ secretApprovers.map(({ id }) => ({
approverId: id, approverId: id,
policyId: doc.id policyId: doc.id
@@ -104,7 +104,7 @@ export const secretApprovalPolicyServiceFactory = ({
approvals, approvals,
secretPolicyId secretPolicyId
}: TUpdateSapDTO) => { }: TUpdateSapDTO) => {
const secretApprovalPolicy = await secretApprovalPolicyDal.findById(secretPolicyId); const secretApprovalPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId);
if (!secretApprovalPolicy) if (!secretApprovalPolicy)
throw new BadRequestError({ message: "Secret approval policy not found" }); throw new BadRequestError({ message: "Secret approval policy not found" });
@@ -118,8 +118,8 @@ export const secretApprovalPolicyServiceFactory = ({
ProjectPermissionSub.SecretApproval ProjectPermissionSub.SecretApproval
); );
const updatedSap = await secretApprovalPolicyDal.transaction(async (tx) => { const updatedSap = await secretApprovalPolicyDAL.transaction(async (tx) => {
const doc = await secretApprovalPolicyDal.updateById( const doc = await secretApprovalPolicyDAL.updateById(
secretApprovalPolicy.id, secretApprovalPolicy.id,
{ {
approvals, approvals,
@@ -129,7 +129,7 @@ export const secretApprovalPolicyServiceFactory = ({
tx tx
); );
if (approvers) { if (approvers) {
const secretApprovers = await projectMembershipDal.find( const secretApprovers = await projectMembershipDAL.find(
{ {
projectId: secretApprovalPolicy.projectId, projectId: secretApprovalPolicy.projectId,
$in: { id: approvers } $in: { id: approvers }
@@ -140,8 +140,8 @@ export const secretApprovalPolicyServiceFactory = ({
throw new BadRequestError({ message: "Approver not found in project" }); throw new BadRequestError({ message: "Approver not found in project" });
if (doc.approvals > secretApprovers.length) if (doc.approvals > secretApprovers.length)
throw new BadRequestError({ message: "Approvals cannot be greater than approvers" }); throw new BadRequestError({ message: "Approvals cannot be greater than approvers" });
await sapApproverDal.delete({ policyId: doc.id }, tx); await sapApproverDAL.delete({ policyId: doc.id }, tx);
await sapApproverDal.insertMany( await sapApproverDAL.insertMany(
secretApprovers.map(({ id }) => ({ secretApprovers.map(({ id }) => ({
approverId: id, approverId: id,
policyId: doc.id policyId: doc.id
@@ -159,7 +159,7 @@ export const secretApprovalPolicyServiceFactory = ({
}; };
const deleteSap = async ({ secretPolicyId, actor, actorId }: TDeleteSapDTO) => { const deleteSap = async ({ secretPolicyId, actor, actorId }: TDeleteSapDTO) => {
const sapPolicy = await secretApprovalPolicyDal.findById(secretPolicyId); const sapPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId);
if (!sapPolicy) throw new BadRequestError({ message: "Secret approval policy not found" }); if (!sapPolicy) throw new BadRequestError({ message: "Secret approval policy not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -172,7 +172,7 @@ export const secretApprovalPolicyServiceFactory = ({
ProjectPermissionSub.SecretApproval ProjectPermissionSub.SecretApproval
); );
await secretApprovalPolicyDal.deleteById(secretPolicyId); await secretApprovalPolicyDAL.deleteById(secretPolicyId);
return sapPolicy; return sapPolicy;
}; };
@@ -183,15 +183,15 @@ export const secretApprovalPolicyServiceFactory = ({
ProjectPermissionSub.SecretApproval ProjectPermissionSub.SecretApproval
); );
const sapPolicies = await secretApprovalPolicyDal.find({ projectId }); const sapPolicies = await secretApprovalPolicyDAL.find({ projectId });
return sapPolicies; return sapPolicies;
}; };
const getSapPolicy = async (projectId: string, environment: string, secretPath: string) => { const getSapPolicy = async (projectId: string, environment: string, secretPath: string) => {
const env = await projectEnvDal.findOne({ slug: environment, projectId }); const env = await projectEnvDAL.findOne({ slug: environment, projectId });
if (!env) throw new BadRequestError({ message: "Environment not found" }); if (!env) throw new BadRequestError({ message: "Environment not found" });
const policies = await secretApprovalPolicyDal.find({ envId: env.id }); const policies = await secretApprovalPolicyDAL.find({ envId: env.id });
if (!policies.length) return; if (!policies.length) return;
// this will filter policies either without scoped to secret path or the one that matches with secret path // this will filter policies either without scoped to secret path or the one that matches with secret path
const policiesFilteredByPath = policies.filter( const policiesFilteredByPath = policies.filter(
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSarReviewerDalFactory = ReturnType<typeof sarReviewerDalFactory>; export type TSarReviewerDALFactory = ReturnType<typeof sarReviewerDALFactory>;
export const sarReviewerDalFactory = (db: TDbClient) => { export const sarReviewerDALFactory = (db: TDbClient) => {
const sarReviewerOrm = ormify(db, TableName.SarReviewer); const sarReviewerOrm = ormify(db, TableName.SarReviewer);
return sarReviewerOrm; return sarReviewerOrm;
}; };
@@ -5,9 +5,9 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TSarSecretDalFactory = ReturnType<typeof sarSecretDalFactory>; export type TSarSecretDALFactory = ReturnType<typeof sarSecretDALFactory>;
export const sarSecretDalFactory = (db: TDbClient) => { export const sarSecretDALFactory = (db: TDbClient) => {
const sarSecretOrm = ormify(db, TableName.SarSecret); const sarSecretOrm = ormify(db, TableName.SarSecret);
const findByRequestId = async (requestId: string, tx?: Knex) => { const findByRequestId = async (requestId: string, tx?: Knex) => {
@@ -13,7 +13,7 @@ import {
import { RequestState } from "./secret-approval-request-types"; import { RequestState } from "./secret-approval-request-types";
export type TSecretApprovalRequestDalFactory = ReturnType<typeof secretApprovalRequestDalFactory>; export type TSecretApprovalRequestDALFactory = ReturnType<typeof secretApprovalRequestDALFactory>;
type TFindQueryFilter = { type TFindQueryFilter = {
projectId: string; projectId: string;
@@ -25,7 +25,7 @@ type TFindQueryFilter = {
offset?: number; offset?: number;
}; };
export const secretApprovalRequestDalFactory = (db: TDbClient) => { export const secretApprovalRequestDALFactory = (db: TDbClient) => {
const secretApprovalRequestOrm = ormify(db, TableName.SecretApprovalRequest); const secretApprovalRequestOrm = ormify(db, TableName.SecretApprovalRequest);
const findQuery = (filter: TFindFilter<TSecretApprovalRequests>, tx: Knex) => const findQuery = (filter: TFindFilter<TSecretApprovalRequests>, tx: Knex) =>
@@ -11,18 +11,18 @@ import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { groupBy, pick } from "@app/lib/fn"; import { groupBy, pick } from "@app/lib/fn";
import { alphaNumericNanoId } from "@app/lib/nanoid"; import { alphaNumericNanoId } from "@app/lib/nanoid";
import { ActorType } from "@app/services/auth/auth-type"; import { ActorType } from "@app/services/auth/auth-type";
import { TSecretBlindIndexDalFactory } from "@app/services/secret/secret-blind-index-dal"; import { TSecretBlindIndexDALFactory } from "@app/services/secret/secret-blind-index-dal";
import { TSecretQueueFactory } from "@app/services/secret/secret-queue"; import { TSecretQueueFactory } from "@app/services/secret/secret-queue";
import { TSecretServiceFactory } from "@app/services/secret/secret-service"; import { TSecretServiceFactory } from "@app/services/secret/secret-service";
import { TSecretVersionDalFactory } from "@app/services/secret/secret-version-dal"; import { TSecretVersionDALFactory } from "@app/services/secret/secret-version-dal";
import { TSecretFolderDalFactory } from "@app/services/secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TPermissionServiceFactory } from "../permission/permission-service"; import { TPermissionServiceFactory } from "../permission/permission-service";
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission"; import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
import { TSecretSnapshotServiceFactory } from "../secret-snapshot/secret-snapshot-service"; import { TSecretSnapshotServiceFactory } from "../secret-snapshot/secret-snapshot-service";
import { TSarReviewerDalFactory } from "./sar-reviewer-dal"; import { TSarReviewerDALFactory } from "./sar-reviewer-dal";
import { TSarSecretDalFactory } from "./sar-secret-dal"; import { TSarSecretDALFactory } from "./sar-secret-dal";
import { TSecretApprovalRequestDalFactory } from "./secret-approval-request-dal"; import { TSecretApprovalRequestDALFactory } from "./secret-approval-request-dal";
import { import {
ApprovalStatus, ApprovalStatus,
CommitType, CommitType,
@@ -38,16 +38,16 @@ import {
type TSecretApprovalRequestServiceFactoryDep = { type TSecretApprovalRequestServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
secretApprovalRequestDal: TSecretApprovalRequestDalFactory; secretApprovalRequestDAL: TSecretApprovalRequestDALFactory;
sarSecretDal: TSarSecretDalFactory; sarSecretDAL: TSarSecretDALFactory;
sarReviewerDal: TSarReviewerDalFactory; sarReviewerDAL: TSarReviewerDALFactory;
folderDal: Pick< folderDAL: Pick<
TSecretFolderDalFactory, TSecretFolderDALFactory,
"findBySecretPath" | "findById" | "findSecretPathByFolderIds" "findBySecretPath" | "findById" | "findSecretPathByFolderIds"
>; >;
secretBlindIndexDal: Pick<TSecretBlindIndexDalFactory, "findOne">; secretBlindIndexDAL: Pick<TSecretBlindIndexDALFactory, "findOne">;
snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">; snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;
secretVersionDal: Pick<TSecretVersionDalFactory, "findLatestVersionMany">; secretVersionDAL: Pick<TSecretVersionDALFactory, "findLatestVersionMany">;
secretService: Pick< secretService: Pick<
TSecretServiceFactory, TSecretServiceFactory,
| "fnSecretBulkInsert" | "fnSecretBulkInsert"
@@ -64,15 +64,15 @@ export type TSecretApprovalRequestServiceFactory = ReturnType<
>; >;
export const secretApprovalRequestServiceFactory = ({ export const secretApprovalRequestServiceFactory = ({
secretApprovalRequestDal, secretApprovalRequestDAL,
folderDal, folderDAL,
sarReviewerDal, sarReviewerDAL,
sarSecretDal, sarSecretDAL,
secretBlindIndexDal, secretBlindIndexDAL,
permissionService, permissionService,
snapshotService, snapshotService,
secretService, secretService,
secretVersionDal, secretVersionDAL,
secretQueueService secretQueueService
}: TSecretApprovalRequestServiceFactoryDep) => { }: TSecretApprovalRequestServiceFactoryDep) => {
const requestCount = async ({ projectId, actor, actorId }: TApprovalRequestCountDTO) => { const requestCount = async ({ projectId, actor, actorId }: TApprovalRequestCountDTO) => {
@@ -85,7 +85,7 @@ export const secretApprovalRequestServiceFactory = ({
projectId projectId
); );
const count = await secretApprovalRequestDal.findProjectRequestCount(projectId, membership.id); const count = await secretApprovalRequestDAL.findProjectRequestCount(projectId, membership.id);
return count; return count;
}; };
@@ -103,7 +103,7 @@ export const secretApprovalRequestServiceFactory = ({
throw new BadRequestError({ message: "Cannot use service token" }); throw new BadRequestError({ message: "Cannot use service token" });
const { membership } = await permissionService.getProjectPermission(actor, actorId, projectId); const { membership } = await permissionService.getProjectPermission(actor, actorId, projectId);
const approvals = await secretApprovalRequestDal.findByProjectId({ const approvals = await secretApprovalRequestDAL.findByProjectId({
projectId, projectId,
committer, committer,
environment, environment,
@@ -119,7 +119,7 @@ export const secretApprovalRequestServiceFactory = ({
if (actor === ActorType.SERVICE) if (actor === ActorType.SERVICE)
throw new BadRequestError({ message: "Cannot use service token" }); throw new BadRequestError({ message: "Cannot use service token" });
const secretApprovalRequest = await secretApprovalRequestDal.findById(id); const secretApprovalRequest = await secretApprovalRequestDAL.findById(id);
if (!secretApprovalRequest) if (!secretApprovalRequest)
throw new BadRequestError({ message: "Secret approval request not found" }); throw new BadRequestError({ message: "Secret approval request not found" });
@@ -137,15 +137,15 @@ export const secretApprovalRequestServiceFactory = ({
throw new UnauthorizedError({ message: "User has no access" }); throw new UnauthorizedError({ message: "User has no access" });
} }
const secrets = await sarSecretDal.findByRequestId(secretApprovalRequest.id); const secrets = await sarSecretDAL.findByRequestId(secretApprovalRequest.id);
const secretPath = await folderDal.findSecretPathByFolderIds(secretApprovalRequest.projectId, [ const secretPath = await folderDAL.findSecretPathByFolderIds(secretApprovalRequest.projectId, [
secretApprovalRequest.folderId secretApprovalRequest.folderId
]); ]);
return { ...secretApprovalRequest, secretPath: secretPath?.[0]?.path || "/", commits: secrets }; return { ...secretApprovalRequest, secretPath: secretPath?.[0]?.path || "/", commits: secrets };
}; };
const reviewApproval = async ({ approvalId, actor, status, actorId }: TReviewRequestDTO) => { const reviewApproval = async ({ approvalId, actor, status, actorId }: TReviewRequestDTO) => {
const secretApprovalRequest = await secretApprovalRequestDal.findById(approvalId); const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
if (!secretApprovalRequest) if (!secretApprovalRequest)
throw new BadRequestError({ message: "Secret approval request not found" }); throw new BadRequestError({ message: "Secret approval request 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" });
@@ -163,8 +163,8 @@ export const secretApprovalRequestServiceFactory = ({
) { ) {
throw new UnauthorizedError({ message: "User has no access" }); throw new UnauthorizedError({ message: "User has no access" });
} }
const reviewStatus = await sarReviewerDal.transaction(async (tx) => { const reviewStatus = await sarReviewerDAL.transaction(async (tx) => {
const review = await sarReviewerDal.findOne( const review = await sarReviewerDAL.findOne(
{ {
requestId: secretApprovalRequest.id, requestId: secretApprovalRequest.id,
member: membership.id member: membership.id
@@ -172,7 +172,7 @@ export const secretApprovalRequestServiceFactory = ({
tx tx
); );
if (!review) { if (!review) {
return sarReviewerDal.create( return sarReviewerDAL.create(
{ {
status, status,
requestId: secretApprovalRequest.id, requestId: secretApprovalRequest.id,
@@ -181,13 +181,13 @@ export const secretApprovalRequestServiceFactory = ({
tx tx
); );
} }
return sarReviewerDal.updateById(review.id, { status }, tx); return sarReviewerDAL.updateById(review.id, { status }, tx);
}); });
return reviewStatus; return reviewStatus;
}; };
const updateApprovalStatus = async ({ actorId, status, approvalId, actor }: TStatusChangeDTO) => { const updateApprovalStatus = async ({ actorId, status, approvalId, actor }: TStatusChangeDTO) => {
const secretApprovalRequest = await secretApprovalRequestDal.findById(approvalId); const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
if (!secretApprovalRequest) if (!secretApprovalRequest)
throw new BadRequestError({ message: "Secret approval request not found" }); throw new BadRequestError({ message: "Secret approval request 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" });
@@ -213,7 +213,7 @@ export const secretApprovalRequestServiceFactory = ({
if (secretApprovalRequest.status === RequestState.Open && status === RequestState.Open) if (secretApprovalRequest.status === RequestState.Open && status === RequestState.Open)
throw new BadRequestError({ message: "Approval request is already open" }); throw new BadRequestError({ message: "Approval request is already open" });
const updatedRequest = await secretApprovalRequestDal.updateById(secretApprovalRequest.id, { const updatedRequest = await secretApprovalRequestDAL.updateById(secretApprovalRequest.id, {
status, status,
statusChangeBy: membership.id statusChangeBy: membership.id
}); });
@@ -225,7 +225,7 @@ export const secretApprovalRequestServiceFactory = ({
actor, actor,
actorId actorId
}: TMergeSecretApprovalRequestDTO) => { }: TMergeSecretApprovalRequestDTO) => {
const secretApprovalRequest = await secretApprovalRequestDal.findById(approvalId); const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
if (!secretApprovalRequest) if (!secretApprovalRequest)
throw new BadRequestError({ message: "Secret approval request not found" }); throw new BadRequestError({ message: "Secret approval request 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" });
@@ -255,7 +255,7 @@ export const secretApprovalRequestServiceFactory = ({
if (!hasMinApproval) if (!hasMinApproval)
throw new BadRequestError({ message: "Doesn't have minimum approvals needed" }); throw new BadRequestError({ message: "Doesn't have minimum approvals needed" });
const secretApprovalSecrets = await sarSecretDal.findByRequestId(secretApprovalRequest.id); const secretApprovalSecrets = await sarSecretDAL.findByRequestId(secretApprovalRequest.id);
if (!secretApprovalSecrets) throw new BadRequestError({ message: "No secrets found" }); if (!secretApprovalSecrets) throw new BadRequestError({ message: "No secrets found" });
const conflicts: Array<{ secretId: string; op: CommitType }> = []; const conflicts: Array<{ secretId: string; op: CommitType }> = [];
@@ -308,7 +308,7 @@ export const secretApprovalRequestServiceFactory = ({
({ op }) => op === CommitType.Delete ({ op }) => op === CommitType.Delete
); );
const mergeStatus = await secretApprovalRequestDal.transaction(async (tx) => { const mergeStatus = await secretApprovalRequestDAL.transaction(async (tx) => {
const newSecrets = secretCreationCommits.length const newSecrets = secretCreationCommits.length
? await secretService.fnSecretBulkInsert({ ? await secretService.fnSecretBulkInsert({
tx, tx,
@@ -378,7 +378,7 @@ export const secretApprovalRequestServiceFactory = ({
})) }))
}) })
: []; : [];
const updatedSecretApproval = await secretApprovalRequestDal.updateById( const updatedSecretApproval = await secretApprovalRequestDAL.updateById(
secretApprovalRequest.id, secretApprovalRequest.id,
{ {
conflicts: JSON.stringify(conflicts), conflicts: JSON.stringify(conflicts),
@@ -394,7 +394,7 @@ export const secretApprovalRequestServiceFactory = ({
}; };
}); });
await snapshotService.performSnapshot(folderId); await snapshotService.performSnapshot(folderId);
const folder = await folderDal.findById(folderId); const folder = await folderDAL.findById(folderId);
// TODO(akhilmhdh-pg): change query to do secret path from folder // TODO(akhilmhdh-pg): change query to do secret path from folder
await secretQueueService.syncSecrets({ await secretQueueService.syncSecrets({
projectId, projectId,
@@ -428,12 +428,12 @@ export const secretApprovalRequestServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath }) subject(ProjectPermissionSub.Secrets, { environment, secretPath })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) if (!folder)
throw new BadRequestError({ message: "Folder not found", name: "GenSecretApproval" }); throw new BadRequestError({ message: "Folder not found", name: "GenSecretApproval" });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDal.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) if (!blindIndexCfg)
throw new BadRequestError({ message: "Blind index not found", name: "Update secret" }); throw new BadRequestError({ message: "Blind index not found", name: "Update secret" });
@@ -490,7 +490,7 @@ export const secretApprovalRequestServiceFactory = ({
const updatedSecretIds = updatedSecrets.map( const updatedSecretIds = updatedSecrets.map(
(el) => secsGroupedByBlindIndex[keyName2BlindIndex[el.secretName]][0].id (el) => secsGroupedByBlindIndex[keyName2BlindIndex[el.secretName]][0].id
); );
const latestSecretVersions = await secretVersionDal.findLatestVersionMany( const latestSecretVersions = await secretVersionDAL.findLatestVersionMany(
folderId, folderId,
updatedSecretIds updatedSecretIds
); );
@@ -528,7 +528,7 @@ export const secretApprovalRequestServiceFactory = ({
const deletedSecretIds = deletedSecrets.map( const deletedSecretIds = deletedSecrets.map(
(el) => secretsGroupedByBlindIndex[keyName2BlindIndex[el.secretName]][0].id (el) => secretsGroupedByBlindIndex[keyName2BlindIndex[el.secretName]][0].id
); );
const latestSecretVersions = await secretVersionDal.findLatestVersionMany( const latestSecretVersions = await secretVersionDAL.findLatestVersionMany(
folderId, folderId,
deletedSecretIds deletedSecretIds
); );
@@ -546,8 +546,8 @@ export const secretApprovalRequestServiceFactory = ({
} }
if (!commits.length) throw new BadRequestError({ message: "Empty commits" }); if (!commits.length) throw new BadRequestError({ message: "Empty commits" });
const secretApprovalRequest = await secretApprovalRequestDal.transaction(async (tx) => { const secretApprovalRequest = await secretApprovalRequestDAL.transaction(async (tx) => {
const doc = await secretApprovalRequestDal.create( const doc = await secretApprovalRequestDAL.create(
{ {
folderId, folderId,
slug: alphaNumericNanoId(), slug: alphaNumericNanoId(),
@@ -558,7 +558,7 @@ export const secretApprovalRequestServiceFactory = ({
}, },
tx tx
); );
const approvalCommits = await sarSecretDal.insertMany( const approvalCommits = await sarSecretDAL.insertMany(
commits.map( commits.map(
({ ({
version, version,
@@ -5,9 +5,9 @@ import { SecretRotationsSchema, TableName, TSecretRotations } from "@app/db/sche
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols, sqlNestRelationships, TFindFilter } from "@app/lib/knex"; import { ormify, selectAllTableCols, sqlNestRelationships, TFindFilter } from "@app/lib/knex";
export type TSecretRotationDalFactory = ReturnType<typeof secretRotationDalFactory>; export type TSecretRotationDALFactory = ReturnType<typeof secretRotationDALFactory>;
export const secretRotationDalFactory = (db: TDbClient) => { export const secretRotationDALFactory = (db: TDbClient) => {
const secretRotationOrm = ormify(db, TableName.SecretRotation); const secretRotationOrm = ormify(db, TableName.SecretRotation);
const secretRotationOutputOrm = ormify(db, TableName.SecretRotationOutput); const secretRotationOutputOrm = ormify(db, TableName.SecretRotationOutput);
@@ -10,10 +10,10 @@ import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid"; import { alphaNumericNanoId } from "@app/lib/nanoid";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service"; import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
import { TSecretDalFactory } from "@app/services/secret/secret-dal"; import { TSecretDALFactory } from "@app/services/secret/secret-dal";
import { TSecretVersionDalFactory } from "@app/services/secret/secret-version-dal"; import { TSecretVersionDALFactory } from "@app/services/secret/secret-version-dal";
import { TSecretRotationDalFactory } from "../secret-rotation-dal"; import { TSecretRotationDALFactory } from "../secret-rotation-dal";
import { rotationTemplates } from "../templates"; import { rotationTemplates } from "../templates";
import { import {
TDbProviderClients, TDbProviderClients,
@@ -37,10 +37,10 @@ export type TSecretRotationQueueFactory = ReturnType<typeof secretRotationQueueF
type TSecretRotationQueueFactoryDep = { type TSecretRotationQueueFactoryDep = {
queue: TQueueServiceFactory; queue: TQueueServiceFactory;
secretRotationDal: TSecretRotationDalFactory; secretRotationDAL: TSecretRotationDALFactory;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">; projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
secretDal: Pick<TSecretDalFactory, "bulkUpdate" | "find">; secretDAL: Pick<TSecretDALFactory, "bulkUpdate" | "find">;
secretVersionDal: Pick<TSecretVersionDalFactory, "insertMany" | "findLatestVersionMany">; secretVersionDAL: Pick<TSecretVersionDALFactory, "insertMany" | "findLatestVersionMany">;
}; };
// These error should stop the repeatable job and ask user to reconfigure rotation // These error should stop the repeatable job and ask user to reconfigure rotation
@@ -58,10 +58,10 @@ export class DisableRotationErrors extends Error {
export const secretRotationQueueFactory = ({ export const secretRotationQueueFactory = ({
queue, queue,
secretRotationDal, secretRotationDAL,
projectBotService, projectBotService,
secretDal, secretDAL,
secretVersionDal secretVersionDAL
}: TSecretRotationQueueFactoryDep) => { }: TSecretRotationQueueFactoryDep) => {
const addToQueue = async (rotationId: string, interval: number) => { const addToQueue = async (rotationId: string, interval: number) => {
const appCfg = getConfig(); const appCfg = getConfig();
@@ -102,7 +102,7 @@ export const secretRotationQueueFactory = ({
queue.start(QueueName.SecretRotation, async (job) => { queue.start(QueueName.SecretRotation, async (job) => {
const { rotationId } = job.data; const { rotationId } = job.data;
logger.info(`secretRotationQueue.process: [rotationDocument=${rotationId}]`); logger.info(`secretRotationQueue.process: [rotationDocument=${rotationId}]`);
const secretRotation = await secretRotationDal.findById(rotationId); const secretRotation = await secretRotationDAL.findById(rotationId);
const rotationProvider = rotationTemplates.find( const rotationProvider = rotationTemplates.find(
({ name }) => name === secretRotation?.provider ({ name }) => name === secretRotation?.provider
); );
@@ -111,7 +111,7 @@ export const secretRotationQueueFactory = ({
if (!rotationProvider || !secretRotation) if (!rotationProvider || !secretRotation)
throw new DisableRotationErrors({ message: "Provider not found" }); throw new DisableRotationErrors({ message: "Provider not found" });
const rotationOutputs = await secretRotationDal.findRotationOutputsByRotationId(rotationId); const rotationOutputs = await secretRotationDAL.findRotationOutputsByRotationId(rotationId);
if (!rotationOutputs.length) if (!rotationOutputs.length)
throw new DisableRotationErrors({ message: "Secrets not found" }); throw new DisableRotationErrors({ message: "Secrets not found" });
@@ -227,8 +227,8 @@ export const secretRotationQueueFactory = ({
key key
) )
})); }));
await secretRotationDal.transaction(async (tx) => { await secretRotationDAL.transaction(async (tx) => {
await secretRotationDal.updateById( await secretRotationDAL.updateById(
rotationId, rotationId,
{ {
encryptedData: encVarData.ciphertext, encryptedData: encVarData.ciphertext,
@@ -242,7 +242,7 @@ export const secretRotationQueueFactory = ({
}, },
tx tx
); );
const updatedSecrets = await secretDal.bulkUpdate( const updatedSecrets = await secretDAL.bulkUpdate(
encryptedSecrets.map(({ secretId, value }) => ({ encryptedSecrets.map(({ secretId, value }) => ({
// this secret id is validated when user is inserted // this secret id is validated when user is inserted
filter: { id: secretId, type: SecretType.Shared }, filter: { id: secretId, type: SecretType.Shared },
@@ -254,7 +254,7 @@ export const secretRotationQueueFactory = ({
})), })),
tx tx
); );
await secretVersionDal.insertMany( await secretVersionDAL.insertMany(
updatedSecrets.map(({ id, updatedAt, createdAt, ...el }) => ({ updatedSecrets.map(({ id, updatedAt, createdAt, ...el }) => ({
...el, ...el,
secretId: id secretId: id
@@ -271,7 +271,7 @@ export const secretRotationQueueFactory = ({
} }
} }
await secretRotationDal.updateById(rotationId, { await secretRotationDAL.updateById(rotationId, {
status: "failed", status: "failed",
statusMessage: (error as Error).message.slice(0, 500), statusMessage: (error as Error).message.slice(0, 500),
lastRotatedAt: new Date() lastRotatedAt: new Date()
@@ -4,14 +4,14 @@ import Ajv from "ajv";
import { infisicalSymmetricEncypt } from "@app/lib/crypto/encryption"; import { infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectPermission } from "@app/lib/types"; import { TProjectPermission } from "@app/lib/types";
import { TProjectDalFactory } from "@app/services/project/project-dal"; import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TSecretDalFactory } from "@app/services/secret/secret-dal"; import { TSecretDALFactory } from "@app/services/secret/secret-dal";
import { TSecretFolderDalFactory } from "@app/services/secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TLicenseServiceFactory } from "../license/license-service"; import { TLicenseServiceFactory } from "../license/license-service";
import { TPermissionServiceFactory } from "../permission/permission-service"; import { TPermissionServiceFactory } from "../permission/permission-service";
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission"; import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
import { TSecretRotationDalFactory } from "./secret-rotation-dal"; import { TSecretRotationDALFactory } from "./secret-rotation-dal";
import { TSecretRotationQueueFactory } from "./secret-rotation-queue"; import { TSecretRotationQueueFactory } from "./secret-rotation-queue";
import { TSecretRotationEncData } from "./secret-rotation-queue/secret-rotation-queue-types"; import { TSecretRotationEncData } from "./secret-rotation-queue/secret-rotation-queue-types";
import { import {
@@ -24,10 +24,10 @@ import {
import { rotationTemplates } from "./templates"; import { rotationTemplates } from "./templates";
type TSecretRotationServiceFactoryDep = { type TSecretRotationServiceFactoryDep = {
secretRotationDal: TSecretRotationDalFactory; secretRotationDAL: TSecretRotationDALFactory;
projectDal: Pick<TProjectDalFactory, "findById">; projectDAL: Pick<TProjectDALFactory, "findById">;
folderDal: Pick<TSecretFolderDalFactory, "findBySecretPath">; folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
secretDal: Pick<TSecretDalFactory, "find">; secretDAL: Pick<TSecretDALFactory, "find">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
secretRotationQueue: TSecretRotationQueueFactory; secretRotationQueue: TSecretRotationQueueFactory;
@@ -37,13 +37,13 @@ export type TSecretRotationServiceFactory = ReturnType<typeof secretRotationServ
const ajv = new Ajv({ strict: false }); const ajv = new Ajv({ strict: false });
export const secretRotationServiceFactory = ({ export const secretRotationServiceFactory = ({
secretRotationDal, secretRotationDAL,
permissionService, permissionService,
secretRotationQueue, secretRotationQueue,
licenseService, licenseService,
projectDal, projectDAL,
folderDal, folderDAL,
secretDal secretDAL
}: TSecretRotationServiceFactoryDep) => { }: TSecretRotationServiceFactoryDep) => {
const getProviderTemplates = async ({ actor, actorId, projectId }: TProjectPermission) => { const getProviderTemplates = async ({ actor, actorId, projectId }: TProjectPermission) => {
const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId); const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId);
@@ -75,21 +75,21 @@ export const secretRotationServiceFactory = ({
ProjectPermissionSub.SecretRotation ProjectPermissionSub.SecretRotation
); );
const folder = await folderDal.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) throw new BadRequestError({ message: "Secret path not found" }); if (!folder) throw new BadRequestError({ message: "Secret path not found" });
ForbiddenError.from(permission).throwUnlessCan( ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionActions.Edit, ProjectPermissionActions.Edit,
subject(ProjectPermissionSub.Secrets, { environment, secretPath }) subject(ProjectPermissionSub.Secrets, { environment, secretPath })
); );
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 BadRequestError({ message: "Secrets not found" }); throw new BadRequestError({ message: "Secrets not found" });
const project = await projectDal.findById(projectId); const project = await projectDAL.findById(projectId);
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
if (!plan.secretRotation) if (!plan.secretRotation)
throw new BadRequestError({ throw new BadRequestError({
@@ -123,8 +123,8 @@ export const secretRotationServiceFactory = ({
creds: [] creds: []
}; };
const encData = infisicalSymmetricEncypt(JSON.stringify(unencryptedData)); const encData = infisicalSymmetricEncypt(JSON.stringify(unencryptedData));
const secretRotation = secretRotationDal.transaction(async (tx) => { const secretRotation = secretRotationDAL.transaction(async (tx) => {
const doc = await secretRotationDal.create( const doc = await secretRotationDAL.create(
{ {
provider, provider,
secretPath, secretPath,
@@ -139,7 +139,7 @@ export const secretRotationServiceFactory = ({
tx tx
); );
await secretRotationQueue.addToQueue(doc.id, doc.interval); await secretRotationQueue.addToQueue(doc.id, doc.interval);
const outputSecretMapping = await secretRotationDal.secretOutputInsertMany( const outputSecretMapping = await secretRotationDAL.secretOutputInsertMany(
Object.entries(outputs).map(([key, secretId]) => ({ key, secretId, rotationId: doc.id })), Object.entries(outputs).map(([key, secretId]) => ({ key, secretId, rotationId: doc.id })),
tx tx
); );
@@ -149,7 +149,7 @@ export const secretRotationServiceFactory = ({
}; };
const getById = async ({ rotationId, actor, actorId }: TGetByIdDTO) => { const getById = async ({ rotationId, actor, actorId }: TGetByIdDTO) => {
const [doc] = await secretRotationDal.find({ id: rotationId }); const [doc] = await secretRotationDAL.find({ id: rotationId });
if (!doc) throw new BadRequestError({ message: "Rotation not found" }); if (!doc) throw new BadRequestError({ message: "Rotation not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -170,15 +170,15 @@ export const secretRotationServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
ProjectPermissionSub.SecretRotation ProjectPermissionSub.SecretRotation
); );
const doc = await secretRotationDal.find({ projectId }); const doc = await secretRotationDAL.find({ projectId });
return doc; return doc;
}; };
const restartById = async ({ actor, actorId, rotationId }: TRestartDTO) => { const restartById = async ({ actor, actorId, rotationId }: TRestartDTO) => {
const doc = await secretRotationDal.findById(rotationId); const doc = await secretRotationDAL.findById(rotationId);
if (!doc) throw new BadRequestError({ message: "Rotation not found" }); if (!doc) throw new BadRequestError({ message: "Rotation 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);
if (!plan.secretRotation) if (!plan.secretRotation)
throw new BadRequestError({ throw new BadRequestError({
@@ -201,7 +201,7 @@ export const secretRotationServiceFactory = ({
}; };
const deleteById = async ({ actor, actorId, rotationId }: TDeleteDTO) => { const deleteById = async ({ actor, actorId, rotationId }: TDeleteDTO) => {
const doc = await secretRotationDal.findById(rotationId); const doc = await secretRotationDAL.findById(rotationId);
if (!doc) throw new BadRequestError({ message: "Rotation not found" }); if (!doc) throw new BadRequestError({ message: "Rotation not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -213,8 +213,8 @@ export const secretRotationServiceFactory = ({
ProjectPermissionActions.Delete, ProjectPermissionActions.Delete,
ProjectPermissionSub.SecretRotation ProjectPermissionSub.SecretRotation
); );
const deletedDoc = await secretRotationDal.transaction(async (tx) => { const deletedDoc = await secretRotationDAL.transaction(async (tx) => {
const strat = await secretRotationDal.deleteById(rotationId, tx); const strat = await secretRotationDAL.deleteById(rotationId, tx);
await secretRotationQueue.removeFromQueue(strat.id, strat.interval); await secretRotationQueue.removeFromQueue(strat.id, strat.interval);
return strat; return strat;
}); });
@@ -5,9 +5,9 @@ import { TableName,TGitAppOrgInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TGitAppDalFactory = ReturnType<typeof gitAppDalFactory>; export type TGitAppDALFactory = ReturnType<typeof gitAppDALFactory>;
export const gitAppDalFactory = (db: TDbClient) => { export const gitAppDALFactory = (db: TDbClient) => {
const gitAppOrm = ormify(db, TableName.GitAppOrg); const gitAppOrm = ormify(db, TableName.GitAppOrg);
const upsert = async (data: TGitAppOrgInsert, tx?: Knex) => { const upsert = async (data: TGitAppOrgInsert, tx?: Knex) => {
@@ -5,9 +5,9 @@ import { TableName,TGitAppInstallSessionsInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TGitAppInstallSessionDalFactory = ReturnType<typeof gitAppInstallSessionDalFactory>; export type TGitAppInstallSessionDALFactory = ReturnType<typeof gitAppInstallSessionDALFactory>;
export const gitAppInstallSessionDalFactory = (db: TDbClient) => { export const gitAppInstallSessionDALFactory = (db: TDbClient) => {
const gitAppInstallSessionOrm = ormify(db, TableName.GitAppInstallSession); const gitAppInstallSessionOrm = ormify(db, TableName.GitAppInstallSession);
const upsert = async (data: TGitAppInstallSessionsInsert, tx?: Knex) => { const upsert = async (data: TGitAppInstallSessionsInsert, tx?: Knex) => {
@@ -5,9 +5,9 @@ import { TableName,TSecretScanningGitRisksInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSecretScanningDalFactory = ReturnType<typeof secretScanningDalFactory>; export type TSecretScanningDALFactory = ReturnType<typeof secretScanningDALFactory>;
export const secretScanningDalFactory = (db: TDbClient) => { export const secretScanningDALFactory = (db: TDbClient) => {
const gitRiskOrm = ormify(db, TableName.SecretScanningGitRisk); const gitRiskOrm = ormify(db, TableName.SecretScanningGitRisk);
const upsert = async (data: TSecretScanningGitRisksInsert[], tx?: Knex) => { const upsert = async (data: TSecretScanningGitRisksInsert[], tx?: Knex) => {
@@ -4,10 +4,10 @@ import { OrgMembershipRole } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger"; import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TOrgDalFactory } from "@app/services/org/org-dal"; import { TOrgDALFactory } from "@app/services/org/org-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service"; import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { TSecretScanningDalFactory } from "../secret-scanning-dal"; import { TSecretScanningDALFactory } from "../secret-scanning-dal";
import { import {
scanContentAndGetFindings, scanContentAndGetFindings,
scanFullRepoContentAndGetFindings scanFullRepoContentAndGetFindings
@@ -20,18 +20,18 @@ import {
type TSecretScanningQueueFactoryDep = { type TSecretScanningQueueFactoryDep = {
queueService: TQueueServiceFactory; queueService: TQueueServiceFactory;
secretScanningDal: TSecretScanningDalFactory; secretScanningDAL: TSecretScanningDALFactory;
smtpService: Pick<TSmtpService, "sendMail">; smtpService: Pick<TSmtpService, "sendMail">;
orgMembershipDal: Pick<TOrgDalFactory, "findMembership">; orgMembershipDAL: Pick<TOrgDALFactory, "findMembership">;
}; };
export type TSecretScanningQueueFactory = ReturnType<typeof secretScanningQueueFactory>; export type TSecretScanningQueueFactory = ReturnType<typeof secretScanningQueueFactory>;
export const secretScanningQueueFactory = ({ export const secretScanningQueueFactory = ({
queueService, queueService,
secretScanningDal, secretScanningDAL,
smtpService, smtpService,
orgMembershipDal: orgMemberDal, orgMembershipDAL: orgMemberDAL,
}: TSecretScanningQueueFactoryDep) => { }: TSecretScanningQueueFactoryDep) => {
const startFullRepoScan = async (payload: TScanFullRepoEventPayload) => { const startFullRepoScan = async (payload: TScanFullRepoEventPayload) => {
await queueService.queue(QueueName.SecretFullRepoScan, QueueJobs.SecretScan, payload, { await queueService.queue(QueueName.SecretFullRepoScan, QueueJobs.SecretScan, payload, {
@@ -63,7 +63,7 @@ export const secretScanningQueueFactory = ({
const getOrgAdminEmails = async (organizationId: string) => { const getOrgAdminEmails = async (organizationId: string) => {
// get emails of admins // get emails of admins
const adminsOfWork = await orgMemberDal.findMembership({ const adminsOfWork = await orgMemberDAL.findMembership({
orgId: organizationId, orgId: organizationId,
role: OrgMembershipRole.Admin role: OrgMembershipRole.Admin
}); });
@@ -112,9 +112,9 @@ export const secretScanningQueueFactory = ({
} }
} }
} }
await secretScanningDal.transaction(async (tx) => { await secretScanningDAL.transaction(async (tx) => {
if (!Object.keys(allFindingsByFingerprint).length) return; if (!Object.keys(allFindingsByFingerprint).length) return;
secretScanningDal.upsert( secretScanningDAL.upsert(
Object.keys(allFindingsByFingerprint).map((key) => ({ Object.keys(allFindingsByFingerprint).map((key) => ({
installationId, installationId,
email: allFindingsByFingerprint[key].Email, email: allFindingsByFingerprint[key].Email,
@@ -178,10 +178,10 @@ export const secretScanningQueueFactory = ({
installationId, installationId,
repository.fullName repository.fullName
); );
await secretScanningDal.transaction(async (tx) => { await secretScanningDAL.transaction(async (tx) => {
if (!findings.length) return; if (!findings.length) return;
// eslint-disable-next-line // eslint-disable-next-line
await secretScanningDal.upsert( await secretScanningDAL.upsert(
findings.map((finding) => ({ findings.map((finding) => ({
installationId, installationId,
email: finding.Email, email: finding.Email,
@@ -12,9 +12,9 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { UnauthorizedError } from "@app/lib/errors"; import { UnauthorizedError } from "@app/lib/errors";
import { TGitAppDalFactory } from "./git-app-dal"; import { TGitAppDALFactory } from "./git-app-dal";
import { TGitAppInstallSessionDalFactory } from "./git-app-install-session-dal"; import { TGitAppInstallSessionDALFactory } from "./git-app-install-session-dal";
import { TSecretScanningDalFactory } from "./secret-scanning-dal"; import { TSecretScanningDALFactory } from "./secret-scanning-dal";
import { TSecretScanningQueueFactory } from "./secret-scanning-queue"; import { TSecretScanningQueueFactory } from "./secret-scanning-queue";
import { import {
SecretScanningRiskStatus, SecretScanningRiskStatus,
@@ -27,18 +27,18 @@ import {
type TSecretScanningServiceFactoryDep = { type TSecretScanningServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">; permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
secretScanningDal: TSecretScanningDalFactory; secretScanningDAL: TSecretScanningDALFactory;
gitAppInstallSessionDal: TGitAppInstallSessionDalFactory; gitAppInstallSessionDAL: TGitAppInstallSessionDALFactory;
gitAppOrgDal: TGitAppDalFactory; gitAppOrgDAL: TGitAppDALFactory;
secretScanningQueue: TSecretScanningQueueFactory; secretScanningQueue: TSecretScanningQueueFactory;
}; };
export type TSecretScanningServiceFactory = ReturnType<typeof secretScanningServiceFactory>; export type TSecretScanningServiceFactory = ReturnType<typeof secretScanningServiceFactory>;
export const secretScanningServiceFactory = ({ export const secretScanningServiceFactory = ({
secretScanningDal, secretScanningDAL,
gitAppOrgDal, gitAppOrgDAL,
gitAppInstallSessionDal, gitAppInstallSessionDAL,
permissionService, permissionService,
secretScanningQueue secretScanningQueue
}: TSecretScanningServiceFactoryDep) => { }: TSecretScanningServiceFactoryDep) => {
@@ -50,7 +50,7 @@ export const secretScanningServiceFactory = ({
); );
const sessionId = crypto.randomBytes(16).toString("hex"); const sessionId = crypto.randomBytes(16).toString("hex");
await gitAppInstallSessionDal.upsert({ orgId, sessionId, userId: actorId }); await gitAppInstallSessionDAL.upsert({ orgId, sessionId, userId: actorId });
return { sessionId }; return { sessionId };
}; };
@@ -60,7 +60,7 @@ export const secretScanningServiceFactory = ({
installationId, installationId,
actor actor
}: TLinkInstallSessionDTO) => { }: TLinkInstallSessionDTO) => {
const session = await gitAppInstallSessionDal.findOne({ sessionId }); const session = await gitAppInstallSessionDAL.findOne({ sessionId });
if (!session) throw new UnauthorizedError({ message: "Session not found" }); if (!session) throw new UnauthorizedError({ message: "Session not found" });
const { permission } = await permissionService.getOrgPermission(actor, actorId, session.orgId); const { permission } = await permissionService.getOrgPermission(actor, actorId, session.orgId);
@@ -68,9 +68,9 @@ export const secretScanningServiceFactory = ({
OrgPermissionActions.Create, OrgPermissionActions.Create,
OrgPermissionSubjects.SecretScanning OrgPermissionSubjects.SecretScanning
); );
const installatedApp = await gitAppOrgDal.transaction(async (tx) => { const installatedApp = await gitAppOrgDAL.transaction(async (tx) => {
await gitAppInstallSessionDal.deleteById(session.id, tx); await gitAppInstallSessionDAL.deleteById(session.id, tx);
return gitAppOrgDal.upsert({ orgId: session.orgId, installationId, userId: actorId }, tx); return gitAppOrgDAL.upsert({ orgId: session.orgId, installationId, userId: actorId }, tx);
}); });
const appCfg = getConfig(); const appCfg = getConfig();
@@ -104,7 +104,7 @@ export const secretScanningServiceFactory = ({
OrgPermissionSubjects.SecretScanning OrgPermissionSubjects.SecretScanning
); );
const appInstallation = await gitAppOrgDal.findOne({ orgId }); const appInstallation = await gitAppOrgDAL.findOne({ orgId });
return Boolean(appInstallation); return Boolean(appInstallation);
}; };
@@ -114,7 +114,7 @@ export const secretScanningServiceFactory = ({
OrgPermissionActions.Read, OrgPermissionActions.Read,
OrgPermissionSubjects.SecretScanning OrgPermissionSubjects.SecretScanning
); );
const risks = await secretScanningDal.find({ orgId }, { sort: [["createdAt", "desc"]] }); const risks = await secretScanningDAL.find({ orgId }, { sort: [["createdAt", "desc"]] });
return { risks }; return { risks };
}; };
@@ -139,7 +139,7 @@ export const secretScanningServiceFactory = ({
].includes(status) ].includes(status)
); );
const risk = await secretScanningDal.updateById(riskId, { const risk = await secretScanningDAL.updateById(riskId, {
status, status,
isResolved: isRiskResolved isResolved: isRiskResolved
}); });
@@ -152,7 +152,7 @@ export const secretScanningServiceFactory = ({
return; return;
} }
const installationLink = await gitAppOrgDal.findOne({ const installationLink = await gitAppOrgDAL.findOne({
installationId: String(installation.id) installationId: String(installation.id)
}); });
if (!installationLink) return; if (!installationLink) return;
@@ -167,15 +167,15 @@ export const secretScanningServiceFactory = ({
}; };
const handleRepoDeleteEvent = async (installationId: string, repositoryIds: string[]) => { const handleRepoDeleteEvent = async (installationId: string, repositoryIds: string[]) => {
await secretScanningDal.transaction(async (tx) => { await secretScanningDAL.transaction(async (tx) => {
if (repositoryIds.length) { if (repositoryIds.length) {
await Promise.all( await Promise.all(
repositoryIds.map((repoId) => repositoryIds.map((repoId) =>
secretScanningDal.delete({ repositoryId: repoId }, tx) secretScanningDAL.delete({ repositoryId: repoId }, tx)
) )
); );
} }
await gitAppOrgDal.delete({ installationId }, tx); await gitAppOrgDAL.delete({ installationId }, tx);
}); });
}; };
@@ -3,10 +3,10 @@ import { ForbiddenError } from "@casl/ability";
import { BadRequestError, InternalServerError } from "@app/lib/errors"; import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn"; import { groupBy } from "@app/lib/fn";
import { logger } from "@app/lib/logger"; import { logger } from "@app/lib/logger";
import { TSecretDalFactory } from "@app/services/secret/secret-dal"; import { TSecretDALFactory } from "@app/services/secret/secret-dal";
import { TSecretVersionDalFactory } from "@app/services/secret/secret-version-dal"; import { TSecretVersionDALFactory } from "@app/services/secret/secret-version-dal";
import { TSecretFolderDalFactory } from "@app/services/secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TSecretFolderVersionDalFactory } from "@app/services/secret-folder/secret-folder-version-dal"; import { TSecretFolderVersionDALFactory } from "@app/services/secret-folder/secret-folder-version-dal";
import { TLicenseServiceFactory } from "../license/license-service"; import { TLicenseServiceFactory } from "../license/license-service";
import { TPermissionServiceFactory } from "../permission/permission-service"; import { TPermissionServiceFactory } from "../permission/permission-service";
@@ -17,22 +17,22 @@ import {
TProjectSnapshotListDTO, TProjectSnapshotListDTO,
TRollbackSnapshotDTO TRollbackSnapshotDTO
} from "./secret-snapshot-types"; } from "./secret-snapshot-types";
import { TSnapshotDalFactory } from "./snapshot-dal"; import { TSnapshotDALFactory } from "./snapshot-dal";
import { TSnapshotFolderDalFactory } from "./snapshot-folder-dal"; import { TSnapshotFolderDALFactory } from "./snapshot-folder-dal";
import { TSnapshotSecretDalFactory } from "./snapshot-secret-dal"; import { TSnapshotSecretDALFactory } from "./snapshot-secret-dal";
type TSecretSnapshotServiceFactoryDep = { type TSecretSnapshotServiceFactoryDep = {
snapshotDal: TSnapshotDalFactory; snapshotDAL: TSnapshotDALFactory;
snapshotSecretDal: TSnapshotSecretDalFactory; snapshotSecretDAL: TSnapshotSecretDALFactory;
snapshotFolderDal: TSnapshotFolderDalFactory; snapshotFolderDAL: TSnapshotFolderDALFactory;
secretVersionDal: Pick<TSecretVersionDalFactory, "insertMany" | "findLatestVersionByFolderId">; secretVersionDAL: Pick<TSecretVersionDALFactory, "insertMany" | "findLatestVersionByFolderId">;
folderVersionDal: Pick< folderVersionDAL: Pick<
TSecretFolderVersionDalFactory, TSecretFolderVersionDALFactory,
"findLatestVersionByFolderId" | "insertMany" "findLatestVersionByFolderId" | "insertMany"
>; >;
secretDal: Pick<TSecretDalFactory, "delete" | "insertMany">; secretDAL: Pick<TSecretDALFactory, "delete" | "insertMany">;
folderDal: Pick< folderDAL: Pick<
TSecretFolderDalFactory, TSecretFolderDALFactory,
"findById" | "findBySecretPath" | "delete" | "insertMany" "findById" | "findBySecretPath" | "delete" | "insertMany"
>; >;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
@@ -42,13 +42,13 @@ type TSecretSnapshotServiceFactoryDep = {
export type TSecretSnapshotServiceFactory = ReturnType<typeof secretSnapshotServiceFactory>; export type TSecretSnapshotServiceFactory = ReturnType<typeof secretSnapshotServiceFactory>;
export const secretSnapshotServiceFactory = ({ export const secretSnapshotServiceFactory = ({
snapshotDal, snapshotDAL,
folderVersionDal, folderVersionDAL,
secretVersionDal, secretVersionDAL,
snapshotSecretDal, snapshotSecretDAL,
snapshotFolderDal, snapshotFolderDAL,
folderDal, folderDAL,
secretDal, secretDAL,
permissionService, permissionService,
licenseService licenseService
}: TSecretSnapshotServiceFactoryDep) => { }: TSecretSnapshotServiceFactoryDep) => {
@@ -65,10 +65,10 @@ export const secretSnapshotServiceFactory = ({
ProjectPermissionSub.SecretRollback ProjectPermissionSub.SecretRollback
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found" }); if (!folder) throw new BadRequestError({ message: "Folder not found" });
const count = await snapshotDal.countOfSnapshotsByFolderId(folder.id); const count = await snapshotDAL.countOfSnapshotsByFolderId(folder.id);
return count; return count;
}; };
@@ -87,10 +87,10 @@ export const secretSnapshotServiceFactory = ({
ProjectPermissionSub.SecretRollback ProjectPermissionSub.SecretRollback
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found" }); if (!folder) throw new BadRequestError({ message: "Folder not found" });
const snapshots = await snapshotDal.find( const snapshots = await snapshotDAL.find(
{ folderId: folder.id }, { folderId: folder.id },
{ limit, offset, sort: [["createdAt", "desc"]] } { limit, offset, sort: [["createdAt", "desc"]] }
); );
@@ -98,7 +98,7 @@ export const secretSnapshotServiceFactory = ({
}; };
const getSnapshotData = async ({ actorId, actor, id }: TGetSnapshotDataDTO) => { const getSnapshotData = async ({ actorId, actor, id }: TGetSnapshotDataDTO) => {
const snapshot = await snapshotDal.findSecretSnapshotDataById(id); const snapshot = await snapshotDAL.findSecretSnapshotDataById(id);
if (!snapshot) throw new BadRequestError({ message: "Snapshot not found" }); if (!snapshot) throw new BadRequestError({ message: "Snapshot not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@@ -117,13 +117,13 @@ export const secretSnapshotServiceFactory = ({
if (!licenseService.isValidLicense) if (!licenseService.isValidLicense)
throw new InternalServerError({ message: "Invalid license" }); throw new InternalServerError({ message: "Invalid license" });
const snapshot = await snapshotDal.transaction(async (tx) => { const snapshot = await snapshotDAL.transaction(async (tx) => {
const folder = await folderDal.findById(folderId, tx); const folder = await folderDAL.findById(folderId, tx);
if (!folder) throw new BadRequestError({ message: "Folder not found" }); if (!folder) throw new BadRequestError({ message: "Folder not found" });
const secretVersions = await secretVersionDal.findLatestVersionByFolderId(folderId, tx); const secretVersions = await secretVersionDAL.findLatestVersionByFolderId(folderId, tx);
const folderVersions = await folderVersionDal.findLatestVersionByFolderId(folderId, tx); const folderVersions = await folderVersionDAL.findLatestVersionByFolderId(folderId, tx);
const newSnapshot = await snapshotDal.create( const newSnapshot = await snapshotDAL.create(
{ {
folderId, folderId,
envId: folder.environment.envId, envId: folder.environment.envId,
@@ -131,7 +131,7 @@ export const secretSnapshotServiceFactory = ({
}, },
tx tx
); );
const snapshotSecrets = await snapshotSecretDal.insertMany( const snapshotSecrets = await snapshotSecretDAL.insertMany(
secretVersions.map(({ id }) => ({ secretVersions.map(({ id }) => ({
secretVersionId: id, secretVersionId: id,
envId: folder.environment.envId, envId: folder.environment.envId,
@@ -139,7 +139,7 @@ export const secretSnapshotServiceFactory = ({
})), })),
tx tx
); );
const snapshotFolders = await snapshotFolderDal.insertMany( const snapshotFolders = await snapshotFolderDAL.insertMany(
folderVersions.map(({ id }) => ({ folderVersions.map(({ id }) => ({
folderVersionId: id, folderVersionId: id,
envId: folder.environment.envId, envId: folder.environment.envId,
@@ -160,7 +160,7 @@ export const secretSnapshotServiceFactory = ({
}; };
const rollbackSnapshot = async ({ id: snapshotId, actor, actorId }: TRollbackSnapshotDTO) => { const rollbackSnapshot = async ({ id: snapshotId, actor, actorId }: TRollbackSnapshotDTO) => {
const snapshot = await snapshotDal.findById(snapshotId); const snapshot = await snapshotDAL.findById(snapshotId);
if (!snapshot) throw new BadRequestError({ message: "Snapshot not found" }); if (!snapshot) throw new BadRequestError({ message: "Snapshot not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -173,19 +173,19 @@ export const secretSnapshotServiceFactory = ({
ProjectPermissionSub.SecretRollback ProjectPermissionSub.SecretRollback
); );
const rollback = await snapshotDal.transaction(async (tx) => { const rollback = await snapshotDAL.transaction(async (tx) => {
const rollbackSnaps = await snapshotDal.findRecursivelySnapshots(snapshot.id, tx); const rollbackSnaps = await snapshotDAL.findRecursivelySnapshots(snapshot.id, tx);
// this will remove all secrets in current folder // this will remove all secrets in current folder
const deletedTopLevelSecs = await secretDal.delete({ folderId: snapshot.folderId }, tx); const deletedTopLevelSecs = await secretDAL.delete({ folderId: snapshot.folderId }, tx);
const deletedTopLevelSecsGroupById = groupBy(deletedTopLevelSecs, (item) => item.id); const deletedTopLevelSecsGroupById = groupBy(deletedTopLevelSecs, (item) => item.id);
// this will remove all secrets and folders on child // this will remove all secrets and folders on child
// due to sql foreign key and link list connection removing the folders removes everything below too // due to sql foreign key and link list connection removing the folders removes everything below too
const deletedFolders = await folderDal.delete({ parentId: snapshot.folderId }, tx); const deletedFolders = await folderDAL.delete({ parentId: snapshot.folderId }, tx);
const deletedTopLevelFolders = groupBy( const deletedTopLevelFolders = groupBy(
deletedFolders.filter(({ parentId }) => parentId === snapshot.folderId), deletedFolders.filter(({ parentId }) => parentId === snapshot.folderId),
(item) => item.id (item) => item.id
); );
const folders = await folderDal.insertMany( const folders = await folderDAL.insertMany(
rollbackSnaps.flatMap(({ folderVersion, folderId }) => rollbackSnaps.flatMap(({ folderVersion, folderId }) =>
folderVersion.map(({ name, id, latestFolderVersion }) => ({ folderVersion.map(({ name, id, latestFolderVersion }) => ({
envId: snapshot.envId, envId: snapshot.envId,
@@ -197,7 +197,7 @@ export const secretSnapshotServiceFactory = ({
), ),
tx tx
); );
const secrets = await secretDal.insertMany( const secrets = await secretDAL.insertMany(
rollbackSnaps.flatMap(({ secretVersions, folderId }) => rollbackSnaps.flatMap(({ secretVersions, folderId }) =>
secretVersions.map( secretVersions.map(
({ ({
@@ -219,7 +219,7 @@ export const secretSnapshotServiceFactory = ({
), ),
tx tx
); );
const folderVersions = await folderVersionDal.insertMany( const folderVersions = await folderVersionDAL.insertMany(
folders.map(({ version, name, id, envId }) => ({ folders.map(({ version, name, id, envId }) => ({
name, name,
version, version,
@@ -228,11 +228,11 @@ export const secretSnapshotServiceFactory = ({
})), })),
tx tx
); );
const secretVersions = await secretVersionDal.insertMany( const secretVersions = await secretVersionDAL.insertMany(
secrets.map(({ id, updatedAt, createdAt, ...el }) => ({ ...el, secretId: id })), secrets.map(({ id, updatedAt, createdAt, ...el }) => ({ ...el, secretId: id })),
tx tx
); );
const newSnapshot = await snapshotDal.create( const newSnapshot = await snapshotDAL.create(
{ {
folderId: snapshot.folderId, folderId: snapshot.folderId,
envId: snapshot.envId, envId: snapshot.envId,
@@ -240,7 +240,7 @@ export const secretSnapshotServiceFactory = ({
}, },
tx tx
); );
const snapshotSecrets = await snapshotSecretDal.insertMany( const snapshotSecrets = await snapshotSecretDAL.insertMany(
secretVersions secretVersions
.filter(({ secretId }) => Boolean(deletedTopLevelSecsGroupById?.[secretId])) .filter(({ secretId }) => Boolean(deletedTopLevelSecsGroupById?.[secretId]))
.map(({ id }) => ({ .map(({ id }) => ({
@@ -250,7 +250,7 @@ export const secretSnapshotServiceFactory = ({
})), })),
tx tx
); );
const snapshotFolders = await snapshotFolderDal.insertMany( const snapshotFolders = await snapshotFolderDAL.insertMany(
folderVersions folderVersions
.filter(({ folderId }) => Boolean(deletedTopLevelFolders?.[folderId])) .filter(({ folderId }) => Boolean(deletedTopLevelFolders?.[folderId]))
.map(({ id }) => ({ .map(({ id }) => ({
@@ -12,9 +12,9 @@ import {
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex"; import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
export type TSnapshotDalFactory = ReturnType<typeof snapshotDalFactory>; export type TSnapshotDALFactory = ReturnType<typeof snapshotDALFactory>;
export const snapshotDalFactory = (db: TDbClient) => { export const snapshotDALFactory = (db: TDbClient) => {
const secretSnapshotOrm = ormify(db, TableName.Snapshot); const secretSnapshotOrm = ormify(db, TableName.Snapshot);
const findById = async (id: string, tx?: Knex) => { const findById = async (id: string, tx?: Knex) => {
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSnapshotFolderDalFactory = ReturnType<typeof snapshotFolderDalFactory>; export type TSnapshotFolderDALFactory = ReturnType<typeof snapshotFolderDALFactory>;
export const snapshotFolderDalFactory = (db: TDbClient) => { export const snapshotFolderDALFactory = (db: TDbClient) => {
const snapshotFolderOrm = ormify(db, TableName.SnapshotFolder); const snapshotFolderOrm = ormify(db, TableName.SnapshotFolder);
return snapshotFolderOrm; return snapshotFolderOrm;
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSnapshotSecretDalFactory = ReturnType<typeof snapshotSecretDalFactory>; export type TSnapshotSecretDALFactory = ReturnType<typeof snapshotSecretDALFactory>;
export const snapshotSecretDalFactory = (db: TDbClient) => { export const snapshotSecretDALFactory = (db: TDbClient) => {
const snapshotSecretOrm = ormify(db, TableName.SnapshotSecret); const snapshotSecretOrm = ormify(db, TableName.SnapshotSecret);
return snapshotSecretOrm; return snapshotSecretOrm;
}; };
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TTrustedIpDalFactory = ReturnType<typeof trustedIpDalFactory>; export type TTrustedIpDALFactory = ReturnType<typeof trustedIpDALFactory>;
export const trustedIpDalFactory = (db: TDbClient) => { export const trustedIpDALFactory = (db: TDbClient) => {
const trustedIpOrm = ormify(db, TableName.TrustedIps); const trustedIpOrm = ormify(db, TableName.TrustedIps);
return trustedIpOrm; return trustedIpOrm;
}; };
@@ -3,28 +3,28 @@ import { ForbiddenError } from "@casl/ability";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";
import { TProjectPermission } from "@app/lib/types"; import { TProjectPermission } from "@app/lib/types";
import { TProjectDalFactory } from "@app/services/project/project-dal"; import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TLicenseServiceFactory } from "../license/license-service"; import { TLicenseServiceFactory } from "../license/license-service";
import { TPermissionServiceFactory } from "../permission/permission-service"; import { TPermissionServiceFactory } from "../permission/permission-service";
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission"; import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
import { TTrustedIpDalFactory } from "./trusted-ip-dal"; import { TTrustedIpDALFactory } from "./trusted-ip-dal";
import { TCreateIpDTO, TDeleteIpDTO, TUpdateIpDTO } from "./trusted-ip-types"; import { TCreateIpDTO, TDeleteIpDTO, TUpdateIpDTO } from "./trusted-ip-types";
type TTrustedIpServiceFactoryDep = { type TTrustedIpServiceFactoryDep = {
trustedIpDal: TTrustedIpDalFactory; trustedIpDAL: TTrustedIpDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
projectDal: Pick<TProjectDalFactory, "findById">; projectDAL: Pick<TProjectDALFactory, "findById">;
}; };
export type TTrustedIpServiceFactory = ReturnType<typeof trustedIpServiceFactory>; export type TTrustedIpServiceFactory = ReturnType<typeof trustedIpServiceFactory>;
export const trustedIpServiceFactory = ({ export const trustedIpServiceFactory = ({
trustedIpDal, trustedIpDAL,
permissionService, permissionService,
licenseService, licenseService,
projectDal projectDAL
}: TTrustedIpServiceFactoryDep) => { }: TTrustedIpServiceFactoryDep) => {
const listIpsByProjectId = async ({ projectId, actor, actorId }: TProjectPermission) => { const listIpsByProjectId = async ({ projectId, actor, actorId }: TProjectPermission) => {
const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId); const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId);
@@ -32,7 +32,7 @@ export const trustedIpServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
ProjectPermissionSub.IpAllowList ProjectPermissionSub.IpAllowList
); );
const trustedIps = await trustedIpDal.find({ const trustedIps = await trustedIpDAL.find({
projectId projectId
}); });
return trustedIps; return trustedIps;
@@ -52,7 +52,7 @@ export const trustedIpServiceFactory = ({
ProjectPermissionSub.IpAllowList ProjectPermissionSub.IpAllowList
); );
const project = await projectDal.findById(projectId); const project = await projectDAL.findById(projectId);
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
if (!plan.ipAllowlisting) if (!plan.ipAllowlisting)
throw new BadRequestError({ throw new BadRequestError({
@@ -67,7 +67,7 @@ export const trustedIpServiceFactory = ({
}); });
const { ipAddress, type, prefix } = extractIPDetails(ip); const { ipAddress, type, prefix } = extractIPDetails(ip);
const trustedIp = await trustedIpDal.create({ const trustedIp = await trustedIpDAL.create({
projectId, projectId,
ipAddress, ipAddress,
type, type,
@@ -93,7 +93,7 @@ export const trustedIpServiceFactory = ({
ProjectPermissionSub.IpAllowList ProjectPermissionSub.IpAllowList
); );
const project = await projectDal.findById(projectId); const project = await projectDAL.findById(projectId);
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
if (!plan.ipAllowlisting) if (!plan.ipAllowlisting)
throw new BadRequestError({ throw new BadRequestError({
@@ -108,7 +108,7 @@ export const trustedIpServiceFactory = ({
}); });
const { ipAddress, type, prefix } = extractIPDetails(ip); const { ipAddress, type, prefix } = extractIPDetails(ip);
const [trustedIp] = await trustedIpDal.update( const [trustedIp] = await trustedIpDAL.update(
{ projectId, id: trustedIpId }, { projectId, id: trustedIpId },
{ {
projectId, projectId,
@@ -129,7 +129,7 @@ export const trustedIpServiceFactory = ({
ProjectPermissionSub.IpAllowList ProjectPermissionSub.IpAllowList
); );
const project = await projectDal.findById(projectId); const project = await projectDAL.findById(projectId);
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
if (!plan.ipAllowlisting) if (!plan.ipAllowlisting)
throw new BadRequestError({ throw new BadRequestError({
@@ -137,7 +137,7 @@ export const trustedIpServiceFactory = ({
"Failed to add IP access range due to plan restriction. Upgrade plan to add IP access range." "Failed to add IP access range due to plan restriction. Upgrade plan to add IP access range."
}); });
const [trustedIp] = await trustedIpDal.delete({ projectId, id: trustedIpId }); const [trustedIp] = await trustedIpDAL.delete({ projectId, id: trustedIpId });
return { trustedIp, project }; // for audit log return { trustedIp, project }; // for audit log
}; };
+220 -220
View File
@@ -2,98 +2,98 @@ import { Knex } from "knex";
import { z } from "zod"; import { z } from "zod";
import { registerV1EERoutes } from "@app/ee/routes/v1"; import { registerV1EERoutes } from "@app/ee/routes/v1";
import { auditLogDalFactory } from "@app/ee/services/audit-log/audit-log-dal"; import { auditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";
import { auditLogQueueServiceFactory } from "@app/ee/services/audit-log/audit-log-queue"; import { auditLogQueueServiceFactory } from "@app/ee/services/audit-log/audit-log-queue";
import { auditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-service"; import { auditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-service";
import { licenseDalFactory } from "@app/ee/services/license/license-dal"; import { licenseDALFactory } from "@app/ee/services/license/license-dal";
import { licenseServiceFactory } from "@app/ee/services/license/license-service"; import { licenseServiceFactory } from "@app/ee/services/license/license-service";
import { permissionDalFactory } from "@app/ee/services/permission/permission-dal"; import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";
import { permissionServiceFactory } from "@app/ee/services/permission/permission-service"; import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";
import { samlConfigDalFactory } from "@app/ee/services/saml-config/saml-config-dal"; import { samlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";
import { samlConfigServiceFactory } from "@app/ee/services/saml-config/saml-config-service"; import { samlConfigServiceFactory } from "@app/ee/services/saml-config/saml-config-service";
import { sapApproverDalFactory } from "@app/ee/services/secret-approval-policy/sap-approver-dal"; import { sapApproverDALFactory } from "@app/ee/services/secret-approval-policy/sap-approver-dal";
import { secretApprovalPolicyDalFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-dal"; import { secretApprovalPolicyDALFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-dal";
import { secretApprovalPolicyServiceFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-service"; import { secretApprovalPolicyServiceFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-service";
import { sarReviewerDalFactory } from "@app/ee/services/secret-approval-request/sar-reviewer-dal"; import { sarReviewerDALFactory } from "@app/ee/services/secret-approval-request/sar-reviewer-dal";
import { sarSecretDalFactory } from "@app/ee/services/secret-approval-request/sar-secret-dal"; import { sarSecretDALFactory } from "@app/ee/services/secret-approval-request/sar-secret-dal";
import { secretApprovalRequestDalFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-dal"; import { secretApprovalRequestDALFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-dal";
import { secretApprovalRequestServiceFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-service"; import { secretApprovalRequestServiceFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-service";
import { secretRotationDalFactory } from "@app/ee/services/secret-rotation/secret-rotation-dal"; import { secretRotationDALFactory } from "@app/ee/services/secret-rotation/secret-rotation-dal";
import { secretRotationQueueFactory } from "@app/ee/services/secret-rotation/secret-rotation-queue"; import { secretRotationQueueFactory } from "@app/ee/services/secret-rotation/secret-rotation-queue";
import { secretRotationServiceFactory } from "@app/ee/services/secret-rotation/secret-rotation-service"; import { secretRotationServiceFactory } from "@app/ee/services/secret-rotation/secret-rotation-service";
import { gitAppDalFactory } from "@app/ee/services/secret-scanning/git-app-dal"; import { gitAppDALFactory } from "@app/ee/services/secret-scanning/git-app-dal";
import { gitAppInstallSessionDalFactory } from "@app/ee/services/secret-scanning/git-app-install-session-dal"; import { gitAppInstallSessionDALFactory } from "@app/ee/services/secret-scanning/git-app-install-session-dal";
import { secretScanningDalFactory } from "@app/ee/services/secret-scanning/secret-scanning-dal"; import { secretScanningDALFactory } from "@app/ee/services/secret-scanning/secret-scanning-dal";
import { secretScanningQueueFactory } from "@app/ee/services/secret-scanning/secret-scanning-queue"; import { secretScanningQueueFactory } from "@app/ee/services/secret-scanning/secret-scanning-queue";
import { secretScanningServiceFactory } from "@app/ee/services/secret-scanning/secret-scanning-service"; import { secretScanningServiceFactory } from "@app/ee/services/secret-scanning/secret-scanning-service";
import { secretSnapshotServiceFactory } from "@app/ee/services/secret-snapshot/secret-snapshot-service"; import { secretSnapshotServiceFactory } from "@app/ee/services/secret-snapshot/secret-snapshot-service";
import { snapshotDalFactory } from "@app/ee/services/secret-snapshot/snapshot-dal"; import { snapshotDALFactory } from "@app/ee/services/secret-snapshot/snapshot-dal";
import { snapshotFolderDalFactory } from "@app/ee/services/secret-snapshot/snapshot-folder-dal"; import { snapshotFolderDALFactory } from "@app/ee/services/secret-snapshot/snapshot-folder-dal";
import { snapshotSecretDalFactory } from "@app/ee/services/secret-snapshot/snapshot-secret-dal"; import { snapshotSecretDALFactory } from "@app/ee/services/secret-snapshot/snapshot-secret-dal";
import { trustedIpDalFactory } from "@app/ee/services/trusted-ip/trusted-ip-dal"; import { trustedIpDALFactory } from "@app/ee/services/trusted-ip/trusted-ip-dal";
import { trustedIpServiceFactory } from "@app/ee/services/trusted-ip/trusted-ip-service"; import { trustedIpServiceFactory } from "@app/ee/services/trusted-ip/trusted-ip-service";
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { TQueueServiceFactory } from "@app/queue"; import { TQueueServiceFactory } from "@app/queue";
import { apiKeyDalFactory } from "@app/services/api-key/api-key-dal"; import { apiKeyDALFactory } from "@app/services/api-key/api-key-dal";
import { apiKeyServiceFactory } from "@app/services/api-key/api-key-service"; import { apiKeyServiceFactory } from "@app/services/api-key/api-key-service";
import { authDalFactory } from "@app/services/auth/auth-dal"; import { authDALFactory } from "@app/services/auth/auth-dal";
import { authLoginServiceFactory } from "@app/services/auth/auth-login-service"; import { authLoginServiceFactory } from "@app/services/auth/auth-login-service";
import { authPaswordServiceFactory } from "@app/services/auth/auth-password-service"; import { authPaswordServiceFactory } from "@app/services/auth/auth-password-service";
import { authSignupServiceFactory } from "@app/services/auth/auth-signup-service"; import { authSignupServiceFactory } from "@app/services/auth/auth-signup-service";
import { tokenDalFactory } from "@app/services/auth-token/auth-token-dal"; import { tokenDALFactory } from "@app/services/auth-token/auth-token-dal";
import { tokenServiceFactory } from "@app/services/auth-token/auth-token-service"; import { tokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { identityDalFactory } from "@app/services/identity/identity-dal"; import { identityDALFactory } from "@app/services/identity/identity-dal";
import { identityOrgDalFactory } from "@app/services/identity/identity-org-dal"; import { identityOrgDALFactory } from "@app/services/identity/identity-org-dal";
import { identityServiceFactory } from "@app/services/identity/identity-service"; import { identityServiceFactory } from "@app/services/identity/identity-service";
import { identityAccessTokenDalFactory } from "@app/services/identity-access-token/identity-access-token-dal"; import { identityAccessTokenDALFactory } from "@app/services/identity-access-token/identity-access-token-dal";
import { identityAccessTokenServiceFactory } from "@app/services/identity-access-token/identity-access-token-service"; import { identityAccessTokenServiceFactory } from "@app/services/identity-access-token/identity-access-token-service";
import { identityProjectDalFactory } from "@app/services/identity-project/identity-project-dal"; import { identityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";
import { identityProjectServiceFactory } from "@app/services/identity-project/identity-project-service"; import { identityProjectServiceFactory } from "@app/services/identity-project/identity-project-service";
import { identityUaClientSecretDalFactory } from "@app/services/identity-ua/identity-ua-client-secret-dal"; import { identityUaClientSecretDALFactory } from "@app/services/identity-ua/identity-ua-client-secret-dal";
import { identityUaDalFactory } from "@app/services/identity-ua/identity-ua-dal"; import { identityUaDALFactory } from "@app/services/identity-ua/identity-ua-dal";
import { identityUaServiceFactory } from "@app/services/identity-ua/identity-ua-service"; import { identityUaServiceFactory } from "@app/services/identity-ua/identity-ua-service";
import { integrationDalFactory } from "@app/services/integration/integration-dal"; import { integrationDALFactory } from "@app/services/integration/integration-dal";
import { integrationServiceFactory } from "@app/services/integration/integration-service"; import { integrationServiceFactory } from "@app/services/integration/integration-service";
import { integrationAuthDalFactory } from "@app/services/integration-auth/integration-auth-dal"; import { integrationAuthDALFactory } from "@app/services/integration-auth/integration-auth-dal";
import { integrationAuthServiceFactory } from "@app/services/integration-auth/integration-auth-service"; import { integrationAuthServiceFactory } from "@app/services/integration-auth/integration-auth-service";
import { incidentContactDalFactory } from "@app/services/org/incident-contacts-dal"; import { incidentContactDALFactory } from "@app/services/org/incident-contacts-dal";
import { orgBotDalFactory } from "@app/services/org/org-bot-dal"; import { orgBotDALFactory } from "@app/services/org/org-bot-dal";
import { orgDalFactory } from "@app/services/org/org-dal"; import { orgDALFactory } from "@app/services/org/org-dal";
import { orgRoleDalFactory } from "@app/services/org/org-role-dal"; import { orgRoleDALFactory } from "@app/services/org/org-role-dal";
import { orgRoleServiceFactory } from "@app/services/org/org-role-service"; import { orgRoleServiceFactory } from "@app/services/org/org-role-service";
import { orgServiceFactory } from "@app/services/org/org-service"; import { orgServiceFactory } from "@app/services/org/org-service";
import { projectDalFactory } from "@app/services/project/project-dal"; import { projectDALFactory } from "@app/services/project/project-dal";
import { projectServiceFactory } from "@app/services/project/project-service"; import { projectServiceFactory } from "@app/services/project/project-service";
import { projectBotDalFactory } from "@app/services/project-bot/project-bot-dal"; import { projectBotDALFactory } from "@app/services/project-bot/project-bot-dal";
import { projectBotServiceFactory } from "@app/services/project-bot/project-bot-service"; import { projectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
import { projectEnvDalFactory } from "@app/services/project-env/project-env-dal"; import { projectEnvDALFactory } from "@app/services/project-env/project-env-dal";
import { projectEnvServiceFactory } from "@app/services/project-env/project-env-service"; import { projectEnvServiceFactory } from "@app/services/project-env/project-env-service";
import { projectKeyDalFactory } from "@app/services/project-key/project-key-dal"; import { projectKeyDALFactory } from "@app/services/project-key/project-key-dal";
import { projectKeyServiceFactory } from "@app/services/project-key/project-key-service"; import { projectKeyServiceFactory } from "@app/services/project-key/project-key-service";
import { projectMembershipDalFactory } from "@app/services/project-membership/project-membership-dal"; import { projectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
import { projectMembershipServiceFactory } from "@app/services/project-membership/project-membership-service"; import { projectMembershipServiceFactory } from "@app/services/project-membership/project-membership-service";
import { projectRoleDalFactory } from "@app/services/project-role/project-role-dal"; import { projectRoleDALFactory } from "@app/services/project-role/project-role-dal";
import { projectRoleServiceFactory } from "@app/services/project-role/project-role-service"; import { projectRoleServiceFactory } from "@app/services/project-role/project-role-service";
import { secretBlindIndexDalFactory } from "@app/services/secret/secret-blind-index-dal"; import { secretBlindIndexDALFactory } from "@app/services/secret/secret-blind-index-dal";
import { secretDalFactory } from "@app/services/secret/secret-dal"; import { secretDALFactory } from "@app/services/secret/secret-dal";
import { secretQueueFactory } from "@app/services/secret/secret-queue"; import { secretQueueFactory } from "@app/services/secret/secret-queue";
import { secretServiceFactory } from "@app/services/secret/secret-service"; import { secretServiceFactory } from "@app/services/secret/secret-service";
import { secretVersionDalFactory } from "@app/services/secret/secret-version-dal"; import { secretVersionDALFactory } from "@app/services/secret/secret-version-dal";
import { secretFolderDalFactory } from "@app/services/secret-folder/secret-folder-dal"; import { secretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { secretFolderServiceFactory } from "@app/services/secret-folder/secret-folder-service"; import { secretFolderServiceFactory } from "@app/services/secret-folder/secret-folder-service";
import { secretFolderVersionDalFactory } from "@app/services/secret-folder/secret-folder-version-dal"; import { secretFolderVersionDALFactory } from "@app/services/secret-folder/secret-folder-version-dal";
import { secretImportDalFactory } from "@app/services/secret-import/secret-import-dal"; import { secretImportDALFactory } from "@app/services/secret-import/secret-import-dal";
import { secretImportServiceFactory } from "@app/services/secret-import/secret-import-service"; import { secretImportServiceFactory } from "@app/services/secret-import/secret-import-service";
import { secretTagDalFactory } from "@app/services/secret-tag/secret-tag-dal"; import { secretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
import { secretTagServiceFactory } from "@app/services/secret-tag/secret-tag-service"; import { secretTagServiceFactory } from "@app/services/secret-tag/secret-tag-service";
import { serviceTokenDalFactory } from "@app/services/service-token/service-token-dal"; import { serviceTokenDALFactory } from "@app/services/service-token/service-token-dal";
import { serviceTokenServiceFactory } from "@app/services/service-token/service-token-service"; import { serviceTokenServiceFactory } from "@app/services/service-token/service-token-service";
import { TSmtpService } from "@app/services/smtp/smtp-service"; import { TSmtpService } from "@app/services/smtp/smtp-service";
import { superAdminDalFactory } from "@app/services/super-admin/super-admin-dal"; import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
import { superAdminServiceFactory } from "@app/services/super-admin/super-admin-service"; import { superAdminServiceFactory } from "@app/services/super-admin/super-admin-service";
import { userDalFactory } from "@app/services/user/user-dal"; import { userDALFactory } from "@app/services/user/user-dal";
import { userServiceFactory } from "@app/services/user/user-service"; import { userServiceFactory } from "@app/services/user/user-service";
import { webhookDalFactory } from "@app/services/webhook/webhook-dal"; import { webhookDALFactory } from "@app/services/webhook/webhook-dal";
import { webhookServiceFactory } from "@app/services/webhook/webhook-service"; import { webhookServiceFactory } from "@app/services/webhook/webhook-service";
import { injectAuditLogInfo } from "../plugins/audit-log"; import { injectAuditLogInfo } from "../plugins/audit-log";
@@ -115,312 +115,312 @@ export const registerRoutes = async (
server.register(registerSecretScannerGhApp, { prefix: "/ss-webhook" }); server.register(registerSecretScannerGhApp, { prefix: "/ss-webhook" });
// db layers // db layers
const userDal = userDalFactory(db); const userDAL = userDALFactory(db);
const authDal = authDalFactory(db); const authDAL = authDALFactory(db);
const authTokenDal = tokenDalFactory(db); const authTokenDAL = tokenDALFactory(db);
const orgDal = orgDalFactory(db); const orgDAL = orgDALFactory(db);
const orgBotDal = orgBotDalFactory(db); const orgBotDAL = orgBotDALFactory(db);
const incidentContactDal = incidentContactDalFactory(db); const incidentContactDAL = incidentContactDALFactory(db);
const orgRoleDal = orgRoleDalFactory(db); const orgRoleDAL = orgRoleDALFactory(db);
const superAdminDal = superAdminDalFactory(db); const superAdminDAL = superAdminDALFactory(db);
const apiKeyDal = apiKeyDalFactory(db); const apiKeyDAL = apiKeyDALFactory(db);
const projectDal = projectDalFactory(db); const projectDAL = projectDALFactory(db);
const projectMembershipDal = projectMembershipDalFactory(db); const projectMembershipDAL = projectMembershipDALFactory(db);
const projectRoleDal = projectRoleDalFactory(db); const projectRoleDAL = projectRoleDALFactory(db);
const projectEnvDal = projectEnvDalFactory(db); const projectEnvDAL = projectEnvDALFactory(db);
const projectKeyDal = projectKeyDalFactory(db); const projectKeyDAL = projectKeyDALFactory(db);
const projectBotDal = projectBotDalFactory(db); const projectBotDAL = projectBotDALFactory(db);
const secretDal = secretDalFactory(db); const secretDAL = secretDALFactory(db);
const secretTagDal = secretTagDalFactory(db); const secretTagDAL = secretTagDALFactory(db);
const folderDal = secretFolderDalFactory(db); const folderDAL = secretFolderDALFactory(db);
const folderVersionDal = secretFolderVersionDalFactory(db); const folderVersionDAL = secretFolderVersionDALFactory(db);
const secretImportDal = secretImportDalFactory(db); const secretImportDAL = secretImportDALFactory(db);
const secretVersionDal = secretVersionDalFactory(db); const secretVersionDAL = secretVersionDALFactory(db);
const secretBlindIndexDal = secretBlindIndexDalFactory(db); const secretBlindIndexDAL = secretBlindIndexDALFactory(db);
const integrationDal = integrationDalFactory(db); const integrationDAL = integrationDALFactory(db);
const integrationAuthDal = integrationAuthDalFactory(db); const integrationAuthDAL = integrationAuthDALFactory(db);
const webhookDal = webhookDalFactory(db); const webhookDAL = webhookDALFactory(db);
const serviceTokenDal = serviceTokenDalFactory(db); const serviceTokenDAL = serviceTokenDALFactory(db);
const identityDal = identityDalFactory(db); const identityDAL = identityDALFactory(db);
const identityAccessTokenDal = identityAccessTokenDalFactory(db); const identityAccessTokenDAL = identityAccessTokenDALFactory(db);
const identityOrgMembershipDal = identityOrgDalFactory(db); const identityOrgMembershipDAL = identityOrgDALFactory(db);
const identityProjectDal = identityProjectDalFactory(db); const identityProjectDAL = identityProjectDALFactory(db);
const identityUaDal = identityUaDalFactory(db); const identityUaDAL = identityUaDALFactory(db);
const identityUaClientSecretDal = identityUaClientSecretDalFactory(db); const identityUaClientSecretDAL = identityUaClientSecretDALFactory(db);
const auditLogDal = auditLogDalFactory(db); const auditLogDAL = auditLogDALFactory(db);
const trustedIpDal = trustedIpDalFactory(db); const trustedIpDAL = trustedIpDALFactory(db);
// ee db layer ops // ee db layer ops
const permissionDal = permissionDalFactory(db); const permissionDAL = permissionDALFactory(db);
const samlConfigDal = samlConfigDalFactory(db); const samlConfigDAL = samlConfigDALFactory(db);
const sapApproverDal = sapApproverDalFactory(db); const sapApproverDAL = sapApproverDALFactory(db);
const secretApprovalPolicyDal = secretApprovalPolicyDalFactory(db); const secretApprovalPolicyDAL = secretApprovalPolicyDALFactory(db);
const secretApprovalRequestDal = secretApprovalRequestDalFactory(db); const secretApprovalRequestDAL = secretApprovalRequestDALFactory(db);
const sarReviewerDal = sarReviewerDalFactory(db); const sarReviewerDAL = sarReviewerDALFactory(db);
const sarSecretDal = sarSecretDalFactory(db); const sarSecretDAL = sarSecretDALFactory(db);
const secretRotationDal = secretRotationDalFactory(db); const secretRotationDAL = secretRotationDALFactory(db);
const snapshotDal = snapshotDalFactory(db); const snapshotDAL = snapshotDALFactory(db);
const snapshotSecretDal = snapshotSecretDalFactory(db); const snapshotSecretDAL = snapshotSecretDALFactory(db);
const snapshotFolderDal = snapshotFolderDalFactory(db); const snapshotFolderDAL = snapshotFolderDALFactory(db);
const gitAppInstallSessionDal = gitAppInstallSessionDalFactory(db); const gitAppInstallSessionDAL = gitAppInstallSessionDALFactory(db);
const gitAppOrgDal = gitAppDalFactory(db); const gitAppOrgDAL = gitAppDALFactory(db);
const secretScanningDal = secretScanningDalFactory(db); const secretScanningDAL = secretScanningDALFactory(db);
const licenseDal = licenseDalFactory(db); const licenseDAL = licenseDALFactory(db);
const permissionService = permissionServiceFactory({ const permissionService = permissionServiceFactory({
permissionDal, permissionDAL,
orgRoleDal, orgRoleDAL,
projectRoleDal, projectRoleDAL,
serviceTokenDal serviceTokenDAL
}); });
const licenseService = licenseServiceFactory({ permissionService, orgDal, licenseDal }); const licenseService = licenseServiceFactory({ permissionService, orgDAL, licenseDAL });
const trustedIpService = trustedIpServiceFactory({ const trustedIpService = trustedIpServiceFactory({
licenseService, licenseService,
projectDal, projectDAL,
trustedIpDal, trustedIpDAL,
permissionService permissionService
}); });
const auditLogQueue = auditLogQueueServiceFactory({ const auditLogQueue = auditLogQueueServiceFactory({
auditLogDal, auditLogDAL,
queueService, queueService,
projectDal, projectDAL,
licenseService licenseService
}); });
const auditLogService = auditLogServiceFactory({ auditLogDal, permissionService, auditLogQueue }); const auditLogService = auditLogServiceFactory({ auditLogDAL, permissionService, auditLogQueue });
const sapService = secretApprovalPolicyServiceFactory({ const sapService = secretApprovalPolicyServiceFactory({
projectMembershipDal, projectMembershipDAL,
projectEnvDal, projectEnvDAL,
sapApproverDal, sapApproverDAL,
permissionService, permissionService,
secretApprovalPolicyDal secretApprovalPolicyDAL
}); });
const samlService = samlConfigServiceFactory({ const samlService = samlConfigServiceFactory({
permissionService, permissionService,
orgBotDal, orgBotDAL,
orgDal, orgDAL,
userDal, userDAL,
samlConfigDal, samlConfigDAL,
licenseService licenseService
}); });
const tokenService = tokenServiceFactory({ tokenDal: authTokenDal, userDal }); const tokenService = tokenServiceFactory({ tokenDAL: authTokenDAL, userDAL });
const userService = userServiceFactory({ userDal }); const userService = userServiceFactory({ userDAL });
const loginService = authLoginServiceFactory({ userDal, smtpService, tokenService }); const loginService = authLoginServiceFactory({ userDAL, smtpService, tokenService });
const passwordService = authPaswordServiceFactory({ const passwordService = authPaswordServiceFactory({
tokenService, tokenService,
smtpService, smtpService,
authDal, authDAL,
userDal userDAL
}); });
const orgService = orgServiceFactory({ const orgService = orgServiceFactory({
licenseService, licenseService,
samlConfigDal, samlConfigDAL,
orgRoleDal, orgRoleDAL,
permissionService, permissionService,
orgDal, orgDAL,
incidentContactDal, incidentContactDAL,
tokenService, tokenService,
smtpService, smtpService,
userDal, userDAL,
orgBotDal orgBotDAL
}); });
const signupService = authSignupServiceFactory({ const signupService = authSignupServiceFactory({
tokenService, tokenService,
smtpService, smtpService,
authDal, authDAL,
userDal, userDAL,
orgDal, orgDAL,
orgService, orgService,
licenseService licenseService
}); });
const orgRoleService = orgRoleServiceFactory({ permissionService, orgRoleDal }); const orgRoleService = orgRoleServiceFactory({ permissionService, orgRoleDAL });
const superAdminService = superAdminServiceFactory({ const superAdminService = superAdminServiceFactory({
userDal, userDAL,
authService: loginService, authService: loginService,
serverCfgDal: superAdminDal, serverCfgDAL: superAdminDAL,
orgService orgService
}); });
const apiKeyService = apiKeyServiceFactory({ apiKeyDal, userDal }); const apiKeyService = apiKeyServiceFactory({ apiKeyDAL, userDAL });
const secretScanningQueue = secretScanningQueueFactory({ const secretScanningQueue = secretScanningQueueFactory({
smtpService, smtpService,
secretScanningDal, secretScanningDAL,
queueService, queueService,
orgMembershipDal: orgDal orgMembershipDAL: orgDAL
}); });
const secretScanningService = secretScanningServiceFactory({ const secretScanningService = secretScanningServiceFactory({
permissionService, permissionService,
gitAppOrgDal, gitAppOrgDAL,
gitAppInstallSessionDal, gitAppInstallSessionDAL,
secretScanningDal, secretScanningDAL,
secretScanningQueue secretScanningQueue
}); });
const projectService = projectServiceFactory({ const projectService = projectServiceFactory({
permissionService, permissionService,
projectDal, projectDAL,
secretBlindIndexDal, secretBlindIndexDAL,
projectEnvDal, projectEnvDAL,
projectMembershipDal, projectMembershipDAL,
folderDal, folderDAL,
licenseService licenseService
}); });
const projectMembershipService = projectMembershipServiceFactory({ const projectMembershipService = projectMembershipServiceFactory({
projectMembershipDal, projectMembershipDAL,
projectDal, projectDAL,
permissionService, permissionService,
orgDal, orgDAL,
userDal, userDAL,
smtpService, smtpService,
projectKeyDal, projectKeyDAL,
projectRoleDal, projectRoleDAL,
licenseService licenseService
}); });
const projectEnvService = projectEnvServiceFactory({ const projectEnvService = projectEnvServiceFactory({
permissionService, permissionService,
projectEnvDal, projectEnvDAL,
licenseService, licenseService,
projectDal, projectDAL,
folderDal folderDAL
}); });
const projectKeyService = projectKeyServiceFactory({ const projectKeyService = projectKeyServiceFactory({
permissionService, permissionService,
projectKeyDal, projectKeyDAL,
projectMembershipDal projectMembershipDAL
}); });
const projectRoleService = projectRoleServiceFactory({ permissionService, projectRoleDal }); const projectRoleService = projectRoleServiceFactory({ permissionService, projectRoleDAL });
const snapshotService = secretSnapshotServiceFactory({ const snapshotService = secretSnapshotServiceFactory({
folderDal, folderDAL,
secretDal, secretDAL,
snapshotDal, snapshotDAL,
snapshotFolderDal, snapshotFolderDAL,
snapshotSecretDal, snapshotSecretDAL,
secretVersionDal, secretVersionDAL,
folderVersionDal, folderVersionDAL,
permissionService, permissionService,
licenseService licenseService
}); });
const webhookService = webhookServiceFactory({ const webhookService = webhookServiceFactory({
permissionService, permissionService,
webhookDal, webhookDAL,
projectEnvDal projectEnvDAL
}); });
const secretTagService = secretTagServiceFactory({ secretTagDal, permissionService }); const secretTagService = secretTagServiceFactory({ secretTagDAL, permissionService });
const folderService = secretFolderServiceFactory({ const folderService = secretFolderServiceFactory({
permissionService, permissionService,
folderDal, folderDAL,
folderVersionDal, folderVersionDAL,
projectEnvDal, projectEnvDAL,
snapshotService snapshotService
}); });
const secretImportService = secretImportServiceFactory({ const secretImportService = secretImportServiceFactory({
projectEnvDal, projectEnvDAL,
folderDal, folderDAL,
permissionService, permissionService,
secretImportDal, secretImportDAL,
secretDal secretDAL
}); });
const projectBotService = projectBotServiceFactory({ permissionService, projectBotDal }); const projectBotService = projectBotServiceFactory({ permissionService, projectBotDAL });
const integrationAuthService = integrationAuthServiceFactory({ const integrationAuthService = integrationAuthServiceFactory({
integrationAuthDal, integrationAuthDAL,
integrationDal, integrationDAL,
permissionService, permissionService,
projectBotDal, projectBotDAL,
projectBotService projectBotService
}); });
const secretQueueService = secretQueueFactory({ const secretQueueService = secretQueueFactory({
queueService, queueService,
secretDal, secretDAL,
folderDal, folderDAL,
integrationAuthService, integrationAuthService,
projectBotService, projectBotService,
integrationDal, integrationDAL,
secretImportDal, secretImportDAL,
projectEnvDal, projectEnvDAL,
webhookDal webhookDAL
}); });
const secretService = secretServiceFactory({ const secretService = secretServiceFactory({
folderDal, folderDAL,
secretVersionDal, secretVersionDAL,
secretBlindIndexDal, secretBlindIndexDAL,
permissionService, permissionService,
secretDal, secretDAL,
secretTagDal, secretTagDAL,
snapshotService, snapshotService,
secretQueueService, secretQueueService,
secretImportDal, secretImportDAL,
projectBotService projectBotService
}); });
const sarService = secretApprovalRequestServiceFactory({ const sarService = secretApprovalRequestServiceFactory({
permissionService, permissionService,
folderDal, folderDAL,
sarSecretDal, sarSecretDAL,
sarReviewerDal, sarReviewerDAL,
secretVersionDal, secretVersionDAL,
secretBlindIndexDal, secretBlindIndexDAL,
secretApprovalRequestDal, secretApprovalRequestDAL,
secretService, secretService,
snapshotService, snapshotService,
secretQueueService secretQueueService
}); });
const secretRotationQueue = secretRotationQueueFactory({ const secretRotationQueue = secretRotationQueueFactory({
secretRotationDal, secretRotationDAL,
queue: queueService, queue: queueService,
secretDal, secretDAL,
secretVersionDal, secretVersionDAL,
projectBotService projectBotService
}); });
const secretRotationService = secretRotationServiceFactory({ const secretRotationService = secretRotationServiceFactory({
permissionService, permissionService,
secretRotationDal, secretRotationDAL,
secretRotationQueue, secretRotationQueue,
projectDal, projectDAL,
licenseService, licenseService,
secretDal, secretDAL,
folderDal folderDAL
}); });
const integrationService = integrationServiceFactory({ const integrationService = integrationServiceFactory({
permissionService, permissionService,
folderDal, folderDAL,
integrationDal, integrationDAL,
integrationAuthDal, integrationAuthDAL,
secretQueueService secretQueueService
}); });
const serviceTokenService = serviceTokenServiceFactory({ const serviceTokenService = serviceTokenServiceFactory({
projectEnvDal, projectEnvDAL,
serviceTokenDal, serviceTokenDAL,
permissionService permissionService
}); });
const identityService = identityServiceFactory({ const identityService = identityServiceFactory({
permissionService, permissionService,
identityDal, identityDAL,
identityOrgMembershipDal identityOrgMembershipDAL
}); });
const identityAccessTokenService = identityAccessTokenServiceFactory({ identityAccessTokenDal }); const identityAccessTokenService = identityAccessTokenServiceFactory({ identityAccessTokenDAL });
const identityProjectService = identityProjectServiceFactory({ const identityProjectService = identityProjectServiceFactory({
permissionService, permissionService,
projectDal, projectDAL,
identityProjectDal, identityProjectDAL,
identityOrgMembershipDal identityOrgMembershipDAL
}); });
const identityUaService = identityUaServiceFactory({ const identityUaService = identityUaServiceFactory({
identityOrgMembershipDal, identityOrgMembershipDAL,
permissionService, permissionService,
identityDal, identityDAL,
identityAccessTokenDal, identityAccessTokenDAL,
identityUaClientSecretDal, identityUaClientSecretDAL,
identityUaDal, identityUaDAL,
licenseService licenseService
}); });
@@ -469,10 +469,10 @@ export const registerRoutes = async (
}); });
server.decorate<FastifyZodProvider["store"]>("store", { server.decorate<FastifyZodProvider["store"]>("store", {
user: userDal user: userDAL
}); });
await server.register(injectIdentity, { userDal, serviceTokenDal }); await server.register(injectIdentity, { userDAL, serviceTokenDAL });
await server.register(injectPermission); await server.register(injectPermission);
await server.register(injectAuditLogInfo); await server.register(injectAuditLogInfo);
@@ -2,6 +2,6 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TApiKeyDalFactory = ReturnType<typeof apiKeyDalFactory>; export type TApiKeyDALFactory = ReturnType<typeof apiKeyDALFactory>;
export const apiKeyDalFactory = (db: TDbClient) => ormify(db, TableName.ApiKey); export const apiKeyDALFactory = (db: TDbClient) => ormify(db, TableName.ApiKey);
@@ -6,21 +6,21 @@ import { TApiKeys } from "@app/db/schemas/api-keys";
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors"; import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TApiKeyDalFactory } from "./api-key-dal"; import { TApiKeyDALFactory } from "./api-key-dal";
type TApiKeyServiceFactoryDep = { type TApiKeyServiceFactoryDep = {
apiKeyDal: TApiKeyDalFactory; apiKeyDAL: TApiKeyDALFactory;
userDal: Pick<TUserDalFactory, "findById">; userDAL: Pick<TUserDALFactory, "findById">;
}; };
export type TApiKeyServiceFactory = ReturnType<typeof apiKeyServiceFactory>; export type TApiKeyServiceFactory = ReturnType<typeof apiKeyServiceFactory>;
const formatApiKey = ({ secretHash, ...data }: TApiKeys) => data; const formatApiKey = ({ secretHash, ...data }: TApiKeys) => data;
export const apiKeyServiceFactory = ({ apiKeyDal, userDal }: TApiKeyServiceFactoryDep) => { export const apiKeyServiceFactory = ({ apiKeyDAL, userDAL }: TApiKeyServiceFactoryDep) => {
const getMyApiKeys = async (userId: string) => { const getMyApiKeys = async (userId: string) => {
const apiKeys = await apiKeyDal.find({ userId }); const apiKeys = await apiKeyDAL.find({ userId });
return apiKeys.map((key) => formatApiKey(key)); return apiKeys.map((key) => formatApiKey(key));
}; };
@@ -31,7 +31,7 @@ export const apiKeyServiceFactory = ({ apiKeyDal, userDal }: TApiKeyServiceFacto
const expiresAt = new Date(); const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + expiresIn); expiresAt.setSeconds(expiresAt.getSeconds() + expiresIn);
const apiKeyData = await apiKeyDal.create({ const apiKeyData = await apiKeyDAL.create({
userId, userId,
name, name,
expiresAt, expiresAt,
@@ -44,7 +44,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) if (!apiKeyData)
throw new BadRequestError({ message: "Failed to find api key", name: "delete api key" }); throw new BadRequestError({ message: "Failed to find api key", name: "delete api key" });
return formatApiKey(apiKeyData); return formatApiKey(apiKeyData);
@@ -52,18 +52,18 @@ export const apiKeyServiceFactory = ({ apiKeyDal, userDal }: TApiKeyServiceFacto
const fnValidateApiKey = async (token: string) => { const fnValidateApiKey = async (token: string) => {
const [, TOKEN_IDENTIFIER, TOKEN_SECRET] = <[string, string, string]>token.split(".", 3); const [, TOKEN_IDENTIFIER, TOKEN_SECRET] = <[string, string, string]>token.split(".", 3);
const apiKey = await apiKeyDal.findById(TOKEN_IDENTIFIER); const apiKey = await apiKeyDAL.findById(TOKEN_IDENTIFIER);
if (!apiKey) throw new UnauthorizedError(); if (!apiKey) throw new UnauthorizedError();
if (apiKey.expiresAt && new Date(apiKey.expiresAt) < new Date()) { if (apiKey.expiresAt && new Date(apiKey.expiresAt) < new Date()) {
await apiKeyDal.deleteById(apiKey.id); await apiKeyDAL.deleteById(apiKey.id);
throw new UnauthorizedError(); throw new UnauthorizedError();
} }
const isMatch = await bcrypt.compare(TOKEN_SECRET, apiKey.secretHash); const isMatch = await bcrypt.compare(TOKEN_SECRET, apiKey.secretHash);
if (!isMatch) throw new UnauthorizedError(); if (!isMatch) throw new UnauthorizedError();
await apiKeyDal.updateById(apiKey.id, { lastUsed: new Date() }); await apiKeyDAL.updateById(apiKey.id, { lastUsed: new Date() });
const user = await userDal.findById(apiKey.userId); const user = await userDAL.findById(apiKey.userId);
return user; return user;
}; };
@@ -5,13 +5,13 @@ import { TableName, TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
import { TDeleteTokenForUserDalDTO } from "./auth-token-types"; import { TDeleteTokenForUserDALDTO } from "./auth-token-types";
export type TTokenDalConfig = {}; export type TTokenDALConfig = {};
export type TTokenDalFactory = ReturnType<typeof tokenDalFactory>; export type TTokenDALFactory = ReturnType<typeof tokenDALFactory>;
export const tokenDalFactory = (db: TDbClient) => { export const tokenDALFactory = (db: TDbClient) => {
const authOrm = ormify(db, TableName.AuthTokens); const authOrm = ormify(db, TableName.AuthTokens);
const findOneTokenSession = async ( const findOneTokenSession = async (
@@ -29,7 +29,7 @@ export const tokenDalFactory = (db: TDbClient) => {
userId, userId,
type, type,
orgId orgId
}: TDeleteTokenForUserDalDTO): Promise<TAuthTokens[] | undefined> => { }: TDeleteTokenForUserDALDTO): Promise<TAuthTokens[] | undefined> => {
try { try {
const doc = await db(TableName.AuthTokens) const doc = await db(TableName.AuthTokens)
.where({ userId, type, orgId }) .where({ userId, type, orgId })
@@ -44,7 +44,7 @@ export const tokenDalFactory = (db: TDbClient) => {
const decrementTriesField = async ({ const decrementTriesField = async ({
userId, userId,
type type
}: TDeleteTokenForUserDalDTO): Promise<void> => { }: TDeleteTokenForUserDALDTO): Promise<void> => {
try { try {
await db(TableName.AuthTokens).where({ userId, type }).decrement("triesLeft", 1); await db(TableName.AuthTokens).where({ userId, type }).decrement("triesLeft", 1);
} catch (error) { } catch (error) {
@@ -7,8 +7,8 @@ import { getConfig } from "@app/lib/config/env";
import { UnauthorizedError } from "@app/lib/errors"; import { UnauthorizedError } from "@app/lib/errors";
import { AuthModeJwtTokenPayload } from "../auth/auth-type"; import { AuthModeJwtTokenPayload } from "../auth/auth-type";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TTokenDalFactory } from "./auth-token-dal"; import { TTokenDALFactory } from "./auth-token-dal";
import { import {
TCreateTokenForUserDTO, TCreateTokenForUserDTO,
TIssueAuthTokenDTO, TIssueAuthTokenDTO,
@@ -17,8 +17,8 @@ import {
} from "./auth-token-types"; } from "./auth-token-types";
type TAuthTokenServiceFactoryDep = { type TAuthTokenServiceFactoryDep = {
tokenDal: TTokenDalFactory; tokenDAL: TTokenDALFactory;
userDal: Pick<TUserDalFactory, "findById">; userDAL: Pick<TUserDALFactory, "findById">;
}; };
export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>; export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
@@ -59,14 +59,14 @@ export const getTokenConfig = (tokenType: TokenType) => {
} }
}; };
export const tokenServiceFactory = ({ tokenDal, userDal }: TAuthTokenServiceFactoryDep) => { export const tokenServiceFactory = ({ tokenDAL, userDAL }: TAuthTokenServiceFactoryDep) => {
const createTokenForUser = async ({ type, userId, orgId }: TCreateTokenForUserDTO) => { const createTokenForUser = async ({ type, userId, orgId }: TCreateTokenForUserDTO) => {
const { token, ...tkCfg } = getTokenConfig(type); const { token, ...tkCfg } = getTokenConfig(type);
const appCfg = getConfig(); const appCfg = getConfig();
const tokenHash = await bcrypt.hash(token, appCfg.SALT_ROUNDS); const tokenHash = await bcrypt.hash(token, appCfg.SALT_ROUNDS);
await tokenDal.transaction(async (tx) => { await tokenDAL.transaction(async (tx) => {
await tokenDal.delete({ userId, type, orgId: orgId || null }, tx); await tokenDAL.delete({ userId, type, orgId: orgId || null }, tx);
const newToken = await tokenDal.create( const newToken = await tokenDAL.create(
{ {
tokenHash, tokenHash,
expiresAt: tkCfg.expiresAt, expiresAt: tkCfg.expiresAt,
@@ -89,11 +89,11 @@ export const tokenServiceFactory = ({ tokenDal, userDal }: TAuthTokenServiceFact
code, code,
orgId orgId
}: TValidateTokenForUserDTO): Promise<TAuthTokens | undefined> => { }: TValidateTokenForUserDTO): Promise<TAuthTokens | undefined> => {
const token = await tokenDal.findOne({ type, userId, orgId: orgId || null }); const token = await tokenDAL.findOne({ type, userId, orgId: orgId || null });
// validate token // validate token
if (!token) throw new Error("Failed to find token"); if (!token) throw new Error("Failed to find token");
if (token?.expiresAt && new Date(token.expiresAt) < new Date()) { if (token?.expiresAt && new Date(token.expiresAt) < new Date()) {
await tokenDal.delete({ type, userId, orgId }); await tokenDAL.delete({ type, userId, orgId });
throw new Error("Token expired. Please try again"); throw new Error("Token expired. Please try again");
} }
@@ -101,15 +101,15 @@ export const tokenServiceFactory = ({ tokenDal, userDal }: TAuthTokenServiceFact
if (!isValidToken) { if (!isValidToken) {
if (token?.triesLeft) { if (token?.triesLeft) {
if (token.triesLeft === 1) { if (token.triesLeft === 1) {
await tokenDal.deleteTokenForUser({ type, userId, orgId: orgId || null }); await tokenDAL.deleteTokenForUser({ type, userId, orgId: orgId || null });
} else { } else {
await tokenDal.decrementTriesField({ type, userId, orgId: orgId || null }); await tokenDAL.decrementTriesField({ type, userId, orgId: orgId || null });
} }
} }
throw new Error("Invalid token"); throw new Error("Invalid token");
} }
const deletedToken = await tokenDal.delete({ type, userId, orgId: orgId || null }); const deletedToken = await tokenDAL.delete({ type, userId, orgId: orgId || null });
return deletedToken?.[0]; return deletedToken?.[0];
}; };
@@ -118,9 +118,9 @@ export const tokenServiceFactory = ({ tokenDal, userDal }: TAuthTokenServiceFact
ip, ip,
userAgent userAgent
}: TIssueAuthTokenDTO): Promise<TAuthTokenSessions | undefined> => { }: TIssueAuthTokenDTO): Promise<TAuthTokenSessions | undefined> => {
let session = await tokenDal.findOneTokenSession({ userId, ip, userAgent }); let session = await tokenDAL.findOneTokenSession({ userId, ip, userAgent });
if (!session) { if (!session) {
session = await tokenDal.insertTokenSession(userId, ip, userAgent); session = await tokenDAL.insertTokenSession(userId, ip, userAgent);
} }
return session; return session;
}; };
@@ -129,18 +129,18 @@ export const tokenServiceFactory = ({ tokenDal, userDal }: TAuthTokenServiceFact
userId: string, userId: string,
sessionId: string sessionId: string
): Promise<TAuthTokenSessions | undefined> => ): Promise<TAuthTokenSessions | undefined> =>
tokenDal.incrementTokenSessionVersion(userId, sessionId); tokenDAL.incrementTokenSessionVersion(userId, sessionId);
const getUserTokenSessionById = async (id: string, userId: string) => const getUserTokenSessionById = async (id: string, userId: string) =>
tokenDal.findOneTokenSession({ id, userId }); tokenDAL.findOneTokenSession({ id, userId });
const getTokenSessionByUser = async (userId: string) => tokenDal.findTokenSessions({ userId }); const getTokenSessionByUser = async (userId: string) => tokenDAL.findTokenSessions({ userId });
const revokeAllMySessions = async (userId: string) => tokenDal.deleteTokenSession({ userId }); const revokeAllMySessions = async (userId: string) => tokenDAL.deleteTokenSession({ userId });
// to parse jwt identity in inject identity plugin // to parse jwt identity in inject identity plugin
const fnValidateJwtIdentity = async (token: AuthModeJwtTokenPayload) => { const fnValidateJwtIdentity = async (token: AuthModeJwtTokenPayload) => {
const session = await tokenDal.findOneTokenSession({ const session = await tokenDAL.findOneTokenSession({
id: token.tokenVersionId, id: token.tokenVersionId,
userId: token.userId userId: token.userId
}); });
@@ -148,7 +148,7 @@ export const tokenServiceFactory = ({ tokenDal, userDal }: TAuthTokenServiceFact
if (token.accessVersion !== session.accessVersion) if (token.accessVersion !== session.accessVersion)
throw new UnauthorizedError({ name: "Stale session" }); throw new UnauthorizedError({ name: "Stale session" });
const user = await userDal.findById(session.userId); const user = await userDAL.findById(session.userId);
if (!user || !user.isAccepted) throw new UnauthorizedError({ name: "Token user not found" }); if (!user || !user.isAccepted) throw new UnauthorizedError({ name: "Token user not found" });
return { user, tokenVersionId: token.tokenVersionId }; return { user, tokenVersionId: token.tokenVersionId };
@@ -23,7 +23,7 @@ export type TValidateTokenForUserDTO = {
orgId?: string; orgId?: string;
}; };
export type TUpsertTokenForUserDalDTO = { export type TUpsertTokenForUserDALDTO = {
type: TokenType; type: TokenType;
expiresAt: Date; expiresAt: Date;
userId: string; userId: string;
@@ -31,12 +31,12 @@ export type TUpsertTokenForUserDalDTO = {
triesLeft?: number; triesLeft?: number;
}; };
export type TGetTokenForUserDalDTO = { export type TGetTokenForUserDALDTO = {
userId: string; userId: string;
type: TokenType; type: TokenType;
}; };
export type TDeleteTokenForUserDalDTO = { export type TDeleteTokenForUserDALDTO = {
userId: string; userId: string;
type: TokenType; type: TokenType;
orgId: string | null; orgId: string | null;
+2 -2
View File
@@ -4,9 +4,9 @@ import { TDbClient } from "@app/db";
import { TableName, TBackupPrivateKey } from "@app/db/schemas"; import { TableName, TBackupPrivateKey } from "@app/db/schemas";
import { withTransaction } from "@app/lib/knex"; import { withTransaction } from "@app/lib/knex";
export type TAuthDalFactory = ReturnType<typeof authDalFactory>; export type TAuthDALFactory = ReturnType<typeof authDALFactory>;
export const authDalFactory = (db: TDbClient) => { export const authDALFactory = (db: TDbClient) => {
const getBackupPrivateKeyByUserId = async (userId: string) => const getBackupPrivateKeyByUserId = async (userId: string) =>
db(TableName.BackupPrivateKey).where({ userId }).first("*"); db(TableName.BackupPrivateKey).where({ userId }).first("*");
@@ -8,7 +8,7 @@ import { BadRequestError } from "@app/lib/errors";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service"; import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types"; import { TokenType } from "../auth-token/auth-token-types";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service"; import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { validateProviderAuthToken } from "./auth-fns"; import { validateProviderAuthToken } from "./auth-fns";
import { import {
TLoginClientProofDTO, TLoginClientProofDTO,
@@ -19,14 +19,14 @@ import {
import { AuthMethod, AuthTokenType } from "./auth-type"; import { AuthMethod, AuthTokenType } from "./auth-type";
type TAuthLoginServiceFactoryDep = { type TAuthLoginServiceFactoryDep = {
userDal: TUserDalFactory; userDAL: TUserDALFactory;
tokenService: TAuthTokenServiceFactory; tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService; smtpService: TSmtpService;
}; };
export type TAuthLoginFactory = ReturnType<typeof authLoginServiceFactory>; export type TAuthLoginFactory = ReturnType<typeof authLoginServiceFactory>;
export const authLoginServiceFactory = ({ export const authLoginServiceFactory = ({
userDal, userDAL,
tokenService, tokenService,
smtpService smtpService
}: TAuthLoginServiceFactoryDep) => { }: TAuthLoginServiceFactoryDep) => {
@@ -43,7 +43,7 @@ export const authLoginServiceFactory = ({
if (!isDeviceSeen) { if (!isDeviceSeen) {
const newDeviceList = devices.concat([{ ip, userAgent }]); const newDeviceList = devices.concat([{ ip, userAgent }]);
await userDal.updateById(user.id, { devices: JSON.stringify(newDeviceList) }); await userDAL.updateById(user.id, { devices: JSON.stringify(newDeviceList) });
await smtpService.sendMail({ await smtpService.sendMail({
template: SmtpTemplates.NewDeviceJoin, template: SmtpTemplates.NewDeviceJoin,
subjectLine: "Successful login from new device", subjectLine: "Successful login from new device",
@@ -124,7 +124,7 @@ export const authLoginServiceFactory = ({
providerAuthToken, providerAuthToken,
clientPublicKey clientPublicKey
}: TLoginGenServerPublicKeyDTO) => { }: TLoginGenServerPublicKeyDTO) => {
const userEnc = await userDal.findUserEncKeyByEmail(email); const userEnc = await userDAL.findUserEncKeyByEmail(email);
if (!userEnc || (userEnc && !userEnc.isAccepted)) { if (!userEnc || (userEnc && !userEnc.isAccepted)) {
throw new Error("Failed to find user"); throw new Error("Failed to find user");
} }
@@ -133,7 +133,7 @@ export const authLoginServiceFactory = ({
} }
const serverSrpKey = await generateSrpServerKey(userEnc.salt, userEnc.verifier); const serverSrpKey = await generateSrpServerKey(userEnc.salt, userEnc.verifier);
const userEncKeys = await userDal.updateUserEncryptionByUserId(userEnc.userId, { const userEncKeys = await userDAL.updateUserEncryptionByUserId(userEnc.userId, {
clientPublicKey, clientPublicKey,
serverPrivateKey: serverSrpKey.privateKey serverPrivateKey: serverSrpKey.privateKey
}); });
@@ -151,7 +151,7 @@ export const authLoginServiceFactory = ({
ip, ip,
userAgent userAgent
}: TLoginClientProofDTO) => { }: TLoginClientProofDTO) => {
const userEnc = await userDal.findUserEncKeyByEmail(email); const userEnc = await userDAL.findUserEncKeyByEmail(email);
if (!userEnc) throw new Error("Failed to find user"); if (!userEnc) throw new Error("Failed to find user");
const cfg = getConfig(); const cfg = getConfig();
@@ -170,7 +170,7 @@ export const authLoginServiceFactory = ({
); );
if (!isValidClientProof) throw new Error("Failed to authenticate. Try again?"); if (!isValidClientProof) throw new Error("Failed to authenticate. Try again?");
await userDal.updateUserEncryptionByUserId(userEnc.userId, { await userDAL.updateUserEncryptionByUserId(userEnc.userId, {
serverPrivateKey: null, serverPrivateKey: null,
clientPublicKey: null clientPublicKey: null
}); });
@@ -195,7 +195,7 @@ export const authLoginServiceFactory = ({
* saved in frontend * saved in frontend
*/ */
const resendMfaToken = async (userId: string) => { const resendMfaToken = async (userId: string) => {
const user = await userDal.findById(userId); const user = await userDAL.findById(userId);
if (!user) return; if (!user) return;
await sendUserMfaCode(user.id, user.email); await sendUserMfaCode(user.id, user.email);
}; };
@@ -210,7 +210,7 @@ export const authLoginServiceFactory = ({
userId, userId,
code: mfaToken code: mfaToken
}); });
const userEnc = await userDal.findUserEncKeyByUserId(userId); const userEnc = await userDAL.findUserEncKeyByUserId(userId);
if (!userEnc) throw new Error("Failed to authenticate user"); if (!userEnc) throw new Error("Failed to authenticate user");
const token = await generateUserTokens({ ...userEnc, id: userEnc.userId }, ip, userAgent); const token = await generateUserTokens({ ...userEnc, id: userEnc.userId }, ip, userAgent);
@@ -227,14 +227,14 @@ export const authLoginServiceFactory = ({
callbackPort, callbackPort,
isSignupAllowed isSignupAllowed
}: TOauthLoginDTO) => { }: TOauthLoginDTO) => {
let user = await userDal.findUserByEmail(email); let user = await userDAL.findUserByEmail(email);
const appCfg = getConfig(); const appCfg = getConfig();
const isOauthSignUpDisabled = !isSignupAllowed && !user; const isOauthSignUpDisabled = !isSignupAllowed && !user;
if (isOauthSignUpDisabled) if (isOauthSignUpDisabled)
throw new BadRequestError({ message: "User signup disabled", name: "Oauth 2 login" }); throw new BadRequestError({ message: "User signup disabled", name: "Oauth 2 login" });
if (!user) { if (!user) {
user = await userDal.create({ email, firstName, lastName, authMethods: [authMethod] }); user = await userDAL.create({ email, firstName, lastName, authMethods: [authMethod] });
} }
const isLinkingRequired = !user?.authMethods?.includes(authMethod); const isLinkingRequired = !user?.authMethods?.includes(authMethod);
const isUserCompleted = user.isAccepted; const isUserCompleted = user.isAccepted;
@@ -7,8 +7,8 @@ import { generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service"; import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types"; import { TokenType } from "../auth-token/auth-token-types";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service"; import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TAuthDalFactory } from "./auth-dal"; import { TAuthDALFactory } from "./auth-dal";
import { import {
TChangePasswordDTO, TChangePasswordDTO,
TCreateBackupPrivateKeyDTO, TCreateBackupPrivateKeyDTO,
@@ -17,16 +17,16 @@ import {
import { AuthTokenType } from "./auth-type"; import { AuthTokenType } from "./auth-type";
type TAuthPasswordServiceFactoryDep = { type TAuthPasswordServiceFactoryDep = {
authDal: TAuthDalFactory; authDAL: TAuthDALFactory;
userDal: TUserDalFactory; userDAL: TUserDALFactory;
tokenService: TAuthTokenServiceFactory; tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService; smtpService: TSmtpService;
}; };
export type TAuthPasswordFactory = ReturnType<typeof authPaswordServiceFactory>; export type TAuthPasswordFactory = ReturnType<typeof authPaswordServiceFactory>;
export const authPaswordServiceFactory = ({ export const authPaswordServiceFactory = ({
authDal, authDAL,
userDal, userDAL,
tokenService, tokenService,
smtpService smtpService
}: TAuthPasswordServiceFactoryDep) => { }: TAuthPasswordServiceFactoryDep) => {
@@ -35,11 +35,11 @@ export const authPaswordServiceFactory = ({
* Gets srp server user salt and server public key * Gets srp server user salt and server public key
*/ */
const generateServerPubKey = async (userId: string, clientPublicKey: string) => { const generateServerPubKey = async (userId: string, clientPublicKey: string) => {
const userEnc = await userDal.findUserEncKeyByUserId(userId); const userEnc = await userDAL.findUserEncKeyByUserId(userId);
if (!userEnc) throw new Error("Failed to find user"); if (!userEnc) throw new Error("Failed to find user");
const serverSrpKey = await generateSrpServerKey(userEnc.salt, userEnc.verifier); const serverSrpKey = await generateSrpServerKey(userEnc.salt, userEnc.verifier);
const userEncKeys = await userDal.updateUserEncryptionByUserId(userEnc.userId, { const userEncKeys = await userDAL.updateUserEncryptionByUserId(userEnc.userId, {
clientPublicKey, clientPublicKey,
serverPrivateKey: serverSrpKey.privateKey serverPrivateKey: serverSrpKey.privateKey
}); });
@@ -63,10 +63,10 @@ export const authPaswordServiceFactory = ({
verifier, verifier,
tokenVersionId tokenVersionId
}: TChangePasswordDTO) => { }: TChangePasswordDTO) => {
const userEnc = await userDal.findUserEncKeyByUserId(userId); const userEnc = await userDAL.findUserEncKeyByUserId(userId);
if (!userEnc) throw new Error("Failed to find user"); if (!userEnc) throw new Error("Failed to find user");
await userDal.updateUserEncryptionByUserId(userEnc.userId, { await userDAL.updateUserEncryptionByUserId(userEnc.userId, {
serverPrivateKey: null, serverPrivateKey: null,
clientPublicKey: null clientPublicKey: null
}); });
@@ -81,7 +81,7 @@ export const authPaswordServiceFactory = ({
); );
if (!isValidClientProof) throw new Error("Failed to authenticate. Try again?"); if (!isValidClientProof) throw new Error("Failed to authenticate. Try again?");
await userDal.updateUserEncryptionByUserId(userId, { await userDAL.updateUserEncryptionByUserId(userId, {
encryptionVersion: 2, encryptionVersion: 2,
protectedKey, protectedKey,
protectedKeyIV, protectedKeyIV,
@@ -104,7 +104,7 @@ export const authPaswordServiceFactory = ({
* Email password reset flow via email. Step 1 send email * Email password reset flow via email. Step 1 send email
*/ */
const sendPasswordResetEmail = async (email: string) => { const sendPasswordResetEmail = async (email: string) => {
const user = await userDal.findUserByEmail(email); const user = await userDAL.findUserByEmail(email);
// ignore as user is not found to avoid an outside entity to identify infisical registered accounts // ignore as user is not found to avoid an outside entity to identify infisical registered accounts
if (!user || (user && !user.isAccepted)) return; if (!user || (user && !user.isAccepted)) return;
@@ -131,7 +131,7 @@ export const authPaswordServiceFactory = ({
* */ * */
const verifyPasswordResetEmail = async (email: string, code: string) => { const verifyPasswordResetEmail = async (email: string, code: string) => {
const cfg = getConfig(); const cfg = getConfig();
const user = await userDal.findUserByEmail(email); const user = await userDAL.findUserByEmail(email);
// ignore as user is not found to avoid an outside entity to identify infisical registered accounts // ignore as user is not found to avoid an outside entity to identify infisical registered accounts
if (!user || (user && !user.isAccepted)) { if (!user || (user && !user.isAccepted)) {
throw new Error("Failed email verification for pass reset"); throw new Error("Failed email verification for pass reset");
@@ -168,7 +168,7 @@ export const authPaswordServiceFactory = ({
encryptedPrivateKeyTag, encryptedPrivateKeyTag,
userId userId
}: TResetPasswordViaBackupKeyDTO) => { }: TResetPasswordViaBackupKeyDTO) => {
await userDal.updateUserEncryptionByUserId(userId, { await userDAL.updateUserEncryptionByUserId(userId, {
encryptionVersion: 2, encryptionVersion: 2,
protectedKey, protectedKey,
protectedKeyIV, protectedKeyIV,
@@ -195,7 +195,7 @@ export const authPaswordServiceFactory = ({
tag, tag,
userId userId
}: TCreateBackupPrivateKeyDTO) => { }: TCreateBackupPrivateKeyDTO) => {
const userEnc = await userDal.findUserEncKeyByUserId(userId); const userEnc = await userDAL.findUserEncKeyByUserId(userId);
if (!userEnc || (userEnc && !userEnc.isAccepted)) { if (!userEnc || (userEnc && !userEnc.isAccepted)) {
throw new Error("Failed to find user"); throw new Error("Failed to find user");
} }
@@ -210,8 +210,8 @@ export const authPaswordServiceFactory = ({
clientProof clientProof
); );
if (!isValidClientProff) throw new Error("failed to create backup key"); if (!isValidClientProff) throw new Error("failed to create backup key");
const backup = await authDal.transaction(async (tx) => { const backup = await authDAL.transaction(async (tx) => {
const backupKey = await authDal.upsertBackupKey( const backupKey = await authDAL.upsertBackupKey(
userEnc.userId, userEnc.userId,
{ {
encryptedPrivateKey, encryptedPrivateKey,
@@ -225,7 +225,7 @@ export const authPaswordServiceFactory = ({
tx tx
); );
await userDal.updateUserEncryptionByUserId( await userDAL.updateUserEncryptionByUserId(
userEnc.userId, userEnc.userId,
{ {
serverPrivateKey: null, serverPrivateKey: null,
@@ -243,11 +243,11 @@ export const authPaswordServiceFactory = ({
* Return user back up * Return user back up
* */ * */
const getBackupPrivateKeyOfUser = async (userId: string) => { const getBackupPrivateKeyOfUser = async (userId: string) => {
const user = await userDal.findUserEncKeyByUserId(userId); const user = await userDAL.findUserEncKeyByUserId(userId);
if (!user || (user && !user.isAccepted)) { if (!user || (user && !user.isAccepted)) {
throw new Error("Failed to find user"); throw new Error("Failed to find user");
} }
const backupKey = await authDal.getBackupPrivateKeyByUserId(userId); const backupKey = await authDAL.getBackupPrivateKeyByUserId(userId);
if (!backupKey) throw new Error("Failed to find user backup key"); if (!backupKey) throw new Error("Failed to find user backup key");
return backupKey; return backupKey;
@@ -8,20 +8,20 @@ import { isDisposableEmail } from "@app/lib/validator";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service"; import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types"; import { TokenType } from "../auth-token/auth-token-types";
import { TOrgDalFactory } from "../org/org-dal"; import { TOrgDALFactory } from "../org/org-dal";
import { TOrgServiceFactory } from "../org/org-service"; import { TOrgServiceFactory } from "../org/org-service";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service"; import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TAuthDalFactory } from "./auth-dal"; import { TAuthDALFactory } from "./auth-dal";
import { validateProviderAuthToken, validateSignUpAuthorization } from "./auth-fns"; import { validateProviderAuthToken, validateSignUpAuthorization } from "./auth-fns";
import { TCompleteAccountInviteDTO, TCompleteAccountSignupDTO } from "./auth-signup-type"; import { TCompleteAccountInviteDTO, TCompleteAccountSignupDTO } from "./auth-signup-type";
import { AuthMethod, AuthTokenType } from "./auth-type"; import { AuthMethod, AuthTokenType } from "./auth-type";
type TAuthSignupDep = { type TAuthSignupDep = {
authDal: TAuthDalFactory; authDAL: TAuthDALFactory;
userDal: TUserDalFactory; userDAL: TUserDALFactory;
orgService: Pick<TOrgServiceFactory, "createOrganization">; orgService: Pick<TOrgServiceFactory, "createOrganization">;
orgDal: TOrgDalFactory; orgDAL: TOrgDALFactory;
tokenService: TAuthTokenServiceFactory; tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService; smtpService: TSmtpService;
licenseService: Pick<TLicenseServiceFactory, "updateSubscriptionOrgMemberCount">; licenseService: Pick<TLicenseServiceFactory, "updateSubscriptionOrgMemberCount">;
@@ -29,12 +29,12 @@ type TAuthSignupDep = {
export type TAuthSignupFactory = ReturnType<typeof authSignupServiceFactory>; export type TAuthSignupFactory = ReturnType<typeof authSignupServiceFactory>;
export const authSignupServiceFactory = ({ export const authSignupServiceFactory = ({
authDal, authDAL,
userDal, userDAL,
tokenService, tokenService,
smtpService, smtpService,
orgService, orgService,
orgDal, orgDAL,
licenseService licenseService
}: TAuthSignupDep) => { }: TAuthSignupDep) => {
// first step of signup. create user and send email // first step of signup. create user and send email
@@ -44,13 +44,13 @@ export const authSignupServiceFactory = ({
throw new Error("Provided a disposable email"); throw new Error("Provided a disposable email");
} }
let user = await userDal.findUserByEmail(email); let user = await userDAL.findUserByEmail(email);
if (user && user.isAccepted) { if (user && user.isAccepted) {
// TODO(akhilmhdh-pg): copy as old one. this needs to be changed due to security issues // TODO(akhilmhdh-pg): copy as old one. this needs to be changed due to security issues
throw new Error("Failed to send verification code for complete account"); throw new Error("Failed to send verification code for complete account");
} }
if (!user) { if (!user) {
user = await userDal.create({ authMethods: [AuthMethod.EMAIL], email }); user = await userDAL.create({ authMethods: [AuthMethod.EMAIL], email });
} }
if (!user) throw new Error("Failed to create user"); if (!user) throw new Error("Failed to create user");
@@ -70,7 +70,7 @@ export const authSignupServiceFactory = ({
}; };
const verifyEmailSignup = async (email: string, code: string) => { const verifyEmailSignup = async (email: string, code: string) => {
const user = await userDal.findUserByEmail(email); const user = await userDAL.findUserByEmail(email);
if (!user || (user && user.isAccepted)) { if (!user || (user && user.isAccepted)) {
// TODO(akhilmhdh): copy as old one. this needs to be changed due to security issues // TODO(akhilmhdh): copy as old one. this needs to be changed due to security issues
throw new Error("Failed to send verification code for complete account"); throw new Error("Failed to send verification code for complete account");
@@ -115,7 +115,7 @@ export const authSignupServiceFactory = ({
userAgent, userAgent,
authorization authorization
}: TCompleteAccountSignupDTO) => { }: TCompleteAccountSignupDTO) => {
const user = await userDal.findUserByEmail(email); const user = await userDAL.findUserByEmail(email);
if (!user || (user && user.isAccepted)) { if (!user || (user && user.isAccepted)) {
throw new Error("Failed to complete account for complete user"); throw new Error("Failed to complete account for complete user");
} }
@@ -126,10 +126,10 @@ export const authSignupServiceFactory = ({
validateSignUpAuthorization(authorization, user.id); validateSignUpAuthorization(authorization, user.id);
} }
const updateduser = await authDal.transaction(async (tx) => { const updateduser = await authDAL.transaction(async (tx) => {
const us = await userDal.updateById(user.id, { firstName, lastName, isAccepted: true }, tx); const us = await userDAL.updateById(user.id, { firstName, lastName, isAccepted: true }, tx);
if (!us) throw new Error("User not found"); if (!us) throw new Error("User not found");
const userEncKey = await userDal.upsertUserEncryptionKey( const userEncKey = await userDAL.upsertUserEncryptionKey(
us.id, us.id,
{ {
salt, salt,
@@ -157,7 +157,7 @@ export const authSignupServiceFactory = ({
await orgService.createOrganization(user.id, user.email, organizationName); await orgService.createOrganization(user.id, user.email, organizationName);
} }
const updatedMembersips = await orgDal.updateMembership( const updatedMembersips = await orgDAL.updateMembership(
{ inviteEmail: email, status: OrgMembershipStatus.Invited }, { inviteEmail: email, status: OrgMembershipStatus.Invited },
{ userId: user.id, status: OrgMembershipStatus.Accepted } { userId: user.id, status: OrgMembershipStatus.Accepted }
); );
@@ -218,12 +218,12 @@ export const authSignupServiceFactory = ({
encryptedPrivateKeyIV, encryptedPrivateKeyIV,
encryptedPrivateKeyTag encryptedPrivateKeyTag
}: TCompleteAccountInviteDTO) => { }: TCompleteAccountInviteDTO) => {
const user = await userDal.findUserByEmail(email); const user = await userDAL.findUserByEmail(email);
if (!user || (user && user.isAccepted)) { if (!user || (user && user.isAccepted)) {
throw new Error("Failed to complete account for complete user"); throw new Error("Failed to complete account for complete user");
} }
const [orgMembership] = await orgDal.findMembership({ const [orgMembership] = await orgDAL.findMembership({
inviteEmail: email, inviteEmail: email,
status: OrgMembershipStatus.Invited status: OrgMembershipStatus.Invited
}); });
@@ -233,10 +233,10 @@ export const authSignupServiceFactory = ({
name: "complete account invite" name: "complete account invite"
}); });
const updateduser = await authDal.transaction(async (tx) => { const updateduser = await authDAL.transaction(async (tx) => {
const us = await userDal.updateById(user.id, { firstName, lastName, isAccepted: true }, tx); const us = await userDAL.updateById(user.id, { firstName, lastName, isAccepted: true }, tx);
if (!us) throw new Error("User not found"); if (!us) throw new Error("User not found");
const userEncKey = await userDal.upsertUserEncryptionKey( const userEncKey = await userDAL.upsertUserEncryptionKey(
us.id, us.id,
{ {
salt, salt,
@@ -253,7 +253,7 @@ export const authSignupServiceFactory = ({
tx tx
); );
const updatedMembersips = await orgDal.updateMembership( const updatedMembersips = await orgDAL.updateMembership(
{ inviteEmail: email, status: OrgMembershipStatus.Invited }, { inviteEmail: email, status: OrgMembershipStatus.Invited },
{ userId: us.id, status: OrgMembershipStatus.Accepted }, { userId: us.id, status: OrgMembershipStatus.Accepted },
tx tx
@@ -5,9 +5,9 @@ import { TableName,TIdentityAccessTokens } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TIdentityAccessTokenDalFactory = ReturnType<typeof identityAccessTokenDalFactory>; export type TIdentityAccessTokenDALFactory = ReturnType<typeof identityAccessTokenDALFactory>;
export const identityAccessTokenDalFactory = (db: TDbClient) => { export const identityAccessTokenDALFactory = (db: TDbClient) => {
const identityAccessTokenOrm = ormify(db, TableName.IdentityAccessToken); const identityAccessTokenOrm = ormify(db, TableName.IdentityAccessToken);
const findOne = async (filter: Partial<TIdentityAccessTokens>, tx?: Knex) => { const findOne = async (filter: Partial<TIdentityAccessTokens>, tx?: Knex) => {
@@ -6,14 +6,14 @@ import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { checkIPAgainstBlocklist, TIp } from "@app/lib/ip"; import { checkIPAgainstBlocklist, TIp } from "@app/lib/ip";
import { AuthTokenType } from "../auth/auth-type"; import { AuthTokenType } from "../auth/auth-type";
import { TIdentityAccessTokenDalFactory } from "./identity-access-token-dal"; import { TIdentityAccessTokenDALFactory } from "./identity-access-token-dal";
import { import {
TIdentityAccessTokenJwtPayload, TIdentityAccessTokenJwtPayload,
TRenewAccessTokenDTO TRenewAccessTokenDTO
} from "./identity-access-token-types"; } from "./identity-access-token-types";
type TIdentityAccessTokenServiceFactoryDep = { type TIdentityAccessTokenServiceFactoryDep = {
identityAccessTokenDal: TIdentityAccessTokenDalFactory; identityAccessTokenDAL: TIdentityAccessTokenDALFactory;
}; };
export type TIdentityAccessTokenServiceFactory = ReturnType< export type TIdentityAccessTokenServiceFactory = ReturnType<
@@ -21,7 +21,7 @@ export type TIdentityAccessTokenServiceFactory = ReturnType<
>; >;
export const identityAccessTokenServiceFactory = ({ export const identityAccessTokenServiceFactory = ({
identityAccessTokenDal identityAccessTokenDAL
}: TIdentityAccessTokenServiceFactoryDep) => { }: TIdentityAccessTokenServiceFactoryDep) => {
const validateAccessTokenExp = async (identityAccessToken: TIdentityAccessTokens) => { const validateAccessTokenExp = async (identityAccessToken: TIdentityAccessTokens) => {
const { const {
@@ -92,7 +92,7 @@ export const identityAccessTokenServiceFactory = ({
if (decodedToken.authTokenType !== AuthTokenType.IDENTITY_ACCESS_TOKEN) if (decodedToken.authTokenType !== AuthTokenType.IDENTITY_ACCESS_TOKEN)
throw new UnauthorizedError(); throw new UnauthorizedError();
const identityAccessToken = await identityAccessTokenDal.findOne({ const identityAccessToken = await identityAccessTokenDAL.findOne({
[`${TableName.IdentityAccessToken}.id` as "id"]: decodedToken.identityAccessTokenId, [`${TableName.IdentityAccessToken}.id` as "id"]: decodedToken.identityAccessTokenId,
isAccessTokenRevoked: false isAccessTokenRevoked: false
}); });
@@ -100,7 +100,7 @@ export const identityAccessTokenServiceFactory = ({
validateAccessTokenExp(identityAccessToken); validateAccessTokenExp(identityAccessToken);
const updatedIdentityAccessToken = await identityAccessTokenDal.updateById( const updatedIdentityAccessToken = await identityAccessTokenDAL.updateById(
identityAccessToken.id, identityAccessToken.id,
{ {
accessTokenLastRenewedAt: new Date() accessTokenLastRenewedAt: new Date()
@@ -114,7 +114,7 @@ export const identityAccessTokenServiceFactory = ({
token: TIdentityAccessTokenJwtPayload, token: TIdentityAccessTokenJwtPayload,
ipAddress?: string ipAddress?: string
) => { ) => {
const identityAccessToken = await identityAccessTokenDal.findOne({ const identityAccessToken = await identityAccessTokenDAL.findOne({
[`${TableName.IdentityAccessToken}.id` as "id"]: token.identityAccessTokenId, [`${TableName.IdentityAccessToken}.id` as "id"]: token.identityAccessTokenId,
isAccessTokenRevoked: false isAccessTokenRevoked: false
}); });
@@ -5,9 +5,9 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TIdentityProjectDalFactory = ReturnType<typeof identityProjectDalFactory>; export type TIdentityProjectDALFactory = ReturnType<typeof identityProjectDALFactory>;
export const identityProjectDalFactory = (db: TDbClient) => { export const identityProjectDALFactory = (db: TDbClient) => {
const identityProjectOrm = ormify(db, TableName.IdentityProjectMembership); const identityProjectOrm = ormify(db, TableName.IdentityProjectMembership);
const findByProjectId = async (projectId: string, tx?: Knex) => { const findByProjectId = async (projectId: string, tx?: Knex) => {
@@ -10,9 +10,9 @@ import { isAtLeastAsPrivileged } from "@app/lib/casl";
import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors"; import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";
import { ActorType } from "../auth/auth-type"; import { ActorType } from "../auth/auth-type";
import { TIdentityOrgDalFactory } from "../identity/identity-org-dal"; import { TIdentityOrgDALFactory } from "../identity/identity-org-dal";
import { TProjectDalFactory } from "../project/project-dal"; import { TProjectDALFactory } from "../project/project-dal";
import { TIdentityProjectDalFactory } from "./identity-project-dal"; import { TIdentityProjectDALFactory } from "./identity-project-dal";
import { import {
TCreateProjectIdentityDTO, TCreateProjectIdentityDTO,
TDeleteProjectIdentityDTO, TDeleteProjectIdentityDTO,
@@ -21,9 +21,9 @@ import {
} from "./identity-project-types"; } from "./identity-project-types";
type TIdentityProjectServiceFactoryDep = { type TIdentityProjectServiceFactoryDep = {
identityProjectDal: TIdentityProjectDalFactory; identityProjectDAL: TIdentityProjectDALFactory;
projectDal: Pick<TProjectDalFactory, "findById">; projectDAL: Pick<TProjectDALFactory, "findById">;
identityOrgMembershipDal: Pick<TIdentityOrgDalFactory, "findOne">; identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "findOne">;
permissionService: Pick< permissionService: Pick<
TPermissionServiceFactory, TPermissionServiceFactory,
"getProjectPermission" | "getProjectPermissionByRole" "getProjectPermission" | "getProjectPermissionByRole"
@@ -33,10 +33,10 @@ type TIdentityProjectServiceFactoryDep = {
export type TIdentityProjectServiceFactory = ReturnType<typeof identityProjectServiceFactory>; export type TIdentityProjectServiceFactory = ReturnType<typeof identityProjectServiceFactory>;
export const identityProjectServiceFactory = ({ export const identityProjectServiceFactory = ({
identityProjectDal, identityProjectDAL,
permissionService, permissionService,
identityOrgMembershipDal, identityOrgMembershipDAL,
projectDal projectDAL
}: TIdentityProjectServiceFactoryDep) => { }: TIdentityProjectServiceFactoryDep) => {
const createProjectIdentity = async ({ const createProjectIdentity = async ({
identityId, identityId,
@@ -51,14 +51,14 @@ export const identityProjectServiceFactory = ({
ProjectPermissionSub.Identity ProjectPermissionSub.Identity
); );
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);
const identityOrgMembership = await identityOrgMembershipDal.findOne({ const identityOrgMembership = await identityOrgMembershipDAL.findOne({
identityId, identityId,
orgId: project.orgId orgId: project.orgId
}); });
@@ -76,7 +76,7 @@ export const identityProjectServiceFactory = ({
}); });
const isCustomRole = Boolean(customRole); const isCustomRole = Boolean(customRole);
const projectIdentity = await identityProjectDal.create({ const projectIdentity = await identityProjectDAL.create({
identityId, identityId,
projectId: project.id, projectId: project.id,
role: isCustomRole ? ProjectMembershipRole.Custom : role, role: isCustomRole ? ProjectMembershipRole.Custom : role,
@@ -98,7 +98,7 @@ export const identityProjectServiceFactory = ({
ProjectPermissionSub.Identity ProjectPermissionSub.Identity
); );
const projectIdentity = await identityProjectDal.findOne({ identityId, projectId }); const projectIdentity = await identityProjectDAL.findOne({ identityId, projectId });
if (!projectIdentity) if (!projectIdentity)
throw new BadRequestError({ throw new BadRequestError({
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}`
@@ -125,7 +125,7 @@ export const identityProjectServiceFactory = ({
if (isCustomRole) customRole = customOrgRole; if (isCustomRole) customRole = customOrgRole;
} }
const [updatedProjectIdentity] = await identityProjectDal.update( const [updatedProjectIdentity] = await identityProjectDAL.update(
{ projectId, identityId: projectIdentity.identityId }, { projectId, identityId: projectIdentity.identityId },
{ {
role: customRole ? ProjectMembershipRole.Custom : role, role: customRole ? ProjectMembershipRole.Custom : role,
@@ -141,7 +141,7 @@ export const identityProjectServiceFactory = ({
actor, actor,
projectId projectId
}: TDeleteProjectIdentityDTO) => { }: TDeleteProjectIdentityDTO) => {
const identityProjectMembership = await identityProjectDal.findOne({ identityId, projectId }); const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
if (!identityProjectMembership) if (!identityProjectMembership)
throw new BadRequestError({ message: `Failed to find identity with id ${identityId}` }); throw new BadRequestError({ message: `Failed to find identity with id ${identityId}` });
@@ -163,7 +163,7 @@ export const identityProjectServiceFactory = ({
if (!hasRequiredPriviledges) if (!hasRequiredPriviledges)
throw new ForbiddenRequestError({ message: "Failed to delete more privileged identity" }); throw new ForbiddenRequestError({ message: "Failed to delete more privileged identity" });
const [deletedIdentity] = await identityProjectDal.delete({ identityId }); const [deletedIdentity] = await identityProjectDAL.delete({ identityId });
return deletedIdentity; return deletedIdentity;
}; };
@@ -174,7 +174,7 @@ export const identityProjectServiceFactory = ({
ProjectPermissionSub.Identity ProjectPermissionSub.Identity
); );
const identityMemberhips = await identityProjectDal.findByProjectId(projectId); const identityMemberhips = await identityProjectDAL.findByProjectId(projectId);
return identityMemberhips; return identityMemberhips;
}; };
@@ -5,9 +5,9 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TIdentityUaClientSecretDalFactory = ReturnType<typeof identityUaClientSecretDalFactory>; export type TIdentityUaClientSecretDALFactory = ReturnType<typeof identityUaClientSecretDALFactory>;
export const identityUaClientSecretDalFactory = (db: TDbClient) => { export const identityUaClientSecretDALFactory = (db: TDbClient) => {
const uaClientSecretOrm = ormify(db, TableName.IdentityUaClientSecret); const uaClientSecretOrm = ormify(db, TableName.IdentityUaClientSecret);
const incrementUsage = async (id: string, tx?: Knex) => { const incrementUsage = async (id: string, tx?: Knex) => {
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TIdentityUaDalFactory = ReturnType<typeof identityUaDalFactory>; export type TIdentityUaDALFactory = ReturnType<typeof identityUaDALFactory>;
export const identityUaDalFactory = (db: TDbClient) => { export const identityUaDALFactory = (db: TDbClient) => {
const universalAuthOrm = ormify(db, TableName.IdentityUniversalAuth); const universalAuthOrm = ormify(db, TableName.IdentityUniversalAuth);
return universalAuthOrm; return universalAuthOrm;
@@ -17,12 +17,12 @@ import { BadRequestError, ForbiddenRequestError, UnauthorizedError } from "@app/
import { checkIPAgainstBlocklist, extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip"; import { checkIPAgainstBlocklist, extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { ActorType, AuthTokenType } from "../auth/auth-type"; import { ActorType, AuthTokenType } from "../auth/auth-type";
import { TIdentityDalFactory } from "../identity/identity-dal"; import { TIdentityDALFactory } from "../identity/identity-dal";
import { TIdentityOrgDalFactory } from "../identity/identity-org-dal"; import { TIdentityOrgDALFactory } from "../identity/identity-org-dal";
import { TIdentityAccessTokenDalFactory } from "../identity-access-token/identity-access-token-dal"; import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";
import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types"; import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";
import { TIdentityUaClientSecretDalFactory } from "./identity-ua-client-secret-dal"; import { TIdentityUaClientSecretDALFactory } from "./identity-ua-client-secret-dal";
import { TIdentityUaDalFactory } from "./identity-ua-dal"; import { TIdentityUaDALFactory } from "./identity-ua-dal";
import { import {
TAttachUaDTO, TAttachUaDTO,
TCreateUaClientSecretDTO, TCreateUaClientSecretDTO,
@@ -33,11 +33,11 @@ import {
} from "./identity-ua-types"; } from "./identity-ua-types";
type TIdentityUaServiceFactoryDep = { type TIdentityUaServiceFactoryDep = {
identityUaDal: TIdentityUaDalFactory; identityUaDAL: TIdentityUaDALFactory;
identityUaClientSecretDal: TIdentityUaClientSecretDalFactory; identityUaClientSecretDAL: TIdentityUaClientSecretDALFactory;
identityAccessTokenDal: TIdentityAccessTokenDalFactory; identityAccessTokenDAL: TIdentityAccessTokenDALFactory;
identityOrgMembershipDal: TIdentityOrgDalFactory; identityOrgMembershipDAL: TIdentityOrgDALFactory;
identityDal: Pick<TIdentityDalFactory, "updateById">; identityDAL: Pick<TIdentityDALFactory, "updateById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">; permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
}; };
@@ -45,23 +45,23 @@ type TIdentityUaServiceFactoryDep = {
export type TIdentityUaServiceFactory = ReturnType<typeof identityUaServiceFactory>; export type TIdentityUaServiceFactory = ReturnType<typeof identityUaServiceFactory>;
export const identityUaServiceFactory = ({ export const identityUaServiceFactory = ({
identityUaDal, identityUaDAL,
identityUaClientSecretDal, identityUaClientSecretDAL,
identityAccessTokenDal, identityAccessTokenDAL,
identityOrgMembershipDal, identityOrgMembershipDAL,
identityDal, identityDAL,
permissionService, permissionService,
licenseService licenseService
}: TIdentityUaServiceFactoryDep) => { }: TIdentityUaServiceFactoryDep) => {
const login = async (clientId: string, clientSecret: string, ip: string) => { const login = async (clientId: string, clientSecret: string, ip: string) => {
const identityUa = await identityUaDal.findOne({ clientId }); const identityUa = await identityUaDAL.findOne({ clientId });
if (!identityUa) throw new UnauthorizedError(); if (!identityUa) throw new UnauthorizedError();
checkIPAgainstBlocklist({ checkIPAgainstBlocklist({
ipAddress: ip, ipAddress: ip,
trustedIps: identityUa.clientSecretTrustedIps as TIp[] trustedIps: identityUa.clientSecretTrustedIps as TIp[]
}); });
const clientSecrtInfo = await identityUaClientSecretDal.find({ const clientSecrtInfo = await identityUaClientSecretDAL.find({
identityUAId: identityUa.id, identityUAId: identityUa.id,
isClientSecretRevoked: false isClientSecretRevoked: false
}); });
@@ -80,7 +80,7 @@ export const identityUaServiceFactory = ({
const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds); const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds);
if (currentDate > expirationTime) { if (currentDate > expirationTime) {
await identityUaClientSecretDal.updateById(validClientSecretInfo.id, { await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
isClientSecretRevoked: true isClientSecretRevoked: true
}); });
@@ -93,7 +93,7 @@ export const identityUaServiceFactory = ({
if (clientSecretNumUsesLimit > 0 && clientSecretNumUses === clientSecretNumUsesLimit) { if (clientSecretNumUsesLimit > 0 && clientSecretNumUses === clientSecretNumUsesLimit) {
// number of times client secret can be used for // number of times client secret can be used for
// a login operation reached // a login operation reached
await identityUaClientSecretDal.updateById(validClientSecretInfo.id, { await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
isClientSecretRevoked: true isClientSecretRevoked: true
}); });
throw new UnauthorizedError({ throw new UnauthorizedError({
@@ -102,12 +102,12 @@ export const identityUaServiceFactory = ({
}); });
} }
const identityAccessToken = await identityUaDal.transaction(async (tx) => { const identityAccessToken = await identityUaDAL.transaction(async (tx) => {
const uaClientSecretDoc = await identityUaClientSecretDal.incrementUsage( const uaClientSecretDoc = await identityUaClientSecretDAL.incrementUsage(
validClientSecretInfo.id, validClientSecretInfo.id,
tx tx
); );
const newToken = await identityAccessTokenDal.create( const newToken = await identityAccessTokenDAL.create(
{ {
identityId: identityUa.identityId, identityId: identityUa.identityId,
authType: IdentityAuthMethod.Univeral, authType: IdentityAuthMethod.Univeral,
@@ -152,7 +152,7 @@ export const identityUaServiceFactory = ({
actorId, actorId,
actor actor
}: TAttachUaDTO) => { }: TAttachUaDTO) => {
const identityMembershipOrg = await identityOrgMembershipDal.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" });
if (identityMembershipOrg.identity.authMethod) if (identityMembershipOrg.identity.authMethod)
throw new BadRequestError({ throw new BadRequestError({
@@ -209,8 +209,8 @@ export const identityUaServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress); return extractIPDetails(accessTokenTrustedIp.ipAddress);
}); });
const identityUa = await identityUaDal.transaction(async (tx) => { const identityUa = await identityUaDAL.transaction(async (tx) => {
const doc = await identityUaDal.create( const doc = await identityUaDAL.create(
{ {
identityId: identityMembershipOrg.identityId, identityId: identityMembershipOrg.identityId,
clientId: crypto.randomUUID(), clientId: crypto.randomUUID(),
@@ -222,7 +222,7 @@ export const identityUaServiceFactory = ({
}, },
tx tx
); );
await identityDal.updateById( await identityDAL.updateById(
identityMembershipOrg.identityId, identityMembershipOrg.identityId,
{ {
authMethod: IdentityAuthMethod.Univeral authMethod: IdentityAuthMethod.Univeral
@@ -244,14 +244,14 @@ export const identityUaServiceFactory = ({
actorId, actorId,
actor actor
}: TUpdateUaDTO) => { }: TUpdateUaDTO) => {
const identityMembershipOrg = await identityOrgMembershipDal.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" });
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"
}); });
const uaIdentityAuth = await identityUaDal.findOne({ identityId }); const uaIdentityAuth = await identityUaDAL.findOne({ identityId });
if ( if (
(accessTokenMaxTTL || uaIdentityAuth.accessTokenMaxTTL) > 0 && (accessTokenMaxTTL || uaIdentityAuth.accessTokenMaxTTL) > 0 &&
@@ -307,7 +307,7 @@ export const identityUaServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress); return extractIPDetails(accessTokenTrustedIp.ipAddress);
}); });
const updatedUaAuth = await identityUaDal.updateById(uaIdentityAuth.id, { const updatedUaAuth = await identityUaDAL.updateById(uaIdentityAuth.id, {
clientSecretTrustedIps: reformattedClientSecretTrustedIps clientSecretTrustedIps: reformattedClientSecretTrustedIps
? JSON.stringify(reformattedClientSecretTrustedIps) ? JSON.stringify(reformattedClientSecretTrustedIps)
: undefined, : undefined,
@@ -322,14 +322,14 @@ export const identityUaServiceFactory = ({
}; };
const getIdentityUa = async ({ identityId, actorId, actor }: TGetUaDTO) => { const getIdentityUa = async ({ identityId, actorId, actor }: TGetUaDTO) => {
const identityMembershipOrg = await identityOrgMembershipDal.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" });
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"
}); });
const uaIdentityAuth = await identityUaDal.findOne({ identityId }); const uaIdentityAuth = await identityUaDAL.findOne({ identityId });
const { permission } = await permissionService.getOrgPermission( const { permission } = await permissionService.getOrgPermission(
actor, actor,
@@ -351,7 +351,7 @@ export const identityUaServiceFactory = ({
description, description,
numUsesLimit numUsesLimit
}: TCreateUaClientSecretDTO) => { }: TCreateUaClientSecretDTO) => {
const identityMembershipOrg = await identityOrgMembershipDal.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
@@ -381,11 +381,11 @@ export const identityUaServiceFactory = ({
const appCfg = getConfig(); const appCfg = getConfig();
const clientSecret = crypto.randomBytes(32).toString("hex"); const clientSecret = crypto.randomBytes(32).toString("hex");
const clientSecretHash = await bcrypt.hash(clientSecret, appCfg.SALT_ROUNDS); const clientSecretHash = await bcrypt.hash(clientSecret, appCfg.SALT_ROUNDS);
const identityUniversalAuth = await identityUaDal.findOne({ const identityUniversalAuth = await identityUaDAL.findOne({
identityId identityId
}); });
const identityUaClientSecret = await identityUaClientSecretDal.create({ const identityUaClientSecret = await identityUaClientSecretDAL.create({
identityUAId: identityUniversalAuth.id, identityUAId: identityUniversalAuth.id,
description, description,
clientSecretPrefix: clientSecret.slice(0, 4), clientSecretPrefix: clientSecret.slice(0, 4),
@@ -404,7 +404,7 @@ export const identityUaServiceFactory = ({
}; };
const getUaClientSecrets = async ({ actor, actorId, identityId }: TGetUaClientSecretsDTO) => { const getUaClientSecrets = async ({ actor, actorId, identityId }: TGetUaClientSecretsDTO) => {
const identityMembershipOrg = await identityOrgMembershipDal.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
@@ -431,11 +431,11 @@ export const identityUaServiceFactory = ({
message: "Failed to add identity to project with more privileged role" message: "Failed to add identity to project with more privileged role"
}); });
const identityUniversalAuth = await identityUaDal.findOne({ const identityUniversalAuth = await identityUaDAL.findOne({
identityId identityId
}); });
const clientSecrets = await identityUaClientSecretDal.find({ const clientSecrets = await identityUaClientSecretDAL.find({
identityUAId: identityUniversalAuth.id, identityUAId: identityUniversalAuth.id,
isClientSecretRevoked: false isClientSecretRevoked: false
}); });
@@ -448,7 +448,7 @@ export const identityUaServiceFactory = ({
actor, actor,
clientSecretId clientSecretId
}: TRevokeUaClientSecretDTO) => { }: TRevokeUaClientSecretDTO) => {
const identityMembershipOrg = await identityOrgMembershipDal.findOne({ identityId }); const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" }); if (!identityMembershipOrg) throw new BadRequestError({ message: "Failed to find identity" });
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral) if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.Univeral)
throw new BadRequestError({ throw new BadRequestError({
@@ -475,7 +475,7 @@ export const identityUaServiceFactory = ({
message: "Failed to add identity to project with more privileged role" message: "Failed to add identity to project with more privileged role"
}); });
const clientSecret = await identityUaClientSecretDal.updateById(clientSecretId, { const clientSecret = await identityUaClientSecretDAL.updateById(clientSecretId, {
isClientSecretRevoked: true isClientSecretRevoked: true
}); });
return { ...clientSecret, identityId, orgId: identityMembershipOrg.orgId }; return { ...clientSecret, identityId, orgId: identityMembershipOrg.orgId };
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TIdentityDalFactory = ReturnType<typeof identityDalFactory>; export type TIdentityDALFactory = ReturnType<typeof identityDALFactory>;
export const identityDalFactory = (db: TDbClient) => { export const identityDALFactory = (db: TDbClient) => {
const identityOrm = ormify(db, TableName.Identity); const identityOrm = ormify(db, TableName.Identity);
return identityOrm; return identityOrm;
}; };
@@ -5,9 +5,9 @@ import { TableName, TIdentityOrgMemberships } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TIdentityOrgDalFactory = ReturnType<typeof identityOrgDalFactory>; export type TIdentityOrgDALFactory = ReturnType<typeof identityOrgDALFactory>;
export const identityOrgDalFactory = (db: TDbClient) => { export const identityOrgDALFactory = (db: TDbClient) => {
const identityOrgOrm = ormify(db, TableName.IdentityOrgMembership); const identityOrgOrm = ormify(db, TableName.IdentityOrgMembership);
const findOne = async (filter: Partial<TIdentityOrgMemberships>, tx?: Knex) => { const findOne = async (filter: Partial<TIdentityOrgMemberships>, tx?: Knex) => {
@@ -11,21 +11,21 @@ import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";
import { TOrgPermission } from "@app/lib/types"; import { TOrgPermission } from "@app/lib/types";
import { ActorType } from "../auth/auth-type"; import { ActorType } from "../auth/auth-type";
import { TIdentityDalFactory } from "./identity-dal"; import { TIdentityDALFactory } from "./identity-dal";
import { TIdentityOrgDalFactory } from "./identity-org-dal"; import { TIdentityOrgDALFactory } from "./identity-org-dal";
import { TCreateIdentityDTO, TDeleteIdentityDTO, TUpdateIdentityDTO } from "./identity-types"; import { TCreateIdentityDTO, TDeleteIdentityDTO, TUpdateIdentityDTO } from "./identity-types";
type TIdentityServiceFactoryDep = { type TIdentityServiceFactoryDep = {
identityDal: TIdentityDalFactory; identityDAL: TIdentityDALFactory;
identityOrgMembershipDal: TIdentityOrgDalFactory; identityOrgMembershipDAL: TIdentityOrgDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getOrgPermissionByRole">; permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getOrgPermissionByRole">;
}; };
export type TIdentityServiceFactory = ReturnType<typeof identityServiceFactory>; export type TIdentityServiceFactory = ReturnType<typeof identityServiceFactory>;
export const identityServiceFactory = ({ export const identityServiceFactory = ({
identityDal, identityDAL,
identityOrgMembershipDal, identityOrgMembershipDAL,
permissionService permissionService
}: TIdentityServiceFactoryDep) => { }: TIdentityServiceFactoryDep) => {
const createIdentity = async ({ name, role, actor, orgId, actorId }: TCreateIdentityDTO) => { const createIdentity = async ({ name, role, actor, orgId, actorId }: TCreateIdentityDTO) => {
@@ -42,9 +42,9 @@ export const identityServiceFactory = ({
if (!hasRequiredPriviledges) if (!hasRequiredPriviledges)
throw new BadRequestError({ message: "Failed to create a more privileged identity" }); throw new BadRequestError({ message: "Failed to create a more privileged identity" });
const identity = await identityDal.transaction(async (tx) => { const identity = await identityDAL.transaction(async (tx) => {
const newIdentity = await identityDal.create({ name }, tx); const newIdentity = await identityDAL.create({ name }, tx);
await identityOrgMembershipDal.create( await identityOrgMembershipDAL.create(
{ {
identityId: newIdentity.id, identityId: newIdentity.id,
orgId, orgId,
@@ -61,7 +61,7 @@ export const identityServiceFactory = ({
}; };
const updateIdentity = async ({ id, role, name, actor, actorId }: TUpdateIdentityDTO) => { const updateIdentity = async ({ id, role, name, actor, actorId }: TUpdateIdentityDTO) => {
const identityOrgMembership = await identityOrgMembershipDal.findOne({ identityId: id }); const identityOrgMembership = await identityOrgMembershipDAL.findOne({ identityId: id });
if (!identityOrgMembership) if (!identityOrgMembership)
throw new BadRequestError({ message: `Failed to find identity with id ${id}` }); throw new BadRequestError({ message: `Failed to find identity with id ${id}` });
@@ -96,12 +96,12 @@ export const identityServiceFactory = ({
if (isCustomRole) customRole = customOrgRole; if (isCustomRole) customRole = customOrgRole;
} }
const identity = await identityDal.transaction(async (tx) => { const identity = await identityDAL.transaction(async (tx) => {
const newIdentity = name const newIdentity = name
? await identityDal.updateById(id, { name }, tx) ? await identityDAL.updateById(id, { name }, tx)
: await identityDal.findById(id, tx); : await identityDAL.findById(id, tx);
if (role) { if (role) {
await identityOrgMembershipDal.update( await identityOrgMembershipDAL.update(
{ identityId: id }, { identityId: id },
{ {
role: customRole ? OrgMembershipRole.Custom : role, role: customRole ? OrgMembershipRole.Custom : role,
@@ -117,7 +117,7 @@ export const identityServiceFactory = ({
}; };
const deleteIdentity = async ({ actorId, actor, id }: TDeleteIdentityDTO) => { const deleteIdentity = async ({ actorId, actor, id }: TDeleteIdentityDTO) => {
const identityOrgMembership = await identityOrgMembershipDal.findOne({ identityId: id }); const identityOrgMembership = await identityOrgMembershipDAL.findOne({ identityId: id });
if (!identityOrgMembership) if (!identityOrgMembership)
throw new BadRequestError({ message: `Failed to find identity with id ${id}` }); throw new BadRequestError({ message: `Failed to find identity with id ${id}` });
@@ -139,7 +139,7 @@ export const identityServiceFactory = ({
if (!hasRequiredPriviledges) if (!hasRequiredPriviledges)
throw new ForbiddenRequestError({ message: "Failed to delete more privileged identity" }); throw new ForbiddenRequestError({ message: "Failed to delete more privileged identity" });
const deletedIdentity = await identityDal.deleteById(id); const deletedIdentity = await identityDAL.deleteById(id);
return { ...deletedIdentity, orgId: identityOrgMembership.orgId }; return { ...deletedIdentity, orgId: identityOrgMembership.orgId };
}; };
@@ -150,7 +150,7 @@ export const identityServiceFactory = ({
OrgPermissionSubjects.Identity OrgPermissionSubjects.Identity
); );
const identityMemberhips = await identityOrgMembershipDal.findByOrgId(orgId); const identityMemberhips = await identityOrgMembershipDAL.findByOrgId(orgId);
return identityMemberhips; return identityMemberhips;
}; };
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TIntegrationAuthDalFactory = ReturnType<typeof integrationAuthDalFactory>; export type TIntegrationAuthDALFactory = ReturnType<typeof integrationAuthDALFactory>;
export const integrationAuthDalFactory = (db: TDbClient) => { export const integrationAuthDALFactory = (db: TDbClient) => {
const integrationAuthOrm = ormify(db, TableName.IntegrationAuth); const integrationAuthOrm = ormify(db, TableName.IntegrationAuth);
return integrationAuthOrm; return integrationAuthOrm;
}; };
@@ -19,11 +19,11 @@ import {
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectPermission } from "@app/lib/types"; import { TProjectPermission } from "@app/lib/types";
import { TIntegrationDalFactory } from "../integration/integration-dal"; import { TIntegrationDALFactory } from "../integration/integration-dal";
import { TProjectBotDalFactory } from "../project-bot/project-bot-dal"; import { TProjectBotDALFactory } from "../project-bot/project-bot-dal";
import { TProjectBotServiceFactory } from "../project-bot/project-bot-service"; import { TProjectBotServiceFactory } from "../project-bot/project-bot-service";
import { getApps } from "./integration-app-list"; import { getApps } from "./integration-app-list";
import { TIntegrationAuthDalFactory } from "./integration-auth-dal"; import { TIntegrationAuthDALFactory } from "./integration-auth-dal";
import { import {
TBitbucketWorkspace, TBitbucketWorkspace,
TChecklyGroups, TChecklyGroups,
@@ -54,10 +54,10 @@ import { getTeams } from "./integration-team";
import { exchangeCode, exchangeRefresh } from "./integration-token"; import { exchangeCode, exchangeRefresh } from "./integration-token";
type TIntegrationAuthServiceFactoryDep = { type TIntegrationAuthServiceFactoryDep = {
integrationAuthDal: TIntegrationAuthDalFactory; integrationAuthDAL: TIntegrationAuthDALFactory;
integrationDal: Pick<TIntegrationDalFactory, "delete">; integrationDAL: Pick<TIntegrationDALFactory, "delete">;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">; projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
projectBotDal: Pick<TProjectBotDalFactory, "findOne">; projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
}; };
@@ -65,9 +65,9 @@ export type TIntegrationAuthServiceFactory = ReturnType<typeof integrationAuthSe
export const integrationAuthServiceFactory = ({ export const integrationAuthServiceFactory = ({
permissionService, permissionService,
integrationAuthDal, integrationAuthDAL,
integrationDal, integrationDAL,
projectBotDal, projectBotDAL,
projectBotService projectBotService
}: TIntegrationAuthServiceFactoryDep) => { }: TIntegrationAuthServiceFactoryDep) => {
const listIntegrationAuthByProjectId = async ({ const listIntegrationAuthByProjectId = async ({
@@ -80,12 +80,12 @@ export const integrationAuthServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const authorizations = await integrationAuthDal.find({ projectId }); const authorizations = await integrationAuthDAL.find({ projectId });
return authorizations; return authorizations;
}; };
const getIntegrationAuth = async ({ actor, id, actorId }: TGetIntegrationAuthDTO) => { const getIntegrationAuth = async ({ actor, id, actorId }: TGetIntegrationAuthDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -117,7 +117,7 @@ export const integrationAuthServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const bot = await projectBotDal.findOne({ isActive: true, projectId }); const bot = await projectBotDAL.findOne({ isActive: true, projectId });
if (!bot) if (!bot)
throw new BadRequestError({ message: "Bot must be enabled for oauth2 code token exchange" }); throw new BadRequestError({ message: "Bot must be enabled for oauth2 code token exchange" });
@@ -154,12 +154,12 @@ export const integrationAuthServiceFactory = ({
updateDoc.accessTag = accessEncToken.tag; updateDoc.accessTag = accessEncToken.tag;
updateDoc.accessCiphertext = accessEncToken.ciphertext; updateDoc.accessCiphertext = accessEncToken.ciphertext;
} }
return integrationAuthDal.transaction(async (tx) => { return integrationAuthDAL.transaction(async (tx) => {
const doc = await integrationAuthDal.findOne({ projectId, integration }, tx); const doc = await integrationAuthDAL.findOne({ projectId, integration }, tx);
if (!doc) { if (!doc) {
return integrationAuthDal.create(updateDoc, tx); return integrationAuthDAL.create(updateDoc, tx);
} }
return integrationAuthDal.updateById(doc.id, updateDoc, tx); return integrationAuthDAL.updateById(doc.id, updateDoc, tx);
}); });
}; };
@@ -183,7 +183,7 @@ export const integrationAuthServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const bot = await projectBotDal.findOne({ isActive: true, projectId }); const bot = await projectBotDAL.findOne({ isActive: true, projectId });
if (!bot) if (!bot)
throw new BadRequestError({ message: "Bot must be enabled for oauth2 code token exchange" }); throw new BadRequestError({ message: "Bot must be enabled for oauth2 code token exchange" });
@@ -235,7 +235,7 @@ export const integrationAuthServiceFactory = ({
updateDoc.accessIdCiphertext = accessEncToken.ciphertext; updateDoc.accessIdCiphertext = accessEncToken.ciphertext;
} }
} }
return integrationAuthDal.create(updateDoc); return integrationAuthDAL.create(updateDoc);
}; };
// helper function // helper function
@@ -274,7 +274,7 @@ export const integrationAuthServiceFactory = ({
const refreshEncToken = encryptSymmetric128BitHexKeyUTF8(tokenDetails.refreshToken, botKey); const refreshEncToken = encryptSymmetric128BitHexKeyUTF8(tokenDetails.refreshToken, botKey);
const accessEncToken = encryptSymmetric128BitHexKeyUTF8(tokenDetails.accessToken, botKey); const accessEncToken = encryptSymmetric128BitHexKeyUTF8(tokenDetails.accessToken, botKey);
accessToken = tokenDetails.accessToken; accessToken = tokenDetails.accessToken;
await integrationAuthDal.updateById(integrationAuth.id, { await integrationAuthDAL.updateById(integrationAuth.id, {
refreshIV: refreshEncToken.iv, refreshIV: refreshEncToken.iv,
refreshTag: refreshEncToken.tag, refreshTag: refreshEncToken.tag,
refreshCiphertext: refreshEncToken.ciphertext, refreshCiphertext: refreshEncToken.ciphertext,
@@ -309,7 +309,7 @@ export const integrationAuthServiceFactory = ({
id, id,
workspaceSlug workspaceSlug
}: TIntegrationAuthAppsDTO) => { }: TIntegrationAuthAppsDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -336,7 +336,7 @@ export const integrationAuthServiceFactory = ({
}; };
const getIntegrationAuthTeams = async ({ actor, actorId, id }: TIntegrationAuthTeamsDTO) => { const getIntegrationAuthTeams = async ({ actor, actorId, id }: TIntegrationAuthTeamsDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -365,7 +365,7 @@ export const integrationAuthServiceFactory = ({
actor, actor,
actorId actorId
}: TIntegrationAuthVercelBranchesDTO) => { }: TIntegrationAuthVercelBranchesDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -405,7 +405,7 @@ export const integrationAuthServiceFactory = ({
id, id,
accountId accountId
}: TIntegrationAuthChecklyGroupsDTO) => { }: TIntegrationAuthChecklyGroupsDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -436,7 +436,7 @@ export const integrationAuthServiceFactory = ({
}; };
const getQoveryOrgs = async ({ actorId, actor, id }: TIntegrationAuthQoveryOrgsDTO) => { const getQoveryOrgs = async ({ actorId, actor, id }: TIntegrationAuthQoveryOrgsDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -469,7 +469,7 @@ export const integrationAuthServiceFactory = ({
id, id,
orgId orgId
}: TIntegrationAuthQoveryProjectDTO) => { }: TIntegrationAuthQoveryProjectDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -504,7 +504,7 @@ export const integrationAuthServiceFactory = ({
actor, actor,
actorId actorId
}: TIntegrationAuthQoveryEnvironmentsDTO) => { }: TIntegrationAuthQoveryEnvironmentsDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -544,7 +544,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
environmentId environmentId
}: TIntegrationAuthQoveryScopesDTO) => { }: TIntegrationAuthQoveryScopesDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -583,7 +583,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
environmentId environmentId
}: TIntegrationAuthQoveryScopesDTO) => { }: TIntegrationAuthQoveryScopesDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -622,7 +622,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
environmentId environmentId
}: TIntegrationAuthQoveryScopesDTO) => { }: TIntegrationAuthQoveryScopesDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -661,7 +661,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
appId appId
}: TIntegrationAuthRailwayEnvDTO) => { }: TIntegrationAuthRailwayEnvDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -727,7 +727,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
appId appId
}: TIntegrationAuthRailwayServicesDTO) => { }: TIntegrationAuthRailwayServicesDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -811,7 +811,7 @@ export const integrationAuthServiceFactory = ({
actor, actor,
id id
}: TIntegrationAuthBitbucketWorkspaceDTO) => { }: TIntegrationAuthBitbucketWorkspaceDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -862,7 +862,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
appId appId
}: TIntegrationAuthNorthflankSecretGroupDTO) => { }: TIntegrationAuthNorthflankSecretGroupDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -929,7 +929,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
actor actor
}: TGetIntegrationAuthTeamCityBuildConfigDTO) => { }: TGetIntegrationAuthTeamCityBuildConfigDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -979,7 +979,7 @@ export const integrationAuthServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const integrations = await integrationAuthDal.delete({ integration, projectId }); const integrations = await integrationAuthDAL.delete({ integration, projectId });
return integrations; return integrations;
}; };
@@ -988,7 +988,7 @@ export const integrationAuthServiceFactory = ({
actorId, actorId,
actor actor
}: TDeleteIntegrationAuthByIdDTO) => { }: TDeleteIntegrationAuthByIdDTO) => {
const integrationAuth = await integrationAuthDal.findById(id); const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" }); if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -1001,10 +1001,10 @@ export const integrationAuthServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
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 BadRequestError({ message: "Faled to find integration" }); if (!doc) throw new BadRequestError({ message: "Faled to find integration" });
await integrationDal.delete({ integrationAuthId: doc.id }, tx); await integrationDAL.delete({ integrationAuthId: doc.id }, tx);
return doc; return doc;
}); });
@@ -5,9 +5,9 @@ import { TableName, TIntegrations } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TIntegrationDalFactory = ReturnType<typeof integrationDalFactory>; export type TIntegrationDALFactory = ReturnType<typeof integrationDALFactory>;
export const integrationDalFactory = (db: TDbClient) => { export const integrationDALFactory = (db: TDbClient) => {
const integrationOrm = ormify(db, TableName.Integration); const integrationOrm = ormify(db, TableName.Integration);
const integrationFindQuery = (tx: Knex, filter: Partial<TIntegrations>) => const integrationFindQuery = (tx: Knex, filter: Partial<TIntegrations>) =>
@@ -8,10 +8,10 @@ import {
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectPermission } from "@app/lib/types"; import { TProjectPermission } from "@app/lib/types";
import { TIntegrationAuthDalFactory } from "../integration-auth/integration-auth-dal"; import { TIntegrationAuthDALFactory } from "../integration-auth/integration-auth-dal";
import { TSecretQueueFactory } from "../secret/secret-queue"; import { TSecretQueueFactory } from "../secret/secret-queue";
import { TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TIntegrationDalFactory } from "./integration-dal"; import { TIntegrationDALFactory } from "./integration-dal";
import { import {
TCreateIntegrationDTO, TCreateIntegrationDTO,
TDeleteIntegrationDTO, TDeleteIntegrationDTO,
@@ -19,9 +19,9 @@ import {
} from "./integration-types"; } from "./integration-types";
type TIntegrationServiceFactoryDep = { type TIntegrationServiceFactoryDep = {
integrationDal: TIntegrationDalFactory; integrationDAL: TIntegrationDALFactory;
integrationAuthDal: TIntegrationAuthDalFactory; integrationAuthDAL: TIntegrationAuthDALFactory;
folderDal: Pick<TSecretFolderDalFactory, "findBySecretPath">; folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
secretQueueService: Pick<TSecretQueueFactory, "syncIntegrations">; secretQueueService: Pick<TSecretQueueFactory, "syncIntegrations">;
}; };
@@ -29,9 +29,9 @@ type TIntegrationServiceFactoryDep = {
export type TIntegrationServiceFactory = ReturnType<typeof integrationServiceFactory>; export type TIntegrationServiceFactory = ReturnType<typeof integrationServiceFactory>;
export const integrationServiceFactory = ({ export const integrationServiceFactory = ({
integrationDal, integrationDAL,
integrationAuthDal, integrationAuthDAL,
folderDal, folderDAL,
permissionService, permissionService,
secretQueueService secretQueueService
}: TIntegrationServiceFactoryDep) => { }: TIntegrationServiceFactoryDep) => {
@@ -54,7 +54,7 @@ export const integrationServiceFactory = ({
targetEnvironment, targetEnvironment,
targetEnvironmentId targetEnvironmentId
}: TCreateIntegrationDTO) => { }: TCreateIntegrationDTO) => {
const integrationAuth = await integrationAuthDal.findById(integrationAuthId); const integrationAuth = await integrationAuthDAL.findById(integrationAuthId);
if (!integrationAuth) throw new BadRequestError({ message: "Integration auth not found" }); if (!integrationAuth) throw new BadRequestError({ message: "Integration auth not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -67,14 +67,14 @@ export const integrationServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const folder = await folderDal.findBySecretPath( const folder = await folderDAL.findBySecretPath(
integrationAuth.projectId, integrationAuth.projectId,
sourceEnvironment, sourceEnvironment,
secretPath secretPath
); );
if (!folder) throw new BadRequestError({ message: "Folder path not found" }); if (!folder) throw new BadRequestError({ message: "Folder path not found" });
const integration = await integrationDal.create({ const integration = await integrationDAL.create({
envId: folder.envId, envId: folder.envId,
secretPath, secretPath,
isActive, isActive,
@@ -113,7 +113,7 @@ export const integrationServiceFactory = ({
environment, environment,
secretPath secretPath
}: TUpdateIntegrationDTO) => { }: TUpdateIntegrationDTO) => {
const integration = await integrationDal.findById(id); const integration = await integrationDAL.findById(id);
if (!integration) throw new BadRequestError({ message: "Integration auth not found" }); if (!integration) throw new BadRequestError({ message: "Integration auth not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -126,10 +126,10 @@ export const integrationServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const folder = await folderDal.findBySecretPath(integration.projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(integration.projectId, environment, secretPath);
if (!folder) throw new BadRequestError({ message: "Folder path not found" }); if (!folder) throw new BadRequestError({ message: "Folder path not found" });
const updatedIntegration = await integrationDal.updateById(id, { const updatedIntegration = await integrationDAL.updateById(id, {
envId: folder.envId, envId: folder.envId,
isActive, isActive,
app, app,
@@ -143,7 +143,7 @@ export const integrationServiceFactory = ({
}; };
const deleteIntegration = async ({ actorId, id, actor }: TDeleteIntegrationDTO) => { const deleteIntegration = async ({ actorId, id, actor }: TDeleteIntegrationDTO) => {
const integration = await integrationDal.findById(id); const integration = await integrationDAL.findById(id);
if (!integration) throw new BadRequestError({ message: "Integration auth not found" }); if (!integration) throw new BadRequestError({ message: "Integration auth not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -156,7 +156,7 @@ export const integrationServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const deletedIntegration = await integrationDal.deleteById(id); const deletedIntegration = await integrationDAL.deleteById(id);
return { ...integration, ...deletedIntegration }; return { ...integration, ...deletedIntegration };
}; };
@@ -167,7 +167,7 @@ export const integrationServiceFactory = ({
ProjectPermissionSub.Integrations ProjectPermissionSub.Integrations
); );
const integrations = await integrationDal.findByProjectId(projectId); const integrations = await integrationDAL.findByProjectId(projectId);
return integrations; return integrations;
}; };
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName, TIncidentContacts } from "@app/db/schemas"; import { TableName, TIncidentContacts } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
export type TIncidentContactsDalFactory = ReturnType<typeof incidentContactDalFactory>; export type TIncidentContactsDALFactory = ReturnType<typeof incidentContactDALFactory>;
export const incidentContactDalFactory = (db: TDbClient) => { export const incidentContactDALFactory = (db: TDbClient) => {
const create = async (orgId: string, email: string) => { const create = async (orgId: string, email: string) => {
try { try {
const [incidentContact] = await db(TableName.IncidentContact) const [incidentContact] = await db(TableName.IncidentContact)
+2 -2
View File
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TOrgBotDalFactory = ReturnType<typeof orgBotDalFactory>; export type TOrgBotDALFactory = ReturnType<typeof orgBotDALFactory>;
export const orgBotDalFactory = (db: TDbClient) => { export const orgBotDALFactory = (db: TDbClient) => {
const orgBotOrm = ormify(db, TableName.OrgBot); const orgBotOrm = ormify(db, TableName.OrgBot);
return orgBotOrm; return orgBotOrm;
}; };
+2 -2
View File
@@ -18,9 +18,9 @@ import {
withTransaction withTransaction
} from "@app/lib/knex"; } from "@app/lib/knex";
export type TOrgDalFactory = ReturnType<typeof orgDalFactory>; export type TOrgDALFactory = ReturnType<typeof orgDALFactory>;
export const orgDalFactory = (db: TDbClient) => { export const orgDALFactory = (db: TDbClient) => {
const findOrgById = async (orgId: string) => { const findOrgById = async (orgId: string) => {
try { try {
const org = await db(TableName.Organization).where({ id: orgId }).first(); const org = await db(TableName.Organization).where({ id: orgId }).first();
+2 -2
View File
@@ -2,6 +2,6 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TOrgRoleDalFactory = ReturnType<typeof orgRoleDalFactory>; export type TOrgRoleDALFactory = ReturnType<typeof orgRoleDALFactory>;
export const orgRoleDalFactory = (db: TDbClient) => ormify(db, TableName.OrgRoles); export const orgRoleDALFactory = (db: TDbClient) => ormify(db, TableName.OrgRoles);
@@ -11,17 +11,17 @@ import {
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TOrgRoleDalFactory } from "./org-role-dal"; import { TOrgRoleDALFactory } from "./org-role-dal";
type TOrgRoleServiceFactoryDep = { type TOrgRoleServiceFactoryDep = {
orgRoleDal: TOrgRoleDalFactory; orgRoleDAL: TOrgRoleDALFactory;
permissionService: TPermissionServiceFactory; permissionService: TPermissionServiceFactory;
}; };
export type TOrgRoleServiceFactory = ReturnType<typeof orgRoleServiceFactory>; export type TOrgRoleServiceFactory = ReturnType<typeof orgRoleServiceFactory>;
export const orgRoleServiceFactory = ({ export const orgRoleServiceFactory = ({
orgRoleDal, orgRoleDAL,
permissionService permissionService
}: TOrgRoleServiceFactoryDep) => { }: TOrgRoleServiceFactoryDep) => {
const createRole = async ( const createRole = async (
@@ -34,9 +34,9 @@ export const orgRoleServiceFactory = ({
OrgPermissionActions.Create, OrgPermissionActions.Create,
OrgPermissionSubjects.Role OrgPermissionSubjects.Role
); );
const existingRole = await orgRoleDal.findOne({ slug: data.slug, orgId }); const existingRole = await orgRoleDAL.findOne({ slug: data.slug, orgId });
if (existingRole) throw new BadRequestError({ name: "Create Role", message: "Duplicate role" }); if (existingRole) throw new BadRequestError({ name: "Create Role", message: "Duplicate role" });
const role = await orgRoleDal.create({ const role = await orgRoleDAL.create({
...data, ...data,
orgId, orgId,
permissions: JSON.stringify(data.permissions) permissions: JSON.stringify(data.permissions)
@@ -56,11 +56,11 @@ export const orgRoleServiceFactory = ({
OrgPermissionSubjects.Role OrgPermissionSubjects.Role
); );
if (data?.slug) { if (data?.slug) {
const existingRole = await orgRoleDal.findOne({ slug: data.slug, orgId }); const existingRole = await orgRoleDAL.findOne({ slug: data.slug, orgId });
if (existingRole && existingRole.id !== roleId) if (existingRole && existingRole.id !== roleId)
throw new BadRequestError({ name: "Update Role", message: "Duplicate role" }); throw new BadRequestError({ name: "Update Role", message: "Duplicate role" });
} }
const [updatedRole] = await orgRoleDal.update( const [updatedRole] = await orgRoleDAL.update(
{ id: roleId, orgId }, { id: roleId, orgId },
{ ...data, permissions: data.permissions ? JSON.stringify(data.permissions) : undefined } { ...data, permissions: data.permissions ? JSON.stringify(data.permissions) : undefined }
); );
@@ -74,7 +74,7 @@ export const orgRoleServiceFactory = ({
OrgPermissionActions.Delete, OrgPermissionActions.Delete,
OrgPermissionSubjects.Role OrgPermissionSubjects.Role
); );
const [deletedRole] = await orgRoleDal.delete({ id: roleId, orgId }); const [deletedRole] = await orgRoleDAL.delete({ id: roleId, orgId });
if (!deleteRole) throw new BadRequestError({ message: "Role not found", name: "Update role" }); if (!deleteRole) throw new BadRequestError({ message: "Role not found", name: "Update role" });
return deletedRole; return deletedRole;
@@ -86,7 +86,7 @@ export const orgRoleServiceFactory = ({
OrgPermissionActions.Read, OrgPermissionActions.Read,
OrgPermissionSubjects.Role OrgPermissionSubjects.Role
); );
const customRoles = await orgRoleDal.find({ orgId }); const customRoles = await orgRoleDAL.find({ orgId });
const roles = [ const roles = [
{ {
id: "b11b49a9-09a9-4443-916a-4246f9ff2c69", // dummy userid id: "b11b49a9-09a9-4443-916a-4246f9ff2c69", // dummy userid
+47 -47
View File
@@ -8,7 +8,7 @@ import {
OrgPermissionSubjects OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission"; } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
import { TSamlConfigDalFactory } from "@app/ee/services/saml-config/saml-config-dal"; import { TSamlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { generateAsymmetricKeyPair } from "@app/lib/crypto"; import { generateAsymmetricKeyPair } from "@app/lib/crypto";
import { generateSymmetricKey, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption"; import { generateSymmetricKey, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
@@ -19,11 +19,11 @@ import { AuthMethod, AuthTokenType } from "../auth/auth-type";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service"; import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types"; import { TokenType } from "../auth-token/auth-token-types";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service"; import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TIncidentContactsDalFactory } from "./incident-contacts-dal"; import { TIncidentContactsDALFactory } from "./incident-contacts-dal";
import { TOrgBotDalFactory } from "./org-bot-dal"; import { TOrgBotDALFactory } from "./org-bot-dal";
import { TOrgDalFactory } from "./org-dal"; import { TOrgDALFactory } from "./org-dal";
import { TOrgRoleDalFactory } from "./org-role-dal"; import { TOrgRoleDALFactory } from "./org-role-dal";
import { import {
TDeleteOrgMembershipDTO, TDeleteOrgMembershipDTO,
TInviteUserToOrgDTO, TInviteUserToOrgDTO,
@@ -32,12 +32,12 @@ import {
} from "./org-types"; } from "./org-types";
type TOrgServiceFactoryDep = { type TOrgServiceFactoryDep = {
orgDal: TOrgDalFactory; orgDAL: TOrgDALFactory;
orgBotDal: TOrgBotDalFactory; orgBotDAL: TOrgBotDALFactory;
orgRoleDal: TOrgRoleDalFactory; orgRoleDAL: TOrgRoleDALFactory;
userDal: TUserDalFactory; userDAL: TUserDALFactory;
incidentContactDal: TIncidentContactsDalFactory; incidentContactDAL: TIncidentContactsDALFactory;
samlConfigDal: Pick<TSamlConfigDalFactory, "findOne">; samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne">;
smtpService: TSmtpService; smtpService: TSmtpService;
tokenService: TAuthTokenServiceFactory; tokenService: TAuthTokenServiceFactory;
permissionService: TPermissionServiceFactory; permissionService: TPermissionServiceFactory;
@@ -50,23 +50,23 @@ type TOrgServiceFactoryDep = {
export type TOrgServiceFactory = ReturnType<typeof orgServiceFactory>; export type TOrgServiceFactory = ReturnType<typeof orgServiceFactory>;
export const orgServiceFactory = ({ export const orgServiceFactory = ({
orgDal, orgDAL,
userDal, userDAL,
orgRoleDal, orgRoleDAL,
incidentContactDal, incidentContactDAL,
permissionService, permissionService,
smtpService, smtpService,
tokenService, tokenService,
orgBotDal, orgBotDAL,
licenseService, licenseService,
samlConfigDal samlConfigDAL
}: TOrgServiceFactoryDep) => { }: TOrgServiceFactoryDep) => {
/* /*
* Get organization details by the organization id * Get organization details by the organization id
* */ * */
const findOrganizationById = async (userId: string, orgId: string) => { const findOrganizationById = async (userId: string, orgId: string) => {
await permissionService.getUserOrgPermission(userId, orgId); await permissionService.getUserOrgPermission(userId, orgId);
const org = await orgDal.findOrgById(orgId); const org = await orgDAL.findOrgById(orgId);
if (!org) if (!org)
throw new BadRequestError({ name: "Org not found", message: "Organization not found" }); throw new BadRequestError({ name: "Org not found", message: "Organization not found" });
return org; return org;
@@ -75,7 +75,7 @@ export const orgServiceFactory = ({
* Get all organization a user part of * Get all organization a user part of
* */ * */
const findAllOrganizationOfUser = async (userId: string) => { const findAllOrganizationOfUser = async (userId: string) => {
const orgs = await orgDal.findAllOrgsByUserId(userId); const orgs = await orgDAL.findAllOrgsByUserId(userId);
return orgs; return orgs;
}; };
/* /*
@@ -88,7 +88,7 @@ export const orgServiceFactory = ({
OrgPermissionSubjects.Member OrgPermissionSubjects.Member
); );
const members = await orgDal.findAllOrgMembers(orgId); const members = await orgDAL.findAllOrgMembers(orgId);
return members; return members;
}; };
/* /*
@@ -100,7 +100,7 @@ export const orgServiceFactory = ({
OrgPermissionActions.Edit, OrgPermissionActions.Edit,
OrgPermissionSubjects.Settings OrgPermissionSubjects.Settings
); );
const org = await orgDal.updateById(orgId, { name }); const org = await orgDAL.updateById(orgId, { name });
if (!org) if (!org)
throw new BadRequestError({ name: "Org not found", message: "Organization not found" }); throw new BadRequestError({ name: "Org not found", message: "Organization not found" });
return org; return org;
@@ -127,9 +127,9 @@ export const orgServiceFactory = ({
} = infisicalSymmetricEncypt(key); } = infisicalSymmetricEncypt(key);
const customerId = await licenseService.generateOrgCustomerId(orgName, userEmail); const customerId = await licenseService.generateOrgCustomerId(orgName, userEmail);
const organization = await orgDal.transaction(async (tx) => { const organization = await orgDAL.transaction(async (tx) => {
const org = await orgDal.create({ name: orgName, customerId }, tx); const org = await orgDAL.create({ name: orgName, customerId }, tx);
await orgDal.createMembership( await orgDAL.createMembership(
{ {
userId, userId,
orgId: org.id, orgId: org.id,
@@ -138,7 +138,7 @@ export const orgServiceFactory = ({
}, },
tx tx
); );
await orgBotDal.create( await orgBotDAL.create(
{ {
name: org.name, name: org.name,
publicKey, publicKey,
@@ -170,7 +170,7 @@ export const orgServiceFactory = ({
if (membership.role !== OrgMembershipRole.Admin) if (membership.role !== OrgMembershipRole.Admin)
throw new UnauthorizedError({ name: "Delete org by id", message: "Not an admin" }); throw new UnauthorizedError({ name: "Delete org by id", message: "Not an admin" });
const organization = await orgDal.deleteById(orgId); const organization = await orgDAL.deleteById(orgId);
if (organization.customerId) { if (organization.customerId) {
await licenseService.removeOrgCustomer(organization.customerId); await licenseService.removeOrgCustomer(organization.customerId);
} }
@@ -194,7 +194,7 @@ export const orgServiceFactory = ({
const isCustomRole = !Object.values(OrgMembershipRole).includes(role as OrgMembershipRole); const isCustomRole = !Object.values(OrgMembershipRole).includes(role as OrgMembershipRole);
if (isCustomRole) { if (isCustomRole) {
const customRole = await orgRoleDal.findOne({ slug: role, orgId }); const customRole = await orgRoleDAL.findOne({ slug: role, orgId });
if (!customRole) if (!customRole)
throw new BadRequestError({ name: "Update membership", message: "Role not found" }); throw new BadRequestError({ name: "Update membership", message: "Role not found" });
@@ -205,7 +205,7 @@ export const orgServiceFactory = ({
"Failed to assign custom role due to RBAC restriction. Upgrade plan to assign custom role to member." "Failed to assign custom role due to RBAC restriction. Upgrade plan to assign custom role to member."
}); });
const [membership] = await orgDal.updateMembership( const [membership] = await orgDAL.updateMembership(
{ id: membershipId, orgId }, { id: membershipId, orgId },
{ {
role: OrgMembershipRole.Custom, role: OrgMembershipRole.Custom,
@@ -215,7 +215,7 @@ export const orgServiceFactory = ({
return membership; return membership;
} }
const [membership] = await orgDal.updateMembership( const [membership] = await orgDAL.updateMembership(
{ id: membershipId, orgId }, { id: membershipId, orgId },
{ role, roleId: null } { role, roleId: null }
); );
@@ -231,7 +231,7 @@ export const orgServiceFactory = ({
OrgPermissionSubjects.Member OrgPermissionSubjects.Member
); );
const samlCfg = await samlConfigDal.findOne({ orgId }); const samlCfg = await samlConfigDAL.findOne({ orgId });
if (samlCfg && samlCfg.isActive) { if (samlCfg && samlCfg.isActive) {
throw new BadRequestError({ throw new BadRequestError({
message: "Failed to invite member due to SAML SSO configured for organization" message: "Failed to invite member due to SAML SSO configured for organization"
@@ -246,12 +246,12 @@ export const orgServiceFactory = ({
"Failed to invite member due to member limit reached. Upgrade plan to invite more members." "Failed to invite member due to member limit reached. Upgrade plan to invite more members."
}); });
} }
const invitee = await orgDal.transaction(async (tx) => { const invitee = await orgDAL.transaction(async (tx) => {
const inviteeUser = await userDal.findUserByEmail(inviteeEmail, tx); const inviteeUser = await userDAL.findUserByEmail(inviteeEmail, tx);
if (inviteeUser) { if (inviteeUser) {
// if user already exist means its already part of infisical // if user already exist means its already part of infisical
// Thus the signup flow is not needed anymore // Thus the signup flow is not needed anymore
const [inviteeMembership] = await orgDal.findMembership( const [inviteeMembership] = await orgDAL.findMembership(
{ orgId, userId: inviteeUser.id }, { orgId, userId: inviteeUser.id },
{ tx } { tx }
); );
@@ -263,7 +263,7 @@ export const orgServiceFactory = ({
} }
if (!inviteeMembership) { if (!inviteeMembership) {
await orgDal.createMembership( await orgDAL.createMembership(
{ {
userId: inviteeUser.id, userId: inviteeUser.id,
inviteEmail: inviteeEmail, inviteEmail: inviteeEmail,
@@ -284,7 +284,7 @@ export const orgServiceFactory = ({
}); });
} }
// not invited before // not invited before
const user = await userDal.create( const user = await userDAL.create(
{ {
email: inviteeEmail, email: inviteeEmail,
isAccepted: false, isAccepted: false,
@@ -292,7 +292,7 @@ export const orgServiceFactory = ({
}, },
tx tx
); );
await orgDal.createMembership( await orgDAL.createMembership(
{ {
inviteEmail: inviteeEmail, inviteEmail: inviteeEmail,
orgId, orgId,
@@ -311,8 +311,8 @@ export const orgServiceFactory = ({
orgId orgId
}); });
const org = await orgDal.findOrgById(orgId); const org = await orgDAL.findOrgById(orgId);
const user = await userDal.findById(userId); const user = await userDAL.findById(userId);
const appCfg = getConfig(); const appCfg = getConfig();
await smtpService.sendMail({ await smtpService.sendMail({
template: SmtpTemplates.OrgInvite, template: SmtpTemplates.OrgInvite,
@@ -340,11 +340,11 @@ export const orgServiceFactory = ({
* magic link and issue a temporary signup token for user to complete setting up their account * magic link and issue a temporary signup token for user to complete setting up their account
*/ */
const verifyUserToOrg = async ({ orgId, email, code }: TVerifyUserToOrgDTO) => { const verifyUserToOrg = async ({ orgId, email, code }: TVerifyUserToOrgDTO) => {
const user = await userDal.findUserByEmail(email); const user = await userDAL.findUserByEmail(email);
if (!user) { if (!user) {
throw new BadRequestError({ message: "Invalid request", name: "Verify user to org" }); throw new BadRequestError({ message: "Invalid request", name: "Verify user to org" });
} }
const [orgMembership] = await orgDal.findMembership({ const [orgMembership] = await orgDAL.findMembership({
userId: user.id, userId: user.id,
status: OrgMembershipStatus.Invited, status: OrgMembershipStatus.Invited,
orgId orgId
@@ -365,7 +365,7 @@ export const orgServiceFactory = ({
if (user.isAccepted) { if (user.isAccepted) {
// this means user has already completed signup process // this means user has already completed signup process
// isAccepted is set true when keys are exchanged // isAccepted is set true when keys are exchanged
await orgDal.updateMembershipById(orgMembership.id, { await orgDAL.updateMembershipById(orgMembership.id, {
orgId, orgId,
status: OrgMembershipStatus.Accepted status: OrgMembershipStatus.Accepted
}); });
@@ -395,7 +395,7 @@ export const orgServiceFactory = ({
OrgPermissionSubjects.Member OrgPermissionSubjects.Member
); );
const membership = await orgDal.deleteMembershipById(membershipId, orgId); const membership = await orgDAL.deleteMembershipById(membershipId, orgId);
await licenseService.updateSubscriptionOrgMemberCount(orgId); await licenseService.updateSubscriptionOrgMemberCount(orgId);
return membership; return membership;
@@ -410,7 +410,7 @@ export const orgServiceFactory = ({
OrgPermissionActions.Read, OrgPermissionActions.Read,
OrgPermissionSubjects.IncidentAccount OrgPermissionSubjects.IncidentAccount
); );
const incidentContacts = await incidentContactDal.findByOrgId(orgId); const incidentContacts = await incidentContactDAL.findByOrgId(orgId);
return incidentContacts; return incidentContacts;
}; };
@@ -420,7 +420,7 @@ export const orgServiceFactory = ({
OrgPermissionActions.Create, OrgPermissionActions.Create,
OrgPermissionSubjects.IncidentAccount OrgPermissionSubjects.IncidentAccount
); );
const doesIncidentContactExist = await incidentContactDal.findOne(orgId, { email }); const doesIncidentContactExist = await incidentContactDAL.findOne(orgId, { email });
if (doesIncidentContactExist) { if (doesIncidentContactExist) {
throw new BadRequestError({ throw new BadRequestError({
message: "Incident contact already exist", message: "Incident contact already exist",
@@ -428,7 +428,7 @@ export const orgServiceFactory = ({
}); });
} }
const incidentContact = await incidentContactDal.create(orgId, email); const incidentContact = await incidentContactDAL.create(orgId, email);
return incidentContact; return incidentContact;
}; };
@@ -439,7 +439,7 @@ export const orgServiceFactory = ({
OrgPermissionSubjects.IncidentAccount OrgPermissionSubjects.IncidentAccount
); );
const incidentContact = await incidentContactDal.deleteById(id, orgId); const incidentContact = await incidentContactDAL.deleteById(id, orgId);
return incidentContact; return incidentContact;
}; };
@@ -5,9 +5,9 @@ import { TableName, TProjectBots } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TProjectBotDalFactory = ReturnType<typeof projectBotDalFactory>; export type TProjectBotDALFactory = ReturnType<typeof projectBotDALFactory>;
export const projectBotDalFactory = (db: TDbClient) => { export const projectBotDALFactory = (db: TDbClient) => {
const projectBotOrm = ormify(db, TableName.ProjectBot); const projectBotOrm = ormify(db, TableName.ProjectBot);
const findOne = async (filter: Partial<TProjectBots>, tx?: Knex) => { const findOne = async (filter: Partial<TProjectBots>, tx?: Knex) => {
@@ -18,18 +18,18 @@ import {
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectPermission } from "@app/lib/types"; import { TProjectPermission } from "@app/lib/types";
import { TProjectBotDalFactory } from "./project-bot-dal"; import { TProjectBotDALFactory } from "./project-bot-dal";
import { TSetActiveStateDTO } from "./project-bot-types"; import { TSetActiveStateDTO } from "./project-bot-types";
type TProjectBotServiceFactoryDep = { type TProjectBotServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
projectBotDal: TProjectBotDalFactory; projectBotDAL: TProjectBotDALFactory;
}; };
export type TProjectBotServiceFactory = ReturnType<typeof projectBotServiceFactory>; export type TProjectBotServiceFactory = ReturnType<typeof projectBotServiceFactory>;
export const projectBotServiceFactory = ({ export const projectBotServiceFactory = ({
projectBotDal, projectBotDAL,
permissionService permissionService
}: TProjectBotServiceFactoryDep) => { }: TProjectBotServiceFactoryDep) => {
const getBotKey = async (projectId: string) => { const getBotKey = async (projectId: string) => {
@@ -37,7 +37,7 @@ export const projectBotServiceFactory = ({
const encryptionKey = appCfg.ENCRYPTION_KEY; const encryptionKey = appCfg.ENCRYPTION_KEY;
const rootEncryptionKey = appCfg.ROOT_ENCRYPTION_KEY; const rootEncryptionKey = appCfg.ROOT_ENCRYPTION_KEY;
const bot = await projectBotDal.findOne({ projectId }); const bot = await projectBotDAL.findOne({ projectId });
if (!bot) throw new BadRequestError({ message: "failed to find bot key" }); if (!bot) throw new BadRequestError({ message: "failed to find bot key" });
if (!bot.isActive) throw new BadRequestError({ message: "Bot is not active" }); if (!bot.isActive) throw new BadRequestError({ message: "Bot is not active" });
if (!bot.encryptedProjectKeyNonce || !bot.encryptedProjectKey) if (!bot.encryptedProjectKeyNonce || !bot.encryptedProjectKey)
@@ -85,14 +85,14 @@ export const projectBotServiceFactory = ({
); );
const appCfg = getConfig(); const appCfg = getConfig();
const bot = await projectBotDal.transaction(async (tx) => { const bot = await projectBotDAL.transaction(async (tx) => {
const doc = await projectBotDal.findOne({ projectId }, tx); const doc = await projectBotDAL.findOne({ projectId }, tx);
if (doc) return doc; if (doc) return doc;
const { publicKey, privateKey } = generateAsymmetricKeyPair(); const { publicKey, privateKey } = generateAsymmetricKeyPair();
if (appCfg.ROOT_ENCRYPTION_KEY) { if (appCfg.ROOT_ENCRYPTION_KEY) {
const { iv, tag, ciphertext } = encryptSymmetric(privateKey, appCfg.ROOT_ENCRYPTION_KEY); const { iv, tag, ciphertext } = encryptSymmetric(privateKey, appCfg.ROOT_ENCRYPTION_KEY);
return projectBotDal.create( return projectBotDAL.create(
{ {
name: "Infisical Bot", name: "Infisical Bot",
projectId, projectId,
@@ -112,7 +112,7 @@ export const projectBotServiceFactory = ({
privateKey, privateKey,
appCfg.ENCRYPTION_KEY appCfg.ENCRYPTION_KEY
); );
return projectBotDal.create( return projectBotDAL.create(
{ {
name: "Infisical Bot", name: "Infisical Bot",
projectId, projectId,
@@ -139,7 +139,7 @@ export const projectBotServiceFactory = ({
actorId, actorId,
isActive isActive
}: TSetActiveStateDTO) => { }: TSetActiveStateDTO) => {
const bot = await projectBotDal.findById(botId); const bot = await projectBotDAL.findById(botId);
if (!bot) throw new BadRequestError({ message: "Bot not found" }); if (!bot) throw new BadRequestError({ message: "Bot not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -156,7 +156,7 @@ export const projectBotServiceFactory = ({
if (!botKey?.nonce || !botKey?.encryptedKey) { if (!botKey?.nonce || !botKey?.encryptedKey) {
throw new BadRequestError({ message: "Failed to set bot active - missing bot key" }); throw new BadRequestError({ message: "Failed to set bot active - missing bot key" });
} }
const doc = await projectBotDal.updateById(botId, { const doc = await projectBotDAL.updateById(botId, {
isActive: true, isActive: true,
encryptedProjectKey: botKey.encryptedKey, encryptedProjectKey: botKey.encryptedKey,
encryptedProjectKeyNonce: botKey.nonce, encryptedProjectKeyNonce: botKey.nonce,
@@ -166,7 +166,7 @@ export const projectBotServiceFactory = ({
return doc; return doc;
} }
const doc = await projectBotDal.updateById(botId, { const doc = await projectBotDAL.updateById(botId, {
isActive: false, isActive: false,
encryptedProjectKey: null, encryptedProjectKey: null,
encryptedProjectKeyNonce: null encryptedProjectKeyNonce: null
@@ -5,9 +5,9 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TProjectEnvDalFactory = ReturnType<typeof projectEnvDalFactory>; export type TProjectEnvDALFactory = ReturnType<typeof projectEnvDALFactory>;
export const projectEnvDalFactory = (db: TDbClient) => { export const projectEnvDALFactory = (db: TDbClient) => {
const projectEnvOrm = ormify(db, TableName.Environment); const projectEnvOrm = ormify(db, TableName.Environment);
const findBySlugs = async (projectId: string, env: string[], tx?: Knex) => { const findBySlugs = async (projectId: string, env: string[], tx?: Knex) => {
@@ -8,15 +8,15 @@ import {
} from "@app/ee/services/permission/project-permission"; } from "@app/ee/services/permission/project-permission";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectDalFactory } from "../project/project-dal"; import { TProjectDALFactory } from "../project/project-dal";
import { TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TProjectEnvDalFactory } from "./project-env-dal"; import { TProjectEnvDALFactory } from "./project-env-dal";
import { TCreateEnvDTO, TDeleteEnvDTO, TUpdateEnvDTO } from "./project-env-types"; import { TCreateEnvDTO, TDeleteEnvDTO, TUpdateEnvDTO } from "./project-env-types";
type TProjectEnvServiceFactoryDep = { type TProjectEnvServiceFactoryDep = {
projectEnvDal: TProjectEnvDalFactory; projectEnvDAL: TProjectEnvDALFactory;
folderDal: Pick<TSecretFolderDalFactory, "create">; folderDAL: Pick<TSecretFolderDALFactory, "create">;
projectDal: Pick<TProjectDalFactory, "findById">; projectDAL: Pick<TProjectDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
}; };
@@ -24,11 +24,11 @@ type TProjectEnvServiceFactoryDep = {
export type TProjectEnvServiceFactory = ReturnType<typeof projectEnvServiceFactory>; export type TProjectEnvServiceFactory = ReturnType<typeof projectEnvServiceFactory>;
export const projectEnvServiceFactory = ({ export const projectEnvServiceFactory = ({
projectEnvDal, projectEnvDAL,
permissionService, permissionService,
licenseService, licenseService,
projectDal, projectDAL,
folderDal folderDAL
}: TProjectEnvServiceFactoryDep) => { }: TProjectEnvServiceFactoryDep) => {
const createEnvironment = async ({ projectId, actorId, actor, name, slug }: TCreateEnvDTO) => { const createEnvironment = async ({ projectId, actorId, actor, name, slug }: TCreateEnvDTO) => {
const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId); const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId);
@@ -37,7 +37,7 @@ export const projectEnvServiceFactory = ({
ProjectPermissionSub.Environments ProjectPermissionSub.Environments
); );
const envs = await projectEnvDal.find({ projectId }); const envs = await projectEnvDAL.find({ projectId });
const existingEnv = envs.find(({ slug: envSlug }) => envSlug === slug); const existingEnv = envs.find(({ slug: envSlug }) => envSlug === slug);
if (existingEnv) if (existingEnv)
throw new BadRequestError({ throw new BadRequestError({
@@ -45,7 +45,7 @@ export const projectEnvServiceFactory = ({
name: "Create envv" name: "Create envv"
}); });
const project = await projectDal.findById(projectId); const project = await projectDAL.findById(projectId);
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
if (plan.environmentLimit !== null && envs.length >= plan.environmentLimit) { if (plan.environmentLimit !== null && envs.length >= plan.environmentLimit) {
// case: limit imposed on number of environments allowed // case: limit imposed on number of environments allowed
@@ -56,10 +56,10 @@ export const projectEnvServiceFactory = ({
}); });
} }
const env = await projectEnvDal.transaction(async (tx) => { const env = await projectEnvDAL.transaction(async (tx) => {
const lastPos = await projectEnvDal.findLastEnvPosition(projectId, tx); const lastPos = await projectEnvDAL.findLastEnvPosition(projectId, tx);
const doc = await projectEnvDal.create({ slug, name, projectId, position: lastPos + 1 }, tx); const doc = await projectEnvDAL.create({ slug, name, projectId, position: lastPos + 1 }, tx);
await folderDal.create({ name: "root", parentId: null, envId: doc.id, version: 1 }, tx); await folderDAL.create({ name: "root", parentId: null, envId: doc.id, version: 1 }, tx);
return doc; return doc;
}); });
return env; return env;
@@ -80,11 +80,11 @@ export const projectEnvServiceFactory = ({
ProjectPermissionSub.Environments ProjectPermissionSub.Environments
); );
const oldEnv = await projectEnvDal.findOne({ id, projectId }); const oldEnv = await projectEnvDAL.findOne({ id, projectId });
if (!oldEnv) throw new BadRequestError({ message: "Environment not found" }); if (!oldEnv) throw new BadRequestError({ message: "Environment not found" });
if (slug) { if (slug) {
const existingEnv = await projectEnvDal.findOne({ slug }); const existingEnv = await projectEnvDAL.findOne({ slug });
if (existingEnv && existingEnv.id !== id) { if (existingEnv && existingEnv.id !== id) {
throw new BadRequestError({ throw new BadRequestError({
message: "Environment with slug already exist", message: "Environment with slug already exist",
@@ -93,11 +93,11 @@ export const projectEnvServiceFactory = ({
} }
} }
const env = await projectEnvDal.transaction(async (tx) => { const env = await projectEnvDAL.transaction(async (tx) => {
if (position) { if (position) {
await projectEnvDal.updateAllPosition(projectId, oldEnv.position, position, tx); await projectEnvDAL.updateAllPosition(projectId, oldEnv.position, position, tx);
} }
return projectEnvDal.updateById(oldEnv.id, { name, slug, position }, tx); return projectEnvDAL.updateById(oldEnv.id, { name, slug, position }, tx);
}); });
return { environment: env, old: oldEnv }; return { environment: env, old: oldEnv };
}; };
@@ -109,15 +109,15 @@ export const projectEnvServiceFactory = ({
ProjectPermissionSub.Environments ProjectPermissionSub.Environments
); );
const env = await projectEnvDal.transaction(async (tx) => { const env = await projectEnvDAL.transaction(async (tx) => {
const [doc] = await projectEnvDal.delete({ id, projectId }, tx); const [doc] = await projectEnvDAL.delete({ id, projectId }, tx);
if (!doc) if (!doc)
throw new BadRequestError({ throw new BadRequestError({
message: "Env doesn't exist", message: "Env doesn't exist",
name: "Re-order env" name: "Re-order env"
}); });
await projectEnvDal.updateAllPosition(projectId, doc.position, -1, tx); await projectEnvDAL.updateAllPosition(projectId, doc.position, -1, tx);
return doc; return doc;
}); });
return env; return env;
@@ -3,9 +3,9 @@ import { TableName, TProjectKeys } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TProjectKeyDalFactory = ReturnType<typeof projectKeyDalFactory>; export type TProjectKeyDALFactory = ReturnType<typeof projectKeyDALFactory>;
export const projectKeyDalFactory = (db: TDbClient) => { export const projectKeyDALFactory = (db: TDbClient) => {
const projectKeyOrm = ormify(db, TableName.ProjectKeys); const projectKeyOrm = ormify(db, TableName.ProjectKeys);
const findLatestProjectKey = async ( const findLatestProjectKey = async (
@@ -7,21 +7,21 @@ import {
} from "@app/ee/services/permission/project-permission"; } from "@app/ee/services/permission/project-permission";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectMembershipDalFactory } from "../project-membership/project-membership-dal"; import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";
import { TProjectKeyDalFactory } from "./project-key-dal"; import { TProjectKeyDALFactory } from "./project-key-dal";
import { TGetLatestProjectKeyDTO, TUploadProjectKeyDTO } from "./project-key-types"; import { TGetLatestProjectKeyDTO, TUploadProjectKeyDTO } from "./project-key-types";
type TProjectKeyServiceFactoryDep = { type TProjectKeyServiceFactoryDep = {
permissionService: TPermissionServiceFactory; permissionService: TPermissionServiceFactory;
projectKeyDal: TProjectKeyDalFactory; projectKeyDAL: TProjectKeyDALFactory;
projectMembershipDal: TProjectMembershipDalFactory; projectMembershipDAL: TProjectMembershipDALFactory;
}; };
export type TProjectKeyServiceFactory = ReturnType<typeof projectKeyServiceFactory>; export type TProjectKeyServiceFactory = ReturnType<typeof projectKeyServiceFactory>;
export const projectKeyServiceFactory = ({ export const projectKeyServiceFactory = ({
projectKeyDal, projectKeyDAL,
projectMembershipDal, projectMembershipDAL,
permissionService permissionService
}: TProjectKeyServiceFactoryDep) => { }: TProjectKeyServiceFactoryDep) => {
const uploadProjectKeys = async ({ const uploadProjectKeys = async ({
@@ -38,7 +38,7 @@ export const projectKeyServiceFactory = ({
ProjectPermissionSub.Member ProjectPermissionSub.Member
); );
const receiverMembership = await projectMembershipDal.findOne({ const receiverMembership = await projectMembershipDAL.findOne({
userId: receiverId, userId: receiverId,
projectId projectId
}); });
@@ -48,12 +48,12 @@ export const projectKeyServiceFactory = ({
name: "Upload project keys" name: "Upload project keys"
}); });
await projectKeyDal.create({ projectId, receiverId, encryptedKey, nonce, senderId: actorId }); await projectKeyDAL.create({ projectId, receiverId, encryptedKey, nonce, senderId: actorId });
}; };
const getLatestProjectKey = async ({ actorId, projectId, actor }: TGetLatestProjectKeyDTO) => { const getLatestProjectKey = async ({ actorId, projectId, actor }: TGetLatestProjectKeyDTO) => {
await permissionService.getProjectPermission(actor, actorId, projectId); await permissionService.getProjectPermission(actor, actorId, projectId);
const latestKey = await projectKeyDal.findLatestProjectKey(actorId, projectId); const latestKey = await projectKeyDAL.findLatestProjectKey(actorId, projectId);
return latestKey; return latestKey;
}; };
@@ -63,7 +63,7 @@ export const projectKeyServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
ProjectPermissionSub.Member ProjectPermissionSub.Member
); );
return projectKeyDal.findAllProjectUserPubKeys(projectId); return projectKeyDAL.findAllProjectUserPubKeys(projectId);
}; };
return { return {
@@ -3,9 +3,9 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TProjectMembershipDalFactory = ReturnType<typeof projectMembershipDalFactory>; export type TProjectMembershipDALFactory = ReturnType<typeof projectMembershipDALFactory>;
export const projectMembershipDalFactory = (db: TDbClient) => { export const projectMembershipDALFactory = (db: TDbClient) => {
const projectMemberOrm = ormify(db, TableName.ProjectMembership); const projectMemberOrm = ormify(db, TableName.ProjectMembership);
// special query // special query
@@ -11,13 +11,13 @@ import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn"; import { groupBy } from "@app/lib/fn";
import { TOrgDalFactory } from "../org/org-dal"; import { TOrgDALFactory } from "../org/org-dal";
import { TProjectDalFactory } from "../project/project-dal"; import { TProjectDALFactory } from "../project/project-dal";
import { TProjectKeyDalFactory } from "../project-key/project-key-dal"; import { TProjectKeyDALFactory } from "../project-key/project-key-dal";
import { TProjectRoleDalFactory } from "../project-role/project-role-dal"; import { TProjectRoleDALFactory } from "../project-role/project-role-dal";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service"; import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TProjectMembershipDalFactory } from "./project-membership-dal"; import { TProjectMembershipDALFactory } from "./project-membership-dal";
import { import {
TAddUsersToWorkspaceDTO, TAddUsersToWorkspaceDTO,
TDeleteProjectMembershipDTO, TDeleteProjectMembershipDTO,
@@ -29,12 +29,12 @@ import {
type TProjectMembershipServiceFactoryDep = { type TProjectMembershipServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
smtpService: TSmtpService; smtpService: TSmtpService;
projectMembershipDal: TProjectMembershipDalFactory; projectMembershipDAL: TProjectMembershipDALFactory;
userDal: Pick<TUserDalFactory, "findById" | "findOne">; userDAL: Pick<TUserDALFactory, "findById" | "findOne">;
projectRoleDal: Pick<TProjectRoleDalFactory, "findOne">; projectRoleDAL: Pick<TProjectRoleDALFactory, "findOne">;
orgDal: Pick<TOrgDalFactory, "findMembership">; orgDAL: Pick<TOrgDALFactory, "findMembership">;
projectDal: Pick<TProjectDalFactory, "findById">; projectDAL: Pick<TProjectDALFactory, "findById">;
projectKeyDal: Pick<TProjectKeyDalFactory, "findLatestProjectKey" | "delete" | "insertMany">; projectKeyDAL: Pick<TProjectKeyDALFactory, "findLatestProjectKey" | "delete" | "insertMany">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
}; };
@@ -42,13 +42,13 @@ export type TProjectMembershipServiceFactory = ReturnType<typeof projectMembersh
export const projectMembershipServiceFactory = ({ export const projectMembershipServiceFactory = ({
permissionService, permissionService,
projectMembershipDal, projectMembershipDAL,
smtpService, smtpService,
projectRoleDal, projectRoleDAL,
orgDal, orgDAL,
userDal, userDAL,
projectDal, projectDAL,
projectKeyDal, projectKeyDAL,
licenseService licenseService
}: TProjectMembershipServiceFactoryDep) => { }: TProjectMembershipServiceFactoryDep) => {
const getProjectMemberships = async ({ actorId, actor, projectId }: TGetProjectMembershipDTO) => { const getProjectMemberships = async ({ actorId, actor, projectId }: TGetProjectMembershipDTO) => {
@@ -58,7 +58,7 @@ export const projectMembershipServiceFactory = ({
ProjectPermissionSub.Member ProjectPermissionSub.Member
); );
return projectMembershipDal.findAllProjectMembers(projectId); return projectMembershipDAL.findAllProjectMembers(projectId);
}; };
const inviteUserToProject = async ({ const inviteUserToProject = async ({
@@ -73,14 +73,14 @@ export const projectMembershipServiceFactory = ({
ProjectPermissionSub.Member ProjectPermissionSub.Member
); );
const invitee = await userDal.findOne({ email }); const invitee = await userDAL.findOne({ email });
if (!invitee || !invitee.isAccepted) if (!invitee || !invitee.isAccepted)
throw new BadRequestError({ throw new BadRequestError({
message: "Faield to validate invitee", message: "Faield to validate invitee",
name: "Invite user to project" name: "Invite user to project"
}); });
const inviteeMembership = await projectMembershipDal.findOne({ const inviteeMembership = await projectMembershipDAL.findOne({
userId: invitee.id, userId: invitee.id,
projectId projectId
}); });
@@ -90,8 +90,8 @@ export const projectMembershipServiceFactory = ({
name: "Invite user to project" name: "Invite user to project"
}); });
const project = await projectDal.findById(projectId); const project = await projectDAL.findById(projectId);
const inviteeMembershipOrg = await orgDal.findMembership({ const inviteeMembershipOrg = await orgDAL.findMembership({
userId: invitee.id, userId: invitee.id,
orgId: project.orgId, orgId: project.orgId,
status: OrgMembershipStatus.Accepted status: OrgMembershipStatus.Accepted
@@ -102,14 +102,14 @@ export const projectMembershipServiceFactory = ({
name: "Invite user to project" name: "Invite user to project"
}); });
const latestKey = await projectKeyDal.findLatestProjectKey(actorId, projectId); const latestKey = await projectKeyDAL.findLatestProjectKey(actorId, projectId);
await projectMembershipDal.create({ await projectMembershipDAL.create({
userId: invitee.id, userId: invitee.id,
projectId, projectId,
role: ProjectMembershipRole.Member role: ProjectMembershipRole.Member
}); });
const sender = await userDal.findById(actorId); const sender = await userDAL.findById(actorId);
const appCfg = getConfig(); const appCfg = getConfig();
await smtpService.sendMail({ await smtpService.sendMail({
template: SmtpTemplates.WorkspaceInvite, template: SmtpTemplates.WorkspaceInvite,
@@ -132,7 +132,7 @@ export const projectMembershipServiceFactory = ({
actor, actor,
members members
}: TAddUsersToWorkspaceDTO) => { }: TAddUsersToWorkspaceDTO) => {
const project = await projectDal.findById(projectId); const project = await projectDAL.findById(projectId);
if (!project) throw new BadRequestError({ message: "Project not found" }); if (!project) throw new BadRequestError({ message: "Project not found" });
const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId); const { permission } = await permissionService.getProjectPermission(actor, actorId, projectId);
@@ -140,7 +140,7 @@ export const projectMembershipServiceFactory = ({
ProjectPermissionActions.Create, ProjectPermissionActions.Create,
ProjectPermissionSub.Member ProjectPermissionSub.Member
); );
const orgMembers = await orgDal.findMembership({ const orgMembers = await orgDAL.findMembership({
orgId: project.orgId, orgId: project.orgId,
$in: { $in: {
[`${TableName.OrgMembership}.id` as "id"]: members.map( [`${TableName.OrgMembership}.id` as "id"]: members.map(
@@ -151,15 +151,15 @@ export const projectMembershipServiceFactory = ({
if (orgMembers.length !== members.length) if (orgMembers.length !== members.length)
throw new BadRequestError({ message: "Some users are not part of org" }); throw new BadRequestError({ message: "Some users are not part of org" });
const existingMembers = await projectMembershipDal.find({ const existingMembers = await projectMembershipDAL.find({
projectId, projectId,
$in: { userId: orgMembers.map(({ userId }) => userId).filter(Boolean) as string[] } $in: { userId: orgMembers.map(({ userId }) => userId).filter(Boolean) as string[] }
}); });
if (existingMembers.length) if (existingMembers.length)
throw new BadRequestError({ message: "Some users are already part of project" }); throw new BadRequestError({ message: "Some users are already part of project" });
await projectMembershipDal.transaction(async (tx) => { await projectMembershipDAL.transaction(async (tx) => {
await projectMembershipDal.insertMany( await projectMembershipDAL.insertMany(
orgMembers.map(({ userId }) => ({ orgMembers.map(({ userId }) => ({
projectId, projectId,
userId: userId as string, userId: userId as string,
@@ -168,7 +168,7 @@ export const projectMembershipServiceFactory = ({
tx tx
); );
const encKeyGroupByOrgMembId = groupBy(members, (i) => i.orgMembershipId); const encKeyGroupByOrgMembId = groupBy(members, (i) => i.orgMembershipId);
await projectKeyDal.insertMany( await projectKeyDAL.insertMany(
orgMembers.map(({ userId, id }) => ({ orgMembers.map(({ userId, id }) => ({
encryptedKey: encKeyGroupByOrgMembId[id][0].workspaceEncryptedKey, encryptedKey: encKeyGroupByOrgMembId[id][0].workspaceEncryptedKey,
nonce: encKeyGroupByOrgMembId[id][0].workspaceEncryptedNonce, nonce: encKeyGroupByOrgMembId[id][0].workspaceEncryptedNonce,
@@ -179,7 +179,7 @@ export const projectMembershipServiceFactory = ({
tx tx
); );
}); });
const sender = await userDal.findById(actorId); const sender = await userDAL.findById(actorId);
const appCfg = getConfig(); const appCfg = getConfig();
await smtpService.sendMail({ await smtpService.sendMail({
template: SmtpTemplates.WorkspaceInvite, template: SmtpTemplates.WorkspaceInvite,
@@ -212,10 +212,10 @@ export const projectMembershipServiceFactory = ({
role as ProjectMembershipRole role as ProjectMembershipRole
); );
if (isCustomRole) { if (isCustomRole) {
const customRole = await projectRoleDal.findOne({ slug: role, projectId }); const customRole = await projectRoleDAL.findOne({ slug: role, projectId });
if (!customRole) if (!customRole)
throw new BadRequestError({ name: "Update project membership", message: "Role not found" }); throw new BadRequestError({ name: "Update project membership", message: "Role not found" });
const project = await projectDal.findById(customRole.projectId); const project = await projectDAL.findById(customRole.projectId);
const plan = await licenseService.getPlan(project.orgId); const plan = await licenseService.getPlan(project.orgId);
if (!plan?.rbac) if (!plan?.rbac)
throw new BadRequestError({ throw new BadRequestError({
@@ -223,7 +223,7 @@ export const projectMembershipServiceFactory = ({
"Failed to assign custom role due to RBAC restriction. Upgrade plan to assign custom role to member." "Failed to assign custom role due to RBAC restriction. Upgrade plan to assign custom role to member."
}); });
const [membership] = await projectMembershipDal.update( const [membership] = await projectMembershipDAL.update(
{ id: membershipId, projectId }, { id: membershipId, projectId },
{ {
role: ProjectMembershipRole.Custom, role: ProjectMembershipRole.Custom,
@@ -233,7 +233,7 @@ export const projectMembershipServiceFactory = ({
return membership; return membership;
} }
const [membership] = await projectMembershipDal.update( const [membership] = await projectMembershipDAL.update(
{ id: membershipId, projectId }, { id: membershipId, projectId },
{ role, roleId: null } { role, roleId: null }
); );
@@ -252,12 +252,12 @@ export const projectMembershipServiceFactory = ({
ProjectPermissionSub.Member ProjectPermissionSub.Member
); );
const membership = await projectMembershipDal.transaction(async (tx) => { const membership = await projectMembershipDAL.transaction(async (tx) => {
const [deletedMembership] = await projectMembershipDal.delete( const [deletedMembership] = await projectMembershipDAL.delete(
{ projectId, id: membershipId }, { projectId, id: membershipId },
tx tx
); );
await projectKeyDal.delete({ receiverId: deletedMembership.userId, projectId }, tx); await projectKeyDAL.delete({ receiverId: deletedMembership.userId, projectId }, tx);
return deletedMembership; return deletedMembership;
}); });
return membership; return membership;
@@ -2,6 +2,6 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TProjectRoleDalFactory = ReturnType<typeof projectRoleDalFactory>; export type TProjectRoleDALFactory = ReturnType<typeof projectRoleDALFactory>;
export const projectRoleDalFactory = (db: TDbClient) => ormify(db, TableName.ProjectRoles); export const projectRoleDALFactory = (db: TDbClient) => ormify(db, TableName.ProjectRoles);
@@ -14,10 +14,10 @@ import {
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { ActorType } from "../auth/auth-type"; import { ActorType } from "../auth/auth-type";
import { TProjectRoleDalFactory } from "./project-role-dal"; import { TProjectRoleDALFactory } from "./project-role-dal";
type TProjectRoleServiceFactoryDep = { type TProjectRoleServiceFactoryDep = {
projectRoleDal: TProjectRoleDalFactory; projectRoleDAL: TProjectRoleDALFactory;
permissionService: Pick< permissionService: Pick<
TPermissionServiceFactory, TPermissionServiceFactory,
"getProjectPermission" | "getUserProjectPermission" "getProjectPermission" | "getUserProjectPermission"
@@ -27,7 +27,7 @@ type TProjectRoleServiceFactoryDep = {
export type TProjectRoleServiceFactory = ReturnType<typeof projectRoleServiceFactory>; export type TProjectRoleServiceFactory = ReturnType<typeof projectRoleServiceFactory>;
export const projectRoleServiceFactory = ({ export const projectRoleServiceFactory = ({
projectRoleDal, projectRoleDAL,
permissionService permissionService
}: TProjectRoleServiceFactoryDep) => { }: TProjectRoleServiceFactoryDep) => {
const createRole = async ( const createRole = async (
@@ -41,9 +41,9 @@ export const projectRoleServiceFactory = ({
ProjectPermissionActions.Create, ProjectPermissionActions.Create,
ProjectPermissionSub.Role ProjectPermissionSub.Role
); );
const existingRole = await projectRoleDal.findOne({ slug: data.slug, projectId }); const existingRole = await projectRoleDAL.findOne({ slug: data.slug, projectId });
if (existingRole) throw new BadRequestError({ name: "Create Role", message: "Duplicate role" }); if (existingRole) throw new BadRequestError({ name: "Create Role", message: "Duplicate role" });
const role = await projectRoleDal.create({ const role = await projectRoleDAL.create({
...data, ...data,
projectId, projectId,
permissions: JSON.stringify(data.permissions) permissions: JSON.stringify(data.permissions)
@@ -64,11 +64,11 @@ export const projectRoleServiceFactory = ({
ProjectPermissionSub.Role ProjectPermissionSub.Role
); );
if (data?.slug) { if (data?.slug) {
const existingRole = await projectRoleDal.findOne({ slug: data.slug, projectId }); const existingRole = await projectRoleDAL.findOne({ slug: data.slug, projectId });
if (existingRole && existingRole.id !== roleId) if (existingRole && existingRole.id !== roleId)
throw new BadRequestError({ name: "Update Role", message: "Duplicate role" }); throw new BadRequestError({ name: "Update Role", message: "Duplicate role" });
} }
const [updatedRole] = await projectRoleDal.update( const [updatedRole] = await projectRoleDAL.update(
{ id: roleId, projectId }, { id: roleId, projectId },
{ ...data, permissions: data.permissions ? JSON.stringify(data.permissions) : undefined } { ...data, permissions: data.permissions ? JSON.stringify(data.permissions) : undefined }
); );
@@ -87,7 +87,7 @@ export const projectRoleServiceFactory = ({
ProjectPermissionActions.Delete, ProjectPermissionActions.Delete,
ProjectPermissionSub.Role ProjectPermissionSub.Role
); );
const [deletedRole] = await projectRoleDal.delete({ id: roleId, projectId }); const [deletedRole] = await projectRoleDAL.delete({ id: roleId, projectId });
if (!deleteRole) throw new BadRequestError({ message: "Role not found", name: "Update role" }); if (!deleteRole) throw new BadRequestError({ message: "Role not found", name: "Update role" });
return deletedRole; return deletedRole;
@@ -99,7 +99,7 @@ export const projectRoleServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
ProjectPermissionSub.Role ProjectPermissionSub.Role
); );
const customRoles = await projectRoleDal.find({ projectId }); const customRoles = await projectRoleDAL.find({ projectId });
const roles = [ const roles = [
{ {
id: "b11b49a9-09a9-4443-916a-4246f9ff2c69", // dummy userid id: "b11b49a9-09a9-4443-916a-4246f9ff2c69", // dummy userid
@@ -3,9 +3,9 @@ import { ProjectsSchema, TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex"; import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
export type TProjectDalFactory = ReturnType<typeof projectDalFactory>; export type TProjectDALFactory = ReturnType<typeof projectDALFactory>;
export const projectDalFactory = (db: TDbClient) => { export const projectDALFactory = (db: TDbClient) => {
const projectOrm = ormify(db, TableName.Project); const projectOrm = ormify(db, TableName.Project);
const findAllProjects = async (userId: string) => { const findAllProjects = async (userId: string) => {
@@ -15,11 +15,11 @@ import { getConfig } from "@app/lib/config/env";
import { createSecretBlindIndex } from "@app/lib/crypto"; import { createSecretBlindIndex } from "@app/lib/crypto";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectEnvDalFactory } from "../project-env/project-env-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
import { TProjectMembershipDalFactory } from "../project-membership/project-membership-dal"; import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";
import { TSecretBlindIndexDalFactory } from "../secret/secret-blind-index-dal"; import { TSecretBlindIndexDALFactory } from "../secret/secret-blind-index-dal";
import { ROOT_FOLDER_NAME, TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { ROOT_FOLDER_NAME, TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TProjectDalFactory } from "./project-dal"; import { TProjectDALFactory } from "./project-dal";
import { TCreateProjectDTO, TDeleteProjectDTO, TGetProjectDTO } from "./project-types"; import { TCreateProjectDTO, TDeleteProjectDTO, TGetProjectDTO } from "./project-types";
export const DEFAULT_PROJECT_ENVS = [ export const DEFAULT_PROJECT_ENVS = [
@@ -29,11 +29,11 @@ export const DEFAULT_PROJECT_ENVS = [
]; ];
type TProjectServiceFactoryDep = { type TProjectServiceFactoryDep = {
projectDal: TProjectDalFactory; projectDAL: TProjectDALFactory;
folderDal: Pick<TSecretFolderDalFactory, "insertMany">; folderDAL: Pick<TSecretFolderDALFactory, "insertMany">;
projectEnvDal: Pick<TProjectEnvDalFactory, "insertMany">; projectEnvDAL: Pick<TProjectEnvDALFactory, "insertMany">;
projectMembershipDal: Pick<TProjectMembershipDalFactory, "create">; projectMembershipDAL: Pick<TProjectMembershipDALFactory, "create">;
secretBlindIndexDal: Pick<TSecretBlindIndexDalFactory, "create">; secretBlindIndexDAL: Pick<TSecretBlindIndexDALFactory, "create">;
permissionService: TPermissionServiceFactory; permissionService: TPermissionServiceFactory;
licenseService: Pick<TLicenseServiceFactory, "getPlan">; licenseService: Pick<TLicenseServiceFactory, "getPlan">;
}; };
@@ -41,12 +41,12 @@ type TProjectServiceFactoryDep = {
export type TProjectServiceFactory = ReturnType<typeof projectServiceFactory>; export type TProjectServiceFactory = ReturnType<typeof projectServiceFactory>;
export const projectServiceFactory = ({ export const projectServiceFactory = ({
projectDal, projectDAL,
permissionService, permissionService,
folderDal, folderDAL,
secretBlindIndexDal, secretBlindIndexDAL,
projectMembershipDal, projectMembershipDAL,
projectEnvDal, projectEnvDAL,
licenseService licenseService
}: TProjectServiceFactoryDep) => { }: TProjectServiceFactoryDep) => {
/* /*
@@ -72,10 +72,10 @@ export const projectServiceFactory = ({
}); });
} }
const newProject = projectDal.transaction(async (tx) => { const newProject = projectDAL.transaction(async (tx) => {
const project = await projectDal.create({ name: workspaceName, orgId }, tx); const project = await projectDAL.create({ name: workspaceName, orgId }, tx);
// set user as admin member for proeject // set user as admin member for proeject
await projectMembershipDal.create( await projectMembershipDAL.create(
{ {
userId: actorId, userId: actorId,
role: ProjectMembershipRole.Admin, role: ProjectMembershipRole.Admin,
@@ -84,7 +84,7 @@ export const projectServiceFactory = ({
tx tx
); );
// generate the blind index for project // generate the blind index for project
await secretBlindIndexDal.create( await secretBlindIndexDAL.create(
{ {
projectId: project.id, projectId: project.id,
keyEncoding: blindIndex.keyEncoding, keyEncoding: blindIndex.keyEncoding,
@@ -96,11 +96,11 @@ export const projectServiceFactory = ({
tx tx
); );
// set default environments and root folder for provided environments // set default environments and root folder for provided environments
const envs = await projectEnvDal.insertMany( const envs = await projectEnvDAL.insertMany(
DEFAULT_PROJECT_ENVS.map((el, i) => ({ ...el, projectId: project.id, position: i + 1 })), DEFAULT_PROJECT_ENVS.map((el, i) => ({ ...el, projectId: project.id, position: i + 1 })),
tx tx
); );
await folderDal.insertMany( await folderDAL.insertMany(
envs.map(({ id }) => ({ name: ROOT_FOLDER_NAME, envId: id, version: 1 })), envs.map(({ id }) => ({ name: ROOT_FOLDER_NAME, envId: id, version: 1 })),
tx tx
); );
@@ -119,18 +119,18 @@ export const projectServiceFactory = ({
); );
// TODO(backend-pg): licence server // TODO(backend-pg): licence server
const deletedProject = await projectDal.deleteById(projectId); const deletedProject = await projectDAL.deleteById(projectId);
return deletedProject; return deletedProject;
}; };
const getProjects = async (actorId: string) => { const getProjects = async (actorId: string) => {
const workspaces = await projectDal.findAllProjects(actorId); const workspaces = await projectDAL.findAllProjects(actorId);
return workspaces; return workspaces;
}; };
const getAProject = async ({ actorId, projectId, actor }: TGetProjectDTO) => { const getAProject = async ({ actorId, projectId, actor }: TGetProjectDTO) => {
await permissionService.getProjectPermission(actor, actorId, projectId); await permissionService.getProjectPermission(actor, actorId, projectId);
return projectDal.findProjectById(projectId); return projectDAL.findProjectById(projectId);
}; };
const toggleAutoCapitalization = async ({ const toggleAutoCapitalization = async ({
@@ -145,7 +145,7 @@ export const projectServiceFactory = ({
ProjectPermissionSub.Settings ProjectPermissionSub.Settings
); );
const updatedProject = await projectDal.updateById(projectId, { autoCapitalization }); const updatedProject = await projectDAL.updateById(projectId, { autoCapitalization });
return updatedProject; return updatedProject;
}; };
@@ -161,7 +161,7 @@ export const projectServiceFactory = ({
ProjectPermissionSub.Settings ProjectPermissionSub.Settings
); );
const updatedProject = await projectDal.updateById(projectId, { name }); const updatedProject = await projectDAL.updateById(projectId, { name });
return updatedProject; return updatedProject;
}; };
@@ -225,10 +225,10 @@ const sqlFindSecretPathByFolderId = (db: Knex, projectId: string, folderIds: str
.select("*") .select("*")
.from<TSecretFolders & { child: string | null; path: string }>("parent"); .from<TSecretFolders & { child: string | null; path: string }>("parent");
export type TSecretFolderDalFactory = ReturnType<typeof secretFolderDalFactory>; export type TSecretFolderDALFactory = ReturnType<typeof secretFolderDALFactory>;
// never change this. If u do write a migration for it // never change this. If u do write a migration for it
export const ROOT_FOLDER_NAME = "root"; export const ROOT_FOLDER_NAME = "root";
export const secretFolderDalFactory = (db: TDbClient) => { export const secretFolderDALFactory = (db: TDbClient) => {
const secretFolderOrm = ormify(db, TableName.SecretFolder); const secretFolderOrm = ormify(db, TableName.SecretFolder);
const findBySecretPath = async ( const findBySecretPath = async (
@@ -11,32 +11,32 @@ import {
import { TSecretSnapshotServiceFactory } from "@app/ee/services/secret-snapshot/secret-snapshot-service"; import { TSecretSnapshotServiceFactory } from "@app/ee/services/secret-snapshot/secret-snapshot-service";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectEnvDalFactory } from "../project-env/project-env-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
import { TSecretFolderDalFactory } from "./secret-folder-dal"; import { TSecretFolderDALFactory } from "./secret-folder-dal";
import { import {
TCreateFolderDTO, TCreateFolderDTO,
TDeleteFolderDTO, TDeleteFolderDTO,
TGetFolderDTO, TGetFolderDTO,
TUpdateFolderDTO TUpdateFolderDTO
} from "./secret-folder-types"; } from "./secret-folder-types";
import { TSecretFolderVersionDalFactory } from "./secret-folder-version-dal"; import { TSecretFolderVersionDALFactory } from "./secret-folder-version-dal";
type TSecretFolderServiceFactoryDep = { type TSecretFolderServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">; snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;
folderDal: TSecretFolderDalFactory; folderDAL: TSecretFolderDALFactory;
projectEnvDal: Pick<TProjectEnvDalFactory, "findOne">; projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
folderVersionDal: TSecretFolderVersionDalFactory; folderVersionDAL: TSecretFolderVersionDALFactory;
}; };
export type TSecretFolderServiceFactory = ReturnType<typeof secretFolderServiceFactory>; export type TSecretFolderServiceFactory = ReturnType<typeof secretFolderServiceFactory>;
export const secretFolderServiceFactory = ({ export const secretFolderServiceFactory = ({
folderDal, folderDAL,
snapshotService, snapshotService,
permissionService, permissionService,
projectEnvDal, projectEnvDAL,
folderVersionDal folderVersionDAL
}: TSecretFolderServiceFactoryDep) => { }: TSecretFolderServiceFactoryDep) => {
const createFolder = async ({ const createFolder = async ({
projectId, projectId,
@@ -52,17 +52,17 @@ export const secretFolderServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath }) subject(ProjectPermissionSub.Secrets, { environment, secretPath })
); );
const env = await projectEnvDal.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) if (!env)
throw new BadRequestError({ message: "Environment not found", name: "Create folder" }); throw new BadRequestError({ message: "Environment not found", name: "Create folder" });
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
// that is this request must be idempotent // that is this request must be idempotent
// so we do a tricky move. we try to find the to be created folder path if that is exactly match return that // so we do a tricky move. we try to find the to be created folder path if that is exactly match return that
// else we get some path before that then we will start creating remaining folder // else we get some path before that then we will start creating remaining folder
const pathWithFolder = path.join(secretPath, name); const pathWithFolder = path.join(secretPath, name);
const parentFolder = await folderDal.findClosestFolder( const parentFolder = await folderDAL.findClosestFolder(
projectId, projectId,
environment, environment,
pathWithFolder, pathWithFolder,
@@ -102,8 +102,8 @@ export const secretFolderServiceFactory = ({
} }
); );
parentFolderId = newFolders.at(-1)?.id as string; parentFolderId = newFolders.at(-1)?.id as string;
const docs = await folderDal.insertMany(newFolders, tx); const docs = await folderDAL.insertMany(newFolders, tx);
await folderVersionDal.insertMany( await folderVersionDAL.insertMany(
docs.map((doc) => ({ docs.map((doc) => ({
name: doc.name, name: doc.name,
envId: doc.envId, envId: doc.envId,
@@ -115,11 +115,11 @@ export const secretFolderServiceFactory = ({
} }
} }
const doc = await folderDal.create( const doc = await folderDAL.create(
{ name, envId: env.id, version: 1, parentId: parentFolderId }, { name, envId: env.id, version: 1, parentId: parentFolderId },
tx tx
); );
await folderVersionDal.create( await folderVersionDAL.create(
{ {
name: doc.name, name: doc.name,
envId: doc.envId, envId: doc.envId,
@@ -150,27 +150,27 @@ export const secretFolderServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath }) subject(ProjectPermissionSub.Secrets, { environment, secretPath })
); );
const parentFolder = await folderDal.findBySecretPath(projectId, environment, secretPath); const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!parentFolder) throw new BadRequestError({ message: "Secret path not found" }); if (!parentFolder) throw new BadRequestError({ message: "Secret path not found" });
const env = await projectEnvDal.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) if (!env)
throw new BadRequestError({ message: "Environment not found", name: "Update folder" }); throw new BadRequestError({ message: "Environment not found", name: "Update folder" });
let folder = await folderDal.findOne({ envId: env.id, id, parentId: parentFolder.id }); let folder = await folderDAL.findOne({ envId: env.id, id, parentId: parentFolder.id });
// now folder api accepts id based change // now folder api accepts id based change
// this is for cli and when cli removes this will remove this logic // this is for cli and when cli removes this will remove this logic
if (!folder) { if (!folder) {
folder = await folderDal.findOne({ envId: env.id, name: id, parentId: parentFolder.id }); folder = await folderDAL.findOne({ envId: env.id, name: id, parentId: parentFolder.id });
} }
if (!folder) throw new BadRequestError({ message: "Folder not found" }); if (!folder) throw new BadRequestError({ message: "Folder not found" });
const newFolder = await folderDal.transaction(async (tx) => { const newFolder = await folderDAL.transaction(async (tx) => {
const [doc] = await folderDal.update( const [doc] = await folderDAL.update(
{ envId: env.id, id: folder.id, parentId: parentFolder.id }, { envId: env.id, id: folder.id, parentId: parentFolder.id },
{ name }, { name },
tx tx
); );
await folderVersionDal.create( await folderVersionDAL.create(
{ {
name: doc.name, name: doc.name,
envId: doc.envId, envId: doc.envId,
@@ -201,15 +201,15 @@ export const secretFolderServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath }) subject(ProjectPermissionSub.Secrets, { environment, secretPath })
); );
const env = await projectEnvDal.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) if (!env)
throw new BadRequestError({ message: "Environment not found", name: "Create folder" }); throw new BadRequestError({ message: "Environment not found", name: "Create folder" });
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 BadRequestError({ message: "Secret path not found" }); if (!parentFolder) throw new BadRequestError({ message: "Secret path not found" });
const [doc] = await folderDal.delete({ envId: env.id, id, parentId: parentFolder.id }, tx); const [doc] = await folderDAL.delete({ envId: env.id, id, parentId: parentFolder.id }, tx);
if (!doc) throw new BadRequestError({ message: "Folder not found", name: "Delete folder" }); if (!doc) throw new BadRequestError({ message: "Folder not found", name: "Delete folder" });
return doc; return doc;
}); });
@@ -229,13 +229,13 @@ export const secretFolderServiceFactory = ({
// permission to check does user has access // permission to check does user has access
await permissionService.getProjectPermission(actor, actorId, projectId); await permissionService.getProjectPermission(actor, actorId, projectId);
const env = await projectEnvDal.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) throw new BadRequestError({ message: "Environment not found", name: "get folders" }); if (!env) throw new BadRequestError({ message: "Environment not found", name: "get folders" });
const parentFolder = await folderDal.findBySecretPath(projectId, environment, secretPath); const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!parentFolder) return []; if (!parentFolder) return [];
const folders = await folderDal.find({ envId: env.id, parentId: parentFolder.id }); const folders = await folderDAL.find({ envId: env.id, parentId: parentFolder.id });
return folders; return folders;
}; };
@@ -5,9 +5,9 @@ import { TableName,TSecretFolderVersions } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TSecretFolderVersionDalFactory = ReturnType<typeof secretFolderVersionDalFactory>; export type TSecretFolderVersionDALFactory = ReturnType<typeof secretFolderVersionDALFactory>;
export const secretFolderVersionDalFactory = (db: TDbClient) => { export const secretFolderVersionDALFactory = (db: TDbClient) => {
const secretFolderVerOrm = ormify(db, TableName.SecretFolderVersion); const secretFolderVerOrm = ormify(db, TableName.SecretFolderVersion);
// This will fetch all latest secret versions from a folder // This will fetch all latest secret versions from a folder
@@ -5,9 +5,9 @@ import { TableName,TSecretImports } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSecretImportDalFactory = ReturnType<typeof secretImportDalFactory>; export type TSecretImportDALFactory = ReturnType<typeof secretImportDALFactory>;
export const secretImportDalFactory = (db: TDbClient) => { export const secretImportDALFactory = (db: TDbClient) => {
const secretImportOrm = ormify(db, TableName.SecretImport); const secretImportOrm = ormify(db, TableName.SecretImport);
// we are using postion based sorting as its a small list // we are using postion based sorting as its a small list
@@ -1,21 +1,21 @@
import { SecretType, TSecretImports } from "@app/db/schemas"; import { SecretType, TSecretImports } from "@app/db/schemas";
import { groupBy } from "@app/lib/fn"; import { groupBy } from "@app/lib/fn";
import { TSecretDalFactory } from "../secret/secret-dal"; import { TSecretDALFactory } from "../secret/secret-dal";
import { TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
export const fnSecretsFromImports = async ({ export const fnSecretsFromImports = async ({
allowedImports, allowedImports,
folderDal, folderDAL,
secretDal secretDAL
}: { }: {
allowedImports: (Omit<TSecretImports, "importEnv"> & { allowedImports: (Omit<TSecretImports, "importEnv"> & {
importEnv: { id: string; slug: string; name: string }; importEnv: { id: string; slug: string; name: string };
})[]; })[];
folderDal: Pick<TSecretFolderDalFactory, "findByManySecretPath">; folderDAL: Pick<TSecretFolderDALFactory, "findByManySecretPath">;
secretDal: Pick<TSecretDalFactory, "find">; secretDAL: Pick<TSecretDALFactory, "find">;
}) => { }) => {
const importedFolders = await folderDal.findByManySecretPath( const importedFolders = await folderDAL.findByManySecretPath(
allowedImports.map(({ importEnv, importPath }) => ({ allowedImports.map(({ importEnv, importPath }) => ({
envId: importEnv.id, envId: importEnv.id,
secretPath: importPath secretPath: importPath
@@ -25,7 +25,7 @@ export const fnSecretsFromImports = async ({
if (!folderIds.length) { if (!folderIds.length) {
return []; return [];
} }
const importedSecrets = await secretDal.find({ const importedSecrets = await secretDAL.find({
$in: { folderId: folderIds }, $in: { folderId: folderIds },
type: SecretType.Shared type: SecretType.Shared
}); });
@@ -7,10 +7,10 @@ import {
} from "@app/ee/services/permission/project-permission"; } from "@app/ee/services/permission/project-permission";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectEnvDalFactory } from "../project-env/project-env-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
import { TSecretDalFactory } from "../secret/secret-dal"; import { TSecretDALFactory } from "../secret/secret-dal";
import { TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretImportDalFactory } from "./secret-import-dal"; import { TSecretImportDALFactory } from "./secret-import-dal";
import { fnSecretsFromImports } from "./secret-import-fns"; import { fnSecretsFromImports } from "./secret-import-fns";
import { import {
TCreateSecretImportDTO, TCreateSecretImportDTO,
@@ -21,10 +21,10 @@ import {
} from "./secret-import-types"; } from "./secret-import-types";
type TSecretImportServiceFactoryDep = { type TSecretImportServiceFactoryDep = {
secretImportDal: TSecretImportDalFactory; secretImportDAL: TSecretImportDALFactory;
folderDal: TSecretFolderDalFactory; folderDAL: TSecretFolderDALFactory;
secretDal: Pick<TSecretDalFactory, "find">; secretDAL: Pick<TSecretDALFactory, "find">;
projectEnvDal: TProjectEnvDalFactory; projectEnvDAL: TProjectEnvDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
}; };
@@ -33,11 +33,11 @@ const ERR_SEC_IMP_NOT_FOUND = new BadRequestError({ message: "Secret import not
export type TSecretImportServiceFactory = ReturnType<typeof secretImportServiceFactory>; export type TSecretImportServiceFactory = ReturnType<typeof secretImportServiceFactory>;
export const secretImportServiceFactory = ({ export const secretImportServiceFactory = ({
secretImportDal, secretImportDAL,
projectEnvDal, projectEnvDAL,
permissionService, permissionService,
folderDal, folderDAL,
secretDal secretDAL
}: TSecretImportServiceFactoryDep) => { }: TSecretImportServiceFactoryDep) => {
const createImport = async ({ const createImport = async ({
environment, environment,
@@ -64,17 +64,17 @@ export const secretImportServiceFactory = ({
}) })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create import" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create import" });
// TODO(akhilmhdh-pg): updated permission check add here // TODO(akhilmhdh-pg): updated permission check add here
const [importEnv] = await projectEnvDal.findBySlugs(projectId, [data.environment]); const [importEnv] = await projectEnvDAL.findBySlugs(projectId, [data.environment]);
if (!importEnv) if (!importEnv)
throw new BadRequestError({ error: "Imported env not found", name: "Create import" }); throw new BadRequestError({ error: "Imported env not found", name: "Create import" });
const secImport = await secretImportDal.transaction(async (tx) => { const secImport = await secretImportDAL.transaction(async (tx) => {
const lastPos = await secretImportDal.findLastImportPosition(folder.id, tx); const lastPos = await secretImportDAL.findLastImportPosition(folder.id, tx);
return secretImportDal.create( return secretImportDAL.create(
{ {
folderId: folder.id, folderId: folder.id,
position: lastPos + 1, position: lastPos + 1,
@@ -103,25 +103,25 @@ export const secretImportServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Update import" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Update import" });
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;
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) if (!importedEnv)
throw new BadRequestError({ error: "Imported env not found", name: "Create import" }); throw new BadRequestError({ error: "Imported env not found", name: "Create import" });
const updatedSecImport = await secretImportDal.transaction(async (tx) => { const updatedSecImport = await secretImportDAL.transaction(async (tx) => {
const secImp = await secretImportDal.findOne({ folderId: folder.id, id }); const secImp = await secretImportDAL.findOne({ folderId: folder.id, id });
if (!secImp) throw ERR_SEC_IMP_NOT_FOUND; if (!secImp) throw ERR_SEC_IMP_NOT_FOUND;
if (data.position) { if (data.position) {
await secretImportDal.updateAllPosition(folder.id, secImp.position, data.position, tx); await secretImportDAL.updateAllPosition(folder.id, secImp.position, data.position, tx);
} }
const [doc] = await secretImportDal.update( const [doc] = await secretImportDAL.update(
{ id, folderId: folder.id }, { id, folderId: folder.id },
{ {
position: data?.position, position: data?.position,
@@ -149,16 +149,16 @@ export const secretImportServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Delete import" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Delete import" });
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) if (!doc)
throw new BadRequestError({ name: "Sec imp del", message: "Secret import doc not found" }); throw new BadRequestError({ name: "Sec imp del", message: "Secret import doc not found" });
await secretImportDal.updateAllPosition(folder.id, doc.position, -1, tx); await secretImportDAL.updateAllPosition(folder.id, doc.position, -1, tx);
const importEnv = await projectEnvDal.findById(doc.importEnv); const importEnv = await projectEnvDAL.findById(doc.importEnv);
if (!importEnv) if (!importEnv)
throw new BadRequestError({ error: "Imported env not found", name: "Create import" }); throw new BadRequestError({ error: "Imported env not found", name: "Create import" });
return { ...doc, importEnv }; return { ...doc, importEnv };
@@ -179,10 +179,10 @@ export const secretImportServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Get imports" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Get imports" });
const secImports = await secretImportDal.find({ folderId: folder.id }); const secImports = await secretImportDAL.find({ folderId: folder.id });
return secImports; return secImports;
}; };
@@ -198,11 +198,11 @@ export const secretImportServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) return []; if (!folder) return [];
// this will already order by position // this will already order by position
// so anything based on this order will also be in right position // so anything based on this order will also be in right position
const secretImports = await secretImportDal.find({ folderId: folder.id }); const secretImports = await secretImportDAL.find({ folderId: folder.id });
const allowedImports = secretImports.filter(({ importEnv, importPath }) => const allowedImports = secretImports.filter(({ importEnv, importPath }) =>
permission.can( permission.can(
@@ -213,7 +213,7 @@ export const secretImportServiceFactory = ({
}) })
) )
); );
return fnSecretsFromImports({ allowedImports, folderDal, secretDal }); return fnSecretsFromImports({ allowedImports, folderDAL, secretDAL });
}; };
return { return {
@@ -5,9 +5,9 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSecretTagDalFactory = ReturnType<typeof secretTagDalFactory>; export type TSecretTagDALFactory = ReturnType<typeof secretTagDALFactory>;
export const secretTagDalFactory = (db: TDbClient) => { export const secretTagDALFactory = (db: TDbClient) => {
const secretTagOrm = ormify(db, TableName.SecretTag); const secretTagOrm = ormify(db, TableName.SecretTag);
const secretJnTagOrm = ormify(db, TableName.JnSecretTag); const secretJnTagOrm = ormify(db, TableName.JnSecretTag);
@@ -7,18 +7,18 @@ import {
} from "@app/ee/services/permission/project-permission"; } from "@app/ee/services/permission/project-permission";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TSecretTagDalFactory } from "./secret-tag-dal"; import { TSecretTagDALFactory } from "./secret-tag-dal";
import { TCreateTagDTO, TDeleteTagDTO, TListProjectTagsDTO } from "./secret-tag-types"; import { TCreateTagDTO, TDeleteTagDTO, TListProjectTagsDTO } from "./secret-tag-types";
type TSecretTagServiceFactoryDep = { type TSecretTagServiceFactoryDep = {
secretTagDal: TSecretTagDalFactory; secretTagDAL: TSecretTagDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
}; };
export type TSecretTagServiceFactory = ReturnType<typeof secretTagServiceFactory>; export type TSecretTagServiceFactory = ReturnType<typeof secretTagServiceFactory>;
export const secretTagServiceFactory = ({ export const secretTagServiceFactory = ({
secretTagDal, secretTagDAL,
permissionService permissionService
}: TSecretTagServiceFactoryDep) => { }: TSecretTagServiceFactoryDep) => {
const createTag = async ({ name, slug, actor, color, actorId, projectId }: TCreateTagDTO) => { const createTag = async ({ name, slug, actor, color, actorId, projectId }: TCreateTagDTO) => {
@@ -28,10 +28,10 @@ export const secretTagServiceFactory = ({
ProjectPermissionSub.Tags ProjectPermissionSub.Tags
); );
const existingTag = await secretTagDal.findOne({ slug }); const existingTag = await secretTagDAL.findOne({ slug });
if (existingTag) throw new BadRequestError({ message: "Tag already exist" }); if (existingTag) throw new BadRequestError({ message: "Tag already exist" });
const newTag = await secretTagDal.create({ const newTag = await secretTagDAL.create({
projectId, projectId,
name, name,
slug, slug,
@@ -42,7 +42,7 @@ export const secretTagServiceFactory = ({
}; };
const deleteTag = async ({ actorId, actor, id }: TDeleteTagDTO) => { const deleteTag = async ({ actorId, actor, id }: TDeleteTagDTO) => {
const tag = await secretTagDal.findById(id); const tag = await secretTagDAL.findById(id);
if (!tag) throw new BadRequestError({ message: "Tag doesn't exist" }); if (!tag) throw new BadRequestError({ message: "Tag doesn't exist" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -55,7 +55,7 @@ export const secretTagServiceFactory = ({
ProjectPermissionSub.Tags ProjectPermissionSub.Tags
); );
const deletedTag = await secretTagDal.deleteById(tag.id); const deletedTag = await secretTagDAL.deleteById(tag.id);
return deletedTag; return deletedTag;
}; };
@@ -66,7 +66,7 @@ export const secretTagServiceFactory = ({
ProjectPermissionSub.Tags ProjectPermissionSub.Tags
); );
const tags = await secretTagDal.find({ projectId }); const tags = await secretTagDAL.find({ projectId });
return tags; return tags;
}; };
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSecretBlindIndexDalFactory = ReturnType<typeof secretBlindIndexDalFactory>; export type TSecretBlindIndexDALFactory = ReturnType<typeof secretBlindIndexDALFactory>;
export const secretBlindIndexDalFactory = (db: TDbClient) => { export const secretBlindIndexDALFactory = (db: TDbClient) => {
const secretBlindIndexOrm = ormify(db, TableName.SecretBlindIndex); const secretBlindIndexOrm = ormify(db, TableName.SecretBlindIndex);
return secretBlindIndexOrm; return secretBlindIndexOrm;
}; };
+2 -2
View File
@@ -5,9 +5,9 @@ import { SecretsSchema, SecretType, TableName, TSecrets, TSecretsUpdate } from "
import { BadRequestError, DatabaseError } from "@app/lib/errors"; import { BadRequestError, DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex"; import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
export type TSecretDalFactory = ReturnType<typeof secretDalFactory>; export type TSecretDALFactory = ReturnType<typeof secretDALFactory>;
export const secretDalFactory = (db: TDbClient) => { export const secretDALFactory = (db: TDbClient) => {
const secretOrm = ormify(db, TableName.Secret); const secretOrm = ormify(db, TableName.Secret);
const update = async ( const update = async (
+8 -8
View File
@@ -5,8 +5,8 @@ import { SecretKeyEncoding, TSecretBlindIndexes, TSecrets } from "@app/db/schema
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { buildSecretBlindIndexFromName, decryptSymmetric128BitHexKeyUTF8 } from "@app/lib/crypto"; import { buildSecretBlindIndexFromName, decryptSymmetric128BitHexKeyUTF8 } from "@app/lib/crypto";
import { TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretDalFactory } from "./secret-dal"; import { TSecretDALFactory } from "./secret-dal";
export const generateSecretBlindIndexBySalt = async ( export const generateSecretBlindIndexBySalt = async (
secretName: string, secretName: string,
@@ -28,15 +28,15 @@ export const generateSecretBlindIndexBySalt = async (
type TInterpolateSecretArg = { type TInterpolateSecretArg = {
projectId: string; projectId: string;
secretEncKey: string; secretEncKey: string;
secretDal: Pick<TSecretDalFactory, "findByFolderId">; secretDAL: Pick<TSecretDALFactory, "findByFolderId">;
folderDal: Pick<TSecretFolderDalFactory, "findBySecretPath">; folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
}; };
export const interpolateSecrets = ({ export const interpolateSecrets = ({
projectId, projectId,
secretEncKey, secretEncKey,
secretDal, secretDAL,
folderDal folderDAL
}: TInterpolateSecretArg) => { }: TInterpolateSecretArg) => {
const fetchSecretsCrossEnv = () => { const fetchSecretsCrossEnv = () => {
const fetchCache: Record<string, Record<string, string>> = {}; const fetchCache: Record<string, Record<string, string>> = {};
@@ -49,9 +49,9 @@ export const interpolateSecrets = ({
return fetchCache[uniqKey][secRefKey]; return fetchCache[uniqKey][secRefKey];
} }
const folder = await folderDal.findBySecretPath(projectId, secRefEnv, secRefPathUrl); const folder = await folderDAL.findBySecretPath(projectId, secRefEnv, secRefPathUrl);
if (!folder) return ""; if (!folder) return "";
const secrets = await secretDal.findByFolderId(folder.id); const secrets = await secretDAL.findByFolderId(folder.id);
const decryptedSec = secrets.reduce<Record<string, string>>((prev, secret) => { const decryptedSec = secrets.reduce<Record<string, string>>((prev, secret) => {
const secretKey = decryptSymmetric128BitHexKeyUTF8({ const secretKey = decryptSymmetric128BitHexKeyUTF8({
+27 -27
View File
@@ -4,31 +4,31 @@ import { isSamePath } from "@app/lib/fn";
import { logger } from "@app/lib/logger"; import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TIntegrationDalFactory } from "../integration/integration-dal"; import { TIntegrationDALFactory } from "../integration/integration-dal";
import { TIntegrationAuthServiceFactory } from "../integration-auth/integration-auth-service"; import { TIntegrationAuthServiceFactory } from "../integration-auth/integration-auth-service";
import { syncIntegrationSecrets } from "../integration-auth/integration-sync-secret"; import { syncIntegrationSecrets } from "../integration-auth/integration-sync-secret";
import { TProjectBotServiceFactory } from "../project-bot/project-bot-service"; import { TProjectBotServiceFactory } from "../project-bot/project-bot-service";
import { TProjectEnvDalFactory } from "../project-env/project-env-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
import { TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretImportDalFactory } from "../secret-import/secret-import-dal"; import { TSecretImportDALFactory } from "../secret-import/secret-import-dal";
import { fnSecretsFromImports } from "../secret-import/secret-import-fns"; import { fnSecretsFromImports } from "../secret-import/secret-import-fns";
import { TWebhookDalFactory } from "../webhook/webhook-dal"; import { TWebhookDALFactory } from "../webhook/webhook-dal";
import { fnTriggerWebhook } from "../webhook/webhook-fns"; import { fnTriggerWebhook } from "../webhook/webhook-fns";
import { TSecretDalFactory } from "./secret-dal"; import { TSecretDALFactory } from "./secret-dal";
import { interpolateSecrets } from "./secret-fns"; import { interpolateSecrets } from "./secret-fns";
export type TSecretQueueFactory = ReturnType<typeof secretQueueFactory>; export type TSecretQueueFactory = ReturnType<typeof secretQueueFactory>;
type TSecretQueueFactoryDep = { type TSecretQueueFactoryDep = {
queueService: TQueueServiceFactory; queueService: TQueueServiceFactory;
integrationDal: Pick<TIntegrationDalFactory, "findByProjectIdV2">; integrationDAL: Pick<TIntegrationDALFactory, "findByProjectIdV2">;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">; projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
integrationAuthService: Pick<TIntegrationAuthServiceFactory, "getIntegrationAccessToken">; integrationAuthService: Pick<TIntegrationAuthServiceFactory, "getIntegrationAccessToken">;
folderDal: Pick<TSecretFolderDalFactory, "findBySecretPath" | "findByManySecretPath">; folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath" | "findByManySecretPath">;
secretDal: Pick<TSecretDalFactory, "findByFolderId" | "find">; secretDAL: Pick<TSecretDALFactory, "findByFolderId" | "find">;
secretImportDal: Pick<TSecretImportDalFactory, "find">; secretImportDAL: Pick<TSecretImportDALFactory, "find">;
webhookDal: Pick<TWebhookDalFactory, "findAllWebhooks" | "transaction" | "update" | "bulkUpdate">; webhookDAL: Pick<TWebhookDALFactory, "findAllWebhooks" | "transaction" | "update" | "bulkUpdate">;
projectEnvDal: Pick<TProjectEnvDalFactory, "findOne">; projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
}; };
export type TGetSecrets = { export type TGetSecrets = {
@@ -39,14 +39,14 @@ export type TGetSecrets = {
export const secretQueueFactory = ({ export const secretQueueFactory = ({
queueService, queueService,
integrationDal, integrationDAL,
projectBotService, projectBotService,
integrationAuthService, integrationAuthService,
secretDal, secretDAL,
secretImportDal, secretImportDAL,
folderDal, folderDAL,
webhookDal, webhookDAL,
projectEnvDal projectEnvDAL
}: TSecretQueueFactoryDep) => { }: TSecretQueueFactoryDep) => {
const syncIntegrations = async (dto: TGetSecrets) => { const syncIntegrations = async (dto: TGetSecrets) => {
await queueService.queue(QueueName.IntegrationSync, QueueJobs.IntegrationSync, dto, { await queueService.queue(QueueName.IntegrationSync, QueueJobs.IntegrationSync, dto, {
@@ -79,15 +79,15 @@ export const secretQueueFactory = ({
}; };
const getIntegrationSecrets = async (dto: TGetSecrets & { folderId: string }, key: string) => { const getIntegrationSecrets = async (dto: TGetSecrets & { folderId: string }, key: string) => {
const secrets = await secretDal.findByFolderId(dto.folderId); const secrets = await secretDAL.findByFolderId(dto.folderId);
if (!secrets.length) return {}; if (!secrets.length) return {};
// get imported secrets // get imported secrets
const secretImport = await secretImportDal.find({ folderId: dto.folderId }); const secretImport = await secretImportDAL.find({ folderId: dto.folderId });
const importedSecrets = await fnSecretsFromImports({ const importedSecrets = await fnSecretsFromImports({
allowedImports: secretImport, allowedImports: secretImport,
secretDal, secretDAL,
folderDal folderDAL
}); });
const content: Record< const content: Record<
string, string,
@@ -154,8 +154,8 @@ export const secretQueueFactory = ({
const expandSecrets = interpolateSecrets({ const expandSecrets = interpolateSecrets({
projectId: dto.projectId, projectId: dto.projectId,
secretEncKey: key, secretEncKey: key,
folderDal, folderDAL,
secretDal secretDAL
}); });
await expandSecrets(content); await expandSecrets(content);
return content; return content;
@@ -163,13 +163,13 @@ export const secretQueueFactory = ({
queueService.start(QueueName.IntegrationSync, async (job) => { queueService.start(QueueName.IntegrationSync, async (job) => {
const { environment, projectId, secretPath } = job.data; const { environment, projectId, secretPath } = job.data;
const folder = await folderDal.findBySecretPath(projectId, environment, secretPath); const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
if (!folder) { if (!folder) {
logger.error("Secret path not found"); logger.error("Secret path not found");
return; return;
} }
const integrations = await integrationDal.findByProjectIdV2(projectId, environment); const integrations = await integrationDAL.findByProjectIdV2(projectId, environment);
const toBeSyncedIntegrations = integrations.filter( const toBeSyncedIntegrations = integrations.filter(
({ secretPath: integrationSecPath, isActive }) => ({ secretPath: integrationSecPath, isActive }) =>
isActive && isSamePath(secretPath, integrationSecPath) isActive && isSamePath(secretPath, integrationSecPath)
@@ -226,7 +226,7 @@ export const secretQueueFactory = ({
}); });
queueService.start(QueueName.SecretWebhook, async (job) => { queueService.start(QueueName.SecretWebhook, async (job) => {
await fnTriggerWebhook({ ...job.data, projectEnvDal, webhookDal }); await fnTriggerWebhook({ ...job.data, projectEnvDAL, webhookDAL });
}); });
return { syncSecrets, syncIntegrations }; return { syncSecrets, syncIntegrations };
@@ -20,12 +20,12 @@ import { groupBy, pick } from "@app/lib/fn";
import { ActorType } from "../auth/auth-type"; import { ActorType } from "../auth/auth-type";
import { TProjectBotServiceFactory } from "../project-bot/project-bot-service"; import { TProjectBotServiceFactory } from "../project-bot/project-bot-service";
import { TSecretFolderDalFactory } from "../secret-folder/secret-folder-dal"; import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretImportDalFactory } from "../secret-import/secret-import-dal"; import { TSecretImportDALFactory } from "../secret-import/secret-import-dal";
import { fnSecretsFromImports } from "../secret-import/secret-import-fns"; import { fnSecretsFromImports } from "../secret-import/secret-import-fns";
import { TSecretTagDalFactory } from "../secret-tag/secret-tag-dal"; import { TSecretTagDALFactory } from "../secret-tag/secret-tag-dal";
import { TSecretBlindIndexDalFactory } from "./secret-blind-index-dal"; import { TSecretBlindIndexDALFactory } from "./secret-blind-index-dal";
import { TSecretDalFactory } from "./secret-dal"; import { TSecretDALFactory } from "./secret-dal";
import { decryptSecretRaw, generateSecretBlindIndexBySalt } from "./secret-fns"; import { decryptSecretRaw, generateSecretBlindIndexBySalt } from "./secret-fns";
import { TSecretQueueFactory } from "./secret-queue"; import { TSecretQueueFactory } from "./secret-queue";
import { import {
@@ -50,42 +50,42 @@ import {
TUpdateSecretDTO, TUpdateSecretDTO,
TUpdateSecretRawDTO TUpdateSecretRawDTO
} from "./secret-types"; } from "./secret-types";
import { TSecretVersionDalFactory } from "./secret-version-dal"; import { TSecretVersionDALFactory } from "./secret-version-dal";
type TSecretServiceFactoryDep = { type TSecretServiceFactoryDep = {
secretDal: TSecretDalFactory; secretDAL: TSecretDALFactory;
secretTagDal: TSecretTagDalFactory; secretTagDAL: TSecretTagDALFactory;
secretVersionDal: TSecretVersionDalFactory; secretVersionDAL: TSecretVersionDALFactory;
folderDal: Pick< folderDAL: Pick<
TSecretFolderDalFactory, TSecretFolderDALFactory,
"findBySecretPath" | "updateById" | "findById" | "findByManySecretPath" "findBySecretPath" | "updateById" | "findById" | "findByManySecretPath"
>; >;
secretBlindIndexDal: TSecretBlindIndexDalFactory; secretBlindIndexDAL: TSecretBlindIndexDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">; snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;
secretQueueService: Pick<TSecretQueueFactory, "syncSecrets">; secretQueueService: Pick<TSecretQueueFactory, "syncSecrets">;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">; projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
secretImportDal: Pick<TSecretImportDalFactory, "find">; secretImportDAL: Pick<TSecretImportDALFactory, "find">;
}; };
export type TSecretServiceFactory = ReturnType<typeof secretServiceFactory>; export type TSecretServiceFactory = ReturnType<typeof secretServiceFactory>;
export const secretServiceFactory = ({ export const secretServiceFactory = ({
secretDal, secretDAL,
secretTagDal, secretTagDAL,
secretVersionDal, secretVersionDAL,
folderDal, folderDAL,
secretBlindIndexDal, secretBlindIndexDAL,
permissionService, permissionService,
snapshotService, snapshotService,
secretQueueService, secretQueueService,
projectBotService, projectBotService,
secretImportDal secretImportDAL
}: TSecretServiceFactoryDep) => { }: TSecretServiceFactoryDep) => {
// utility function to get secret blind index data // utility function to get secret blind index data
const interalGenSecBlindIndexByName = async (projectId: string, secretName: string) => { const interalGenSecBlindIndexByName = async (projectId: string, secretName: string) => {
const appCfg = getConfig(); const appCfg = getConfig();
const secretBlindIndexDoc = await secretBlindIndexDal.findOne({ projectId }); const secretBlindIndexDoc = await secretBlindIndexDAL.findOne({ projectId });
if (!secretBlindIndexDoc) if (!secretBlindIndexDoc)
throw new BadRequestError({ message: "Blind index not found", name: "Create secret" }); throw new BadRequestError({ message: "Blind index not found", name: "Create secret" });
@@ -105,7 +105,7 @@ export const secretServiceFactory = ({
// these functions are special functions shared by a couple of resources // these functions are special functions shared by a couple of resources
// used by secret approval, rotation or anywhere in which secret needs to modified // used by secret approval, rotation or anywhere in which secret needs to modified
const fnSecretBulkInsert = async ({ folderId, inputSecrets, tx }: TFnSecretBulkInsert) => { const fnSecretBulkInsert = async ({ folderId, inputSecrets, tx }: TFnSecretBulkInsert) => {
const newSecrets = await secretDal.insertMany( const newSecrets = await secretDAL.insertMany(
inputSecrets.map(({ tags, ...el }) => ({ ...el, folderId })), inputSecrets.map(({ tags, ...el }) => ({ ...el, folderId })),
tx tx
); );
@@ -117,9 +117,9 @@ export const secretServiceFactory = ({
})) }))
); );
if (newSecretTags.length) { if (newSecretTags.length) {
await secretTagDal.saveTagsToSecret(newSecretTags, tx); await secretTagDAL.saveTagsToSecret(newSecretTags, tx);
} }
await secretVersionDal.insertMany( await secretVersionDAL.insertMany(
inputSecrets.map(({ tags, ...el }) => ({ inputSecrets.map(({ tags, ...el }) => ({
...el, ...el,
folderId, folderId,
@@ -137,7 +137,7 @@ export const secretServiceFactory = ({
folderId, folderId,
projectId projectId
}: TFnSecretBulkUpdate) => { }: TFnSecretBulkUpdate) => {
const newSecrets = await secretDal.bulkUpdate( const newSecrets = await secretDAL.bulkUpdate(
inputSecrets.map(({ filter, data: { tags, ...data } }) => ({ inputSecrets.map(({ filter, data: { tags, ...data } }) => ({
filter: { ...filter, folderId }, filter: { ...filter, folderId },
data data
@@ -148,7 +148,7 @@ export const secretServiceFactory = ({
tags?.length ? { tags, secretId: newSecrets[i].id } : [] tags?.length ? { tags, secretId: newSecrets[i].id } : []
); );
if (secsUpdatedTag.length) { if (secsUpdatedTag.length) {
await secretTagDal.deleteTagsManySecret( await secretTagDAL.deleteTagsManySecret(
projectId, projectId,
secsUpdatedTag.flatMap(({ tags }) => tags), secsUpdatedTag.flatMap(({ tags }) => tags),
tx tx
@@ -159,9 +159,9 @@ export const secretServiceFactory = ({
[`${TableName.Secret}Id` as const]: secretId [`${TableName.Secret}Id` as const]: secretId
})) }))
); );
await secretTagDal.saveTagsToSecret(newSecretTags, tx); await secretTagDAL.saveTagsToSecret(newSecretTags, tx);
} }
await secretVersionDal.insertMany( await secretVersionDAL.insertMany(
newSecrets.map(({ id, createdAt, updatedAt, ...el }) => ({ newSecrets.map(({ id, createdAt, updatedAt, ...el }) => ({
...el, ...el,
secretId: id secretId: id
@@ -178,7 +178,7 @@ export const secretServiceFactory = ({
tx, tx,
actorId actorId
}: TFnSecretBulkDelete) => { }: TFnSecretBulkDelete) => {
const deletedSecrets = await secretDal.deleteMany( const deletedSecrets = await secretDAL.deleteMany(
inputSecrets.map(({ type, secretBlindIndex }) => ({ inputSecrets.map(({ type, secretBlindIndex }) => ({
blindIndex: secretBlindIndex, blindIndex: secretBlindIndex,
type type
@@ -220,7 +220,7 @@ export const secretServiceFactory = ({
throw new BadRequestError({ message: "Missing user id for personal secret" }); throw new BadRequestError({ message: "Missing user id for personal secret" });
} }
const secrets = await secretDal.findByBlindIndexes( const secrets = await secretDAL.findByBlindIndexes(
folderId, folderId,
inputSecrets.map(({ secretName, type }) => ({ inputSecrets.map(({ secretName, type }) => ({
blindIndex: keyName2BlindIndex[secretName], blindIndex: keyName2BlindIndex[secretName],
@@ -247,7 +247,7 @@ export const secretServiceFactory = ({
if (inputSecrets.some(({ type }) => type === SecretType.Personal) && !userId) { if (inputSecrets.some(({ type }) => type === SecretType.Personal) && !userId) {
throw new BadRequestError({ message: "Missing user id for personal secret" }); throw new BadRequestError({ message: "Missing user id for personal secret" });
} }
const secrets = await secretDal.findByBlindIndexes( const secrets = await secretDAL.findByBlindIndexes(
folderId, folderId,
inputSecrets.map(({ secretBlindIndex, type }) => ({ inputSecrets.map(({ secretBlindIndex, type }) => ({
blindIndex: secretBlindIndex, blindIndex: secretBlindIndex,
@@ -274,11 +274,11 @@ export const secretServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDal.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) if (!blindIndexCfg)
throw new BadRequestError({ message: "Blind index not found", name: "CreateSecret" }); throw new BadRequestError({ message: "Blind index not found", name: "CreateSecret" });
@@ -296,7 +296,7 @@ export const secretServiceFactory = ({
// if user creating personal check its shared also exist // if user creating personal check its shared also exist
if (inputSecret.type === SecretType.Personal) { if (inputSecret.type === SecretType.Personal) {
const sharedExist = await secretDal.findOne({ const sharedExist = await secretDAL.findOne({
secretBlindIndex: keyName2BlindIndex[inputSecret.secretName], secretBlindIndex: keyName2BlindIndex[inputSecret.secretName],
folderId, folderId,
type: SecretType.Shared type: SecretType.Shared
@@ -310,13 +310,13 @@ 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 const tags = inputSecret.tags
? await secretTagDal.findManyTagsById(projectId, inputSecret.tags) ? await secretTagDAL.findManyTagsById(projectId, inputSecret.tags)
: []; : [];
if ((inputSecret.tags || []).length !== tags.length) if ((inputSecret.tags || []).length !== tags.length)
throw new BadRequestError({ message: "Tag not found" }); throw new BadRequestError({ message: "Tag not found" });
const { secretName, type, ...el } = inputSecret; const { secretName, type, ...el } = inputSecret;
const secret = await secretDal.transaction((tx) => const secret = await secretDAL.transaction((tx) =>
fnSecretBulkInsert({ fnSecretBulkInsert({
folderId, folderId,
inputSecrets: [ inputSecrets: [
@@ -355,11 +355,11 @@ export const secretServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDal.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) if (!blindIndexCfg)
throw new BadRequestError({ message: "Blind index not found", name: "CreateSecret" }); throw new BadRequestError({ message: "Blind index not found", name: "CreateSecret" });
@@ -390,13 +390,13 @@ export const secretServiceFactory = ({
} }
const tags = inputSecret.tags const tags = inputSecret.tags
? await secretTagDal.findManyTagsById(projectId, inputSecret.tags) ? await secretTagDAL.findManyTagsById(projectId, inputSecret.tags)
: []; : [];
if ((inputSecret.tags || []).length !== tags.length) if ((inputSecret.tags || []).length !== tags.length)
throw new BadRequestError({ message: "Tag not found" }); throw new BadRequestError({ message: "Tag not found" });
const { secretName, ...el } = inputSecret; const { secretName, ...el } = inputSecret;
const updatedSecret = await secretDal.transaction(async (tx) => const updatedSecret = await secretDAL.transaction(async (tx) =>
fnSecretBulkUpdate({ fnSecretBulkUpdate({
folderId, folderId,
projectId, projectId,
@@ -449,11 +449,11 @@ export const secretServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDal.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) if (!blindIndexCfg)
throw new BadRequestError({ message: "Blind index not found", name: "CreateSecret" }); throw new BadRequestError({ message: "Blind index not found", name: "CreateSecret" });
@@ -468,7 +468,7 @@ export const secretServiceFactory = ({
blindIndexCfg blindIndexCfg
}); });
const deletedSecret = await secretDal.transaction(async (tx) => const deletedSecret = await secretDAL.transaction(async (tx) =>
fnSecretBulkDelete({ fnSecretBulkDelete({
projectId, projectId,
folderId, folderId,
@@ -504,13 +504,13 @@ export const secretServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) return { secrets: [], imports: [] }; if (!folder) return { secrets: [], imports: [] };
const folderId = folder.id; const folderId = folder.id;
const secrets = await secretDal.findByFolderId(folderId, actorId); const secrets = await secretDAL.findByFolderId(folderId, actorId);
if (includeImports) { if (includeImports) {
const secretImports = await secretImportDal.find({ folderId }); const secretImports = await secretImportDAL.find({ folderId });
const allowedImports = secretImports.filter(({ importEnv, importPath }) => const allowedImports = secretImports.filter(({ importEnv, importPath }) =>
// if its service token allow full access over imported one // if its service token allow full access over imported one
actor === ActorType.SERVICE actor === ActorType.SERVICE
@@ -525,8 +525,8 @@ export const secretServiceFactory = ({
); );
const importedSecrets = await fnSecretsFromImports({ const importedSecrets = await fnSecretsFromImports({
allowedImports, allowedImports,
secretDal, secretDAL,
folderDal folderDAL
}); });
return { return {
secrets: secrets.map((el) => ({ ...el, workspace: projectId, environment })), secrets: secrets.map((el) => ({ ...el, workspace: projectId, environment })),
@@ -552,20 +552,20 @@ export const secretServiceFactory = ({
ProjectPermissionActions.Read, ProjectPermissionActions.Read,
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
const folderId = folder.id; const folderId = folder.id;
const secretBlindIndex = await interalGenSecBlindIndexByName(projectId, secretName); const secretBlindIndex = await interalGenSecBlindIndexByName(projectId, secretName);
const secret = await (typeof version !== undefined const secret = await (typeof version !== undefined
? secretDal.findOne({ ? secretDAL.findOne({
folderId, folderId,
type, type,
userId: type === SecretType.Personal ? actorId : null, userId: type === SecretType.Personal ? actorId : null,
secretBlindIndex secretBlindIndex
}) })
: secretVersionDal : secretVersionDAL
.findOne({ .findOne({
folderId, folderId,
type, type,
@@ -577,7 +577,7 @@ export const secretServiceFactory = ({
// then search for imported secrets // then search for imported secrets
// here we consider the import order also thus starting from bottom // here we consider the import order also thus starting from bottom
if (!secret && includeImports) { if (!secret && includeImports) {
const secretImports = await secretImportDal.find({ folderId }); const secretImports = await secretImportDAL.find({ folderId });
const allowedImports = secretImports.filter(({ importEnv, importPath }) => const allowedImports = secretImports.filter(({ importEnv, importPath }) =>
// if its service token allow full access over imported one // if its service token allow full access over imported one
actor === ActorType.SERVICE actor === ActorType.SERVICE
@@ -592,8 +592,8 @@ export const secretServiceFactory = ({
); );
const importedSecrets = await fnSecretsFromImports({ const importedSecrets = await fnSecretsFromImports({
allowedImports, allowedImports,
secretDal, secretDAL,
folderDal folderDAL
}); });
for (let i = importedSecrets.length - 1; i >= 0; i -= 1) { for (let i = importedSecrets.length - 1; i >= 0; i -= 1) {
for (let j = 0; j < importedSecrets[i].secrets.length; j += 1) { for (let j = 0; j < importedSecrets[i].secrets.length; j += 1) {
@@ -626,11 +626,11 @@ export const secretServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDal.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) if (!blindIndexCfg)
throw new BadRequestError({ message: "Blind index not found", name: "Update secret" }); throw new BadRequestError({ message: "Blind index not found", name: "Update secret" });
@@ -643,10 +643,10 @@ 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 BadRequestError({ message: "Tag not found" }); if (tags.length !== tagIds.length) throw new BadRequestError({ message: "Tag not found" });
const newSecrets = await secretDal.transaction(async (tx) => const newSecrets = await secretDAL.transaction(async (tx) =>
fnSecretBulkInsert({ fnSecretBulkInsert({
inputSecrets: inputSecrets.map(({ secretName, ...el }) => ({ inputSecrets: inputSecrets.map(({ secretName, ...el }) => ({
...el, ...el,
@@ -681,11 +681,11 @@ export const secretServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDal.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) if (!blindIndexCfg)
throw new BadRequestError({ message: "Blind index not found", name: "Update secret" }); throw new BadRequestError({ message: "Blind index not found", name: "Update secret" });
@@ -708,9 +708,9 @@ 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 BadRequestError({ message: "Tag not found" }); if (tagIds.length !== tags.length) throw new BadRequestError({ message: "Tag not found" });
const secrets = await secretDal.transaction(async (tx) => const secrets = await secretDAL.transaction(async (tx) =>
fnSecretBulkUpdate({ fnSecretBulkUpdate({
folderId, folderId,
projectId, projectId,
@@ -752,11 +752,11 @@ export const secretServiceFactory = ({
subject(ProjectPermissionSub.Secrets, { environment, secretPath: path }) subject(ProjectPermissionSub.Secrets, { environment, secretPath: path })
); );
const folder = await folderDal.findBySecretPath(projectId, environment, path); const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" }); if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
const folderId = folder.id; const folderId = folder.id;
const blindIndexCfg = await secretBlindIndexDal.findOne({ projectId }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
if (!blindIndexCfg) if (!blindIndexCfg)
throw new BadRequestError({ message: "Blind index not found", name: "Update secret" }); throw new BadRequestError({ message: "Blind index not found", name: "Update secret" });
@@ -767,7 +767,7 @@ export const secretServiceFactory = ({
blindIndexCfg blindIndexCfg
}); });
const secretsDeleted = await secretDal.transaction(async (tx) => const secretsDeleted = await secretDAL.transaction(async (tx) =>
fnSecretBulkDelete({ fnSecretBulkDelete({
inputSecrets: inputSecrets.map(({ type, secretName }) => ({ inputSecrets: inputSecrets.map(({ type, secretName }) => ({
secretBlindIndex: keyName2BlindIndex[secretName], secretBlindIndex: keyName2BlindIndex[secretName],
@@ -793,10 +793,10 @@ export const secretServiceFactory = ({
offset, offset,
secretId secretId
}: TListSecretVersionDTO) => { }: TListSecretVersionDTO) => {
const secret = await secretDal.findById(secretId); const secret = await secretDAL.findById(secretId);
if (!secret) throw new BadRequestError({ message: "Failed to find secret" }); if (!secret) throw new BadRequestError({ message: "Failed to find secret" });
const folder = await folderDal.findById(secret.folderId); const folder = await folderDAL.findById(secret.folderId);
if (!folder) throw new BadRequestError({ message: "Folder not found" }); if (!folder) throw new BadRequestError({ message: "Folder not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@@ -808,7 +808,7 @@ export const secretServiceFactory = ({
ProjectPermissionSub.SecretRollback ProjectPermissionSub.SecretRollback
); );
const secretVersions = await secretVersionDal.find( const secretVersions = await secretVersionDAL.find(
{ secretId }, { secretId },
{ limit, offset, sort: [["createdAt", "desc"]] } { limit, offset, sort: [["createdAt", "desc"]] }
); );
@@ -995,10 +995,10 @@ export const secretServiceFactory = ({
offset = 0, offset = 0,
secretId secretId
}: TGetSecretVersionsDTO) => { }: TGetSecretVersionsDTO) => {
const secret = await secretDal.findById(secretId); const secret = await secretDAL.findById(secretId);
if (!secret) throw new BadRequestError({ message: "Failed to find secret" }); if (!secret) throw new BadRequestError({ message: "Failed to find secret" });
const folder = await folderDal.findById(secret.folderId); const folder = await folderDAL.findById(secret.folderId);
if (!folder) throw new BadRequestError({ message: "Failed to find secret" }); if (!folder) throw new BadRequestError({ message: "Failed to find secret" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -1011,7 +1011,7 @@ export const secretServiceFactory = ({
ProjectPermissionSub.SecretRollback ProjectPermissionSub.SecretRollback
); );
const secretVersions = await secretVersionDal.find( const secretVersions = await secretVersionDAL.find(
{ secretId }, { secretId },
{ offset, limit, sort: [["createdAt", "desc"]] } { offset, limit, sort: [["createdAt", "desc"]] }
); );
@@ -5,9 +5,9 @@ import { TableName, TSecretVersions } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TSecretVersionDalFactory = ReturnType<typeof secretVersionDalFactory>; export type TSecretVersionDALFactory = ReturnType<typeof secretVersionDALFactory>;
export const secretVersionDalFactory = (db: TDbClient) => { export const secretVersionDALFactory = (db: TDbClient) => {
const secretVersionOrm = ormify(db, TableName.SecretVersion); const secretVersionOrm = ormify(db, TableName.SecretVersion);
// This will fetch all latest secret versions from a folder // This will fetch all latest secret versions from a folder
@@ -2,9 +2,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TServiceTokenDalFactory = ReturnType<typeof serviceTokenDalFactory>; export type TServiceTokenDALFactory = ReturnType<typeof serviceTokenDALFactory>;
export const serviceTokenDalFactory = (db: TDbClient) => { export const serviceTokenDALFactory = (db: TDbClient) => {
const stOrm = ormify(db, TableName.ServiceToken); const stOrm = ormify(db, TableName.ServiceToken);
return stOrm; return stOrm;
}; };
@@ -12,8 +12,8 @@ import { getConfig } from "@app/lib/config/env";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors"; import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { ActorType } from "../auth/auth-type"; import { ActorType } from "../auth/auth-type";
import { TProjectEnvDalFactory } from "../project-env/project-env-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
import { TServiceTokenDalFactory } from "./service-token-dal"; import { TServiceTokenDALFactory } from "./service-token-dal";
import { import {
TCreateServiceTokenDTO, TCreateServiceTokenDTO,
TDeleteServiceTokenDTO, TDeleteServiceTokenDTO,
@@ -22,17 +22,17 @@ import {
} from "./service-token-types"; } from "./service-token-types";
type TServiceTokenServiceFactoryDep = { type TServiceTokenServiceFactoryDep = {
serviceTokenDal: TServiceTokenDalFactory; serviceTokenDAL: TServiceTokenDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
projectEnvDal: Pick<TProjectEnvDalFactory, "findBySlugs">; projectEnvDAL: Pick<TProjectEnvDALFactory, "findBySlugs">;
}; };
export type TServiceTokenServiceFactory = ReturnType<typeof serviceTokenServiceFactory>; export type TServiceTokenServiceFactory = ReturnType<typeof serviceTokenServiceFactory>;
export const serviceTokenServiceFactory = ({ export const serviceTokenServiceFactory = ({
serviceTokenDal, serviceTokenDAL,
permissionService, permissionService,
projectEnvDal projectEnvDAL
}: TServiceTokenServiceFactoryDep) => { }: TServiceTokenServiceFactoryDep) => {
const createServiceToken = async ({ const createServiceToken = async ({
iv, iv,
@@ -63,7 +63,7 @@ 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) if (inputEnvs.length !== scopeEnvs.length)
throw new BadRequestError({ message: "Environment not found" }); throw new BadRequestError({ message: "Environment not found" });
@@ -76,7 +76,7 @@ export const serviceTokenServiceFactory = ({
} }
const createdBy = actorId; const createdBy = actorId;
const serviceToken = await serviceTokenDal.create({ const serviceToken = await serviceTokenDAL.create({
name, name,
createdBy, createdBy,
encryptedKey, encryptedKey,
@@ -95,7 +95,7 @@ export const serviceTokenServiceFactory = ({
}; };
const deleteServiceToken = async ({ actorId, actor, id }: TDeleteServiceTokenDTO) => { const deleteServiceToken = async ({ actorId, actor, id }: TDeleteServiceTokenDTO) => {
const serviceToken = await serviceTokenDal.findById(id); const serviceToken = await serviceTokenDAL.findById(id);
if (!serviceToken) throw new BadRequestError({ message: "Token not found" }); if (!serviceToken) throw new BadRequestError({ message: "Token not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -108,7 +108,7 @@ export const serviceTokenServiceFactory = ({
ProjectPermissionSub.ServiceTokens ProjectPermissionSub.ServiceTokens
); );
const deletedServiceToken = await serviceTokenDal.deleteById(id); const deletedServiceToken = await serviceTokenDAL.deleteById(id);
return deletedServiceToken; return deletedServiceToken;
}; };
@@ -116,7 +116,7 @@ export const serviceTokenServiceFactory = ({
if (actor !== ActorType.SERVICE) if (actor !== ActorType.SERVICE)
throw new BadRequestError({ message: "Service token not found" }); throw new BadRequestError({ message: "Service token not found" });
const serviceToken = await serviceTokenDal.findById(actorId); const serviceToken = await serviceTokenDAL.findById(actorId);
if (!serviceToken) throw new BadRequestError({ message: "Token not found" }); if (!serviceToken) throw new BadRequestError({ message: "Token not found" });
return serviceToken; return serviceToken;
@@ -133,23 +133,23 @@ export const serviceTokenServiceFactory = ({
ProjectPermissionSub.ServiceTokens ProjectPermissionSub.ServiceTokens
); );
const tokens = await serviceTokenDal.find({ projectId }); const tokens = await serviceTokenDAL.find({ projectId });
return tokens; return tokens;
}; };
const fnValidateServiceToken = async (token: string) => { const fnValidateServiceToken = async (token: string) => {
const [, TOKEN_IDENTIFIER, TOKEN_SECRET] = <[string, string, string]>token.split(".", 3); const [, TOKEN_IDENTIFIER, TOKEN_SECRET] = <[string, string, string]>token.split(".", 3);
const serviceToken = await serviceTokenDal.findById(TOKEN_IDENTIFIER); const serviceToken = await serviceTokenDAL.findById(TOKEN_IDENTIFIER);
if (!serviceToken) throw new UnauthorizedError(); if (!serviceToken) throw new UnauthorizedError();
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);
throw new UnauthorizedError({ message: "failed to authenticate expired service token" }); throw new UnauthorizedError({ message: "failed to authenticate expired service token" });
} }
const isMatch = await bcrypt.compare(TOKEN_SECRET, serviceToken.secretHash); const isMatch = await bcrypt.compare(TOKEN_SECRET, serviceToken.secretHash);
if (!isMatch) throw new UnauthorizedError(); if (!isMatch) throw new UnauthorizedError();
const updatedToken = await serviceTokenDal.updateById(serviceToken.id, { const updatedToken = await serviceTokenDAL.updateById(serviceToken.id, {
lastUsed: new Date() lastUsed: new Date()
}); });
return updatedToken; return updatedToken;
@@ -2,6 +2,6 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas"; import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TSuperAdminDalFactory = ReturnType<typeof superAdminDalFactory>; export type TSuperAdminDALFactory = ReturnType<typeof superAdminDALFactory>;
export const superAdminDalFactory = (db: TDbClient) => ormify(db, TableName.SuperAdmin, {}); export const superAdminDALFactory = (db: TDbClient) => ormify(db, TableName.SuperAdmin, {});
@@ -4,13 +4,13 @@ import { BadRequestError } from "@app/lib/errors";
import { TAuthLoginFactory } from "../auth/auth-login-service"; import { TAuthLoginFactory } from "../auth/auth-login-service";
import { AuthMethod } from "../auth/auth-type"; import { AuthMethod } from "../auth/auth-type";
import { TOrgServiceFactory } from "../org/org-service"; import { TOrgServiceFactory } from "../org/org-service";
import { TUserDalFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TSuperAdminDalFactory } from "./super-admin-dal"; import { TSuperAdminDALFactory } from "./super-admin-dal";
import { TAdminSignUpDTO } from "./super-admin-types"; import { TAdminSignUpDTO } from "./super-admin-types";
type TSuperAdminServiceFactoryDep = { type TSuperAdminServiceFactoryDep = {
serverCfgDal: TSuperAdminDalFactory; serverCfgDAL: TSuperAdminDALFactory;
userDal: TUserDalFactory; userDAL: TUserDALFactory;
authService: Pick<TAuthLoginFactory, "generateUserTokens">; authService: Pick<TAuthLoginFactory, "generateUserTokens">;
orgService: Pick<TOrgServiceFactory, "createOrganization">; orgService: Pick<TOrgServiceFactory, "createOrganization">;
}; };
@@ -25,15 +25,15 @@ export const getServerCfg = () => {
}; };
export const superAdminServiceFactory = ({ export const superAdminServiceFactory = ({
serverCfgDal, serverCfgDAL,
userDal, userDAL,
authService, authService,
orgService orgService
}: TSuperAdminServiceFactoryDep) => { }: TSuperAdminServiceFactoryDep) => {
const initServerCfg = async () => { const initServerCfg = async () => {
serverCfg = await serverCfgDal.findOne({}); serverCfg = await serverCfgDAL.findOne({});
if (!serverCfg) { if (!serverCfg) {
const newCfg = await serverCfgDal.create({ initialized: false, allowSignUp: true }); const newCfg = await serverCfgDAL.create({ initialized: false, allowSignUp: true });
serverCfg = newCfg; serverCfg = newCfg;
return newCfg; return newCfg;
} }
@@ -41,7 +41,7 @@ export const superAdminServiceFactory = ({
}; };
const updateServerCfg = async (data: TSuperAdminUpdate) => { const updateServerCfg = async (data: TSuperAdminUpdate) => {
const cfg = await serverCfgDal.updateById(serverCfg.id, data); const cfg = await serverCfgDAL.updateById(serverCfg.id, data);
serverCfg = Object.freeze(cfg); serverCfg = Object.freeze(cfg);
return cfg; return cfg;
}; };
@@ -62,12 +62,12 @@ export const superAdminServiceFactory = ({
ip, ip,
userAgent userAgent
}: TAdminSignUpDTO) => { }: TAdminSignUpDTO) => {
const existingUser = await userDal.findOne({ email }); const existingUser = await userDAL.findOne({ email });
if (existingUser) if (existingUser)
throw new BadRequestError({ name: "Admin sign up", message: "User already exist" }); throw new BadRequestError({ name: "Admin sign up", message: "User already exist" });
const userInfo = await userDal.transaction(async (tx) => { const userInfo = await userDAL.transaction(async (tx) => {
const newUser = await userDal.create( const newUser = await userDAL.create(
{ {
firstName, firstName,
lastName, lastName,
@@ -78,7 +78,7 @@ export const superAdminServiceFactory = ({
}, },
tx tx
); );
const userEnc = await userDal.createUserEncryption( const userEnc = await userDAL.createUserEncryption(
{ {
salt, salt,
encryptionVersion: 2, encryptionVersion: 2,
+2 -2
View File
@@ -12,9 +12,9 @@ import {
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
export type TUserDalFactory = ReturnType<typeof userDalFactory>; export type TUserDALFactory = ReturnType<typeof userDALFactory>;
export const userDalFactory = (db: TDbClient) => { export const userDALFactory = (db: TDbClient) => {
const userOrm = ormify(db, TableName.Users); const userOrm = ormify(db, TableName.Users);
const findUserByEmail = async (email: string, tx?: Knex) => userOrm.findOne({ email }, tx); const findUserByEmail = async (email: string, tx?: Knex) => userOrm.findOne({ email }, tx);
+13 -13
View File
@@ -1,17 +1,17 @@
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { AuthMethod } from "../auth/auth-type"; import { AuthMethod } from "../auth/auth-type";
import { TUserDalFactory } from "./user-dal"; import { TUserDALFactory } from "./user-dal";
type TUserServiceFactoryDep = { type TUserServiceFactoryDep = {
userDal: TUserDalFactory; userDAL: TUserDALFactory;
}; };
export type TUserServiceFactory = ReturnType<typeof userServiceFactory>; export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;
export const userServiceFactory = ({ userDal }: TUserServiceFactoryDep) => { export const userServiceFactory = ({ userDAL }: TUserServiceFactoryDep) => {
const toggleUserMfa = async (userId: string, isMfaEnabled: boolean) => { const toggleUserMfa = async (userId: string, isMfaEnabled: boolean) => {
const updatedUser = await userDal.updateById(userId, { const updatedUser = await userDAL.updateById(userId, {
isMfaEnabled, isMfaEnabled,
mfaMethods: isMfaEnabled ? ["email"] : [] mfaMethods: isMfaEnabled ? ["email"] : []
}); });
@@ -19,7 +19,7 @@ export const userServiceFactory = ({ userDal }: TUserServiceFactoryDep) => {
}; };
const updateUserName = async (userId: string, firstName: string, lastName: string) => { const updateUserName = async (userId: string, firstName: string, lastName: string) => {
const updatedUser = await userDal.updateById(userId, { const updatedUser = await userDAL.updateById(userId, {
firstName, firstName,
lastName lastName
}); });
@@ -27,7 +27,7 @@ export const userServiceFactory = ({ userDal }: TUserServiceFactoryDep) => {
}; };
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 BadRequestError({ name: "Update auth methods" }); if (!user) throw new BadRequestError({ name: "Update auth methods" });
const hasSamlEnabled = user?.authMethods?.some((method) => const hasSamlEnabled = user?.authMethods?.some((method) =>
@@ -41,34 +41,34 @@ export const userServiceFactory = ({ userDal }: TUserServiceFactoryDep) => {
message: "Failed to update auth methods due to SAML SSO " message: "Failed to update auth methods due to SAML SSO "
}); });
const updatedUser = await userDal.updateById(userId, { authMethods }); const updatedUser = await userDAL.updateById(userId, { authMethods });
return updatedUser; return updatedUser;
}; };
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 BadRequestError({ message: "user not found", name: "Get Me" }); if (!user) throw new BadRequestError({ message: "user not found", name: "Get Me" });
return user; return user;
}; };
const deleteMe = async (userId: string) => { const deleteMe = async (userId: string) => {
const user = await userDal.deleteById(userId); const user = await userDAL.deleteById(userId);
return user; return user;
}; };
// user actions operations // user actions operations
const createUserAction = async (userId: string, action: string) => { const createUserAction = async (userId: string, action: string) => {
const userAction = await userDal.transaction(async (tx) => { const userAction = await userDAL.transaction(async (tx) => {
const existingAction = await userDal.findOneUserAction({ action, userId }, tx); const existingAction = await userDAL.findOneUserAction({ action, userId }, tx);
if (existingAction) return existingAction; if (existingAction) return existingAction;
return userDal.createUserAction({ action, userId }, tx); return userDAL.createUserAction({ action, userId }, tx);
}); });
return userAction; return userAction;
}; };
const getUserAction = async (userId: string, action: string) => { const getUserAction = async (userId: string, action: string) => {
const userAction = await userDal.findOneUserAction({ action, userId }); const userAction = await userDAL.findOneUserAction({ action, userId });
return userAction; return userAction;
}; };
@@ -5,9 +5,9 @@ import { TableName, TWebhooks, TWebhooksUpdate } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex"; import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TWebhookDalFactory = ReturnType<typeof webhookDalFactory>; export type TWebhookDALFactory = ReturnType<typeof webhookDALFactory>;
export const webhookDalFactory = (db: TDbClient) => { export const webhookDALFactory = (db: TDbClient) => {
const webhookOrm = ormify(db, TableName.Webhook); const webhookOrm = ormify(db, TableName.Webhook);
const webhookFindQuery = (tx: Knex, filter: Partial<TWebhooks>) => const webhookFindQuery = (tx: Knex, filter: Partial<TWebhooks>) =>
+11 -11
View File
@@ -9,8 +9,8 @@ import { decryptSymmetric, decryptSymmetric128BitHexKeyUTF8 } from "@app/lib/cry
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger"; import { logger } from "@app/lib/logger";
import { TProjectEnvDalFactory } from "../project-env/project-env-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
import { TWebhookDalFactory } from "./webhook-dal"; import { TWebhookDALFactory } from "./webhook-dal";
const WEBHOOK_TRIGGER_TIMEOUT = 15 * 1000; const WEBHOOK_TRIGGER_TIMEOUT = 15 * 1000;
export const triggerWebhookRequest = async ( export const triggerWebhookRequest = async (
@@ -76,8 +76,8 @@ export type TFnTriggerWebhookDTO = {
projectId: string; projectId: string;
secretPath: string; secretPath: string;
environment: string; environment: string;
webhookDal: Pick<TWebhookDalFactory, "findAllWebhooks" | "transaction" | "update" | "bulkUpdate">; webhookDAL: Pick<TWebhookDALFactory, "findAllWebhooks" | "transaction" | "update" | "bulkUpdate">;
projectEnvDal: Pick<TProjectEnvDalFactory, "findOne">; projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
}; };
// this is reusable function // this is reusable function
// used in secret queue to trigger webhook and update status when secrets changes // used in secret queue to trigger webhook and update status when secrets changes
@@ -85,10 +85,10 @@ export const fnTriggerWebhook = async ({
environment, environment,
secretPath, secretPath,
projectId, projectId,
webhookDal, webhookDAL,
projectEnvDal projectEnvDAL
}: TFnTriggerWebhookDTO) => { }: TFnTriggerWebhookDTO) => {
const webhooks = await webhookDal.findAllWebhooks(projectId, environment); const webhooks = await webhookDAL.findAllWebhooks(projectId, environment);
const toBeTriggeredHooks = webhooks.filter( const toBeTriggeredHooks = webhooks.filter(
({ secretPath: hookSecretPath, isDisabled }) => ({ secretPath: hookSecretPath, isDisabled }) =>
!isDisabled && picomatch.isMatch(secretPath, hookSecretPath, { strictSlashes: false }) !isDisabled && picomatch.isMatch(secretPath, hookSecretPath, { strictSlashes: false })
@@ -114,18 +114,18 @@ export const fnTriggerWebhook = async ({
error: data.status === "rejected" && data.reason.message error: data.status === "rejected" && data.reason.message
})); }));
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 BadRequestError({ message: "Env not found" }); if (!env) throw new BadRequestError({ message: "Env 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 } },
{ lastStatus: "success", lastRunErrorMessage: null }, { lastStatus: "success", lastRunErrorMessage: null },
tx tx
); );
} }
if (failedWebhooks.length) { if (failedWebhooks.length) {
await webhookDal.bulkUpdate( await webhookDAL.bulkUpdate(
failedWebhooks.map(({ id, error }) => ({ failedWebhooks.map(({ id, error }) => ({
id, id,
lastRunErrorMessage: error, lastRunErrorMessage: error,
@@ -10,8 +10,8 @@ import { getConfig } from "@app/lib/config/env";
import { encryptSymmetric, encryptSymmetric128BitHexKeyUTF8 } from "@app/lib/crypto"; import { encryptSymmetric, encryptSymmetric128BitHexKeyUTF8 } from "@app/lib/crypto";
import { BadRequestError } from "@app/lib/errors"; import { BadRequestError } from "@app/lib/errors";
import { TProjectEnvDalFactory } from "../project-env/project-env-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
import { TWebhookDalFactory } from "./webhook-dal"; import { TWebhookDALFactory } from "./webhook-dal";
import { getWebhookPayload, triggerWebhookRequest } from "./webhook-fns"; import { getWebhookPayload, triggerWebhookRequest } from "./webhook-fns";
import { import {
TCreateWebhookDTO, TCreateWebhookDTO,
@@ -22,16 +22,16 @@ import {
} from "./webhook-types"; } from "./webhook-types";
type TWebhookServiceFactoryDep = { type TWebhookServiceFactoryDep = {
webhookDal: TWebhookDalFactory; webhookDAL: TWebhookDALFactory;
projectEnvDal: TProjectEnvDalFactory; projectEnvDAL: TProjectEnvDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">; permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
}; };
export type TWebhookServiceFactory = ReturnType<typeof webhookServiceFactory>; export type TWebhookServiceFactory = ReturnType<typeof webhookServiceFactory>;
export const webhookServiceFactory = ({ export const webhookServiceFactory = ({
webhookDal, webhookDAL,
projectEnvDal, projectEnvDAL,
permissionService permissionService
}: TWebhookServiceFactoryDep) => { }: TWebhookServiceFactoryDep) => {
const createWebhook = async ({ const createWebhook = async ({
@@ -48,7 +48,7 @@ export const webhookServiceFactory = ({
ProjectPermissionActions.Create, ProjectPermissionActions.Create,
ProjectPermissionSub.Webhooks ProjectPermissionSub.Webhooks
); );
const env = await projectEnvDal.findOne({ projectId, slug: environment }); const env = await projectEnvDAL.findOne({ projectId, slug: environment });
if (!env) throw new BadRequestError({ message: "Env not found" }); if (!env) throw new BadRequestError({ message: "Env not found" });
const insertDoc: TWebhooksInsert = { const insertDoc: TWebhooksInsert = {
@@ -81,12 +81,12 @@ export const webhookServiceFactory = ({
} }
} }
const webhook = await webhookDal.create(insertDoc); const webhook = await webhookDAL.create(insertDoc);
return { ...webhook, projectId, environment: env }; return { ...webhook, projectId, environment: env };
}; };
const updateWebhook = async ({ actorId, actor, id, isDisabled }: TUpdateWebhookDTO) => { const updateWebhook = async ({ actorId, actor, id, isDisabled }: TUpdateWebhookDTO) => {
const webhook = await webhookDal.findById(id); const webhook = await webhookDAL.findById(id);
if (!webhook) throw new BadRequestError({ message: "Webhook not found" }); if (!webhook) throw new BadRequestError({ message: "Webhook not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -99,12 +99,12 @@ export const webhookServiceFactory = ({
ProjectPermissionSub.Webhooks ProjectPermissionSub.Webhooks
); );
const updatedWebhook = await webhookDal.updateById(id, { isDisabled }); const updatedWebhook = await webhookDAL.updateById(id, { isDisabled });
return { ...webhook, ...updatedWebhook }; return { ...webhook, ...updatedWebhook };
}; };
const deleteWebhook = async ({ id, actor, actorId }: TDeleteWebhookDTO) => { const deleteWebhook = async ({ id, actor, actorId }: TDeleteWebhookDTO) => {
const webhook = await webhookDal.findById(id); const webhook = await webhookDAL.findById(id);
if (!webhook) throw new BadRequestError({ message: "Webhook not found" }); if (!webhook) throw new BadRequestError({ message: "Webhook not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -117,12 +117,12 @@ export const webhookServiceFactory = ({
ProjectPermissionSub.Webhooks ProjectPermissionSub.Webhooks
); );
const deletedWebhook = await webhookDal.deleteById(id); const deletedWebhook = await webhookDAL.deleteById(id);
return { ...webhook, ...deletedWebhook }; return { ...webhook, ...deletedWebhook };
}; };
const testWebhook = async ({ id, actor, actorId }: TTestWebhookDTO) => { const testWebhook = async ({ id, actor, actorId }: TTestWebhookDTO) => {
const webhook = await webhookDal.findById(id); const webhook = await webhookDAL.findById(id);
if (!webhook) throw new BadRequestError({ message: "Webhook not found" }); if (!webhook) throw new BadRequestError({ message: "Webhook not found" });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -145,7 +145,7 @@ export const webhookServiceFactory = ({
webhookError = (err as Error).message; webhookError = (err as Error).message;
} }
const isSuccess = !webhookError; const isSuccess = !webhookError;
const updatedWebhook = await webhookDal.updateById(webhook.id, { const updatedWebhook = await webhookDAL.updateById(webhook.id, {
lastStatus: isSuccess ? "success" : "failed", lastStatus: isSuccess ? "success" : "failed",
lastRunErrorMessage: isSuccess ? null : webhookError lastRunErrorMessage: isSuccess ? null : webhookError
}); });
@@ -165,7 +165,7 @@ export const webhookServiceFactory = ({
ProjectPermissionSub.Webhooks ProjectPermissionSub.Webhooks
); );
return webhookDal.findAllWebhooks(projectId, environment, secretPath); return webhookDAL.findAllWebhooks(projectId, environment, secretPath);
}; };
return { return {