external-user-group-sync.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import type { IUserHasId } from '@growi/core';
  2. import { SocketEventName } from '~/interfaces/websocket';
  3. import ExternalAccount from '~/server/models/external-account';
  4. import S2sMessage from '~/server/models/vo/s2s-message';
  5. import { S2sMessagingService } from '~/server/service/s2s-messaging/base';
  6. import { S2sMessageHandlable } from '~/server/service/s2s-messaging/handlable';
  7. import { excludeTestIdsFromTargetIds } from '~/server/util/compare-objectId';
  8. import loggerFactory from '~/utils/logger';
  9. import { batchProcessPromiseAll } from '~/utils/promise';
  10. import { configManager } from '../../../../server/service/config-manager';
  11. import { externalAccountService } from '../../../../server/service/external-account';
  12. import {
  13. ExternalGroupProviderType, ExternalUserGroupTreeNode, ExternalUserInfo, IExternalUserGroupHasId,
  14. } from '../../interfaces/external-user-group';
  15. import ExternalUserGroup from '../models/external-user-group';
  16. import ExternalUserGroupRelation from '../models/external-user-group-relation';
  17. const logger = loggerFactory('growi:service:external-user-group-sync-service');
  18. // When d = max depth of group trees
  19. // Max space complexity of syncExternalUserGroups will be:
  20. // O(TREES_BATCH_SIZE * d * USERS_BATCH_SIZE)
  21. const TREES_BATCH_SIZE = 10;
  22. const USERS_BATCH_SIZE = 30;
  23. type SyncStatus = { isExecutingSync: boolean, totalCount: number, count: number }
  24. class ExternalUserGroupSyncS2sMessage extends S2sMessage {
  25. syncStatus: SyncStatus;
  26. }
  27. abstract class ExternalUserGroupSyncService implements S2sMessageHandlable {
  28. groupProviderType: ExternalGroupProviderType; // name of external service that contains user group info (e.g: ldap, keycloak)
  29. authProviderType: string | null; // auth provider type (e.g: ldap, oidc). Has to be set before syncExternalUserGroups execution.
  30. socketIoService: any;
  31. s2sMessagingService: S2sMessagingService | null;
  32. syncStatus: SyncStatus = { isExecutingSync: false, totalCount: 0, count: 0 };
  33. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  34. constructor(groupProviderType: ExternalGroupProviderType, s2sMessagingService: S2sMessagingService | null, socketIoService) {
  35. this.groupProviderType = groupProviderType;
  36. this.s2sMessagingService = s2sMessagingService;
  37. this.socketIoService = socketIoService;
  38. }
  39. /**
  40. * @inheritdoc
  41. */
  42. shouldHandleS2sMessage(s2sMessage: ExternalUserGroupSyncS2sMessage): boolean {
  43. return s2sMessage.eventName === 'switchExternalUserGroupExecSyncStatus';
  44. }
  45. /**
  46. * @inheritdoc
  47. */
  48. async handleS2sMessage(s2sMessage: ExternalUserGroupSyncS2sMessage): Promise<void> {
  49. logger.info('Update syncStatus by pubsub notification');
  50. this.syncStatus = s2sMessage.syncStatus;
  51. }
  52. async setSyncStatus(syncStatus: SyncStatus): Promise<void> {
  53. this.syncStatus = syncStatus;
  54. if (this.s2sMessagingService != null) {
  55. const s2sMessage = new ExternalUserGroupSyncS2sMessage('switchExternalUserGroupExecSyncStatus', {
  56. syncStatus: this.syncStatus,
  57. });
  58. try {
  59. await this.s2sMessagingService.publish(s2sMessage);
  60. }
  61. catch (e) {
  62. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  63. }
  64. }
  65. }
  66. /** External user group tree sync method
  67. * 1. Generate external user group tree
  68. * 2. Use createUpdateExternalUserGroup on each node in the tree using DFS
  69. * 3. If preserveDeletedLDAPGroups is false、delete all ExternalUserGroups that were not found during tree search
  70. */
  71. async syncExternalUserGroups(): Promise<void> {
  72. if (this.authProviderType == null) throw new Error('auth provider type is not set');
  73. if (this.syncStatus.isExecutingSync) throw new Error('External user group sync is already being executed');
  74. const preserveDeletedLdapGroups: boolean = configManager?.getConfig('crowi', `external-user-group:${this.groupProviderType}:preserveDeletedGroups`);
  75. const existingExternalUserGroupIds: string[] = [];
  76. const socket = this.socketIoService?.getAdminSocket();
  77. const syncNode = async(node: ExternalUserGroupTreeNode, parentId?: string) => {
  78. const externalUserGroup = await this.createUpdateExternalUserGroup(node, parentId);
  79. existingExternalUserGroupIds.push(externalUserGroup._id);
  80. await this.setSyncStatus({ isExecutingSync: true, totalCount: this.syncStatus.totalCount, count: this.syncStatus.count + 1 });
  81. socket?.emit(SocketEventName.externalUserGroup[this.groupProviderType].GroupSyncProgress, {
  82. totalCount: this.syncStatus.totalCount, count: this.syncStatus.count,
  83. });
  84. // Do not use Promise.all, because the number of promises processed can
  85. // exponentially grow when group tree is enormous
  86. for await (const childNode of node.childGroupNodes) {
  87. await syncNode(childNode, externalUserGroup._id);
  88. }
  89. };
  90. try {
  91. const trees = await this.generateExternalUserGroupTrees();
  92. const totalCount = trees.map(tree => this.getGroupCountOfTree(tree))
  93. .reduce((sum, current) => sum + current);
  94. await this.setSyncStatus({ isExecutingSync: true, totalCount, count: 0 });
  95. await batchProcessPromiseAll(trees, TREES_BATCH_SIZE, async(tree) => {
  96. return syncNode(tree);
  97. });
  98. if (!preserveDeletedLdapGroups) {
  99. await ExternalUserGroup.deleteMany({
  100. _id: { $nin: existingExternalUserGroupIds },
  101. groupProviderType: this.groupProviderType,
  102. provider: this.groupProviderType,
  103. });
  104. await ExternalUserGroupRelation.removeAllInvalidRelations();
  105. }
  106. socket?.emit(SocketEventName.externalUserGroup[this.groupProviderType].GroupSyncCompleted);
  107. }
  108. catch (e) {
  109. logger.error(e.message);
  110. socket?.emit(SocketEventName.externalUserGroup[this.groupProviderType].GroupSyncFailed);
  111. }
  112. finally {
  113. await this.setSyncStatus({ isExecutingSync: false, totalCount: 0, count: 0 });
  114. }
  115. }
  116. /** External user group node sync method
  117. * 1. Create/Update ExternalUserGroup from using information of ExternalUserGroupTreeNode
  118. * 2. For every element in node.userInfos, call getMemberUser and create an ExternalUserGroupRelation with ExternalUserGroup if it does not have one
  119. * 3. Retrun ExternalUserGroup
  120. * @param {string} node Node of external group tree
  121. * @param {string} parentId Parent group id (id in GROWI) of the group we want to create/update
  122. * @returns {Promise<IExternalUserGroupHasId>} ExternalUserGroup that was created/updated
  123. */
  124. private async createUpdateExternalUserGroup(node: ExternalUserGroupTreeNode, parentId?: string): Promise<IExternalUserGroupHasId> {
  125. const externalUserGroup = await ExternalUserGroup.findAndUpdateOrCreateGroup(
  126. node.name, node.id, this.groupProviderType, node.description, parentId,
  127. );
  128. await batchProcessPromiseAll(node.userInfos, USERS_BATCH_SIZE, async(userInfo) => {
  129. const user = await this.getMemberUser(userInfo);
  130. if (user != null) {
  131. const userGroups = await ExternalUserGroup.findGroupsWithAncestorsRecursively(externalUserGroup);
  132. const userGroupIds = userGroups.map(g => g._id);
  133. // remove existing relations from list to create
  134. const existingRelations = await ExternalUserGroupRelation.find({ relatedGroup: { $in: userGroupIds }, relatedUser: user._id });
  135. const existingGroupIds = existingRelations.map(r => r.relatedGroup.toString());
  136. const groupIdsToCreateRelation = excludeTestIdsFromTargetIds(userGroupIds, existingGroupIds);
  137. await ExternalUserGroupRelation.createRelations(groupIdsToCreateRelation, user);
  138. }
  139. });
  140. return externalUserGroup;
  141. }
  142. /** Method to get group member GROWI user
  143. * 1. Search for GROWI user based on user info of 1, and return user
  144. * 2. If autoGenerateUserOnHogeGroupSync is true and GROWI user is not found, create new GROWI user
  145. * @param {ExternalUserInfo} externalUserInfo Search external app/server using this identifier
  146. * @returns {Promise<IUserHasId | null>} User when found or created, null when neither
  147. */
  148. private async getMemberUser(userInfo: ExternalUserInfo): Promise<IUserHasId | null> {
  149. const authProviderType = this.authProviderType;
  150. if (authProviderType == null) throw new Error('auth provider type is not set');
  151. const autoGenerateUserOnGroupSync = configManager?.getConfig('crowi', `external-user-group:${this.groupProviderType}:autoGenerateUserOnGroupSync`);
  152. const getExternalAccount = async() => {
  153. if (autoGenerateUserOnGroupSync && externalAccountService != null) {
  154. return externalAccountService.getOrCreateUser({
  155. id: userInfo.id, username: userInfo.username, name: userInfo.name, email: userInfo.email,
  156. }, authProviderType);
  157. }
  158. return ExternalAccount.findOne({ providerType: this.groupProviderType, accountId: userInfo.id });
  159. };
  160. const externalAccount = await getExternalAccount();
  161. if (externalAccount != null) {
  162. return (await externalAccount.populate<{user: IUserHasId | null}>('user')).user;
  163. }
  164. return null;
  165. }
  166. getGroupCountOfTree(tree: ExternalUserGroupTreeNode): number {
  167. if (tree.childGroupNodes.length === 0) return 1;
  168. let count = 1;
  169. tree.childGroupNodes.forEach((childGroup) => {
  170. count += this.getGroupCountOfTree(childGroup);
  171. });
  172. return count;
  173. }
  174. /** Method to generate external group tree structure
  175. * 1. Fetch user group info from external app/server
  176. * 2. Convert each group tree structure to ExternalUserGroupTreeNode
  177. * 3. Return the root node of each tree
  178. */
  179. abstract generateExternalUserGroupTrees(): Promise<ExternalUserGroupTreeNode[]>
  180. }
  181. export default ExternalUserGroupSyncService;