git-bridge.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import { v4 as uuid } from 'uuid'
  2. import { isExcludedBySharding, startWith } from './helpers/config'
  3. import { ensureUserExists, login } from './helpers/login'
  4. import {
  5. createProject,
  6. enableLinkSharing,
  7. openProjectByName,
  8. openProjectViaLinkSharingAsUser,
  9. shareProjectByEmailAndAcceptInviteViaDash,
  10. } from './helpers/project'
  11. import git from 'isomorphic-git'
  12. import http from 'isomorphic-git/http/web'
  13. import LightningFS from '@isomorphic-git/lightning-fs'
  14. import { throttledRecompile } from './helpers/compile'
  15. const USER = 'user@example.com'
  16. describe('git-bridge', function () {
  17. const ENABLED_VARS = {
  18. GIT_BRIDGE_ENABLED: 'true',
  19. GIT_BRIDGE_HOST: 'git-bridge',
  20. GIT_BRIDGE_PORT: '8000',
  21. V1_HISTORY_URL: 'http://sharelatex:3100/api',
  22. }
  23. function gitURL(projectId: string) {
  24. const url = new URL(Cypress.config().baseUrl!)
  25. url.username = 'git'
  26. url.pathname = `/git/${projectId}`
  27. return url
  28. }
  29. describe('enabled in Server Pro', function () {
  30. if (isExcludedBySharding('PRO_CUSTOM_1')) return
  31. startWith({
  32. pro: true,
  33. vars: ENABLED_VARS,
  34. })
  35. ensureUserExists({ email: USER })
  36. function clearAllTokens() {
  37. cy.findAllByRole('button', { name: 'Remove' })
  38. .not('[disabled]')
  39. .each($button => {
  40. cy.wrap($button).click()
  41. cy.findByRole('button', { name: 'Delete token' }).click()
  42. })
  43. cy.findByRole('dialog').should('not.exist')
  44. }
  45. function maybeClearAllTokens() {
  46. cy.visit('/user/settings')
  47. cy.findByRole('heading', { name: 'Git integration' })
  48. cy.get('button')
  49. .contains(/Generate token|Add another token/)
  50. .then(btn => {
  51. if (btn.text() === 'Add another token') {
  52. clearAllTokens()
  53. }
  54. })
  55. }
  56. beforeEach(function () {
  57. login(USER)
  58. })
  59. it('should render the git-bridge UI in the settings', () => {
  60. maybeClearAllTokens()
  61. cy.visit('/user/settings')
  62. cy.findByRole('heading', { name: 'Git integration' })
  63. cy.findByRole('button', {
  64. name: 'Git integration Generate token',
  65. }).click()
  66. cy.findByLabelText('Git authentication token')
  67. .contains(/olp_[a-zA-Z0-9]{16}/)
  68. .then(el => el.text())
  69. .as('newToken')
  70. cy.findAllByText('Close').last().click()
  71. cy.get('@newToken').then(token => {
  72. // There can be more than one token with the same prefix when retrying
  73. cy.findAllByText(
  74. `${token.slice(0, 'olp_1234'.length)}${'*'.repeat(12)}`
  75. ).should('have.length.at.least', 1)
  76. })
  77. cy.findByRole('button', {
  78. name: 'Git integration Generate token',
  79. }).should('not.exist')
  80. cy.findByRole('button', { name: 'Add another token' }).should('exist')
  81. clearAllTokens()
  82. cy.findByRole('button', {
  83. name: 'Git integration Generate token',
  84. }).should('exist')
  85. cy.findByRole('button', { name: 'Add another token' }).should('not.exist')
  86. })
  87. it('should render the git-bridge UI in the editor', function () {
  88. maybeClearAllTokens()
  89. createProject('git').as('projectId')
  90. cy.findByRole('navigation', {
  91. name: 'Project actions',
  92. })
  93. .findByRole('button', { name: 'Menu' })
  94. .click()
  95. cy.findByTestId('left-menu').within(() => {
  96. cy.findByRole('heading', { name: 'Sync' })
  97. cy.findByRole('button', { name: 'Git' }).click()
  98. })
  99. cy.findByTestId('git-bridge-modal').within(() => {
  100. cy.get('@projectId').then(id => {
  101. cy.findByLabelText('Git clone project command').contains(
  102. `git clone ${gitURL(id.toString())}`
  103. )
  104. })
  105. cy.findByRole('button', {
  106. name: 'Generate token',
  107. }).click()
  108. cy.findByLabelText('Git authentication token').contains(
  109. /olp_[a-zA-Z0-9]{16}/
  110. )
  111. })
  112. // Re-open
  113. cy.url().then(url => cy.visit(url))
  114. cy.findByRole('navigation', {
  115. name: 'Project actions',
  116. })
  117. .findByRole('button', { name: 'Menu' })
  118. .click()
  119. cy.findByTestId('left-menu').within(() => {
  120. cy.findByRole('button', { name: 'Git' }).click()
  121. })
  122. cy.findByTestId('git-bridge-modal').within(() => {
  123. cy.get('@projectId').then(id => {
  124. cy.get('code').contains(`git clone ${gitURL(id.toString())}`)
  125. })
  126. cy.findByRole('button', {
  127. name: 'Generate token',
  128. }).should('not.exist')
  129. cy.findByText(/generate a new one in Account settings/)
  130. cy.findByRole('link', { name: 'Go to settings' })
  131. .should('have.attr', 'target', '_blank')
  132. .and('have.attr', 'href', '/user/settings')
  133. })
  134. })
  135. describe('git access', () => {
  136. ensureUserExists({ email: 'collaborator-rw@example.com' })
  137. ensureUserExists({ email: 'collaborator-ro@example.com' })
  138. ensureUserExists({ email: 'collaborator-link-rw@example.com' })
  139. ensureUserExists({ email: 'collaborator-link-ro@example.com' })
  140. let projectName: string
  141. beforeEach(() => {
  142. projectName = uuid()
  143. createProject(projectName, { open: false }).as('projectId')
  144. })
  145. it('should expose r/w interface to owner', () => {
  146. maybeClearAllTokens()
  147. openProjectByName(projectName)
  148. checkGitAccess('readAndWrite')
  149. })
  150. it('should expose r/w interface to invited r/w collaborator', () => {
  151. shareProjectByEmailAndAcceptInviteViaDash(
  152. projectName,
  153. 'collaborator-rw@example.com',
  154. 'Editor'
  155. )
  156. maybeClearAllTokens()
  157. openProjectByName(projectName)
  158. checkGitAccess('readAndWrite')
  159. })
  160. it('should expose r/o interface to invited r/o collaborator', () => {
  161. shareProjectByEmailAndAcceptInviteViaDash(
  162. projectName,
  163. 'collaborator-ro@example.com',
  164. 'Viewer'
  165. )
  166. maybeClearAllTokens()
  167. openProjectByName(projectName)
  168. checkGitAccess('readOnly')
  169. })
  170. it('should expose r/w interface to link-sharing r/w collaborator', () => {
  171. openProjectByName(projectName)
  172. enableLinkSharing().then(({ linkSharingReadAndWrite }) => {
  173. const email = 'collaborator-link-rw@example.com'
  174. login(email)
  175. maybeClearAllTokens()
  176. openProjectViaLinkSharingAsUser(
  177. linkSharingReadAndWrite,
  178. projectName,
  179. email
  180. )
  181. checkGitAccess('readAndWrite')
  182. })
  183. })
  184. it('should expose r/o interface to link-sharing r/o collaborator', () => {
  185. openProjectByName(projectName)
  186. enableLinkSharing().then(({ linkSharingReadOnly }) => {
  187. const email = 'collaborator-link-ro@example.com'
  188. login(email)
  189. maybeClearAllTokens()
  190. openProjectViaLinkSharingAsUser(
  191. linkSharingReadOnly,
  192. projectName,
  193. email
  194. )
  195. checkGitAccess('readOnly')
  196. })
  197. })
  198. })
  199. function checkGitAccess(access: 'readOnly' | 'readAndWrite') {
  200. const recompile = throttledRecompile()
  201. cy.findByRole('navigation', {
  202. name: 'Project actions',
  203. })
  204. .findByRole('button', { name: 'Menu' })
  205. .click()
  206. cy.findByTestId('left-menu').within(() => {
  207. cy.findByRole('heading', { name: 'Sync' })
  208. cy.findByRole('button', { name: 'Git' }).click()
  209. })
  210. cy.get('@projectId').then(projectId => {
  211. cy.findByTestId('git-bridge-modal').within(() => {
  212. cy.findByLabelText('Git clone project command').contains(
  213. `git clone ${gitURL(projectId.toString())}`
  214. )
  215. })
  216. cy.findByRole('heading', { name: 'Clone with Git' })
  217. cy.findByRole('button', {
  218. name: 'Generate token',
  219. }).click()
  220. cy.get('code')
  221. .contains(/olp_[a-zA-Z0-9]{16}/)
  222. .then(async tokenEl => {
  223. const token = tokenEl.text()
  224. // close Git modal
  225. cy.findAllByText('Close').last().click()
  226. // close editor menu
  227. cy.get('.left-menu-modal-backdrop').click()
  228. const fs = new LightningFS('fs')
  229. const dir = `/${projectId}`
  230. async function readFile(path: string): Promise<string> {
  231. return new Promise((resolve, reject) => {
  232. fs.readFile(path, { encoding: 'utf8' }, (err, blob) => {
  233. if (err) return reject(err)
  234. resolve(blob as string)
  235. })
  236. })
  237. }
  238. async function writeFile(path: string, data: string) {
  239. return new Promise<void>((resolve, reject) => {
  240. fs.writeFile(path, data, undefined, err => {
  241. if (err) return reject(err)
  242. resolve()
  243. })
  244. })
  245. }
  246. const commonOptions = {
  247. dir,
  248. fs,
  249. }
  250. const url = gitURL(projectId.toString())
  251. url.username = '' // basic auth is specified separately.
  252. const httpOptions = {
  253. http,
  254. url: url.toString(),
  255. headers: {
  256. Authorization: `Basic ${Buffer.from(`git:${token}`).toString('base64')}`,
  257. },
  258. }
  259. const authorOptions = {
  260. author: { name: 'user', email: USER },
  261. committer: { name: 'user', email: USER },
  262. }
  263. const mainTex = `${dir}/main.tex`
  264. // Clone
  265. cy.then({ timeout: 10_000 }, async () => {
  266. await git.clone({
  267. ...commonOptions,
  268. ...httpOptions,
  269. })
  270. })
  271. cy.findByText(/\\documentclass/)
  272. .parent()
  273. .parent()
  274. .then(async editor => {
  275. const onDisk = await readFile(mainTex)
  276. expect(onDisk.replaceAll('\n', '')).to.equal(editor.text())
  277. })
  278. const text = `
  279. \\documentclass{article}
  280. \\begin{document}
  281. Hello world
  282. \\end{document}
  283. `
  284. // Make a change
  285. cy.then(async () => {
  286. await writeFile(mainTex, text)
  287. await git.add({
  288. ...commonOptions,
  289. filepath: 'main.tex',
  290. })
  291. await git.commit({
  292. ...commonOptions,
  293. ...authorOptions,
  294. message: 'Swap main.tex',
  295. })
  296. })
  297. if (access === 'readAndWrite') {
  298. // check history before push
  299. cy.findAllByText('History').last().click()
  300. cy.findByText('(via Git)').should('not.exist')
  301. cy.findAllByText('Back to editor').last().click()
  302. cy.then(async () => {
  303. await git.push({
  304. ...commonOptions,
  305. ...httpOptions,
  306. })
  307. })
  308. } else {
  309. cy.then(async () => {
  310. try {
  311. await git.push({
  312. ...commonOptions,
  313. ...httpOptions,
  314. })
  315. expect.fail('push should have failed')
  316. } catch (err) {
  317. expect(err).to.match(/branches were not updated/)
  318. expect(err).to.match(/forbidden/)
  319. }
  320. })
  321. return // return early, below are write access bits
  322. }
  323. // check push in editor
  324. cy.findByText(/\\documentclass/)
  325. .parent()
  326. .parent()
  327. .should('have.text', text.replaceAll('\n', ''))
  328. // Wait for history sync - trigger flush by toggling the UI
  329. cy.findAllByText('History').last().click()
  330. cy.findAllByText('Back to editor').last().click()
  331. // check push in history
  332. cy.findAllByText('History').last().click()
  333. cy.findByText(/Hello world/)
  334. cy.findByText('(via Git)').should('exist')
  335. // Back to the editor
  336. cy.findAllByText('Back to editor').last().click()
  337. cy.findByText(/\\documentclass/)
  338. .parent()
  339. .parent()
  340. .click()
  341. .type('% via editor{enter}')
  342. // Trigger flush via compile
  343. recompile()
  344. // Back into the history, check what we just added
  345. cy.findAllByText('History').last().click()
  346. cy.findByText(/% via editor/)
  347. // Pull the change
  348. cy.then(async () => {
  349. await git.pull({
  350. ...commonOptions,
  351. ...httpOptions,
  352. ...authorOptions,
  353. })
  354. expect(await readFile(mainTex)).to.equal(text + '% via editor\n')
  355. })
  356. })
  357. })
  358. }
  359. })
  360. function checkDisabled() {
  361. ensureUserExists({ email: USER })
  362. it('should not render the git-bridge UI in the settings', () => {
  363. login(USER)
  364. cy.visit('/user/settings')
  365. cy.findByRole('heading', { name: 'Git integration' }).should('not.exist')
  366. })
  367. it('should not render the git-bridge UI in the editor', function () {
  368. login(USER)
  369. createProject('maybe git')
  370. cy.findByRole('navigation', {
  371. name: 'Project actions',
  372. })
  373. .findByRole('button', { name: 'Menu' })
  374. .click()
  375. cy.findByTestId('left-menu').within(() => {
  376. cy.findByRole('button', { name: 'Word Count' }) // wait for lazy loading
  377. cy.findByRole('heading', { name: 'Sync' }).should('not.exist')
  378. cy.findByRole('button', { name: 'Git' }).should('not.exist')
  379. })
  380. })
  381. }
  382. describe('disabled in Server Pro', () => {
  383. if (isExcludedBySharding('PRO_DEFAULT_1')) return
  384. startWith({
  385. pro: true,
  386. })
  387. checkDisabled()
  388. })
  389. describe('unavailable in CE', () => {
  390. if (isExcludedBySharding('CE_CUSTOM_1')) return
  391. startWith({
  392. pro: false,
  393. vars: ENABLED_VARS,
  394. })
  395. checkDisabled()
  396. })
  397. })