SAMLHelper.mjs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import fs from 'node:fs'
  2. import path from 'node:path'
  3. import { SignedXml } from 'xml-crypto'
  4. import { SamlLog } from '../../../../app/src/models/SamlLog.js'
  5. import { expect } from 'chai'
  6. import zlib from 'node:zlib'
  7. import { fileURLToPath } from 'node:url'
  8. import xml2js from 'xml2js'
  9. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  10. const samlDataDefaults = {
  11. firstName: 'first-name',
  12. hasEntitlement: 'Y',
  13. issuer: 'Overleaf',
  14. lastName: 'last-name',
  15. requestId: 'dummy-request-id',
  16. }
  17. function samlValue(val) {
  18. if (!Array.isArray(val)) {
  19. val = [val]
  20. }
  21. return val
  22. .map(
  23. v =>
  24. `<saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">${v}</saml:AttributeValue>`
  25. )
  26. .join('')
  27. }
  28. function makeAttribute(attribute, value) {
  29. if (!value) {
  30. return ''
  31. }
  32. return `<saml:AttributeStatement>
  33. <saml:Attribute Name="${attribute}" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
  34. ${samlValue(value)}
  35. </saml:Attribute>
  36. </saml:AttributeStatement>`
  37. }
  38. function createMockSamlAssertion(samlData = {}, opts = {}) {
  39. const {
  40. email,
  41. firstName,
  42. hasEntitlement,
  43. issuer,
  44. lastName,
  45. uniqueId,
  46. requestId,
  47. } = {
  48. ...samlDataDefaults,
  49. ...samlData,
  50. }
  51. const { signedAssertion = true } = opts
  52. const userIdAttributeName = samlData.userIdAttribute || 'uniqueId'
  53. const userIdAttribute = `<saml:AttributeStatement>
  54. <saml:Attribute Name="${userIdAttributeName}" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
  55. <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">${uniqueId}</saml:AttributeValue>
  56. </saml:Attribute>
  57. </saml:AttributeStatement>`
  58. const userIdAttributeLegacy =
  59. samlData.userIdAttributeLegacy && samlData.uniqueIdLegacy
  60. ? `<saml:AttributeStatement><saml:Attribute Name="${samlData.userIdAttributeLegacy}" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"><saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">${samlData.uniqueIdLegacy}</saml:AttributeValue></saml:Attribute></saml:AttributeStatement>`
  61. : ''
  62. const nameId =
  63. userIdAttributeName && userIdAttributeName !== 'nameID'
  64. ? `<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">mock@email.com</saml:NameID>`
  65. : ''
  66. const samlAssertion = `<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="t835VaiI1fph1yk8yhdD4OtyBQ4" IssueInstant="2018-08-09T08:56:30.126Z" Version="2.0">
  67. <saml:Issuer>${issuer}</saml:Issuer>
  68. <saml:Subject>
  69. ${nameId}
  70. <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
  71. <saml:SubjectConfirmationData Recipient="*******" NotOnOrAfter="2028-08-09T09:01:30.126Z" InResponseTo="${requestId}" />
  72. </saml:SubjectConfirmation>
  73. </saml:Subject>
  74. <saml:Conditions NotBefore="2008-08-09T08:51:30.126Z" NotOnOrAfter="2028-08-09T09:01:30.126Z">
  75. <saml:AudienceRestriction>
  76. <saml:Audience>${issuer}</saml:Audience>
  77. </saml:AudienceRestriction>
  78. </saml:Conditions>
  79. <saml:AuthnStatement SessionIndex="t835VaiI1fph1yk8yhdD4OtyBQ4" AuthnInstant="2018-08-09T08:56:30.118Z">
  80. <saml:AuthnContext>
  81. <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
  82. </saml:AuthnContext>
  83. </saml:AuthnStatement>
  84. ${makeAttribute('email', email)}
  85. ${makeAttribute('firstName', firstName)}
  86. <saml:AttributeStatement>
  87. <saml:Attribute Name="hasEntitlement" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
  88. <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">${hasEntitlement}</saml:AttributeValue>
  89. </saml:Attribute>
  90. </saml:AttributeStatement>
  91. <saml:AttributeStatement>
  92. <saml:Attribute Name="issuer" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
  93. <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">${issuer}</saml:AttributeValue>
  94. </saml:Attribute>
  95. </saml:AttributeStatement>
  96. ${makeAttribute('lastName', lastName)}
  97. ${userIdAttribute}
  98. ${userIdAttributeLegacy}
  99. </saml:Assertion>`
  100. if (!signedAssertion) {
  101. return samlAssertion
  102. }
  103. const sig = new SignedXml()
  104. sig.addReference(
  105. "//*[local-name(.)='Assertion']",
  106. [
  107. 'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
  108. 'http://www.w3.org/2001/10/xml-exc-c14n#',
  109. ],
  110. 'http://www.w3.org/2000/09/xmldsig#sha1'
  111. )
  112. sig.signingKey = fs.readFileSync(
  113. path.resolve(__dirname, '../../files/saml-key.pem'),
  114. 'utf8'
  115. )
  116. sig.computeSignature(samlAssertion)
  117. return sig.getSignedXml()
  118. }
  119. function createMockSamlResponse(samlData = {}, opts = {}) {
  120. const { issuer, requestId } = {
  121. ...samlDataDefaults,
  122. ...samlData,
  123. }
  124. const { signedResponse = true } = opts
  125. const samlAssertion = createMockSamlAssertion(samlData, opts)
  126. let samlResponse = `
  127. <?xml version="1.0" encoding="UTF-8"?>
  128. <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Version="2.0" ID="WQMXUw8BBp4_XWzcuKgaN5tmxpT" IssueInstant="2018-08-09T08:56:30.106Z" InResponseTo="${requestId}">
  129. <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${issuer}</saml:Issuer>
  130. <samlp:Status>
  131. <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
  132. </samlp:Status>
  133. ${samlAssertion}
  134. </samlp:Response>
  135. `
  136. if (signedResponse) {
  137. const sig = new SignedXml()
  138. sig.addReference(
  139. "//*[local-name(.)='Response']",
  140. [
  141. 'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
  142. 'http://www.w3.org/2001/10/xml-exc-c14n#',
  143. ],
  144. 'http://www.w3.org/2000/09/xmldsig#sha1'
  145. )
  146. sig.signingKey = fs.readFileSync(
  147. path.resolve(__dirname, '../../files/saml-key.pem'),
  148. 'utf8'
  149. )
  150. sig.computeSignature(samlResponse)
  151. samlResponse = sig.getSignedXml()
  152. }
  153. return Buffer.from(samlResponse).toString('base64')
  154. }
  155. function samlUniversity(config = {}) {
  156. return {
  157. hostname: 'example-sso.com',
  158. sso_cert: fs
  159. .readFileSync(
  160. path.resolve(__dirname, '../../files/saml-cert.crt'),
  161. 'utf8'
  162. )
  163. .replace(/-----BEGIN CERTIFICATE-----/, '')
  164. .replace(/-----END CERTIFICATE-----/, '')
  165. .replace(/\n/g, ''),
  166. sso_enabled: true,
  167. sso_entry_point: 'http://example-sso.com/saml',
  168. sso_entity_id: 'http://example-sso.com/saml/idp',
  169. university_id: 9999,
  170. university_name: 'Example University',
  171. sso_user_email_attribute: 'email',
  172. sso_user_first_name_attribute: 'firstName',
  173. sso_user_id_attribute: 'uniqueId',
  174. sso_user_last_name_attribute: 'lastName',
  175. sso_license_entitlement_attribute: 'hasEntitlement',
  176. sso_license_entitlement_matcher: 'Y',
  177. sso_signature_algorithm: 'sha256',
  178. ...config,
  179. }
  180. }
  181. async function getParseAndDoChecksForSamlLogs(numberOfLog) {
  182. const logs = await SamlLog.find({}, {})
  183. .sort({ $natural: -1 })
  184. .limit(numberOfLog || 1)
  185. .exec()
  186. logs.forEach(log => {
  187. expect(log.sessionId).to.exist
  188. expect(log.sessionId.length).to.equal(8) // not full session ID
  189. expect(log.createdAt).to.exist
  190. expect(log.jsonData).to.exist
  191. log.parsedJsonData = JSON.parse(log.jsonData)
  192. if (log.samlAssertion) {
  193. log.parsedSamlAssertion = JSON.parse(log.samlAssertion)
  194. }
  195. })
  196. return logs
  197. }
  198. /**
  199. * Parses a SAML request from a redirect URI.
  200. *
  201. * @param {URL} redirectUri - The redirect URI containing the SAML request.
  202. * @returns {Promise<Object>} - A promise that resolves to the parsed SAML request object.
  203. */
  204. async function parseSamlRequest(redirectUri) {
  205. const decoded = redirectUri.searchParams.get('SAMLRequest')
  206. const base64Decoded = Buffer.from(decoded, 'base64')
  207. const inflated = zlib.inflateRawSync(base64Decoded)
  208. return xml2js.parseStringPromise(inflated.toString('utf8'))
  209. }
  210. /**
  211. * Parses the SAML request from the given redirect URI and returns the request ID.
  212. * @param {URL} redirectUri - The redirect URI containing the SAML request.
  213. * @returns {Promise<string>} - A Promise that resolves to the request ID.
  214. */
  215. async function getRequestId(redirectUri) {
  216. const samlRequest = await parseSamlRequest(redirectUri)
  217. return samlRequest['samlp:AuthnRequest'].$.ID
  218. }
  219. const SAMLHelper = {
  220. createMockSamlResponse,
  221. samlUniversity,
  222. getParseAndDoChecksForSamlLogs,
  223. parseSamlRequest,
  224. getRequestId,
  225. }
  226. export default SAMLHelper