groupSSO.mjs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import fs from 'node:fs'
  2. import Path from 'node:path'
  3. import UserModule from './User.mjs'
  4. import SubscriptionHelper from './Subscription.mjs'
  5. import { SSOConfig } from '../../../../app/src/models/SSOConfig.js'
  6. import UserHelper from './UserHelper.mjs'
  7. import SAMLHelper from './SAMLHelper.mjs'
  8. import Settings from '@overleaf/settings'
  9. import { getProviderId } from '../../../../app/src/Features/Subscription/GroupUtils.js'
  10. import UserGetter from '../../../../app/src/Features/User/UserGetter.js'
  11. import { fileURLToPath } from 'node:url'
  12. import { Subscription as SubscriptionModel } from '../../../../app/src/models/Subscription.js'
  13. const { promises: User } = UserModule
  14. const { promises: Subscription } = SubscriptionHelper
  15. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  16. const SAML_TEST_CERT = fs
  17. .readFileSync(Path.resolve(__dirname, '../../files/saml-cert.crt'), 'utf8')
  18. .replace(/-----BEGIN CERTIFICATE-----/, '')
  19. .replace(/-----END CERTIFICATE-----/, '')
  20. .replace(/\n/g, '')
  21. function getEnrollmentUrl(groupId) {
  22. return `/subscription/${groupId}/sso_enrollment`
  23. }
  24. const userIdAttribute = 'nameID'
  25. export const baseSsoConfig = {
  26. entryPoint: 'http://example-sso.com/saml',
  27. certificates: [SAML_TEST_CERT],
  28. signatureAlgorithm: 'sha256',
  29. userIdAttribute,
  30. } // the database also sets enabled and validated, but we cannot set that in the POST request for /manage/groups/:ID/settings/sso
  31. export async function createGroupSSO(
  32. SSOConfigValidated = true,
  33. useSettingsUKAMF
  34. ) {
  35. const nonSSOMemberHelper = await UserHelper.createUser()
  36. const nonSSOMember = nonSSOMemberHelper.user
  37. const groupAdminUser = new User()
  38. const memberUser = new User()
  39. await groupAdminUser.ensureUserExists()
  40. await memberUser.ensureUserExists()
  41. const ssoConfigDoc = {
  42. ...baseSsoConfig,
  43. enabled: true,
  44. validated: SSOConfigValidated,
  45. }
  46. if (useSettingsUKAMF) {
  47. ssoConfigDoc.useSettingsUKAMF = useSettingsUKAMF // conditionally adding because this field was added after group SSO was released and it will be undefined for some groups
  48. }
  49. const ssoConfig = new SSOConfig(ssoConfigDoc)
  50. await ssoConfig.save()
  51. const subscription = new Subscription({
  52. adminId: groupAdminUser._id,
  53. memberIds: [memberUser._id, nonSSOMember._id, groupAdminUser._id],
  54. groupPlan: true,
  55. planCode: 'group_professional_10_enterprise',
  56. features: {
  57. groupSSO: true,
  58. },
  59. ssoConfig: ssoConfig._id,
  60. membersLimit: 10,
  61. })
  62. await subscription.ensureExists()
  63. const subscriptionId = subscription._id.toString()
  64. const enrollmentUrl = getEnrollmentUrl(subscriptionId)
  65. const internalProviderId = getProviderId(subscriptionId)
  66. if (SSOConfigValidated) {
  67. await linkGroupMember(
  68. memberUser.email,
  69. memberUser.password,
  70. subscriptionId,
  71. 'mock@email.com',
  72. useSettingsUKAMF
  73. )
  74. }
  75. const userHelper = new UserHelper()
  76. return {
  77. ssoConfig,
  78. internalProviderId,
  79. userIdAttribute,
  80. subscription,
  81. subscriptionId,
  82. groupAdminUser,
  83. memberUser,
  84. nonSSOMemberHelper,
  85. nonSSOMember,
  86. userHelper,
  87. enrollmentUrl,
  88. }
  89. }
  90. export async function linkGroupMember(
  91. userEmail,
  92. userPassword,
  93. groupId,
  94. externalUserId,
  95. usingSettingsUKAMF
  96. ) {
  97. const samlSettings = usingSettingsUKAMF
  98. ? Settings.saml.ukamf
  99. : Settings.saml.groupSSO
  100. // eslint-disable-next-line no-restricted-syntax
  101. const subscription = await SubscriptionModel.findById(groupId)
  102. .populate('ssoConfig')
  103. .exec()
  104. const userIdAttribute = subscription?.ssoConfig?.userIdAttribute
  105. const internalProviderId = getProviderId(groupId)
  106. const enrollmentUrl = getEnrollmentUrl(groupId)
  107. const userHelper = await UserHelper.loginUser(
  108. {
  109. email: userEmail,
  110. password: userPassword,
  111. },
  112. `/subscription/${groupId}/sso_enrollment`
  113. )
  114. const { headers } = await userHelper.fetch(enrollmentUrl, {
  115. method: 'POST',
  116. })
  117. if (
  118. !headers.get('location') ||
  119. !headers.get('location').includes(samlSettings.initPath)
  120. ) {
  121. throw new Error('invalid redirect when linking to group SSO')
  122. }
  123. const redirectTo = new URL(headers.get('location'))
  124. const initSSOResponse = await userHelper.fetch(redirectTo)
  125. // redirect to IdP
  126. const idpEntryPointUrl = new URL(initSSOResponse.headers.get('location'))
  127. const requestId = await SAMLHelper.getRequestId(idpEntryPointUrl)
  128. const response = await userHelper.fetch(samlSettings.path, {
  129. method: 'POST',
  130. body: new URLSearchParams({
  131. SAMLResponse: SAMLHelper.createMockSamlResponse({
  132. requestId,
  133. userIdAttribute,
  134. uniqueId: externalUserId,
  135. issuer: samlSettings.issuer,
  136. }),
  137. }),
  138. })
  139. if (
  140. response.status !== 302 &&
  141. response.headers.get('location').path !== '/project'
  142. ) {
  143. throw new Error('failed to link group SSO')
  144. }
  145. // ensure user linked
  146. const user = await UserGetter.promises.getUser(
  147. { email: userEmail },
  148. { samlIdentifiers: 1, enrollment: 1 }
  149. )
  150. const { enrollment, samlIdentifiers } = user
  151. const linkedToGroupSSO = samlIdentifiers.some(
  152. identifier => identifier.providerId === internalProviderId
  153. )
  154. const userIsEnrolledInSSO = enrollment.sso.some(
  155. sso => sso.groupId.toString() === groupId.toString()
  156. )
  157. if (!linkedToGroupSSO || !userIsEnrolledInSSO) {
  158. throw new Error('error setting up test user with group SSO linked')
  159. }
  160. return userHelper
  161. }
  162. export async function setConfigAndEnableSSO(
  163. subscriptionHelper,
  164. adminEmailPassword,
  165. config
  166. ) {
  167. config = config || {
  168. entryPoint: 'http://idp.example.com/entry_point',
  169. certificates: [SAML_TEST_CERT],
  170. userIdAttribute: 'email',
  171. userLastNameAttribute: 'lastName',
  172. }
  173. const { email, password } = adminEmailPassword
  174. const userHelper = await UserHelper.loginUser({
  175. email,
  176. password,
  177. })
  178. const createResponse = await userHelper.fetch(
  179. `/manage/groups/${subscriptionHelper._id}/settings/sso`,
  180. {
  181. method: 'POST',
  182. body: JSON.stringify(config),
  183. headers: {
  184. 'Content-Type': 'application/json',
  185. },
  186. }
  187. )
  188. if (createResponse.status !== 201) {
  189. throw new Error(
  190. `failed to set SSO config. Status = ${createResponse.status}`
  191. )
  192. }
  193. await subscriptionHelper.setValidatedSSO()
  194. const enableResponse = await userHelper.fetch(
  195. `/manage/groups/${subscriptionHelper._id}/settings/enableSSO`,
  196. { method: 'POST' }
  197. )
  198. if (enableResponse.status !== 200) {
  199. throw new Error(`failed to enable SSO. Status = ${enableResponse.status}`)
  200. }
  201. }
  202. export default {
  203. createGroupSSO,
  204. linkGroupMember,
  205. baseSsoConfig,
  206. setConfigAndEnableSSO,
  207. }