remove_deleted_users_from_token_access_refs.mjs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import {
  2. db,
  3. READ_PREFERENCE_SECONDARY,
  4. } from '../app/src/infrastructure/mongodb.js'
  5. import BatchedUpdateModule from './helpers/batchedUpdate.mjs'
  6. import mongodb from 'mongodb-legacy'
  7. import minimist from 'minimist'
  8. import CollaboratorsHandler from '../app/src/Features/Collaborators/CollaboratorsHandler.js'
  9. import { fileURLToPath } from 'node:url'
  10. const { ObjectId } = mongodb
  11. const { batchedUpdate } = BatchedUpdateModule
  12. const argv = minimist(process.argv.slice(2), {
  13. string: ['projects'],
  14. boolean: ['dry-run', 'help'],
  15. alias: {
  16. projects: 'p',
  17. },
  18. default: {
  19. 'dry-run': true,
  20. },
  21. })
  22. const DRY_RUN = argv['dry-run']
  23. const PROJECTS_LIST = argv.projects
  24. async function findUserIds() {
  25. const userIds = new Set()
  26. const cursor = db.users.find(
  27. {},
  28. {
  29. projection: { _id: 1 },
  30. readPreference: READ_PREFERENCE_SECONDARY,
  31. }
  32. )
  33. for await (const user of cursor) {
  34. userIds.add(user._id.toString())
  35. if (userIds.size % 1_000_000 === 0) {
  36. console.log(`=> ${userIds.size} users added`, new Date().toISOString())
  37. }
  38. }
  39. console.log(`=> User ids count: ${userIds.size}`)
  40. return userIds
  41. }
  42. async function fixProjectsWithInvalidTokenAccessRefsIds(
  43. DRY_RUN,
  44. PROJECTS_LIST
  45. ) {
  46. if (DRY_RUN) {
  47. console.log('=> Doing dry run')
  48. }
  49. const DELETED_USER_COLLABORATOR_IDS = new Set()
  50. const PROJECTS_WITH_DELETED_USER = new Set()
  51. // get a set of all users ids as an in-memory cache
  52. const userIds = await findUserIds()
  53. // default query for finding all projects with non-existing/null or non-empty token access fields
  54. let query = {
  55. $or: [
  56. { tokenAccessReadOnly_refs: { $not: { $type: 'array' } } },
  57. { tokenAccessReadAndWrite_refs: { $not: { $type: 'array' } } },
  58. { 'tokenAccessReadOnly_refs.0': { $exists: true } },
  59. { 'tokenAccessReadAndWrite_refs.0': { $exists: true } },
  60. ],
  61. }
  62. const projectIds = PROJECTS_LIST?.split(',').map(
  63. projectId => new ObjectId(projectId)
  64. )
  65. // query for finding projects passed in as args
  66. if (projectIds) {
  67. query = { $and: [{ _id: { $in: projectIds } }] }
  68. }
  69. await batchedUpdate(
  70. 'projects',
  71. query,
  72. async projects => {
  73. for (const project of projects) {
  74. const isTokenAccessFieldMissing =
  75. !project.tokenAccessReadOnly_refs ||
  76. !project.tokenAccessReadAndWrite_refs
  77. project.tokenAccessReadOnly_refs ??= []
  78. project.tokenAccessReadAndWrite_refs ??= []
  79. // update the token access fields if necessary
  80. if (isTokenAccessFieldMissing) {
  81. if (DRY_RUN) {
  82. console.log(
  83. `=> DRY RUN - would fix non-existing token access fields in project ${project._id.toString()}`
  84. )
  85. } else {
  86. const fields = [
  87. 'tokenAccessReadOnly_refs',
  88. 'tokenAccessReadAndWrite_refs',
  89. ]
  90. for (const field of fields) {
  91. await db.projects.updateOne(
  92. {
  93. _id: project._id,
  94. [field]: { $not: { $type: 'array' } },
  95. },
  96. { $set: { [field]: [] } }
  97. )
  98. }
  99. console.log(
  100. `=> Fixed non-existing token access fields in project ${project._id.toString()}`
  101. )
  102. }
  103. }
  104. // find the set of user ids that are in the token access fields
  105. // i.e. the set of collaborators
  106. const collaboratorIds = new Set()
  107. for (const roUserId of project.tokenAccessReadOnly_refs) {
  108. collaboratorIds.add(roUserId.toString())
  109. }
  110. for (const rwUserId of project.tokenAccessReadAndWrite_refs) {
  111. collaboratorIds.add(rwUserId.toString())
  112. }
  113. // determine which collaborator ids are not in the `users` collection
  114. // i.e. the user has been deleted
  115. const deletedUserIds = new Set()
  116. for (const collaboratorId of collaboratorIds) {
  117. if (!userIds.has(collaboratorId)) {
  118. deletedUserIds.add(collaboratorId)
  119. }
  120. }
  121. // double-check that users doesn't exist in the users collection
  122. // we don't want to remove users that were added after the initial query
  123. const existingUsersCursor = db.users.find(
  124. { _id: { $in: [...deletedUserIds].map(id => new ObjectId(id)) } },
  125. { _id: 1 }
  126. )
  127. for await (const user of existingUsersCursor) {
  128. const id = user._id.toString()
  129. deletedUserIds.delete(id)
  130. // add the user id to the cache
  131. userIds.add(id)
  132. }
  133. // remove the actual deleted users
  134. for (const deletedUserId of deletedUserIds) {
  135. DELETED_USER_COLLABORATOR_IDS.add(deletedUserId)
  136. PROJECTS_WITH_DELETED_USER.add(project._id.toString())
  137. console.log(
  138. '=> Found deleted user id:',
  139. deletedUserId,
  140. 'in project:',
  141. project._id.toString()
  142. )
  143. if (DRY_RUN) {
  144. console.log(
  145. `=> DRY RUN - would remove deleted ${deletedUserId} from all projects (found in project ${project._id.toString()})`
  146. )
  147. continue
  148. }
  149. console.log(
  150. `=> Removing deleted ${deletedUserId} from all projects (found in project ${project._id.toString()})`
  151. )
  152. await CollaboratorsHandler.promises.removeUserFromAllProjects(
  153. new ObjectId(deletedUserId)
  154. )
  155. }
  156. }
  157. },
  158. { tokenAccessReadOnly_refs: 1, tokenAccessReadAndWrite_refs: 1 }
  159. )
  160. console.log(
  161. `=> ${DRY_RUN ? 'DRY RUN - would delete' : 'Deleted'} user ids (${
  162. DELETED_USER_COLLABORATOR_IDS.size
  163. })`
  164. )
  165. if (DELETED_USER_COLLABORATOR_IDS.size) {
  166. console.log(Array.from(DELETED_USER_COLLABORATOR_IDS).join('\n'))
  167. }
  168. console.log(
  169. `=> Projects with deleted user ids (${PROJECTS_WITH_DELETED_USER.size})`
  170. )
  171. if (PROJECTS_WITH_DELETED_USER.size) {
  172. console.log(Array.from(PROJECTS_WITH_DELETED_USER).join('\n'))
  173. }
  174. }
  175. async function main(DRY_RUN, PROJECTS_LIST) {
  176. await fixProjectsWithInvalidTokenAccessRefsIds(DRY_RUN, PROJECTS_LIST)
  177. }
  178. export default main
  179. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  180. if (argv.help || argv._.length > 1) {
  181. console.error(`Usage: node scripts/remove_deleted_users_from_token_access_refs.js [OPTS]
  182. Finds or removes deleted user ids from token access fields
  183. "tokenAccessReadOnly_refs" and "tokenAccessReadAndWrite_refs" in the "projects" collection.
  184. If no projects are specified, all projects will be processed.
  185. Options:
  186. --dry-run finds projects and deleted users but does not do any updates
  187. --projects list of projects ids to be fixed (comma separated)
  188. `)
  189. process.exit(1)
  190. }
  191. try {
  192. await main(DRY_RUN, PROJECTS_LIST)
  193. console.error('Done')
  194. process.exit(0)
  195. } catch (error) {
  196. console.error(error)
  197. process.exit(1)
  198. }
  199. }