slack-integration.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import { markdownSectionBlock, InvalidGrowiCommandError } from '@growi/slack';
  2. import loggerFactory from '~/utils/logger';
  3. const express = require('express');
  4. const mongoose = require('mongoose');
  5. const urljoin = require('url-join');
  6. const {
  7. verifySlackRequest, parseSlashCommand, InteractionPayloadAccessor, respond,
  8. } = require('@growi/slack');
  9. const logger = loggerFactory('growi:routes:apiv3:slack-integration');
  10. const router = express.Router();
  11. const SlackAppIntegration = mongoose.model('SlackAppIntegration');
  12. const { handleError } = require('../../service/slack-command-handler/error-handler');
  13. const { checkPermission } = require('../../util/slack-integration');
  14. module.exports = (crowi) => {
  15. this.app = crowi.express;
  16. const { configManager, slackIntegrationService } = crowi;
  17. // Check if the access token is correct
  18. async function verifyAccessTokenFromProxy(req, res, next) {
  19. const tokenPtoG = req.headers['x-growi-ptog-tokens'];
  20. if (tokenPtoG == null) {
  21. const message = 'The value of header \'x-growi-ptog-tokens\' must not be empty.';
  22. logger.warn(message, { body: req.body });
  23. return res.status(400).send({ message });
  24. }
  25. const SlackAppIntegrationCount = await SlackAppIntegration.countDocuments({ tokenPtoG });
  26. logger.debug('verifyAccessTokenFromProxy', {
  27. tokenPtoG,
  28. SlackAppIntegrationCount,
  29. });
  30. if (SlackAppIntegrationCount === 0) {
  31. return res.status(403).send({
  32. message: 'The access token that identifies the request source is slackbot-proxy is invalid. Did you setup with `/growi register`.\n'
  33. + 'Or did you delete registration for GROWI ? if so, the link with GROWI has been disconnected. '
  34. + 'Please unregister the information registered in the proxy and setup `/growi register` again.',
  35. });
  36. }
  37. next();
  38. }
  39. async function extractPermissionsCommands(tokenPtoG) {
  40. const slackAppIntegration = await SlackAppIntegration.findOne({ tokenPtoG });
  41. if (slackAppIntegration == null) return null;
  42. const permissionsForBroadcastUseCommands = slackAppIntegration.permissionsForBroadcastUseCommands;
  43. const permissionsForSingleUseCommands = slackAppIntegration.permissionsForSingleUseCommands;
  44. return { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands };
  45. }
  46. // REFACTORIMG THIS MIDDLEWARE GW-7441
  47. async function checkCommandsPermission(req, res, next) {
  48. let { growiCommand } = req.body;
  49. // when /relation-test or from proxy
  50. if (req.body.text == null && growiCommand == null) return next();
  51. const tokenPtoG = req.headers['x-growi-ptog-tokens'];
  52. const extractPermissions = await extractPermissionsCommands(tokenPtoG);
  53. const fromChannel = req.body.channel_name;
  54. const siteUrl = crowi.appService.getSiteUrl();
  55. let commandPermission;
  56. if (extractPermissions != null) { // with proxy
  57. const { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands } = extractPermissions;
  58. commandPermission = Object.fromEntries([...permissionsForBroadcastUseCommands, ...permissionsForSingleUseCommands]);
  59. const isPermitted = checkPermission(commandPermission, growiCommand.growiCommandType, fromChannel);
  60. if (isPermitted) return next();
  61. return res.status(403).send(`It is not allowed to send \`/growi ${growiCommand.growiCommandType}\` command to this GROWI: ${siteUrl}`);
  62. }
  63. // without proxy
  64. growiCommand = parseSlashCommand(req.body);
  65. commandPermission = JSON.parse(configManager.getConfig('crowi', 'slackbot:withoutProxy:commandPermission'));
  66. const isPermitted = checkPermission(commandPermission, growiCommand.growiCommandType, fromChannel);
  67. if (isPermitted) {
  68. return next();
  69. }
  70. // show ephemeral error message if not permitted
  71. res.json({
  72. response_type: 'ephemeral',
  73. text: 'Command forbidden',
  74. blocks: [
  75. markdownSectionBlock(`It is not allowed to send \`/growi ${growiCommand.growiCommandType}\` command to this GROWI: ${siteUrl}`),
  76. ],
  77. });
  78. }
  79. // REFACTORIMG THIS MIDDLEWARE GW-7441
  80. async function checkInteractionsPermission(req, res, next) {
  81. const { interactionPayload, interactionPayloadAccessor } = req;
  82. const siteUrl = crowi.appService.getSiteUrl();
  83. const { actionId, callbackId } = interactionPayloadAccessor.getActionIdAndCallbackIdFromPayLoad();
  84. const callbacIdkOrActionId = callbackId || actionId;
  85. const fromChannel = interactionPayloadAccessor.getChannelName();
  86. const tokenPtoG = req.headers['x-growi-ptog-tokens'];
  87. const extractPermissions = await extractPermissionsCommands(tokenPtoG);
  88. let commandPermission;
  89. if (extractPermissions != null) { // with proxy
  90. const { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands } = extractPermissions;
  91. commandPermission = Object.fromEntries([...permissionsForBroadcastUseCommands, ...permissionsForSingleUseCommands]);
  92. const isPermitted = checkPermission(commandPermission, callbacIdkOrActionId, fromChannel);
  93. if (isPermitted) return next();
  94. return res.status(403).send(`This interaction is forbidden on this GROWI: ${siteUrl}`);
  95. }
  96. // without proxy
  97. commandPermission = JSON.parse(configManager.getConfig('crowi', 'slackbot:withoutProxy:commandPermission'));
  98. const isPermitted = checkPermission(commandPermission, callbacIdkOrActionId, fromChannel);
  99. if (isPermitted) {
  100. return next();
  101. }
  102. // show ephemeral error message if not permitted
  103. res.json({
  104. response_type: 'ephemeral',
  105. text: 'Interaction forbidden',
  106. blocks: [
  107. markdownSectionBlock(`This interaction is forbidden on this GROWI: ${siteUrl}`),
  108. ],
  109. });
  110. }
  111. const addSigningSecretToReq = (req, res, next) => {
  112. req.slackSigningSecret = configManager.getConfig('crowi', 'slackbot:withoutProxy:signingSecret');
  113. return next();
  114. };
  115. const parseSlackInteractionRequest = (req, res, next) => {
  116. if (req.body.payload == null) {
  117. return next(new Error('The payload is not in the request from slack or proxy.'));
  118. }
  119. req.interactionPayload = JSON.parse(req.body.payload);
  120. req.interactionPayloadAccessor = new InteractionPayloadAccessor(req.interactionPayload);
  121. return next();
  122. };
  123. async function handleCommands(req, res, client) {
  124. const { body } = req;
  125. let { growiCommand } = body;
  126. if (growiCommand == null) {
  127. try {
  128. growiCommand = parseSlashCommand(body);
  129. }
  130. catch (err) {
  131. if (err instanceof InvalidGrowiCommandError) {
  132. res.json({
  133. blocks: [
  134. markdownSectionBlock('*Command type is not specified.*'),
  135. markdownSectionBlock('Run `/growi help` to check the commands you can use.'),
  136. ],
  137. });
  138. }
  139. logger.error(err.message);
  140. return;
  141. }
  142. }
  143. const { text } = growiCommand;
  144. if (text == null) {
  145. return 'No text.';
  146. }
  147. /*
  148. * TODO: use parseSlashCommand
  149. */
  150. // Send response immediately to avoid opelation_timeout error
  151. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  152. res.json({
  153. response_type: 'ephemeral',
  154. text: 'Processing your request ...',
  155. });
  156. try {
  157. await crowi.slackIntegrationService.handleCommandRequest(growiCommand, client, body);
  158. }
  159. catch (err) {
  160. await handleError(err, growiCommand.responseUrl);
  161. }
  162. }
  163. // TODO: do investigation and fix if needed GW-7519
  164. router.post('/commands', addSigningSecretToReq, verifySlackRequest, checkCommandsPermission, async(req, res) => {
  165. const client = await slackIntegrationService.generateClientForCustomBotWithoutProxy();
  166. return handleCommands(req, res, client);
  167. });
  168. router.post('/proxied/commands', verifyAccessTokenFromProxy, checkCommandsPermission, async(req, res) => {
  169. const { body } = req;
  170. // eslint-disable-next-line max-len
  171. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  172. if (body.type === 'url_verification') {
  173. return res.send({ challenge: body.challenge });
  174. }
  175. const tokenPtoG = req.headers['x-growi-ptog-tokens'];
  176. const client = await slackIntegrationService.generateClientByTokenPtoG(tokenPtoG);
  177. return handleCommands(req, res, client);
  178. });
  179. async function handleInteractionsRequest(req, res, client) {
  180. // Send response immediately to avoid opelation_timeout error
  181. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  182. res.send();
  183. const { interactionPayload, interactionPayloadAccessor } = req;
  184. const { type } = interactionPayload;
  185. try {
  186. switch (type) {
  187. case 'block_actions':
  188. await crowi.slackIntegrationService.handleBlockActionsRequest(client, interactionPayload, interactionPayloadAccessor);
  189. break;
  190. case 'view_submission':
  191. await crowi.slackIntegrationService.handleViewSubmissionRequest(client, interactionPayload, interactionPayloadAccessor);
  192. break;
  193. default:
  194. break;
  195. }
  196. }
  197. catch (error) {
  198. logger.error(error);
  199. await handleError(error, interactionPayloadAccessor.getResponseUrl());
  200. }
  201. }
  202. // TODO: do investigation and fix if needed GW-7519
  203. router.post('/interactions', addSigningSecretToReq, verifySlackRequest, parseSlackInteractionRequest, checkInteractionsPermission, async(req, res) => {
  204. const client = await slackIntegrationService.generateClientForCustomBotWithoutProxy();
  205. return handleInteractionsRequest(req, res, client);
  206. });
  207. router.post('/proxied/interactions', verifyAccessTokenFromProxy, parseSlackInteractionRequest, checkInteractionsPermission, async(req, res) => {
  208. const tokenPtoG = req.headers['x-growi-ptog-tokens'];
  209. const client = await slackIntegrationService.generateClientByTokenPtoG(tokenPtoG);
  210. return handleInteractionsRequest(req, res, client);
  211. });
  212. router.get('/supported-commands', verifyAccessTokenFromProxy, async(req, res) => {
  213. const tokenPtoG = req.headers['x-growi-ptog-tokens'];
  214. const slackAppIntegration = await SlackAppIntegration.findOne({ tokenPtoG });
  215. const { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands } = slackAppIntegration;
  216. return res.apiv3({ permissionsForBroadcastUseCommands, permissionsForSingleUseCommands });
  217. });
  218. return router;
  219. };