feat(native-integrations): microsoft teams

This commit is contained in:
Daniel Hougaard
2025-04-25 04:35:40 +04:00
parent d7af9e84be
commit b5d229a7c5
71 changed files with 5648 additions and 999 deletions
@@ -0,0 +1,442 @@
/* eslint-disable class-methods-use-this */
import axios from "axios";
import { TeamsActivityHandler, TurnContext } from "botbuilder";
import { z } from "zod";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { TNotification, TriggerFeature } from "@app/lib/workflow-integrations/types";
import { TWorkflowIntegrationDALFactory } from "../workflow-integration/workflow-integration-dal";
import { WorkflowIntegrationStatus } from "../workflow-integration/workflow-integration-types";
import { TMicrosoftTeamsIntegrationDALFactory } from "./microsoft-teams-integration-dal";
export const getMicrosoftTeamsAccessToken = async ({
tenantId,
clientId,
clientSecret,
getBotFrameworkToken = false
}: {
tenantId: string;
clientId: string;
clientSecret: string;
getBotFrameworkToken?: boolean;
}) => {
const details = getBotFrameworkToken
? {
uri: "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
scope: "https://api.botframework.com/.default"
}
: {
uri: `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
scope: "https://graph.microsoft.com/.default"
};
const tokenResponse = await axios.post<{ access_token: string }>(
details.uri,
new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
scope: details.scope,
grant_type: "client_credentials"
})
);
return tokenResponse.data.access_token;
};
export const isBotInstalledInTenant = async ({
tenantId,
botAppId,
botAppPassword,
botId
}: {
tenantId: string;
botAppId: string;
botAppPassword: string;
botId: string;
}) => {
try {
const botAccessToken = await getMicrosoftTeamsAccessToken({
tenantId,
clientId: botAppId.toString(),
clientSecret: botAppPassword.toString(),
getBotFrameworkToken: true
}).catch(() => null);
const accessToken = await getMicrosoftTeamsAccessToken({
tenantId,
clientId: botAppId.toString(),
clientSecret: botAppPassword.toString()
}).catch(() => null);
if (!botAccessToken || !accessToken) {
return {
accessToken: null,
botAccessToken: null,
installed: false,
internalId: null
} as const;
}
const appsResponse = await axios
.get<{ value: { id: string; displayName: string; distributionMethod: string; externalId: string }[] }>(
"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps",
{
headers: {
Authorization: `Bearer ${accessToken}`
}
}
)
.catch((error) => {
logger.error(error, "Error fetching installed apps");
return null;
});
if (!appsResponse) {
return {
installed: false,
internalId: null,
accessToken,
botAccessToken
} as const;
}
const botInstalledInTenant = appsResponse.data.value.find((a) => a.externalId === botId);
if (!botInstalledInTenant) {
return {
installed: false,
internalId: null,
accessToken,
botAccessToken
} as const;
}
return {
installed: true,
internalId: botInstalledInTenant.id,
accessToken,
botAccessToken
} as const;
} catch (error) {
logger.error(error, "Error fetching installed apps");
return {
installed: false,
internalId: null,
accessToken: null,
botAccessToken: null
} as const;
}
};
export const buildTeamsPayload = (notification: TNotification) => {
const appCfg = getConfig();
switch (notification.type) {
case TriggerFeature.SECRET_APPROVAL: {
const { payload } = notification;
const adaptiveCard = {
type: "AdaptiveCard",
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
version: "1.5",
body: [
{
type: "TextBlock",
text: "Secret approval request",
weight: "Bolder",
size: "Large"
},
{
type: "TextBlock",
text: `A secret approval request has been opened by ${payload.userEmail}.`,
wrap: true
},
{
type: "FactSet",
facts: [
{
title: "Environment",
value: payload.environment
},
{
title: "Secret path",
value: payload.secretPath || "/"
},
{
title: `Secret Key${payload.secretKeys.length > 1 ? "s" : ""}`,
value: payload.secretKeys.join(", ")
}
]
}
],
actions: [
{
type: "Action.OpenUrl",
title: "View request in Infisical",
url: `${appCfg.SITE_URL}/secret-manager/${payload.projectId}/approval?requestId=${payload.requestId}`
}
]
};
return {
adaptiveCard
};
}
case TriggerFeature.ACCESS_REQUEST: {
const { payload } = notification;
const adaptiveCard = {
type: "AdaptiveCard",
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
version: "1.5",
body: [
{
type: "TextBlock",
text: "New access approval request pending for review",
weight: "Bolder",
size: "Large"
},
{
type: "TextBlock",
text: `${payload.requesterFullName} (${payload.requesterEmail}) has requested ${
payload.isTemporary ? "temporary" : "permanent"
} access to path '${payload.secretPath}' in the ${payload.environment} environment of ${
payload.projectName
} project.`,
wrap: true
},
{
type: "TextBlock",
text: `The following permissions are requested: ${payload.permissions.join(", ")}`,
wrap: true
},
payload.note
? {
type: "TextBlock",
text: `**User Note**: ${payload.note}`,
wrap: true
}
: null
].filter(Boolean),
actions: [
{
type: "Action.OpenUrl",
title: "View request in Infisical",
url: payload.approvalUrl
}
]
};
return {
adaptiveCard
};
}
default: {
throw new BadRequestError({
message: "Teams notification type not supported."
});
}
}
};
export class TeamsBot extends TeamsActivityHandler {
private botAppId: string;
private botAppPassword: string;
private workflowIntegrationDAL: Pick<TWorkflowIntegrationDALFactory, "update">;
private microsoftTeamsIntegrationDAL: Pick<TMicrosoftTeamsIntegrationDALFactory, "findOne">;
constructor({
botAppId,
botAppPassword,
workflowIntegrationDAL,
microsoftTeamsIntegrationDAL
}: {
botAppId: string;
botAppPassword: string;
workflowIntegrationDAL: Pick<TWorkflowIntegrationDALFactory, "update">;
microsoftTeamsIntegrationDAL: Pick<TMicrosoftTeamsIntegrationDALFactory, "findOne">;
}) {
super();
this.botAppId = botAppId;
this.botAppPassword = botAppPassword;
this.workflowIntegrationDAL = workflowIntegrationDAL;
this.microsoftTeamsIntegrationDAL = microsoftTeamsIntegrationDAL;
// We know when a bot is added, but we can't know when it's fully removed from the tenant.
this.onTeamsMembersAddedEvent(async (membersAdded, _, context) => {
const botWasAdded = membersAdded.some((member) => member.id === context.activity.recipient.id);
if (botWasAdded && context.activity.conversation.tenantId) {
const microsoftTeamIntegration = await this.microsoftTeamsIntegrationDAL.findOne({
tenantId: context.activity.conversation.tenantId
});
await this.workflowIntegrationDAL
.update(
{
id: microsoftTeamIntegration.id,
status: WorkflowIntegrationStatus.PENDING
},
{
status: WorkflowIntegrationStatus.INSTALLED
}
)
.catch((error) => {
logger.error(error, "Microsoft Teams Workflow Integration: Failed to update workflow integration");
});
// This is required in order for the bot to send proactive messages, which is required for the bot to pass the bot release validation step.
await context.sendActivity(
"👋 Thanks for installing the Infisical app! You can now use the bot to send notifications to your selected teams."
);
}
});
}
async run(context: TurnContext) {
console.log("Running Microsoft Teams bot", {
context
});
await super.run(context);
}
async sendMessageToChannel(tenantId: string, channelId: string, teamId: string, notification: TNotification) {
const { adaptiveCard } = buildTeamsPayload(notification);
const botToken = await getMicrosoftTeamsAccessToken({
tenantId,
clientId: this.botAppId,
clientSecret: this.botAppPassword,
getBotFrameworkToken: true
});
const adaptiveCardActivity = {
type: "message",
attachments: [
{
contentType: "application/vnd.microsoft.card.adaptive",
content: adaptiveCard
}
],
conversation: {
id: channelId,
isGroup: true
},
channelData: {
channel: {
id: channelId
},
team: {
id: teamId
}
}
};
await axios.post(
`https://smba.trafficmanager.net/amer/v3/conversations/${channelId}/activities`,
adaptiveCardActivity,
{
headers: {
Authorization: `Bearer ${botToken}`,
"Content-Type": "application/json"
}
}
);
}
// todo: filter out teams that the bot is not a member of
async getTeamsAndChannels(tenantId: string, internalAppId: string) {
try {
const token = await getMicrosoftTeamsAccessToken({
tenantId,
clientId: this.botAppId,
clientSecret: this.botAppPassword
});
const teamsResponse = await axios
.get<{ value: { displayName: string; id: string }[] }>(`https://graph.microsoft.com/v1.0/teams`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.catch((error) => {
logger.error(error, "Microsoft Teams Workflow Integration: Failed to fetch teams");
throw error;
});
const teams = teamsResponse.data.value;
const result = [];
for await (const team of teams) {
try {
// Get installed apps for this team
const installedAppsResponse = await axios.get<{ value: { teamsAppDefinition: { teamsAppId: string } }[] }>(
`https://graph.microsoft.com/v1.0/teams/${team.id}/installedApps?$expand=teamsAppDefinition`,
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
if (!installedAppsResponse.data.value.some((app) => app.teamsAppDefinition.teamsAppId === internalAppId)) {
// eslint-disable-next-line no-continue
continue;
}
} catch (error) {
// eslint-disable-next-line no-continue
continue; // skip this team if we can't determine if the bot is installed
}
const channelsResponse = await axios
.get<{ value: { displayName: string; id: string }[] }>(
`https://graph.microsoft.com/v1.0/teams/${team.id}/channels`,
{
headers: {
Authorization: `Bearer ${token}`
}
}
)
.catch((error) => {
logger.error(error, "Microsoft Teams Workflow Integration: Failed to fetch channels");
throw error;
});
const channels = channelsResponse.data.value.map((channel) => ({
channelName: channel.displayName,
channelId: channel.id
}));
result.push({
teamId: team.id,
teamName: team.displayName,
channels
});
}
return result;
} catch (error) {
logger.error(error, "Microsoft Teams Workflow Integration: Error fetching teams and channels");
throw error;
}
}
}
export const MicrosoftTeamsChannelsSchema = z
.object({
teamId: z.string(),
channelIds: z.array(z.string()).min(1)
})
.optional()
.refine((data) => data === undefined || data?.channelIds.length <= 5, {
message: "You can only select up to 5 microsoft teams channels"
});
@@ -0,0 +1,62 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName, TMicrosoftTeamsIntegrations, TWorkflowIntegrations } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TMicrosoftTeamsIntegrationDALFactory = ReturnType<typeof microsoftTeamsIntegrationDALFactory>;
export const microsoftTeamsIntegrationDALFactory = (db: TDbClient) => {
const microsoftTeamsIntegrationOrm = ormify(db, TableName.MicrosoftTeamsIntegrations);
const findByIdWithWorkflowIntegrationDetails = async (id: string, tx?: Knex) => {
try {
return await (tx || db.replicaNode())(TableName.MicrosoftTeamsIntegrations)
.join(
TableName.WorkflowIntegrations,
`${TableName.MicrosoftTeamsIntegrations}.id`,
`${TableName.WorkflowIntegrations}.id`
)
.select(selectAllTableCols(TableName.MicrosoftTeamsIntegrations))
.select(db.ref("orgId").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("description").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("integration").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("slug").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("status").withSchema(TableName.WorkflowIntegrations))
.where(`${TableName.WorkflowIntegrations}.id`, id)
.first();
} catch (error) {
throw new DatabaseError({ error, name: "Find by ID with Workflow integration details" });
}
};
const findWithWorkflowIntegrationDetails = async (
filter: Partial<TMicrosoftTeamsIntegrations> & Partial<TWorkflowIntegrations>,
tx?: Knex
) => {
try {
return await (tx || db.replicaNode())(TableName.MicrosoftTeamsIntegrations)
.join(
TableName.WorkflowIntegrations,
`${TableName.MicrosoftTeamsIntegrations}.id`,
`${TableName.WorkflowIntegrations}.id`
)
.select(selectAllTableCols(TableName.MicrosoftTeamsIntegrations))
.select(db.ref("orgId").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("description").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("integration").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("slug").withSchema(TableName.WorkflowIntegrations))
.select(db.ref("status").withSchema(TableName.WorkflowIntegrations))
.where(filter);
} catch (error) {
throw new DatabaseError({ error, name: "Find with Workflow integration details" });
}
};
return {
...microsoftTeamsIntegrationOrm,
findByIdWithWorkflowIntegrationDetails,
findWithWorkflowIntegrationDetails
};
};
@@ -0,0 +1,608 @@
import { ForbiddenError } from "@casl/ability";
import {
CloudAdapter,
ConfigurationBotFrameworkAuthentication,
ConfigurationServiceClientCredentialFactory,
Request,
Response
} from "botbuilder";
import { FastifyReply, FastifyRequest } from "fastify";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { TKmsServiceFactory } from "../kms/kms-service";
import { KmsDataKey } from "../kms/kms-types";
import { TSuperAdminDALFactory } from "../super-admin/super-admin-dal";
import { TWorkflowIntegrationDALFactory } from "../workflow-integration/workflow-integration-dal";
import { WorkflowIntegration, WorkflowIntegrationStatus } from "../workflow-integration/workflow-integration-types";
import { isBotInstalledInTenant, TeamsBot } from "./microsoft-teams-fns";
import { TMicrosoftTeamsIntegrationDALFactory } from "./microsoft-teams-integration-dal";
import {
TCheckInstallationStatusDTO,
TCreateMicrosoftTeamsIntegrationDTO,
TDeleteMicrosoftTeamsIntegrationIntegrationDTO,
TGetMicrosoftTeamsIntegrationByIdDTO,
TGetMicrosoftTeamsIntegrationByOrgDTO,
TGetTeamsDTO,
TSendNotificationDTO,
TUpdateMicrosoftTeamsIntegrationDTO
} from "./microsoft-teams-types";
function requestBodyToRecord(body: unknown): Record<string, unknown> {
// if body is null or undefined, return an empty object
if (body === null || body === undefined) {
return {};
}
// if body is not an object or is an array, return an empty object
if (typeof body !== "object" || Array.isArray(body)) {
return {};
}
// at this point, we know body is an object, so safe to cast
return body as Record<string, unknown>;
}
type TMicrosoftTeamsServiceFactoryDep = {
microsoftTeamsIntegrationDAL: Pick<
TMicrosoftTeamsIntegrationDALFactory,
| "deleteById"
| "updateById"
| "create"
| "findOne"
| "findById"
| "findByIdWithWorkflowIntegrationDetails"
| "findWithWorkflowIntegrationDetails"
>;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "encryptWithRootKey" | "decryptWithRootKey">;
workflowIntegrationDAL: Pick<
TWorkflowIntegrationDALFactory,
"transaction" | "create" | "updateById" | "deleteById" | "update" | "findOne"
>;
serverCfgDAL: Pick<TSuperAdminDALFactory, "findById">;
};
export type TMicrosoftTeamsServiceFactory = ReturnType<typeof microsoftTeamsServiceFactory>;
const ADMIN_CONFIG_DB_UUID = "00000000-0000-0000-0000-000000000000";
export const microsoftTeamsServiceFactory = ({
permissionService,
serverCfgDAL,
kmsService,
microsoftTeamsIntegrationDAL,
workflowIntegrationDAL
}: TMicrosoftTeamsServiceFactoryDep) => {
let teamsBot: TeamsBot | null = null;
let adapter: CloudAdapter | null = null;
const initializeTeamsBot = async ({ botAppId, botAppPassword }: { botAppId: string; botAppPassword: string }) => {
logger.info("Initializing Microsoft Teams bot");
teamsBot = new TeamsBot({
botAppId,
botAppPassword,
workflowIntegrationDAL,
microsoftTeamsIntegrationDAL
});
adapter = new CloudAdapter(
new ConfigurationBotFrameworkAuthentication(
{},
new ConfigurationServiceClientCredentialFactory({
MicrosoftAppId: botAppId,
MicrosoftAppPassword: botAppPassword,
MicrosoftAppType: "MultiTenant"
})
)
);
};
const start = async () => {
try {
const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);
if (
serverCfg?.encryptedMicrosoftTeamsAppId &&
serverCfg?.encryptedMicrosoftTeamsClientSecret &&
serverCfg?.encryptedMicrosoftTeamsBotId
) {
const decryptWithRoot = kmsService.decryptWithRootKey();
const decryptedAppId = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsAppId);
const decryptedAppPassword = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsClientSecret);
await initializeTeamsBot({
botAppId: decryptedAppId.toString(),
botAppPassword: decryptedAppPassword.toString()
});
}
} catch (err) {
logger.error(err, "Error initializing Microsoft Teams bot on startup");
}
};
const checkInstallationStatus = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
workflowIntegrationId
}: TCheckInstallationStatusDTO) => {
const { permission } = await permissionService.getOrgPermission(
actor,
actorId,
actorOrgId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
const microsoftTeamsIntegration =
await microsoftTeamsIntegrationDAL.findByIdWithWorkflowIntegrationDetails(workflowIntegrationId);
if (!microsoftTeamsIntegration) {
throw new NotFoundError({
message: `Microsoft Teams integration with ID ${workflowIntegrationId} not found`
});
}
const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);
if (!serverCfg) {
throw new BadRequestError({
message: "Failed to get server configuration."
});
}
if (
!serverCfg.encryptedMicrosoftTeamsAppId ||
!serverCfg.encryptedMicrosoftTeamsClientSecret ||
!serverCfg.encryptedMicrosoftTeamsBotId
) {
throw new BadRequestError({
message: "Microsoft Teams app ID, client secret, or bot ID is not set"
});
}
const decryptWithRoot = kmsService.decryptWithRootKey();
const decryptedAppId = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsAppId);
const decryptedAppPassword = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsClientSecret);
const decryptedBotId = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsBotId);
const teamsBotInfo = await isBotInstalledInTenant({
tenantId: microsoftTeamsIntegration.tenantId,
botAppId: decryptedAppId.toString(),
botAppPassword: decryptedAppPassword.toString(),
botId: decryptedBotId.toString()
});
if (!teamsBotInfo.installed) {
if (microsoftTeamsIntegration.status === WorkflowIntegrationStatus.INSTALLED) {
await workflowIntegrationDAL.updateById(microsoftTeamsIntegration.id, {
status: WorkflowIntegrationStatus.PENDING
});
}
throw new BadRequestError({
message: "Microsoft Teams bot is not installed in the configured Microsoft Teams Tenant"
});
}
if (microsoftTeamsIntegration.status !== WorkflowIntegrationStatus.INSTALLED) {
await workflowIntegrationDAL.updateById(microsoftTeamsIntegration.id, {
status: WorkflowIntegrationStatus.INSTALLED
});
}
};
const createMicrosoftTeamsIntegration = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
slug,
description,
tenantId
}: TCreateMicrosoftTeamsIntegrationDTO) => {
const { permission } = await permissionService.getOrgPermission(
actor,
actorId,
actorOrgId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Settings);
const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);
if (!serverCfg) {
throw new BadRequestError({
message: "Failed to get server configuration."
});
}
const { encryptedMicrosoftTeamsAppId, encryptedMicrosoftTeamsClientSecret, encryptedMicrosoftTeamsBotId } =
serverCfg;
if (!encryptedMicrosoftTeamsAppId || !encryptedMicrosoftTeamsClientSecret || !encryptedMicrosoftTeamsBotId) {
throw new BadRequestError({
message: "Microsoft Teams app ID, client secret, or bot ID is not set"
});
}
const integration = await workflowIntegrationDAL.transaction(async (tx) => {
const workflowIntegration = await workflowIntegrationDAL.create(
{
description,
orgId: actorOrgId,
slug,
integration: WorkflowIntegration.MICROSOFT_TEAMS,
status: WorkflowIntegrationStatus.PENDING
},
tx
);
const microsoftTeamsIntegration = await microsoftTeamsIntegrationDAL.create(
{
// @ts-expect-error id is kept as fixed because it is always equal to the workflow integration ID
id: workflowIntegration.id,
tenantId
},
tx
);
const decryptWithRoot = kmsService.decryptWithRootKey();
const botAppId = decryptWithRoot(encryptedMicrosoftTeamsAppId);
const botAppPassword = decryptWithRoot(encryptedMicrosoftTeamsClientSecret);
const botId = decryptWithRoot(encryptedMicrosoftTeamsBotId);
const teamsBotInfo = await isBotInstalledInTenant({
tenantId: microsoftTeamsIntegration.tenantId,
botAppId: botAppId.toString(),
botAppPassword: botAppPassword.toString(),
botId: botId.toString()
});
if (teamsBotInfo.installed) {
const { encryptor: orgDataKeyEncryptor } = await kmsService.createCipherPairWithDataKey({
orgId: workflowIntegration.orgId,
type: KmsDataKey.Organization
});
const { cipherTextBlob: encryptedAccessToken } = orgDataKeyEncryptor({
plainText: Buffer.from(teamsBotInfo.accessToken, "utf8")
});
const { cipherTextBlob: encryptedBotAccessToken } = orgDataKeyEncryptor({
plainText: Buffer.from(teamsBotInfo.botAccessToken, "utf8")
});
await microsoftTeamsIntegrationDAL.updateById(
microsoftTeamsIntegration.id,
{
internalTeamsAppId: teamsBotInfo.internalId,
encryptedAccessToken,
encryptedBotAccessToken
},
tx
);
await workflowIntegrationDAL.updateById(
workflowIntegration.id,
{
status: WorkflowIntegrationStatus.INSTALLED
},
tx
);
}
return {
...workflowIntegration,
status: workflowIntegration.status as WorkflowIntegrationStatus,
tenantId: microsoftTeamsIntegration.tenantId
};
});
return integration;
};
const getMicrosoftTeamsIntegrationsByOrg = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod
}: TGetMicrosoftTeamsIntegrationByOrgDTO) => {
const { permission } = await permissionService.getOrgPermission(
actor,
actorId,
actorOrgId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Settings);
const microsoftTeamsIntegrations = await microsoftTeamsIntegrationDAL.findWithWorkflowIntegrationDetails({
orgId: actorOrgId
});
return microsoftTeamsIntegrations.map((integration) => ({
...integration,
status: integration.status as WorkflowIntegrationStatus,
tenantId: integration.tenantId
}));
};
const getMicrosoftTeamsIntegrationById = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
id
}: TGetMicrosoftTeamsIntegrationByIdDTO) => {
const microsoftTeamsIntegration = await microsoftTeamsIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id);
if (!microsoftTeamsIntegration) {
throw new NotFoundError({
message: "Microsoft Teams integration not found."
});
}
const { permission } = await permissionService.getOrgPermission(
actor,
actorId,
microsoftTeamsIntegration.orgId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);
return {
...microsoftTeamsIntegration,
status: microsoftTeamsIntegration.status as WorkflowIntegrationStatus
};
};
const updateMicrosoftTeamsIntegration = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
id,
slug,
description
}: TUpdateMicrosoftTeamsIntegrationDTO) => {
const microsoftTeamsIntegration = await microsoftTeamsIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id);
if (!microsoftTeamsIntegration) {
throw new NotFoundError({
message: `Microsoft Teams integration with ID ${id} not found`
});
}
const { permission } = await permissionService.getOrgPermission(
actor,
actorId,
microsoftTeamsIntegration.orgId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
const updatedIntegration = await workflowIntegrationDAL.transaction(async (tx) => {
await workflowIntegrationDAL.updateById(
microsoftTeamsIntegration.id,
{
slug,
description
},
tx
);
const integration = await microsoftTeamsIntegrationDAL.findByIdWithWorkflowIntegrationDetails(
microsoftTeamsIntegration.id,
tx
);
if (!integration) {
throw new NotFoundError({
message: `Microsoft Teams integration with ID ${microsoftTeamsIntegration.id} not found`
});
}
return {
...integration,
status: integration.status as WorkflowIntegrationStatus
};
});
return updatedIntegration;
};
const deleteMicrosoftTeamsIntegration = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
id
}: TDeleteMicrosoftTeamsIntegrationIntegrationDTO) => {
const microsoftTeamsIntegration = await microsoftTeamsIntegrationDAL.findByIdWithWorkflowIntegrationDetails(id);
if (!microsoftTeamsIntegration) {
throw new NotFoundError({
message: `Microsoft Teams integration with ID ${id} not found`
});
}
const { permission } = await permissionService.getOrgPermission(
actor,
actorId,
microsoftTeamsIntegration.orgId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Settings);
await workflowIntegrationDAL.deleteById(id);
return {
...microsoftTeamsIntegration,
status: microsoftTeamsIntegration.status as WorkflowIntegrationStatus
};
};
const getTeams = async ({ actorId, actor, actorOrgId, actorAuthMethod, workflowIntegrationId }: TGetTeamsDTO) => {
const { permission } = await permissionService.getOrgPermission(
actor,
actorId,
actorOrgId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);
const microsoftTeamsIntegration =
await microsoftTeamsIntegrationDAL.findByIdWithWorkflowIntegrationDetails(workflowIntegrationId);
if (!microsoftTeamsIntegration) {
throw new NotFoundError({
message: `Microsoft Teams integration with ID ${workflowIntegrationId} not found`
});
}
if (!teamsBot || !adapter) {
throw new BadRequestError({
message: "Unable to get teams and channels because the Microsoft Teams bot is uninitialized"
});
}
const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);
if (!serverCfg) {
throw new BadRequestError({
message: "Failed to get server configuration."
});
}
if (
!serverCfg.encryptedMicrosoftTeamsAppId ||
!serverCfg.encryptedMicrosoftTeamsClientSecret ||
!serverCfg.encryptedMicrosoftTeamsBotId
) {
throw new BadRequestError({
message: "Microsoft Teams app ID, client secret, or bot ID is not set"
});
}
const decryptWithRoot = kmsService.decryptWithRootKey();
const decryptedAppId = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsAppId);
const decryptedAppPassword = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsClientSecret);
const decryptedBotId = decryptWithRoot(serverCfg.encryptedMicrosoftTeamsBotId);
const { installed, internalId } = await isBotInstalledInTenant({
tenantId: microsoftTeamsIntegration.tenantId,
botAppId: decryptedAppId.toString(),
botAppPassword: decryptedAppPassword.toString(),
botId: decryptedBotId.toString()
});
if (!installed) {
throw new BadRequestError({
message: "Microsoft Teams bot is not installed in the configured Microsoft Teams Tenant"
});
}
const teams = await teamsBot.getTeamsAndChannels(microsoftTeamsIntegration.tenantId, internalId);
return teams;
};
const handleMessageEndpoint = async (req: FastifyRequest, res: FastifyReply) => {
if (!teamsBot || !adapter) {
throw new BadRequestError({
message: "Unable to handle message endpoint because the Microsoft Teams bot is uninitialized"
});
}
// We need to manually build a Response object because the BotFrameworkAdapter expects a Response object. We are using FastifyReply as the underlying socket.
const response: Response = {
socket: res.raw.socket,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
end(...args: any[]): unknown {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
res.raw.end(...args);
return this;
},
header(name: string, value: unknown): unknown {
res.raw.setHeader(name, value as string);
return this;
},
send(...args: unknown[]): unknown {
// For the first argument, which is typically the body
if (args.length > 0) {
const body = args[0];
if (typeof body === "string" || Buffer.isBuffer(body)) {
res.raw.write(body);
} else if (body !== null && body !== undefined) {
const json = JSON.stringify(body);
if (!res.raw.headersSent && !res.raw.getHeader("content-type")) {
res.raw.setHeader("content-type", "application/json");
}
res.raw.write(json);
}
}
const lastArg = args[args.length - 1];
if (typeof lastArg === "function") {
lastArg();
}
return this;
},
status(code: number): unknown {
res.raw.statusCode = code;
return this;
}
};
const request: Request = {
body: requestBodyToRecord(req.body),
headers: req.headers,
method: req.method
};
await adapter.process(request, response, async (context) => {
await teamsBot?.run(context);
});
};
const sendNotification = async ({ tenantId, target, notification }: TSendNotificationDTO) => {
if (!teamsBot || !adapter) {
throw new BadRequestError({
message: "Unable to send notification because the Microsoft Teams bot is uninitialized"
});
}
for await (const channelId of target.channelIds) {
await teamsBot.sendMessageToChannel(tenantId, channelId, target.teamId, notification);
}
};
return {
getMicrosoftTeamsIntegrationsByOrg,
getMicrosoftTeamsIntegrationById,
updateMicrosoftTeamsIntegration,
deleteMicrosoftTeamsIntegration,
createMicrosoftTeamsIntegration,
initializeTeamsBot,
getTeams,
handleMessageEndpoint,
start,
sendNotification,
checkInstallationStatus
};
};
@@ -0,0 +1,36 @@
import { TOrgPermission } from "@app/lib/types";
import { TNotification } from "@app/lib/workflow-integrations/types";
export type TGetMicrosoftTeamsIntegrationByOrgDTO = Omit<TOrgPermission, "orgId">;
export type TCreateMicrosoftTeamsIntegrationDTO = Omit<TOrgPermission, "orgId"> & {
slug: string;
description?: string;
tenantId: string;
};
export type TCheckInstallationStatusDTO = { workflowIntegrationId: string } & Omit<TOrgPermission, "orgId">;
export type TGetMicrosoftTeamsIntegrationByIdDTO = { id: string } & Omit<TOrgPermission, "orgId">;
export type TUpdateMicrosoftTeamsIntegrationDTO = { id: string; slug?: string; description?: string } & Omit<
TOrgPermission,
"orgId"
>;
export type TGetTeamsDTO = Omit<TOrgPermission, "orgId"> & {
workflowIntegrationId: string;
};
export type TDeleteMicrosoftTeamsIntegrationIntegrationDTO = {
id: string;
} & Omit<TOrgPermission, "orgId">;
export type TSendNotificationDTO = {
tenantId: string;
target: {
teamId: string;
channelIds: string[];
};
notification: TNotification;
};
@@ -0,0 +1,28 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TProjectMicrosoftTeamsConfigDALFactory = ReturnType<typeof projectMicrosoftTeamsConfigDALFactory>;
export const projectMicrosoftTeamsConfigDALFactory = (db: TDbClient) => {
const projectMicrosoftTeamsConfigOrm = ormify(db, TableName.ProjectMicrosoftTeamsConfigs);
const getIntegrationDetailsByProject = (projectId: string, tx?: Knex) => {
return (tx || db.replicaNode())(TableName.ProjectMicrosoftTeamsConfigs)
.join(
TableName.MicrosoftTeamsIntegrations,
`${TableName.ProjectMicrosoftTeamsConfigs}.microsoftTeamsIntegrationId`,
`${TableName.MicrosoftTeamsIntegrations}.id`
)
.where("projectId", "=", projectId)
.select(
selectAllTableCols(TableName.ProjectMicrosoftTeamsConfigs),
selectAllTableCols(TableName.MicrosoftTeamsIntegrations)
)
.first();
};
return { ...projectMicrosoftTeamsConfigOrm, getIntegrationDetailsByProject };
};
+251 -56
View File
@@ -43,6 +43,9 @@ import { TIdentityOrgDALFactory } from "../identity/identity-org-dal";
import { TIdentityProjectDALFactory } from "../identity-project/identity-project-dal";
import { TIdentityProjectMembershipRoleDALFactory } from "../identity-project/identity-project-membership-role-dal";
import { TKmsServiceFactory } from "../kms/kms-service";
import { MicrosoftTeamsChannelsSchema } from "../microsoft-teams/microsoft-teams-fns";
import { TMicrosoftTeamsIntegrationDALFactory } from "../microsoft-teams/microsoft-teams-integration-dal";
import { TProjectMicrosoftTeamsConfigDALFactory } from "../microsoft-teams/project-microsoft-teams-config-dal";
import { TOrgDALFactory } from "../org/org-dal";
import { TOrgServiceFactory } from "../org/org-service";
import { TPkiAlertDALFactory } from "../pki-alert/pki-alert-dal";
@@ -60,9 +63,11 @@ import { fnDeleteProjectSecretReminders } from "../secret/secret-fns";
import { ROOT_FOLDER_NAME, TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TProjectSlackConfigDALFactory } from "../slack/project-slack-config-dal";
import { validateSlackChannelsField } from "../slack/slack-auth-validators";
import { TSlackIntegrationDALFactory } from "../slack/slack-integration-dal";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDALFactory } from "../user/user-dal";
import { WorkflowIntegration } from "../workflow-integration/workflow-integration-types";
import { TProjectDALFactory } from "./project-dal";
import { assignWorkspaceKeysToMembers, bootstrapSshProject, createProjectKey } from "./project-fns";
import { TProjectQueueFactory } from "./project-queue";
@@ -70,9 +75,10 @@ import { TProjectSshConfigDALFactory } from "./project-ssh-config-dal";
import {
TCreateProjectDTO,
TDeleteProjectDTO,
TDeleteProjectWorkflowIntegration,
TGetProjectDTO,
TGetProjectKmsKey,
TGetProjectSlackConfig,
TGetProjectWorkflowIntegrationConfig,
TListProjectAlertsDTO,
TListProjectCasDTO,
TListProjectCertificateTemplatesDTO,
@@ -91,8 +97,8 @@ import {
TUpdateProjectDTO,
TUpdateProjectKmsDTO,
TUpdateProjectNameDTO,
TUpdateProjectSlackConfig,
TUpdateProjectVersionLimitDTO,
TUpdateProjectWorkflowIntegration,
TUpgradeProjectDTO
} from "./project-types";
@@ -121,8 +127,19 @@ type TProjectServiceFactoryDep = {
"create" | "findProjectGhostUser" | "findOne" | "delete" | "findAllProjectMembers"
>;
groupProjectDAL: Pick<TGroupProjectDALFactory, "delete">;
projectSlackConfigDAL: Pick<TProjectSlackConfigDALFactory, "findOne" | "transaction" | "updateById" | "create">;
projectSlackConfigDAL: Pick<
TProjectSlackConfigDALFactory,
"findOne" | "transaction" | "updateById" | "create" | "delete"
>;
projectMicrosoftTeamsConfigDAL: Pick<
TProjectMicrosoftTeamsConfigDALFactory,
"findOne" | "transaction" | "updateById" | "create" | "delete"
>;
slackIntegrationDAL: Pick<TSlackIntegrationDALFactory, "findById" | "findByIdWithWorkflowIntegrationDetails">;
microsoftTeamsIntegrationDAL: Pick<
TMicrosoftTeamsIntegrationDALFactory,
"findById" | "findByIdWithWorkflowIntegrationDetails"
>;
projectUserMembershipRoleDAL: Pick<TProjectUserMembershipRoleDALFactory, "create">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "find">;
certificateDAL: Pick<TCertificateDALFactory, "find" | "countCertificatesInProject">;
@@ -195,7 +212,9 @@ export const projectServiceFactory = ({
kmsService,
projectBotDAL,
projectSlackConfigDAL,
projectMicrosoftTeamsConfigDAL,
slackIntegrationDAL,
microsoftTeamsIntegrationDAL,
projectTemplateService,
groupProjectDAL,
smtpService
@@ -1327,13 +1346,14 @@ export const projectServiceFactory = ({
return { secretManagerKmsKey: kmsKey };
};
const getProjectSlackConfig = async ({
const getProjectWorkflowIntegrationConfig = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
projectId
}: TGetProjectSlackConfig) => {
projectId,
integration
}: TGetProjectWorkflowIntegrationConfig) => {
const project = await projectDAL.findById(projectId);
if (!project) {
throw new NotFoundError({
@@ -1352,23 +1372,56 @@ export const projectServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Settings);
return projectSlackConfigDAL.findOne({
projectId: project.id
});
if (integration === WorkflowIntegration.SLACK) {
const config = await projectSlackConfigDAL.findOne({
projectId: project.id
});
if (!config) {
throw new NotFoundError({
message: `Workflow integration config for project '${projectId}' and integration '${integration}' not found`
});
}
return {
...config,
integration,
integrationId: config.slackIntegrationId
};
}
if (integration === WorkflowIntegration.MICROSOFT_TEAMS) {
const config = await projectMicrosoftTeamsConfigDAL.findOne({
projectId: project.id
});
if (!config) {
throw new NotFoundError({
message: `Workflow integration config for project '${projectId}' and integration '${integration}' not found`
});
}
return {
...config,
integration,
integrationId: config.microsoftTeamsIntegrationId
};
}
};
const updateProjectSlackConfig = async ({
const updateProjectWorkflowIntegration = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
projectId,
slackIntegrationId,
integration,
integrationId,
isAccessRequestNotificationEnabled,
accessRequestChannels,
isSecretRequestNotificationEnabled,
secretRequestChannels
}: TUpdateProjectSlackConfig) => {
}: TUpdateProjectWorkflowIntegration) => {
const project = await projectDAL.findById(projectId);
if (!project) {
throw new NotFoundError({
@@ -1376,17 +1429,177 @@ export const projectServiceFactory = ({
});
}
const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(slackIntegrationId);
if (integration === WorkflowIntegration.SLACK) {
const sanitizedAccessRequestChannels = validateSlackChannelsField.parse(accessRequestChannels);
const sanitizedSecretRequestChannels = validateSlackChannelsField.parse(secretRequestChannels);
if (!slackIntegration) {
throw new NotFoundError({
message: `Slack integration with ID '${slackIntegrationId}' not found`
const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(integrationId);
if (!slackIntegration) {
throw new NotFoundError({
message: `Slack integration with ID '${integrationId}' not found`
});
}
if (slackIntegration.orgId !== actorOrgId) {
throw new ForbiddenRequestError({
message: "Selected slack integration is not in the same organization"
});
}
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.Any
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
if (slackIntegration.orgId !== project.orgId) {
throw new ForbiddenRequestError({
message: "Selected slack integration is not in the same organization"
});
}
const updatedWorkflowIntegration = await projectSlackConfigDAL.transaction(async (tx) => {
const slackConfig = await projectSlackConfigDAL.findOne(
{
projectId
},
tx
);
if (slackConfig) {
return projectSlackConfigDAL.updateById(
slackConfig.id,
{
slackIntegrationId: integrationId,
isAccessRequestNotificationEnabled,
accessRequestChannels: sanitizedAccessRequestChannels,
isSecretRequestNotificationEnabled,
secretRequestChannels: sanitizedSecretRequestChannels
},
tx
);
}
return projectSlackConfigDAL.create(
{
projectId,
slackIntegrationId: integrationId,
isAccessRequestNotificationEnabled,
accessRequestChannels: sanitizedAccessRequestChannels,
isSecretRequestNotificationEnabled,
secretRequestChannels: sanitizedSecretRequestChannels
},
tx
);
});
return {
...updatedWorkflowIntegration,
accessRequestChannels: sanitizedAccessRequestChannels,
secretRequestChannels: sanitizedSecretRequestChannels,
integrationId: slackIntegration.id,
integration: WorkflowIntegration.SLACK
} as const;
}
if (integration === WorkflowIntegration.MICROSOFT_TEAMS) {
if (isAccessRequestNotificationEnabled && !accessRequestChannels) {
throw new BadRequestError({
message: "Access request channels are required when access request notifications are enabled"
});
}
if (isSecretRequestNotificationEnabled && !secretRequestChannels) {
throw new BadRequestError({
message: "Secret request channels are required when secret request notifications are enabled"
});
}
if (!secretRequestChannels && !accessRequestChannels) {
throw new BadRequestError({
message: "At least one of access request channels or secret request channels is required"
});
}
const sanitizedAccessRequestChannels = MicrosoftTeamsChannelsSchema.parse(accessRequestChannels);
const sanitizedSecretRequestChannels = MicrosoftTeamsChannelsSchema.parse(secretRequestChannels);
const microsoftTeamsIntegration =
await microsoftTeamsIntegrationDAL.findByIdWithWorkflowIntegrationDetails(integrationId);
if (!microsoftTeamsIntegration) {
throw new NotFoundError({
message: `Microsoft Teams integration with ID '${integrationId}' not found`
});
}
const updatedWorkflowIntegration = await projectMicrosoftTeamsConfigDAL.transaction(async (tx) => {
const microsoftTeamsConfig = await projectMicrosoftTeamsConfigDAL.findOne(
{
projectId
},
tx
);
if (microsoftTeamsConfig) {
return projectMicrosoftTeamsConfigDAL.updateById(
microsoftTeamsConfig.id,
{
microsoftTeamsIntegrationId: integrationId,
isAccessRequestNotificationEnabled,
accessRequestChannels: sanitizedAccessRequestChannels || {},
isSecretRequestNotificationEnabled,
secretRequestChannels: sanitizedSecretRequestChannels || {}
},
tx
);
}
return projectMicrosoftTeamsConfigDAL.create(
{
projectId,
microsoftTeamsIntegrationId: integrationId,
isAccessRequestNotificationEnabled,
accessRequestChannels: sanitizedAccessRequestChannels || {},
isSecretRequestNotificationEnabled,
secretRequestChannels: sanitizedSecretRequestChannels || {}
},
tx
);
});
return {
...updatedWorkflowIntegration,
accessRequestChannels: sanitizedAccessRequestChannels,
secretRequestChannels: sanitizedSecretRequestChannels,
integrationId: microsoftTeamsIntegration.id,
integration: WorkflowIntegration.MICROSOFT_TEAMS
} as const;
}
if (slackIntegration.orgId !== actorOrgId) {
throw new ForbiddenRequestError({
message: "Selected slack integration is not in the same organization"
throw new BadRequestError({
message: `Integration type '${integration as string}' not supported`
});
};
const deleteProjectWorkflowIntegration = async ({
actorId,
actor,
actorOrgId,
actorAuthMethod,
projectId,
integrationId,
integration
}: TDeleteProjectWorkflowIntegration) => {
const project = await projectDAL.findById(projectId);
if (!project) {
throw new NotFoundError({
message: `Project with ID '${projectId}' not found`
});
}
@@ -1399,47 +1612,28 @@ export const projectServiceFactory = ({
actionProjectType: ActionProjectType.Any
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.Settings);
if (slackIntegration.orgId !== project.orgId) {
throw new ForbiddenRequestError({
message: "Selected slack integration is not in the same organization"
if (integration === WorkflowIntegration.SLACK) {
const [deletedIntegration] = await projectSlackConfigDAL.delete({
projectId,
slackIntegrationId: integrationId
});
return deletedIntegration;
}
return projectSlackConfigDAL.transaction(async (tx) => {
const slackConfig = await projectSlackConfigDAL.findOne(
{
projectId
},
tx
);
if (integration === WorkflowIntegration.MICROSOFT_TEAMS) {
const [deletedIntegration] = await projectMicrosoftTeamsConfigDAL.delete({
projectId,
microsoftTeamsIntegrationId: integrationId
});
if (slackConfig) {
return projectSlackConfigDAL.updateById(
slackConfig.id,
{
slackIntegrationId,
isAccessRequestNotificationEnabled,
accessRequestChannels,
isSecretRequestNotificationEnabled,
secretRequestChannels
},
tx
);
}
return deletedIntegration;
}
return projectSlackConfigDAL.create(
{
projectId,
slackIntegrationId,
isAccessRequestNotificationEnabled,
accessRequestChannels,
isSecretRequestNotificationEnabled,
secretRequestChannels
},
tx
);
throw new BadRequestError({
message: `Integration with ID '${integrationId}' not found`
});
};
@@ -1548,8 +1742,9 @@ export const projectServiceFactory = ({
getProjectKmsBackup,
loadProjectKmsBackup,
getProjectKmsKeys,
getProjectSlackConfig,
updateProjectSlackConfig,
getProjectWorkflowIntegrationConfig,
updateProjectWorkflowIntegration,
deleteProjectWorkflowIntegration,
requestProjectAccess,
searchProjects
};
+14 -5
View File
@@ -8,6 +8,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectSshConfigDALFactory } from "@app/services/project/project-ssh-config-dal";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
import { WorkflowIntegration } from "../workflow-integration/workflow-integration-types";
enum KmsType {
External = "external",
@@ -159,14 +160,22 @@ export type TListProjectSshCertificatesDTO = {
limit: number;
} & TProjectPermission;
export type TGetProjectSlackConfig = TProjectPermission;
export type TGetProjectWorkflowIntegrationConfig = TProjectPermission & {
integration: WorkflowIntegration;
};
export type TUpdateProjectSlackConfig = {
slackIntegrationId: string;
export type TUpdateProjectWorkflowIntegration = {
integrationId: string;
integration: WorkflowIntegration;
isAccessRequestNotificationEnabled: boolean;
accessRequestChannels: string;
accessRequestChannels?: string | { teamId: string; channelIds: string[] };
isSecretRequestNotificationEnabled: boolean;
secretRequestChannels: string;
secretRequestChannels?: string | { teamId: string; channelIds: string[] };
} & TProjectPermission;
export type TDeleteProjectWorkflowIntegration = {
integrationId: string;
integration: WorkflowIntegration;
} & TProjectPermission;
export type TBootstrapSshProjectDTO = {
+14 -40
View File
@@ -3,12 +3,13 @@ import { WebClient } from "@slack/web-api";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { TNotification, TriggerFeature } from "@app/lib/workflow-integrations/types";
import { TKmsServiceFactory } from "../kms/kms-service";
import { KmsDataKey } from "../kms/kms-types";
import { TProjectDALFactory } from "../project/project-dal";
import { TProjectSlackConfigDALFactory } from "./project-slack-config-dal";
import { SlackTriggerFeature, TSlackNotification } from "./slack-types";
import { TSendSlackNotificationDTO } from "./slack-types";
export const fetchSlackChannels = async (botKey: string) => {
const slackChannels: {
@@ -41,11 +42,11 @@ export const fetchSlackChannels = async (botKey: string) => {
return slackChannels;
};
const buildSlackPayload = (notification: TSlackNotification) => {
const buildSlackPayload = (notification: TNotification) => {
const appCfg = getConfig();
switch (notification.type) {
case SlackTriggerFeature.SECRET_APPROVAL: {
case TriggerFeature.SECRET_APPROVAL: {
const { payload } = notification;
const messageBody = `A secret approval request has been opened by ${payload.userEmail}.
*Environment*: ${payload.environment}
@@ -79,7 +80,7 @@ View the complete details <${appCfg.SITE_URL}/secret-manager/${payload.projectId
payloadBlocks
};
}
case SlackTriggerFeature.ACCESS_REQUEST: {
case TriggerFeature.ACCESS_REQUEST: {
const { payload } = notification;
const messageBody = `${payload.requesterFullName} (${payload.requesterEmail}) has requested ${
payload.isTemporary ? "temporary" : "permanent"
@@ -125,51 +126,24 @@ User Note: ${payload.note}`
}
};
export const triggerSlackNotification = async ({
projectId,
export const sendSlackNotification = async ({
orgId,
notification,
projectSlackConfigDAL,
projectDAL,
kmsService
}: {
projectId: string;
notification: TSlackNotification;
projectSlackConfigDAL: Pick<TProjectSlackConfigDALFactory, "getIntegrationDetailsByProject">;
projectDAL: Pick<TProjectDALFactory, "findById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
}) => {
const { payloadMessage, payloadBlocks } = buildSlackPayload(notification);
const project = await projectDAL.findById(projectId);
const slackIntegration = await projectSlackConfigDAL.getIntegrationDetailsByProject(project.id);
if (!slackIntegration) {
return;
}
let targetChannelIds: string[] = [];
if (notification.type === SlackTriggerFeature.ACCESS_REQUEST) {
targetChannelIds = slackIntegration.accessRequestChannels?.split(", ") || [];
if (!targetChannelIds.length || !slackIntegration.isAccessRequestNotificationEnabled) {
return;
}
} else if (notification.type === SlackTriggerFeature.SECRET_APPROVAL) {
targetChannelIds = slackIntegration.secretRequestChannels?.split(", ") || [];
if (!targetChannelIds.length || !slackIntegration.isSecretRequestNotificationEnabled) {
return;
}
}
kmsService,
targetChannelIds,
slackIntegration
}: TSendSlackNotificationDTO) => {
const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: project.orgId
orgId
});
const botKey = orgDataKeyDecryptor({
cipherTextBlob: slackIntegration.encryptedBotAccessToken
}).toString("utf8");
const slackWebClient = new WebClient(botKey);
const { payloadMessage, payloadBlocks } = buildSlackPayload(notification);
for await (const conversationId of targetChannelIds) {
// we send both text and blocks for compatibility with barebone clients
await slackWebClient.chat
+11 -31
View File
@@ -1,4 +1,8 @@
import { TSlackIntegrations } from "@app/db/schemas";
import { TOrgPermission } from "@app/lib/types";
import { TNotification } from "@app/lib/workflow-integrations/types";
import { TKmsServiceFactory } from "../kms/kms-service";
export type TGetSlackInstallUrlDTO = {
slug: string;
@@ -48,34 +52,10 @@ export type TReinstallSlackIntegrationDTO = {
slackBotUserId: string;
};
export enum SlackTriggerFeature {
SECRET_APPROVAL = "secret-approval",
ACCESS_REQUEST = "access-request"
}
export type TSlackNotification =
| {
type: SlackTriggerFeature.SECRET_APPROVAL;
payload: {
userEmail: string;
environment: string;
secretPath: string;
requestId: string;
projectId: string;
secretKeys: string[];
};
}
| {
type: SlackTriggerFeature.ACCESS_REQUEST;
payload: {
requesterFullName: string;
requesterEmail: string;
isTemporary: boolean;
secretPath: string;
environment: string;
projectName: string;
permissions: string[];
approvalUrl: string;
note?: string;
};
};
export type TSendSlackNotificationDTO = {
orgId: string;
notification: TNotification;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
targetChannelIds: string[];
slackIntegration: TSlackIntegrations;
};
@@ -20,6 +20,7 @@ import { KMS_ROOT_CONFIG_UUID } from "../kms/kms-fns";
import { TKmsRootConfigDALFactory } from "../kms/kms-root-config-dal";
import { TKmsServiceFactory } from "../kms/kms-service";
import { RootKeyEncryptionStrategy } from "../kms/kms-types";
import { TMicrosoftTeamsServiceFactory } from "../microsoft-teams/microsoft-teams-service";
import { TOrgServiceFactory } from "../org/org-service";
import { TUserDALFactory } from "../user/user-dal";
import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
@@ -47,6 +48,7 @@ type TSuperAdminServiceFactoryDep = {
orgService: Pick<TOrgServiceFactory, "createOrganization">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
licenseService: Pick<TLicenseServiceFactory, "onPremFeatures">;
microsoftTeamsService: Pick<TMicrosoftTeamsServiceFactory, "initializeTeamsBot">;
};
export type TSuperAdminServiceFactory = ReturnType<typeof superAdminServiceFactory>;
@@ -77,7 +79,8 @@ export const superAdminServiceFactory = ({
licenseService,
identityAccessTokenDAL,
identityTokenAuthDAL,
identityOrgMembershipDAL
identityOrgMembershipDAL,
microsoftTeamsService
}: TSuperAdminServiceFactoryDep) => {
const initServerCfg = async () => {
// TODO(akhilmhdh): bad pattern time less change this later to me itself
@@ -125,7 +128,13 @@ export const superAdminServiceFactory = ({
};
const updateServerCfg = async (
data: TSuperAdminUpdate & { slackClientId?: string; slackClientSecret?: string },
data: TSuperAdminUpdate & {
slackClientId?: string;
slackClientSecret?: string;
microsoftTeamsAppId?: string;
microsoftTeamsClientSecret?: string;
microsoftTeamsBotId?: string;
},
userId: string
) => {
const updatedData = data;
@@ -192,10 +201,46 @@ export const superAdminServiceFactory = ({
updatedData.slackClientSecret = undefined;
}
if (data.microsoftTeamsAppId) {
const encryptedClientId = encryptWithRoot(Buffer.from(data.microsoftTeamsAppId));
updatedData.encryptedMicrosoftTeamsAppId = encryptedClientId;
updatedData.microsoftTeamsAppId = undefined;
}
if (data.microsoftTeamsClientSecret) {
const encryptedClientSecret = encryptWithRoot(Buffer.from(data.microsoftTeamsClientSecret));
updatedData.encryptedMicrosoftTeamsClientSecret = encryptedClientSecret;
updatedData.microsoftTeamsClientSecret = undefined;
}
if (data.microsoftTeamsBotId) {
const encryptedBotId = encryptWithRoot(Buffer.from(data.microsoftTeamsBotId));
updatedData.encryptedMicrosoftTeamsBotId = encryptedBotId;
updatedData.microsoftTeamsBotId = undefined;
}
const updatedServerCfg = await serverCfgDAL.updateById(ADMIN_CONFIG_DB_UUID, updatedData);
await keyStore.setItemWithExpiry(ADMIN_CONFIG_KEY, ADMIN_CONFIG_KEY_EXP, JSON.stringify(updatedServerCfg));
if (
updatedServerCfg.encryptedMicrosoftTeamsAppId &&
updatedServerCfg.encryptedMicrosoftTeamsClientSecret &&
updatedServerCfg.encryptedMicrosoftTeamsBotId
) {
const decryptWithRoot = kmsService.decryptWithRootKey();
decryptWithRoot(updatedServerCfg.encryptedMicrosoftTeamsBotId); // validate that we're able to decrypt the bot ID
const decryptedAppId = decryptWithRoot(updatedServerCfg.encryptedMicrosoftTeamsAppId);
const decryptedAppPassword = decryptWithRoot(updatedServerCfg.encryptedMicrosoftTeamsClientSecret);
await microsoftTeamsService.initializeTeamsBot({
botAppId: decryptedAppId.toString(),
botAppPassword: decryptedAppPassword.toString()
});
}
return updatedServerCfg;
};
@@ -488,29 +533,40 @@ export const superAdminServiceFactory = ({
await userDAL.updateById(userId, { superAdmin: true });
};
const getAdminSlackConfig = async () => {
const getAdminIntegrationsConfig = async () => {
const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);
if (!serverCfg) {
throw new NotFoundError({ name: "AdminConfig", message: "Admin config not found" });
}
let clientId = "";
let clientSecret = "";
const decrypt = kmsService.decryptWithRootKey();
if (serverCfg.encryptedSlackClientId) {
clientId = decrypt(serverCfg.encryptedSlackClientId).toString();
}
const slackClientId = serverCfg.encryptedSlackClientId ? decrypt(serverCfg.encryptedSlackClientId).toString() : "";
const slackClientSecret = serverCfg.encryptedSlackClientSecret
? decrypt(serverCfg.encryptedSlackClientSecret).toString()
: "";
if (serverCfg.encryptedSlackClientSecret) {
clientSecret = decrypt(serverCfg.encryptedSlackClientSecret).toString();
}
const microsoftAppId = serverCfg.encryptedMicrosoftTeamsAppId
? decrypt(serverCfg.encryptedMicrosoftTeamsAppId).toString()
: "";
const microsoftClientSecret = serverCfg.encryptedMicrosoftTeamsClientSecret
? decrypt(serverCfg.encryptedMicrosoftTeamsClientSecret).toString()
: "";
const microsoftBotId = serverCfg.encryptedMicrosoftTeamsBotId
? decrypt(serverCfg.encryptedMicrosoftTeamsBotId).toString()
: "";
return {
clientId,
clientSecret
slack: {
clientSecret: slackClientSecret,
clientId: slackClientId
},
microsoftTeams: {
appId: microsoftAppId,
clientSecret: microsoftClientSecret,
botId: microsoftBotId
}
};
};
@@ -578,7 +634,7 @@ export const superAdminServiceFactory = ({
getUsers,
deleteUser,
getIdentities,
getAdminSlackConfig,
getAdminIntegrationsConfig,
updateRootEncryptionStrategy,
getConfiguredEncryptionStrategies,
grantServerAdminAccessToUser,
@@ -1,7 +1,14 @@
import { TOrgPermission } from "@app/lib/types";
export enum WorkflowIntegration {
SLACK = "slack"
SLACK = "slack",
MICROSOFT_TEAMS = "microsoft-teams"
}
export enum WorkflowIntegrationStatus {
PENDING = "pending",
INSTALLED = "installed",
FAILED = "failed"
}
export type TGetWorkflowIntegrationsByOrg = Omit<TOrgPermission, "orgId">;