Begin cert alerting

This commit is contained in:
Tuan Dang
2024-08-07 07:08:47 -07:00
parent 5af53d3398
commit 1690a9429c
32 changed files with 972 additions and 7 deletions
+2
View File
@@ -27,6 +27,7 @@ import { TSecretScanningServiceFactory } from "@app/ee/services/secret-scanning/
import { TSecretSnapshotServiceFactory } from "@app/ee/services/secret-snapshot/secret-snapshot-service";
import { TTrustedIpServiceFactory } from "@app/ee/services/trusted-ip/trusted-ip-service";
import { TAuthMode } from "@app/server/plugins/auth/inject-identity";
import { TAlertServiceFactory } from "@app/services/alert/alert-service";
import { TApiKeyServiceFactory } from "@app/services/api-key/api-key-service";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { TAuthPasswordFactory } from "@app/services/auth/auth-password-service";
@@ -114,6 +115,7 @@ declare module "fastify" {
group: TGroupServiceFactory;
groupProject: TGroupProjectServiceFactory;
apiKey: TApiKeyServiceFactory;
alert: TAlertServiceFactory;
project: TProjectServiceFactory;
projectMembership: TProjectMembershipServiceFactory;
projectEnv: TProjectEnvServiceFactory;
+4
View File
@@ -14,6 +14,9 @@ import {
TAccessApprovalRequestsReviewersInsert,
TAccessApprovalRequestsReviewersUpdate,
TAccessApprovalRequestsUpdate,
TAlerts,
TAlertsInsert,
TAlertsUpdate,
TApiKeys,
TApiKeysInsert,
TApiKeysUpdate,
@@ -416,6 +419,7 @@ declare module "knex/types/tables" {
[TableName.UserAction]: KnexOriginal.CompositeTableType<TUserActions, TUserActionsInsert, TUserActionsUpdate>;
[TableName.SuperAdmin]: KnexOriginal.CompositeTableType<TSuperAdmin, TSuperAdminInsert, TSuperAdminUpdate>;
[TableName.ApiKey]: KnexOriginal.CompositeTableType<TApiKeys, TApiKeysInsert, TApiKeysUpdate>;
[TableName.Alert]: KnexOriginal.CompositeTableType<TAlerts, TAlertsInsert, TAlertsUpdate>;
[TableName.Project]: KnexOriginal.CompositeTableType<TProjects, TProjectsInsert, TProjectsUpdate>;
[TableName.ProjectMembership]: KnexOriginal.CompositeTableType<
TProjectMemberships,
@@ -0,0 +1,26 @@
import { Knex } from "knex";
import { TableName } from "../schemas";
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
export async function up(knex: Knex): Promise<void> {
if (!(await knex.schema.hasTable(TableName.Alert))) {
await knex.schema.createTable(TableName.Alert, (t) => {
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
t.timestamps(true, true, true);
t.string("projectId").notNullable();
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
t.string("name").notNullable();
t.integer("alertBeforeDays").notNullable();
t.string("recipientEmails").notNullable();
});
}
await createOnUpdateTrigger(knex, TableName.Alert);
}
export async function down(knex: Knex): Promise<void> {
// certificates
await knex.schema.dropTableIfExists(TableName.Alert);
await dropOnUpdateTrigger(knex, TableName.Alert);
}
+22
View File
@@ -0,0 +1,22 @@
// Code generated by automation script, DO NOT EDIT.
// Automated by pulling database and generating zod schema
// To update. Just run npm run generate:schema
// Written by akhilmhdh.
import { z } from "zod";
import { TImmutableDBKeys } from "./models";
export const AlertsSchema = z.object({
id: z.string().uuid(),
createdAt: z.date(),
updatedAt: z.date(),
projectId: z.string(),
name: z.string(),
alertBeforeDays: z.number(),
recipientEmails: z.string()
});
export type TAlerts = z.infer<typeof AlertsSchema>;
export type TAlertsInsert = Omit<z.input<typeof AlertsSchema>, TImmutableDBKeys>;
export type TAlertsUpdate = Partial<Omit<z.input<typeof AlertsSchema>, TImmutableDBKeys>>;
+1
View File
@@ -2,6 +2,7 @@ export * from "./access-approval-policies";
export * from "./access-approval-policies-approvers";
export * from "./access-approval-requests";
export * from "./access-approval-requests-reviewers";
export * from "./alerts";
export * from "./api-keys";
export * from "./audit-log-streams";
export * from "./audit-logs";
+1
View File
@@ -9,6 +9,7 @@ export enum TableName {
Certificate = "certificates",
CertificateBody = "certificate_bodies",
CertificateSecret = "certificate_secrets",
Alert = "alerts",
Groups = "groups",
GroupProjectMembership = "group_project_memberships",
GroupProjectMembershipRole = "group_project_membership_roles",
@@ -10,6 +10,7 @@ export enum ProjectPermissionActions {
}
export enum ProjectPermissionSub {
Alerts = "alerts",
Role = "role",
Member = "member",
Groups = "groups",
@@ -63,6 +64,7 @@ export type ProjectPermissionSet =
| [ProjectPermissionActions, ProjectPermissionSub.Identity]
| [ProjectPermissionActions, ProjectPermissionSub.CertificateAuthorities]
| [ProjectPermissionActions, ProjectPermissionSub.Certificates]
| [ProjectPermissionActions, ProjectPermissionSub.Alerts]
| [ProjectPermissionActions.Delete, ProjectPermissionSub.Project]
| [ProjectPermissionActions.Edit, ProjectPermissionSub.Project]
| [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback]
@@ -72,6 +74,11 @@ export type ProjectPermissionSet =
const buildAdminPermissionRules = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
can(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
can(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Alerts);
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Alerts);
can(ProjectPermissionActions.Read, ProjectPermissionSub.Secrets);
can(ProjectPermissionActions.Create, ProjectPermissionSub.Secrets);
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Secrets);
@@ -237,6 +244,8 @@ const buildMemberPermissionRules = () => {
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Certificates);
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Certificates);
can(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
return rules;
};
+9
View File
@@ -73,6 +73,8 @@ import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { TQueueServiceFactory } from "@app/queue";
import { readLimit } from "@app/server/config/rateLimiter";
import { alertDALFactory } from "@app/services/alert/alert-dal";
import { alertServiceFactory } from "@app/services/alert/alert-service";
import { apiKeyDALFactory } from "@app/services/api-key/api-key-dal";
import { apiKeyServiceFactory } from "@app/services/api-key/api-key-service";
import { authDALFactory } from "@app/services/auth/auth-dal";
@@ -216,6 +218,7 @@ export const registerRoutes = async (
const superAdminDAL = superAdminDALFactory(db);
const rateLimitDAL = rateLimitDALFactory(db);
const apiKeyDAL = apiKeyDALFactory(db);
const alertDAL = alertDALFactory(db);
const projectDAL = projectDALFactory(db);
const projectMembershipDAL = projectMembershipDALFactory(db);
@@ -514,6 +517,10 @@ export const registerRoutes = async (
licenseService
});
const apiKeyService = apiKeyServiceFactory({ apiKeyDAL, userDAL });
const alertService = alertServiceFactory({
alertDAL,
permissionService
});
const secretScanningQueue = secretScanningQueueFactory({
telemetryService,
@@ -643,6 +650,7 @@ export const registerRoutes = async (
licenseService,
certificateAuthorityDAL,
certificateDAL,
alertDAL,
projectUserMembershipRoleDAL,
identityProjectMembershipRoleDAL,
keyStore,
@@ -1071,6 +1079,7 @@ export const registerRoutes = async (
orgRole: orgRoleService,
oidc: oidcService,
apiKey: apiKeyService,
alert: alertService,
authToken: tokenService,
superAdmin: superAdminService,
project: projectService,
@@ -0,0 +1,191 @@
import { z } from "zod";
import { AlertsSchema } from "@app/db/schemas";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
export const registerAlertRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
url: "/",
config: {
rateLimit: writeLimit
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
description: "Create alert",
body: z.object({
projectId: z.string().trim(),
name: z.string().trim(),
alertBeforeDays: z.number(),
emails: z.array(z.string())
}),
response: {
200: AlertsSchema
}
},
handler: async (req) => {
const alert = await server.services.alert.createAlert({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body
});
// TODO: audit logging
// await server.services.auditLog.createAuditLog({
// ...req.auditLogInfo,
// projectId: ca.projectId,
// event: {
// type: EventType.REVOKE_CERT,
// metadata: {
// certId: cert.id,
// cn: cert.commonName,
// serialNumber: cert.serialNumber
// }
// }
// });
return alert;
}
});
server.route({
method: "GET",
url: "/:alertId",
config: {
rateLimit: readLimit
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
description: "Get alert",
params: z.object({
alertId: z.string().trim()
}),
response: {
200: AlertsSchema
}
},
handler: async (req) => {
const alert = await server.services.alert.getAlertById({
alertId: req.params.alertId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId
});
// TODO: audit logging
// await server.services.auditLog.createAuditLog({
// ...req.auditLogInfo,
// projectId: ca.projectId,
// event: {
// type: EventType.GET_CA,
// metadata: {
// caId: ca.id,
// dn: ca.dn
// }
// }
// });
return alert;
}
});
server.route({
method: "PATCH",
url: "/:alertId",
config: {
rateLimit: readLimit
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
description: "Update alert",
params: z.object({
alertId: z.string().trim()
}),
body: z.object({
name: z.string().trim().optional(),
alertBeforeDays: z.number().optional(),
emails: z.array(z.string()).optional()
}),
response: {
200: AlertsSchema
}
},
handler: async (req) => {
const alert = await server.services.alert.updateAlert({
alertId: req.params.alertId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body
});
// TODO: audit logging
// await server.services.auditLog.createAuditLog({
// ...req.auditLogInfo,
// projectId: ca.projectId,
// event: {
// type: EventType.GET_CA,
// metadata: {
// caId: ca.id,
// dn: ca.dn
// }
// }
// });
return alert;
}
});
server.route({
method: "DELETE",
url: "/:alertId",
config: {
rateLimit: writeLimit
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
description: "Delete alert",
params: z.object({
alertId: z.string().trim()
}),
response: {
200: AlertsSchema
}
},
handler: async (req) => {
const alert = await server.services.alert.deleteAlert({
alertId: req.params.alertId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId
});
// TODO: audit logging
// await server.services.auditLog.createAuditLog({
// ...req.auditLogInfo,
// projectId: ca.projectId,
// event: {
// type: EventType.DELETE_CERT,
// metadata: {
// certId: deletedCert.id,
// cn: deletedCert.commonName,
// serialNumber: deletedCert.serialNumber
// }
// }
// });
return alert;
}
});
};
+2
View File
@@ -1,4 +1,5 @@
import { registerAdminRouter } from "./admin-router";
import { registerAlertRouter } from "./alert-router";
import { registerAuthRoutes } from "./auth-router";
import { registerProjectBotRouter } from "./bot-router";
import { registerCaRouter } from "./certificate-authority-router";
@@ -48,6 +49,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
},
{ prefix: "/auth" }
);
await server.register(registerAlertRouter, { prefix: "/alerts" });
await server.register(registerPasswordRouter, { prefix: "/password" });
await server.register(registerOrgRouter, { prefix: "/organization" });
await server.register(registerAdminRouter, { prefix: "/admin" });
+31 -1
View File
@@ -1,7 +1,7 @@
import slugify from "@sindresorhus/slugify";
import { z } from "zod";
import { CertificateAuthoritiesSchema, CertificatesSchema, ProjectKeysSchema } from "@app/db/schemas";
import { AlertsSchema, CertificateAuthoritiesSchema, CertificatesSchema, ProjectKeysSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { PROJECTS } from "@app/lib/api-docs";
import { creationLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -392,4 +392,34 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
return { certificates, totalCount };
}
});
server.route({
method: "GET",
url: "/:projectId/alerts",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
projectId: z.string().trim()
}),
response: {
200: z.object({
alerts: z.array(AlertsSchema)
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { alerts } = await server.services.project.listProjectAlerts({
projectId: req.params.projectId,
actorId: req.permission.id,
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type
});
return { alerts };
}
});
};
+12
View File
@@ -0,0 +1,12 @@
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex";
export type TAlertDALFactory = ReturnType<typeof alertDALFactory>;
export const alertDALFactory = (db: TDbClient) => {
const alertOrm = ormify(db, TableName.Alert);
return {
...alertOrm
};
};
+117
View File
@@ -0,0 +1,117 @@
import { ForbiddenError } from "@casl/ability";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { NotFoundError } from "@app/lib/errors";
import { TAlertDALFactory } from "./alert-dal";
import { TCreateAlertDTO, TDeleteAlertDTO, TGetAlertByIdDTO, TUpdateAlertDTO } from "./alert-types";
type TAlertServiceFactoryDep = {
alertDAL: TAlertDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
};
export type TAlertServiceFactory = ReturnType<typeof alertServiceFactory>;
export const alertServiceFactory = ({ alertDAL, permissionService }: TAlertServiceFactoryDep) => {
const createAlert = async ({
projectId,
name,
alertBeforeDays,
emails,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TCreateAlertDTO) => {
const { permission } = await permissionService.getProjectPermission(
actor,
actorId,
projectId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
const alert = await alertDAL.create({
projectId,
name,
alertBeforeDays,
recipientEmails: emails.join(",")
});
return alert;
};
const getAlertById = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TGetAlertByIdDTO) => {
const alert = await alertDAL.findById(alertId);
if (!alert) throw new NotFoundError({ message: "Alert not found" });
const { permission } = await permissionService.getProjectPermission(
actor,
actorId,
alert.projectId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
return alert;
};
const updateAlert = async ({
alertId,
name,
alertBeforeDays,
emails,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TUpdateAlertDTO) => {
let alert = await alertDAL.findById(alertId);
if (!alert) throw new NotFoundError({ message: "Alert not found" });
const { permission } = await permissionService.getProjectPermission(
actor,
actorId,
alert.projectId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
alert = await alertDAL.updateById(alertId, {
name,
alertBeforeDays,
recipientEmails: emails ? emails.join(",") : undefined
});
return alert;
};
const deleteAlert = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteAlertDTO) => {
let alert = await alertDAL.findById(alertId);
if (!alert) throw new NotFoundError({ message: "Alert not found" });
const { permission } = await permissionService.getProjectPermission(
actor,
actorId,
alert.projectId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
alert = await alertDAL.deleteById(alertId);
return alert;
};
return {
createAlert,
getAlertById,
updateAlert,
deleteAlert
};
};
+22
View File
@@ -0,0 +1,22 @@
import { TProjectPermission } from "@app/lib/types";
export type TCreateAlertDTO = {
name: string;
alertBeforeDays: number;
emails: string[];
} & TProjectPermission;
export type TGetAlertByIdDTO = {
alertId: string;
} & Omit<TProjectPermission, "projectId">;
export type TUpdateAlertDTO = {
alertId: string;
name?: string;
alertBeforeDays?: number;
emails?: string[];
} & Omit<TProjectPermission, "projectId">;
export type TDeleteAlertDTO = {
alertId: string;
} & Omit<TProjectPermission, "projectId">;
@@ -13,6 +13,7 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { TProjectPermission } from "@app/lib/types";
import { TAlertDALFactory } from "../alert/alert-dal";
import { ActorType } from "../auth/auth-type";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
@@ -37,6 +38,7 @@ import {
TDeleteProjectDTO,
TGetProjectDTO,
TGetProjectKmsKey,
TListProjectAlertsDTO,
TListProjectCasDTO,
TListProjectCertsDTO,
TLoadProjectKmsBackupDTO,
@@ -70,6 +72,7 @@ type TProjectServiceFactoryDep = {
projectUserMembershipRoleDAL: Pick<TProjectUserMembershipRoleDALFactory, "create">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "find">;
certificateDAL: Pick<TCertificateDALFactory, "find" | "countCertificatesInProject">;
alertDAL: Pick<TAlertDALFactory, "find">;
permissionService: TPermissionServiceFactory;
orgService: Pick<TOrgServiceFactory, "addGhostUser">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
@@ -107,6 +110,7 @@ export const projectServiceFactory = ({
identityProjectMembershipRoleDAL,
certificateAuthorityDAL,
certificateDAL,
alertDAL,
keyStore,
kmsService,
projectBotDAL
@@ -676,6 +680,33 @@ export const projectServiceFactory = ({
};
};
/**
* Return list of alerts configured for project
*/
const listProjectAlerts = async ({
projectId,
actor,
actorId,
actorAuthMethod,
actorOrgId
}: TListProjectAlertsDTO) => {
const { permission } = await permissionService.getProjectPermission(
actor,
actorId,
projectId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
const alerts = await alertDAL.find({ projectId });
return {
alerts
};
};
const updateProjectKmsKey = async ({
projectId,
kms,
@@ -794,6 +825,7 @@ export const projectServiceFactory = ({
upgradeProject,
listProjectCas,
listProjectCertificates,
listProjectAlerts,
updateVersionLimit,
updateAuditLogsRetention,
updateProjectKmsKey,
@@ -106,6 +106,8 @@ export type TListProjectCertsDTO = {
commonName?: string;
} & Omit<TProjectPermission, "projectId">;
export type TListProjectAlertsDTO = TProjectPermission;
export type TUpdateProjectKmsDTO = {
kms: { type: KmsType.Internal } | { type: KmsType.External; kmsId: string };
} & TProjectPermission;