git-bridge.spec.ts 12 KB

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