CompileController.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. let CompileController
  2. const OError = require('@overleaf/o-error')
  3. const Metrics = require('@overleaf/metrics')
  4. const ProjectGetter = require('../Project/ProjectGetter')
  5. const CompileManager = require('./CompileManager')
  6. const ClsiManager = require('./ClsiManager')
  7. const logger = require('@overleaf/logger')
  8. const request = require('request')
  9. const Settings = require('@overleaf/settings')
  10. const SessionManager = require('../Authentication/SessionManager')
  11. const RateLimiter = require('../../infrastructure/RateLimiter')
  12. const ClsiCookieManager = require('./ClsiCookieManager')(
  13. Settings.apis.clsi?.backendGroupName
  14. )
  15. const Path = require('path')
  16. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  17. const COMPILE_TIMEOUT_MS = 10 * 60 * 1000
  18. function getImageNameForProject(projectId, callback) {
  19. ProjectGetter.getProject(projectId, { imageName: 1 }, (err, project) => {
  20. if (err) return callback(err)
  21. if (!project) return callback(new Error('project not found'))
  22. callback(null, project.imageName)
  23. })
  24. }
  25. module.exports = CompileController = {
  26. compile(req, res, next) {
  27. res.setTimeout(COMPILE_TIMEOUT_MS)
  28. const projectId = req.params.Project_id
  29. const isAutoCompile = !!req.query.auto_compile
  30. const enablePdfCaching = !!req.query.enable_pdf_caching
  31. const fileLineErrors = !!req.query.file_line_errors
  32. const userId = SessionManager.getLoggedInUserId(req.session)
  33. const options = {
  34. isAutoCompile,
  35. enablePdfCaching,
  36. fileLineErrors,
  37. }
  38. if (req.body.rootDoc_id) {
  39. options.rootDoc_id = req.body.rootDoc_id
  40. } else if (
  41. req.body.settingsOverride &&
  42. req.body.settingsOverride.rootDoc_id
  43. ) {
  44. // Can be removed after deploy
  45. options.rootDoc_id = req.body.settingsOverride.rootDoc_id
  46. }
  47. if (req.body.compiler) {
  48. options.compiler = req.body.compiler
  49. }
  50. if (req.body.draft) {
  51. options.draft = req.body.draft
  52. }
  53. if (['validate', 'error', 'silent'].includes(req.body.check)) {
  54. options.check = req.body.check
  55. }
  56. if (req.body.incrementalCompilesEnabled) {
  57. options.incrementalCompilesEnabled = true
  58. }
  59. CompileManager.compile(
  60. projectId,
  61. userId,
  62. options,
  63. (
  64. error,
  65. status,
  66. outputFiles,
  67. clsiServerId,
  68. limits,
  69. validationProblems,
  70. stats,
  71. timings,
  72. outputUrlPrefix
  73. ) => {
  74. if (error) {
  75. Metrics.inc('compile-error')
  76. return next(error)
  77. }
  78. Metrics.inc('compile-status', 1, { status })
  79. SplitTestHandler.getAssignment(
  80. req,
  81. res,
  82. 'zonal-clsi-lb-downloads',
  83. {},
  84. (_err, assignment) => {
  85. if (Array.isArray(outputFiles)) {
  86. // NOTE: keep this around as a safeguard for rolling back clsi.
  87. outputFiles.forEach(file => {
  88. file.url = file.url.replace(/^\/zone\/\w/, '')
  89. })
  90. }
  91. let pdfDownloadDomain = Settings.pdfDownloadDomain
  92. if (
  93. assignment?.variant === 'zonal' &&
  94. pdfDownloadDomain &&
  95. outputUrlPrefix
  96. ) {
  97. pdfDownloadDomain += outputUrlPrefix
  98. }
  99. res.json({
  100. status,
  101. outputFiles,
  102. compileGroup: limits?.compileGroup,
  103. clsiServerId,
  104. validationProblems,
  105. stats,
  106. timings,
  107. pdfDownloadDomain,
  108. })
  109. }
  110. )
  111. }
  112. )
  113. },
  114. stopCompile(req, res, next) {
  115. const projectId = req.params.Project_id
  116. const userId = SessionManager.getLoggedInUserId(req.session)
  117. CompileManager.stopCompile(projectId, userId, function (error) {
  118. if (error) {
  119. return next(error)
  120. }
  121. res.sendStatus(200)
  122. })
  123. },
  124. // Used for submissions through the public API
  125. compileSubmission(req, res, next) {
  126. res.setTimeout(COMPILE_TIMEOUT_MS)
  127. const submissionId = req.params.submission_id
  128. const options = {}
  129. if (req.body?.rootResourcePath != null) {
  130. options.rootResourcePath = req.body.rootResourcePath
  131. }
  132. if (req.body?.compiler) {
  133. options.compiler = req.body.compiler
  134. }
  135. if (req.body?.draft) {
  136. options.draft = req.body.draft
  137. }
  138. if (['validate', 'error', 'silent'].includes(req.body?.check)) {
  139. options.check = req.body.check
  140. }
  141. options.compileGroup =
  142. req.body?.compileGroup || Settings.defaultFeatures.compileGroup
  143. options.timeout =
  144. req.body?.timeout || Settings.defaultFeatures.compileTimeout
  145. ClsiManager.sendExternalRequest(
  146. submissionId,
  147. req.body,
  148. options,
  149. function (error, status, outputFiles, clsiServerId, validationProblems) {
  150. if (error) {
  151. return next(error)
  152. }
  153. res.json({
  154. status,
  155. outputFiles,
  156. clsiServerId,
  157. validationProblems,
  158. })
  159. }
  160. )
  161. },
  162. _compileAsUser(req, callback) {
  163. // callback with userId if per-user, undefined otherwise
  164. if (!Settings.disablePerUserCompiles) {
  165. const userId = SessionManager.getLoggedInUserId(req.session)
  166. callback(null, userId)
  167. } else {
  168. callback()
  169. }
  170. }, // do a per-project compile, not per-user
  171. _downloadAsUser(req, callback) {
  172. // callback with userId if per-user, undefined otherwise
  173. if (!Settings.disablePerUserCompiles) {
  174. const userId = SessionManager.getLoggedInUserId(req.session)
  175. callback(null, userId)
  176. } else {
  177. callback()
  178. }
  179. }, // do a per-project compile, not per-user
  180. downloadPdf(req, res, next) {
  181. Metrics.inc('pdf-downloads')
  182. const projectId = req.params.Project_id
  183. const isPdfjsPartialDownload = req.query?.pdfng
  184. const rateLimit = function (callback) {
  185. if (isPdfjsPartialDownload) {
  186. callback(null, true)
  187. } else {
  188. const rateLimitOpts = {
  189. endpointName: 'full-pdf-download',
  190. throttle: 1000,
  191. subjectName: req.ip,
  192. timeInterval: 60 * 60,
  193. }
  194. RateLimiter.addCount(rateLimitOpts, callback)
  195. }
  196. }
  197. ProjectGetter.getProject(projectId, { name: 1 }, function (err, project) {
  198. if (err) {
  199. return next(err)
  200. }
  201. res.contentType('application/pdf')
  202. const filename = `${CompileController._getSafeProjectName(project)}.pdf`
  203. if (req.query.popupDownload) {
  204. res.setContentDisposition('attachment', { filename })
  205. } else {
  206. res.setContentDisposition('', { filename })
  207. }
  208. rateLimit(function (err, canContinue) {
  209. if (err) {
  210. logger.err({ err }, 'error checking rate limit for pdf download')
  211. res.sendStatus(500)
  212. } else if (!canContinue) {
  213. logger.debug(
  214. { projectId, ip: req.ip },
  215. 'rate limit hit downloading pdf'
  216. )
  217. res.sendStatus(500)
  218. } else {
  219. CompileController._downloadAsUser(req, function (error, userId) {
  220. if (error) {
  221. return next(error)
  222. }
  223. const url = CompileController._getFileUrl(
  224. projectId,
  225. userId,
  226. req.params.build_id,
  227. 'output.pdf'
  228. )
  229. CompileController.proxyToClsi(projectId, url, req, res, next)
  230. })
  231. }
  232. })
  233. })
  234. },
  235. _getSafeProjectName(project) {
  236. const wordRegExp = /\W/g
  237. const safeProjectName = project.name.replace(wordRegExp, '_')
  238. return safeProjectName
  239. },
  240. deleteAuxFiles(req, res, next) {
  241. const projectId = req.params.Project_id
  242. const { clsiserverid } = req.query
  243. CompileController._compileAsUser(req, function (error, userId) {
  244. if (error) {
  245. return next(error)
  246. }
  247. CompileManager.deleteAuxFiles(
  248. projectId,
  249. userId,
  250. clsiserverid,
  251. function (error) {
  252. if (error) {
  253. return next(error)
  254. }
  255. res.sendStatus(200)
  256. }
  257. )
  258. })
  259. },
  260. // this is only used by templates, so is not called with a userId
  261. compileAndDownloadPdf(req, res, next) {
  262. const projectId = req.params.project_id
  263. // pass userId as null, since templates are an "anonymous" compile
  264. CompileManager.compile(projectId, null, {}, function (err) {
  265. if (err) {
  266. logger.err(
  267. { err, projectId },
  268. 'something went wrong compile and downloading pdf'
  269. )
  270. res.sendStatus(500)
  271. }
  272. const url = `/project/${projectId}/output/output.pdf`
  273. CompileController.proxyToClsi(projectId, url, req, res, next)
  274. })
  275. },
  276. getFileFromClsi(req, res, next) {
  277. const projectId = req.params.Project_id
  278. CompileController._downloadAsUser(req, function (error, userId) {
  279. if (error) {
  280. return next(error)
  281. }
  282. const url = CompileController._getFileUrl(
  283. projectId,
  284. userId,
  285. req.params.build_id,
  286. req.params.file
  287. )
  288. CompileController.proxyToClsi(projectId, url, req, res, next)
  289. })
  290. },
  291. getFileFromClsiWithoutUser(req, res, next) {
  292. const submissionId = req.params.submission_id
  293. const url = CompileController._getFileUrl(
  294. submissionId,
  295. null,
  296. req.params.build_id,
  297. req.params.file
  298. )
  299. const limits = {
  300. compileGroup:
  301. req.body?.compileGroup ||
  302. req.query?.compileGroup ||
  303. Settings.defaultFeatures.compileGroup,
  304. }
  305. CompileController.proxyToClsiWithLimits(
  306. submissionId,
  307. url,
  308. limits,
  309. req,
  310. res,
  311. next
  312. )
  313. },
  314. // compute a GET file url for a given project, user (optional), build (optional) and file
  315. _getFileUrl(projectId, userId, buildId, file) {
  316. let url
  317. if (userId != null && buildId != null) {
  318. url = `/project/${projectId}/user/${userId}/build/${buildId}/output/${file}`
  319. } else if (userId != null) {
  320. url = `/project/${projectId}/user/${userId}/output/${file}`
  321. } else if (buildId != null) {
  322. url = `/project/${projectId}/build/${buildId}/output/${file}`
  323. } else {
  324. url = `/project/${projectId}/output/${file}`
  325. }
  326. return url
  327. },
  328. // compute a POST url for a project, user (optional) and action
  329. _getUrl(projectId, userId, action) {
  330. let path = `/project/${projectId}`
  331. if (userId != null) {
  332. path += `/user/${userId}`
  333. }
  334. return `${path}/${action}`
  335. },
  336. proxySyncPdf(req, res, next) {
  337. const projectId = req.params.Project_id
  338. const { page, h, v } = req.query
  339. if (!page?.match(/^\d+$/)) {
  340. return next(new Error('invalid page parameter'))
  341. }
  342. if (!h?.match(/^-?\d+\.\d+$/)) {
  343. return next(new Error('invalid h parameter'))
  344. }
  345. if (!v?.match(/^-?\d+\.\d+$/)) {
  346. return next(new Error('invalid v parameter'))
  347. }
  348. // whether this request is going to a per-user container
  349. CompileController._compileAsUser(req, function (error, userId) {
  350. if (error) {
  351. return next(error)
  352. }
  353. getImageNameForProject(projectId, (error, imageName) => {
  354. if (error) return next(error)
  355. const url = CompileController._getUrl(projectId, userId, 'sync/pdf')
  356. const destination = { url, qs: { page, h, v, imageName } }
  357. CompileController.proxyToClsi(projectId, destination, req, res, next)
  358. })
  359. })
  360. },
  361. proxySyncCode(req, res, next) {
  362. const projectId = req.params.Project_id
  363. const { file, line, column } = req.query
  364. if (file == null) {
  365. return next(new Error('missing file parameter'))
  366. }
  367. // Check that we are dealing with a simple file path (this is not
  368. // strictly needed because synctex uses this parameter as a label
  369. // to look up in the synctex output, and does not open the file
  370. // itself). Since we have valid synctex paths like foo/./bar we
  371. // allow those by replacing /./ with /
  372. const testPath = file.replace('/./', '/')
  373. if (Path.resolve('/', testPath) !== `/${testPath}`) {
  374. return next(new Error('invalid file parameter'))
  375. }
  376. if (!line?.match(/^\d+$/)) {
  377. return next(new Error('invalid line parameter'))
  378. }
  379. if (!column?.match(/^\d+$/)) {
  380. return next(new Error('invalid column parameter'))
  381. }
  382. CompileController._compileAsUser(req, function (error, userId) {
  383. if (error) {
  384. return next(error)
  385. }
  386. getImageNameForProject(projectId, (error, imageName) => {
  387. if (error) return next(error)
  388. const url = CompileController._getUrl(projectId, userId, 'sync/code')
  389. const destination = { url, qs: { file, line, column, imageName } }
  390. CompileController.proxyToClsi(projectId, destination, req, res, next)
  391. })
  392. })
  393. },
  394. proxyToClsi(projectId, url, req, res, next) {
  395. if (req.query?.compileGroup) {
  396. CompileController.proxyToClsiWithLimits(
  397. projectId,
  398. url,
  399. { compileGroup: req.query.compileGroup },
  400. req,
  401. res,
  402. next
  403. )
  404. } else {
  405. CompileManager.getProjectCompileLimits(
  406. projectId,
  407. function (error, limits) {
  408. if (error) {
  409. return next(error)
  410. }
  411. CompileController.proxyToClsiWithLimits(
  412. projectId,
  413. url,
  414. limits,
  415. req,
  416. res,
  417. next
  418. )
  419. }
  420. )
  421. }
  422. },
  423. proxyToClsiWithLimits(projectId, url, limits, req, res, next) {
  424. _getPersistenceOptions(
  425. req,
  426. projectId,
  427. limits.compileGroup,
  428. (err, persistenceOptions) => {
  429. let qs
  430. if (err) {
  431. OError.tag(err, 'error getting cookie jar for clsi request')
  432. return next(err)
  433. }
  434. // expand any url parameter passed in as {url:..., qs:...}
  435. if (typeof url === 'object') {
  436. ;({ url, qs } = url)
  437. }
  438. const compilerUrl = Settings.apis.clsi.url
  439. url = `${compilerUrl}${url}`
  440. const oneMinute = 60 * 1000
  441. // the base request
  442. const options = {
  443. url,
  444. method: req.method,
  445. timeout: oneMinute,
  446. ...persistenceOptions,
  447. }
  448. // add any provided query string
  449. if (qs != null) {
  450. options.qs = Object.assign(options.qs || {}, qs)
  451. }
  452. // if we have a build parameter, pass it through to the clsi
  453. if (req.query?.pdfng && req.query?.build != null) {
  454. // only for new pdf viewer
  455. if (options.qs == null) {
  456. options.qs = {}
  457. }
  458. options.qs.build = req.query.build
  459. }
  460. // if we are byte serving pdfs, pass through If-* and Range headers
  461. // do not send any others, there's a proxying loop if Host: is passed!
  462. if (req.query?.pdfng) {
  463. const newHeaders = {}
  464. for (const h in req.headers) {
  465. if (/^(If-|Range)/i.test(h)) {
  466. newHeaders[h] = req.headers[h]
  467. }
  468. }
  469. options.headers = newHeaders
  470. }
  471. const proxy = request(options)
  472. proxy.pipe(res)
  473. proxy.on('error', error =>
  474. logger.warn({ err: error, url }, 'CLSI proxy error')
  475. )
  476. }
  477. )
  478. },
  479. wordCount(req, res, next) {
  480. const projectId = req.params.Project_id
  481. const file = req.query.file || false
  482. const { clsiserverid } = req.query
  483. CompileController._compileAsUser(req, function (error, userId) {
  484. if (error) {
  485. return next(error)
  486. }
  487. CompileManager.wordCount(
  488. projectId,
  489. userId,
  490. file,
  491. clsiserverid,
  492. function (error, body) {
  493. if (error) {
  494. return next(error)
  495. }
  496. res.json(body)
  497. }
  498. )
  499. })
  500. },
  501. }
  502. function _getPersistenceOptions(req, projectId, compileGroup, callback) {
  503. const { clsiserverid } = req.query
  504. const userId = SessionManager.getLoggedInUserId(req)
  505. if (clsiserverid && typeof clsiserverid === 'string') {
  506. callback(null, { qs: { clsiserverid, compileGroup } })
  507. } else {
  508. ClsiCookieManager.getCookieJar(
  509. projectId,
  510. userId,
  511. compileGroup,
  512. (err, jar) => {
  513. callback(err, { jar })
  514. }
  515. )
  516. }
  517. }