input-helper.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import * as core from '@actions/core'
  2. import * as fsHelper from '../lib/fs-helper'
  3. import * as github from '@actions/github'
  4. import * as inputHelper from '../lib/input-helper'
  5. import * as path from 'path'
  6. import * as workflowContextHelper from '../lib/workflow-context-helper'
  7. import {IGitSourceSettings} from '../lib/git-source-settings'
  8. const originalGitHubWorkspace = process.env['GITHUB_WORKSPACE']
  9. const gitHubWorkspace = path.resolve('/checkout-tests/workspace')
  10. // Inputs for mock @actions/core
  11. let inputs = {} as any
  12. // Replicate @actions/core getInput behavior: it trims whitespace by default
  13. // (String.prototype.trim(), which strips characters such as a leading U+FEFF BOM)
  14. // unless trimWhitespace is explicitly set to false.
  15. const getInputImpl = (name: string, options?: {trimWhitespace?: boolean}) => {
  16. const val = inputs[name] ?? ''
  17. if (options && options.trimWhitespace === false) {
  18. return val
  19. }
  20. return typeof val === 'string' ? val.trim() : val
  21. }
  22. // Shallow clone original @actions/github context
  23. let originalContext = {...github.context}
  24. describe('input-helper tests', () => {
  25. beforeAll(() => {
  26. // Mock getInput
  27. jest.spyOn(core, 'getInput').mockImplementation(getInputImpl as any)
  28. // Mock error/warning/info/debug
  29. jest.spyOn(core, 'error').mockImplementation(jest.fn())
  30. jest.spyOn(core, 'warning').mockImplementation(jest.fn())
  31. jest.spyOn(core, 'info').mockImplementation(jest.fn())
  32. jest.spyOn(core, 'debug').mockImplementation(jest.fn())
  33. // Mock github context
  34. jest.spyOn(github.context, 'repo', 'get').mockImplementation(() => {
  35. return {
  36. owner: 'some-owner',
  37. repo: 'some-repo'
  38. }
  39. })
  40. github.context.ref = 'refs/heads/some-ref'
  41. github.context.sha = '1234567890123456789012345678901234567890'
  42. // Mock ./fs-helper directoryExistsSync()
  43. jest
  44. .spyOn(fsHelper, 'directoryExistsSync')
  45. .mockImplementation((path: string) => path == gitHubWorkspace)
  46. // Mock ./workflowContextHelper getOrganizationId()
  47. jest
  48. .spyOn(workflowContextHelper, 'getOrganizationId')
  49. .mockImplementation(() => Promise.resolve(123456))
  50. // GitHub workspace
  51. process.env['GITHUB_WORKSPACE'] = gitHubWorkspace
  52. })
  53. beforeEach(() => {
  54. // Reset inputs
  55. inputs = {}
  56. })
  57. afterAll(() => {
  58. // Restore GitHub workspace
  59. delete process.env['GITHUB_WORKSPACE']
  60. if (originalGitHubWorkspace) {
  61. process.env['GITHUB_WORKSPACE'] = originalGitHubWorkspace
  62. }
  63. // Restore @actions/github context
  64. github.context.ref = originalContext.ref
  65. github.context.sha = originalContext.sha
  66. // Restore
  67. jest.restoreAllMocks()
  68. })
  69. it('sets defaults', async () => {
  70. const settings: IGitSourceSettings = await inputHelper.getInputs()
  71. expect(settings).toBeTruthy()
  72. expect(settings.authToken).toBeFalsy()
  73. expect(settings.clean).toBe(true)
  74. expect(settings.commit).toBeTruthy()
  75. expect(settings.commit).toBe('1234567890123456789012345678901234567890')
  76. expect(settings.sparseCheckout).toBe(undefined)
  77. expect(settings.sparseCheckoutConeMode).toBe(true)
  78. expect(settings.fetchDepth).toBe(1)
  79. expect(settings.fetchTags).toBe(false)
  80. expect(settings.lfs).toBe(false)
  81. expect(settings.ref).toBe('refs/heads/some-ref')
  82. expect(settings.repositoryName).toBe('some-repo')
  83. expect(settings.repositoryOwner).toBe('some-owner')
  84. expect(settings.repositoryPath).toBe(gitHubWorkspace)
  85. expect(settings.setSafeDirectory).toBe(true)
  86. expect(settings.allowUnsafePrCheckout).toBe(false)
  87. })
  88. it('qualifies ref', async () => {
  89. let originalRef = github.context.ref
  90. try {
  91. github.context.ref = 'some-unqualified-ref'
  92. const settings: IGitSourceSettings = await inputHelper.getInputs()
  93. expect(settings).toBeTruthy()
  94. expect(settings.commit).toBe('1234567890123456789012345678901234567890')
  95. expect(settings.ref).toBe('refs/heads/some-unqualified-ref')
  96. } finally {
  97. github.context.ref = originalRef
  98. }
  99. })
  100. it('requires qualified repo', async () => {
  101. inputs.repository = 'some-unqualified-repo'
  102. try {
  103. await inputHelper.getInputs()
  104. throw 'should not reach here'
  105. } catch (err) {
  106. expect(`(${(err as any).message}`).toMatch(
  107. "Invalid repository 'some-unqualified-repo'"
  108. )
  109. }
  110. })
  111. it('roots path', async () => {
  112. inputs.path = 'some-directory/some-subdirectory'
  113. const settings: IGitSourceSettings = await inputHelper.getInputs()
  114. expect(settings.repositoryPath).toBe(
  115. path.join(gitHubWorkspace, 'some-directory', 'some-subdirectory')
  116. )
  117. })
  118. it('sets ref to empty when explicit sha', async () => {
  119. inputs.ref = '1111111111222222222233333333334444444444'
  120. const settings: IGitSourceSettings = await inputHelper.getInputs()
  121. expect(settings.ref).toBeFalsy()
  122. expect(settings.commit).toBe('1111111111222222222233333333334444444444')
  123. })
  124. it('sets sha to empty when explicit ref', async () => {
  125. inputs.ref = 'refs/heads/some-other-ref'
  126. const settings: IGitSourceSettings = await inputHelper.getInputs()
  127. expect(settings.ref).toBe('refs/heads/some-other-ref')
  128. expect(settings.commit).toBeFalsy()
  129. })
  130. it('does not reclassify a ref as sha when a BOM is prefixed', async () => {
  131. // A fork branch named "<U+FEFF>" + 40 hex chars. core.getInput trims the
  132. // BOM by default, which previously collapsed this into a bare SHA and
  133. // bypassed the unsafe fork PR checkout guard.
  134. inputs.ref = '\uFEFF522d932fae5296da51fdf431934425ecf891c6a2'
  135. const settings: IGitSourceSettings = await inputHelper.getInputs()
  136. expect(settings.commit).toBeFalsy()
  137. expect(settings.ref).toBe('522d932fae5296da51fdf431934425ecf891c6a2')
  138. })
  139. it('treats a sha surrounded by ascii whitespace as a commit', async () => {
  140. // ASCII whitespace can only come from the workflow author's YAML (git ref
  141. // names cannot contain it), so trimming it and treating the value as a
  142. // commit is safe.
  143. inputs.ref = ' 1111111111222222222233333333334444444444 '
  144. const settings: IGitSourceSettings = await inputHelper.getInputs()
  145. expect(settings.ref).toBeFalsy()
  146. expect(settings.commit).toBe('1111111111222222222233333333334444444444')
  147. })
  148. it('sets workflow organization ID', async () => {
  149. const settings: IGitSourceSettings = await inputHelper.getInputs()
  150. expect(settings.workflowOrganizationId).toBe(123456)
  151. })
  152. describe('unsafe PR checkout guard', () => {
  153. const forkPayload = {
  154. repository: {id: 100},
  155. pull_request: {
  156. head: {
  157. sha: '1234567890123456789012345678901234567890',
  158. repo: {id: 200, full_name: 'attacker/fork'}
  159. },
  160. merge_commit_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
  161. }
  162. }
  163. it('allows the default self-checkout on a fork pull_request_target', async () => {
  164. const originalEvent = github.context.eventName
  165. const originalPayload = github.context.payload
  166. const originalSha = github.context.sha
  167. try {
  168. github.context.eventName = 'pull_request_target'
  169. github.context.payload = forkPayload as any
  170. // Simulate a rebase/fast-forward merge where the base tip (event SHA)
  171. // equals the PR head SHA. The default self-checkout must still succeed.
  172. github.context.sha = '1234567890123456789012345678901234567890'
  173. const settings: IGitSourceSettings = await inputHelper.getInputs()
  174. expect(settings.commit).toBe('1234567890123456789012345678901234567890')
  175. } finally {
  176. github.context.eventName = originalEvent
  177. github.context.payload = originalPayload
  178. github.context.sha = originalSha
  179. }
  180. })
  181. it('refuses an explicit fork repository on pull_request_target', async () => {
  182. const originalEvent = github.context.eventName
  183. const originalPayload = github.context.payload
  184. try {
  185. github.context.eventName = 'pull_request_target'
  186. github.context.payload = forkPayload as any
  187. inputs.repository = 'attacker/fork'
  188. await expect(inputHelper.getInputs()).rejects.toThrow(
  189. /Refusing to check out fork pull request code/
  190. )
  191. } finally {
  192. github.context.eventName = originalEvent
  193. github.context.payload = originalPayload
  194. }
  195. })
  196. })
  197. })