remove_deleted_users_from_token_access_refs.js 6.8 KB

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