index.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import {
  2. checkChunkResponse,
  3. estimateSizeOfMultipartResponse,
  4. getMultipartBoundary,
  5. resolveMultiPartResponses,
  6. } from '../pdf-preview/util/pdf-caching'
  7. import getMeta from '../../utils/meta'
  8. import OError from '@overleaf/o-error'
  9. import { captureException } from '../../infrastructure/error-reporter'
  10. import { postJSON } from '../../infrastructure/fetch-json'
  11. import {
  12. isSplitTestEnabled,
  13. parseIntFromSplitTest,
  14. } from '../../utils/splitTestUtils'
  15. const MAX_CHECKS_PER_PAGE_LOAD = parseIntFromSplitTest(
  16. 'user-content-domain-access-check-max-checks',
  17. 3
  18. )
  19. const INITIAL_DELAY_MS = parseIntFromSplitTest(
  20. 'user-content-domain-access-check-delay',
  21. 30_000
  22. )
  23. const TIMEOUT_MS = 30_000
  24. const FULL_SIZE = 739
  25. const FULL_HASH =
  26. 'b7d25591c18da373709d3d88ddf5eeab0b5089359e580f051314fd8935df0b73'
  27. const CHUNKS = [
  28. {
  29. start: 0,
  30. end: 21,
  31. hash: 'd2ad9cbf1bc669646c0dfc43fa3167d30ab75077bb46bc9e3624b9e7e168abc2',
  32. },
  33. {
  34. start: 21,
  35. end: 42,
  36. hash: 'd6d110ec0f3f4e27a4050bc2be9c5552cc9092f86b74fec75072c2c9e8483454',
  37. },
  38. {
  39. start: 42,
  40. end: 64,
  41. hash: '8278914487a3a099c9af5aa22ed836d6587ca0beb7bf9a059fb0409667b3eb3d',
  42. },
  43. ]
  44. function pickZone() {
  45. const x = Math.random()
  46. switch (true) {
  47. case x > 0.66:
  48. return 'b'
  49. case x > 0.33:
  50. return 'c'
  51. default:
  52. return 'd'
  53. }
  54. }
  55. function arrayLikeToHex(a: Uint8Array) {
  56. return Array.from(a)
  57. .map(i => i.toString(16).padStart(2, '0'))
  58. .join('')
  59. }
  60. async function hashBody(body: ArrayBuffer) {
  61. const digest = await crypto.subtle.digest('SHA-256', body)
  62. return arrayLikeToHex(new Uint8Array(digest))
  63. }
  64. async function checkHash(
  65. res: Response,
  66. data: ArrayBuffer,
  67. expectedHash: string
  68. ) {
  69. const actualHash = await hashBody(data)
  70. if (actualHash !== expectedHash) {
  71. throw new OError('content hash mismatch', {
  72. actualHash,
  73. expectedHash,
  74. headers: Object.fromEntries(res.headers.entries()),
  75. })
  76. }
  77. }
  78. function randomHex(bytes: number) {
  79. const buf = new Uint8Array(bytes)
  80. crypto.getRandomValues(buf)
  81. return arrayLikeToHex(buf)
  82. }
  83. function genBuildId() {
  84. const date = Date.now().toString(16)
  85. const random = randomHex(8)
  86. return `${date}-${random}`
  87. }
  88. async function singleCheck(
  89. url: string,
  90. init: RequestInit,
  91. estimatedSize: number,
  92. expectedHash: string,
  93. chunks?: Array<any>
  94. ) {
  95. const ac = new AbortController()
  96. setTimeout(() => ac.abort(), TIMEOUT_MS)
  97. init.signal = ac.signal
  98. init.cache = 'no-store'
  99. const res = await fetch(url, init)
  100. checkChunkResponse(res, estimatedSize, init)
  101. const body = await res.arrayBuffer()
  102. if (chunks) {
  103. const boundary = getMultipartBoundary(res, chunks)
  104. const parts = resolveMultiPartResponses({
  105. file: { size: FULL_SIZE },
  106. chunks,
  107. data: new Uint8Array(body),
  108. boundary,
  109. metrics: {},
  110. })
  111. for (const part of parts) {
  112. await checkHash(res, part.data, part.chunk.hash)
  113. }
  114. } else {
  115. await checkHash(res, body, expectedHash)
  116. }
  117. }
  118. export async function checkUserContentDomainAccess(
  119. compileDomainOrigin: string
  120. ) {
  121. // Note: The ids are zero prefixed. No actual user/project uses these ids.
  122. // mongo-id 000000000000000000000000 -> 1970-01-01T00:00:00.000Z
  123. // mongo-id 000000010000000000000000 -> 1970-01-01T00:00:01.000Z
  124. // mongo-id 100000000000000000000000 -> 1978-07-04T21:24:16.000Z
  125. // This allows us to distinguish between check-traffic and regular output
  126. // traffic.
  127. const projectId = `0${randomHex(12).slice(1)}`
  128. const userId = `0${randomHex(12).slice(1)}`
  129. const buildId = genBuildId()
  130. const zone = pickZone()
  131. const urls = []
  132. if (getMeta('ol-user_id')) {
  133. // Logged-in user
  134. urls.push(
  135. `${compileDomainOrigin}/zone/${zone}/project/${projectId}/user/${userId}/build/${buildId}/output/output.pdf`
  136. )
  137. } else {
  138. // Anonymous user
  139. urls.push(
  140. `${compileDomainOrigin}/zone/${zone}/project/${projectId}/build/${buildId}/output/output.pdf`
  141. )
  142. }
  143. const cases = []
  144. for (const url of urls) {
  145. // full download
  146. cases.push({
  147. url,
  148. init: {},
  149. estimatedSize: FULL_SIZE,
  150. hash: FULL_HASH,
  151. })
  152. // range request
  153. const chunk = CHUNKS[0]
  154. cases.push({
  155. url,
  156. init: {
  157. headers: {
  158. Range: `bytes=${chunk.start}-${chunk.end - 1}`,
  159. },
  160. },
  161. estimatedSize: chunk.end - chunk.start,
  162. hash: chunk.hash,
  163. })
  164. // multipart request
  165. cases.push({
  166. url,
  167. init: {
  168. headers: {
  169. Range: `bytes=${CHUNKS.map(c => `${c.start}-${c.end - 1}`).join(
  170. ','
  171. )}`,
  172. },
  173. },
  174. estimatedSize: estimateSizeOfMultipartResponse(CHUNKS),
  175. hash: chunk.hash,
  176. chunks: CHUNKS,
  177. })
  178. }
  179. let failed = 0
  180. let ignoreResult = false
  181. const epochBeforeCheck = networkEpoch
  182. await Promise.all(
  183. cases.map(async ({ url, init, estimatedSize, hash, chunks }) => {
  184. try {
  185. await singleCheck(url, init, estimatedSize, hash, chunks)
  186. } catch (err: any) {
  187. if (!navigator.onLine || epochBeforeCheck !== networkEpoch) {
  188. // It is very likely that the request failed because we are offline or
  189. // the network connection changed just now.
  190. ignoreResult = true
  191. }
  192. if (ignoreResult) return
  193. failed++
  194. OError.tag(err, 'user-content-domain-access-check failed', {
  195. url,
  196. init,
  197. })
  198. if (
  199. isSplitTestEnabled('report-user-content-domain-access-check-error')
  200. ) {
  201. captureException(err, {
  202. tags: { compileDomain: new URL(compileDomainOrigin).hostname },
  203. })
  204. } else {
  205. console.error(OError.getFullStack(err), OError.getFullInfo(err))
  206. }
  207. }
  208. })
  209. )
  210. if (ignoreResult) return false
  211. try {
  212. await postJSON('/record-user-content-domain-access-check-result', {
  213. body: {
  214. failed,
  215. succeeded: cases.length - failed,
  216. isOldDomain:
  217. compileDomainOrigin === getMeta('ol-fallbackCompileDomain'),
  218. },
  219. })
  220. } catch (e) {}
  221. return failed === 0
  222. }
  223. let accessCheckPassed = false
  224. export function userContentDomainAccessCheckPassed() {
  225. return accessCheckPassed
  226. }
  227. let networkEpoch = performance.now()
  228. window.addEventListener('offline', () => {
  229. // We are offline. Abort any scheduled check.
  230. clearTimeout(lastScheduledCheck)
  231. accessCheckPassed = false
  232. networkEpoch = performance.now()
  233. })
  234. window.addEventListener('online', () => {
  235. // We are online again. Schedule another check for this network.
  236. accessCheckPassed = false
  237. networkEpoch = performance.now()
  238. scheduleUserContentDomainAccessCheck()
  239. })
  240. try {
  241. // Note: navigator.connection is not available on Firefox and Safari.
  242. // Docs: https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
  243. navigator.connection.addEventListener('change', () => {
  244. // The network changed. Schedule another check for it.
  245. accessCheckPassed = false
  246. networkEpoch = performance.now()
  247. scheduleUserContentDomainAccessCheck()
  248. })
  249. } catch (e) {}
  250. let lastScheduledCheck: number
  251. let remainingChecks = MAX_CHECKS_PER_PAGE_LOAD
  252. export function scheduleUserContentDomainAccessCheck() {
  253. if (!isSplitTestEnabled('user-content-domain-access-check')) return
  254. clearTimeout(lastScheduledCheck)
  255. const networkEpochBeforeDelay = networkEpoch
  256. lastScheduledCheck = window.setTimeout(() => {
  257. if (!window.navigator.onLine || networkEpochBeforeDelay !== networkEpoch) {
  258. // Must be online for more than INITIAL_DELAY_MS before we check.
  259. // We want to avoid false-positives from flaky network connections.
  260. // Try again in INITIAL_DELAY_MS.
  261. return scheduleUserContentDomainAccessCheck()
  262. }
  263. if (accessCheckPassed) return
  264. if (remainingChecks === 0) {
  265. recordMaxAccessChecksHit()
  266. }
  267. if (remainingChecks-- <= 0) return
  268. if (isSplitTestEnabled('access-check-for-old-compile-domain')) {
  269. checkUserContentDomainAccess(getMeta('ol-fallbackCompileDomain')).catch(
  270. () => {}
  271. )
  272. }
  273. checkUserContentDomainAccess(getMeta('ol-compilesUserContentDomain'))
  274. .then(ok => {
  275. accessCheckPassed = ok
  276. })
  277. .catch(err => {
  278. captureException(err)
  279. })
  280. }, INITIAL_DELAY_MS)
  281. }
  282. function recordMaxAccessChecksHit() {
  283. postJSON('/record-user-content-domain-max-access-checks-hit').catch(() => {})
  284. }