external-user-group-sync.ts 9.6 KB

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