Compare commits

..
Author SHA1 Message Date
copilot-swe-agent[bot] 3d61762e50 Initial plan 2026-07-15 14:45:15 +00:00
10 changed files with 93 additions and 360 deletions
+6 -7
View File
@@ -1,14 +1,13 @@
# Changelog
## v7.0.1
* Skip running unsafe pr check if input is default by @aiqiaoy in https://github.com/actions/checkout/pull/2518
* Trim only ascii whitespace for branch by @aiqiaoy in https://github.com/actions/checkout/pull/2521
* Escape values passed to --unset by @aiqiaoy in https://github.com/actions/checkout/pull/2530
* Various dependency updates
## v7.0.0
* Block checking out fork PR for pull_request_target and workflow_run by @aiqiaoy in https://github.com/actions/checkout/pull/2454
* Various dependency updates
* Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by @dependabot[bot] in https://github.com/actions/checkout/pull/2458
* Bump flatted from 3.3.1 to 3.4.2 by @dependabot[bot] in https://github.com/actions/checkout/pull/2460
* Bump js-yaml from 4.1.0 to 4.2.0 by @dependabot[bot] in https://github.com/actions/checkout/pull/2461
* Bump @actions/core and @actions/tool-cache and Remove uuid by @dependabot[bot] in https://github.com/actions/checkout/pull/2459
* upgrade module to esm and update dependencies by @aiqiaoy in https://github.com/actions/checkout/pull/2463
* Bump the minor-npm-dependencies group across 1 directory with 3 updates by @dependabot[bot] in https://github.com/actions/checkout/pull/2462
## v6.0.3
* Fix checkout init for SHA-256 repositories by @yaananth in https://github.com/actions/checkout/pull/2439
-1
View File
@@ -5,7 +5,6 @@
## What's new
- Safer fork pull request handling: checkout now refuses to check out fork pull request code by default when the workflow is triggered by `pull_request_target` or `workflow_run`. These triggers run with the base repository's `GITHUB_TOKEN`, secrets, and runner access, where executing a fork's code commonly leads to "pwn request" vulnerabilities.
- When a fork pull request triggers a `workflow_run`, checkout only accepts explicit commit SHAs in the workflow commit's history for the same repository by default. Pins other than the workflow commit need a GitHub API comparison with `contents: read` permission. If the comparison cannot verify the pin, use a trusted branch ref instead.
- To opt in after [reviewing the risks](https://gh.io/securely-using-pull_request_target), set the new `allow-unsafe-pr-checkout: true` input.
- Migrated `actions/checkout` to ESM to support new versions of the `@actions/*` packages.
- Updated direct and transitive dependencies, including security fixes for known vulnerabilities.
+5 -138
View File
@@ -5,7 +5,6 @@ import {
expect,
beforeAll,
beforeEach,
afterEach,
afterAll
} from '@jest/globals'
import * as path from 'path'
@@ -25,20 +24,9 @@ const mockGithubContext: any = {
payload: {}
}
// Replicate @actions/core getInput behavior: it trims whitespace by default
// (String.prototype.trim(), which strips characters such as a leading U+FEFF BOM)
// unless trimWhitespace is explicitly set to false.
const getInputImpl = (name: string, options?: {trimWhitespace?: boolean}) => {
const val = inputs[name] ?? ''
if (options && options.trimWhitespace === false) {
return val
}
return typeof val === 'string' ? val.trim() : val
}
// Mock @actions/core before loading input-helper
jest.unstable_mockModule('@actions/core', () => ({
getInput: jest.fn(getInputImpl),
getInput: jest.fn((name: string) => inputs[name]),
getBooleanInput: jest.fn((name: string) => inputs[name]),
getMultilineInput: jest.fn((name: string) =>
inputs[name] ? String(inputs[name]).split('\n').filter(Boolean) : []
@@ -53,12 +41,9 @@ jest.unstable_mockModule('@actions/core', () => ({
}))
// Mock @actions/github before loading input-helper
const mockCompareCommits = jest.fn<() => Promise<unknown>>()
jest.unstable_mockModule('@actions/github', () => ({
context: mockGithubContext,
getOctokit: jest.fn(() => ({
rest: {repos: {compareCommitsWithBasehead: mockCompareCommits}}
}))
getOctokit: jest.fn()
}))
// Mock fs-helper
@@ -91,7 +76,9 @@ describe('input-helper tests', () => {
inputs = {}
jest.clearAllMocks()
// Re-apply default mocks
;(core.getInput as jest.Mock<any>).mockImplementation(getInputImpl as any)
;(core.getInput as jest.Mock<any>).mockImplementation(
(name: string) => inputs[name]
)
mockDirectoryExistsSync.mockImplementation(
(p: string) => p === gitHubWorkspace
)
@@ -189,36 +176,6 @@ describe('input-helper tests', () => {
expect(settings.commit).toBeFalsy()
})
it('does not reclassify a ref as sha when a BOM is prefixed', async () => {
// A fork branch named "<U+FEFF>" + 40 hex chars. core.getInput trims the
// BOM by default, which previously collapsed this into a bare SHA and
// bypassed the unsafe fork PR checkout guard.
inputs.ref = '\uFEFF522d932fae5296da51fdf431934425ecf891c6a2'
const settings: IGitSourceSettings = await inputHelper.getInputs()
expect(settings.commit).toBeFalsy()
expect(settings.ref).toBe('522d932fae5296da51fdf431934425ecf891c6a2')
})
it('does not reclassify a sha-256 ref as sha when a BOM is prefixed', async () => {
inputs.ref =
'\uFEFF1111111111222222222233333333334444444444555555555566666666667777'
const settings: IGitSourceSettings = await inputHelper.getInputs()
expect(settings.commit).toBeFalsy()
expect(settings.ref).toBe(
'1111111111222222222233333333334444444444555555555566666666667777'
)
})
it('treats a sha surrounded by ascii whitespace as a commit', async () => {
// ASCII whitespace can only come from the workflow author's YAML (git ref
// names cannot contain it), so trimming it and treating the value as a
// commit is safe.
inputs.ref = ' 1111111111222222222233333333334444444444 '
const settings: IGitSourceSettings = await inputHelper.getInputs()
expect(settings.ref).toBeFalsy()
expect(settings.commit).toBe('1111111111222222222233333333334444444444')
})
it('sets workflow organization ID', async () => {
const settings: IGitSourceSettings = await inputHelper.getInputs()
expect(settings.workflowOrganizationId).toBe(123456)
@@ -269,94 +226,4 @@ describe('input-helper tests', () => {
}
})
})
describe('explicit checkout pins on a fork PR workflow_run', () => {
const workflowSha = '1234567890123456789012345678901234567890'
const ancestorSha = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
const mergeSha = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
beforeEach(() => {
inputs.token = 'checkout-token'
mockGithubContext.eventName = 'workflow_run'
mockGithubContext.payload = {
repository: {id: 100},
workflow_run: {
event: 'pull_request',
head_repository: {id: 200, full_name: 'fork-owner/some-repo'},
head_sha: 'cccccccccccccccccccccccccccccccccccccccc'
}
}
mockCompareCommits.mockReset()
mockCompareCommits.mockRejectedValue(new Error('API unavailable'))
})
afterEach(() => {
mockGithubContext.eventName = ''
mockGithubContext.payload = {}
})
it.each([
['a PR merge commit outside workflow history', workflowSha, ancestorSha],
['a comparison against an unexpected base', ancestorSha, mergeSha]
])('refuses %s without PR metadata', async (_, base, mergeBase) => {
inputs.ref = mergeSha
mockCompareCommits.mockResolvedValue({
data: {
base_commit: {sha: base},
merge_base_commit: {sha: mergeBase}
}
})
await expect(inputHelper.getInputs()).rejects.toThrow(
/Refusing to check out the requested commit/
)
})
it('allows a pin verified to be in workflow history', async () => {
inputs.ref = ancestorSha.toUpperCase()
mockCompareCommits.mockResolvedValue({
data: {
base_commit: {sha: workflowSha},
merge_base_commit: {sha: ancestorSha}
}
})
await expect(inputHelper.getInputs()).resolves.toMatchObject({
ref: '',
commit: inputs.ref
})
})
it('refuses a pin if the comparison is unavailable', async () => {
inputs.ref = mergeSha
await expect(inputHelper.getInputs()).rejects.toThrow(
/Unable to verify the requested commit/
)
})
it('allows a pin when the workflow explicitly opts out', async () => {
inputs.ref = mergeSha
inputs['allow-unsafe-pr-checkout'] = 'true'
await expect(inputHelper.getInputs()).resolves.toMatchObject({
ref: '',
commit: mergeSha
})
expect(mockCompareCommits).not.toHaveBeenCalled()
})
it.each([
['default checkout', '', 'refs/heads/some-ref', workflowSha],
['named branch', 'refs/heads/main', 'refs/heads/main', undefined],
['workflow commit', workflowSha, '', workflowSha]
])('allows %s without a comparison', async (_, inputRef, ref, commit) => {
inputs.ref = inputRef
const settings = await inputHelper.getInputs()
expect(settings.ref).toBe(ref)
expect(settings.commit).toBe(commit)
expect(mockCompareCommits).not.toHaveBeenCalled()
})
})
})
+60 -66
View File
@@ -34,12 +34,6 @@ jest.unstable_mockModule('@actions/github', () => ({
const {assertSafePrCheckout} =
await import('../src/unsafe-pr-checkout-helper.js')
function check(
input: Parameters<typeof assertSafePrCheckout>[0]
): Promise<void> {
return assertSafePrCheckout(input, 'checkout-token')
}
const originalEventName = mockContext.eventName
const originalPayload = mockContext.payload
@@ -100,191 +94,191 @@ describe('unsafe-pr-checkout-helper', () => {
mockContext.payload = originalPayload
})
it('allows pull_request events untouched', async () => {
it('allows pull_request events untouched', () => {
setContext('pull_request', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: 'attacker/fork',
ref: 'refs/pull/1/merge',
commit: '',
allowUnsafePrCheckout: false
})
).resolves.toBeUndefined()
).not.toThrow()
})
it('allows pull_request_target default checkout (base branch)', async () => {
it('allows pull_request_target default checkout (base branch)', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: 'refs/heads/main',
commit: SAFE_BASE_SHA,
allowUnsafePrCheckout: false
})
).resolves.toBeUndefined()
).not.toThrow()
})
it('allows same-repo pull_request_target checkout of PR head', async () => {
it('allows same-repo pull_request_target checkout of PR head', () => {
setContext('pull_request_target', sameRepoPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: '',
commit: PR_HEAD_SHA,
allowUnsafePrCheckout: false
})
).resolves.toBeUndefined()
).not.toThrow()
})
it('refuses pull_request_target fork PR head SHA checkout', async () => {
it('refuses pull_request_target fork PR head SHA checkout', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: '',
commit: PR_HEAD_SHA,
allowUnsafePrCheckout: false
})
).rejects.toThrow(/Refusing to check out fork pull request code/)
).toThrow(/Refusing to check out fork pull request code/)
})
it('refuses pull_request_target fork PR merge_commit_sha checkout', async () => {
it('refuses pull_request_target fork PR merge_commit_sha checkout', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: '',
commit: PR_MERGE_SHA,
allowUnsafePrCheckout: false
})
).rejects.toThrow(/allow-unsafe-pr-checkout/)
).toThrow(/allow-unsafe-pr-checkout/)
})
it('refuses pull_request_target fork PR ref pattern (head)', async () => {
it('refuses pull_request_target fork PR ref pattern (head)', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: 'refs/pull/42/head',
commit: '',
allowUnsafePrCheckout: false
})
).rejects.toThrow()
).toThrow()
})
it('refuses pull_request_target fork PR ref pattern (merge)', async () => {
it('refuses pull_request_target fork PR ref pattern (merge)', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: 'refs/pull/42/merge',
commit: '',
allowUnsafePrCheckout: false
})
).rejects.toThrow()
).toThrow()
})
it('refuses pull_request_target when repository points at the fork', async () => {
it('refuses pull_request_target when repository points at the fork', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: FORK_QUALIFIED_REPO,
ref: 'refs/heads/main',
commit: '',
allowUnsafePrCheckout: false
})
).rejects.toThrow()
).toThrow()
})
it('allows pull_request_target checkout of an unrelated third-party repo', async () => {
it('allows pull_request_target checkout of an unrelated third-party repo', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: 'some-other/unrelated',
ref: 'refs/heads/main',
commit: '',
allowUnsafePrCheckout: false
})
).resolves.toBeUndefined()
).not.toThrow()
})
it('refuses pull_request_target ignoring repository case differences', async () => {
it('refuses pull_request_target ignoring repository case differences', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: FORK_QUALIFIED_REPO.toUpperCase(),
ref: '',
commit: '',
allowUnsafePrCheckout: false
})
).rejects.toThrow()
).toThrow()
})
it('refuses pull_request_target ignoring commit SHA case differences', async () => {
it('refuses pull_request_target ignoring commit SHA case differences', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: '',
commit: PR_HEAD_SHA.toUpperCase(),
allowUnsafePrCheckout: false
})
).rejects.toThrow()
).toThrow()
})
it('allows pull_request_target fork PR checkout when opted in', async () => {
it('allows pull_request_target fork PR checkout when opted in', () => {
setContext('pull_request_target', forkPullRequestTargetPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: 'refs/pull/42/merge',
commit: '',
allowUnsafePrCheckout: true
})
).resolves.toBeUndefined()
).not.toThrow()
})
it('refuses workflow_run fork PR head_commit.id checkout', async () => {
it('refuses workflow_run fork PR head_commit.id checkout', () => {
setContext('workflow_run', forkWorkflowRunPayload())
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: '',
commit: WORKFLOW_RUN_HEAD_COMMIT_SHA,
allowUnsafePrCheckout: false
})
).rejects.toThrow(/Refusing to check out fork pull request code/)
).toThrow()
})
it('refuses workflow_run with pull_request_target underlying event', async () => {
it('refuses workflow_run with pull_request_target underlying event', () => {
const payload = forkWorkflowRunPayload() as {
workflow_run: {event: string}
}
payload.workflow_run.event = 'pull_request_target'
setContext('workflow_run', payload)
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: '',
commit: WORKFLOW_RUN_HEAD_COMMIT_SHA,
allowUnsafePrCheckout: false
})
).rejects.toThrow(/Refusing to check out fork pull request code/)
).toThrow()
})
it('allows workflow_run same-repo PR (head_repository.id matches base)', async () => {
it('allows workflow_run same-repo PR (head_repository.id matches base)', () => {
const payload = forkWorkflowRunPayload() as {
workflow_run: {head_repository: {id: number}}
}
payload.workflow_run.head_repository.id = BASE_REPO_ID
setContext('workflow_run', payload)
await expect(
check({
expect(() =>
assertSafePrCheckout({
qualifiedRepository: BASE_QUALIFIED_REPO,
ref: '',
commit: WORKFLOW_RUN_HEAD_COMMIT_SHA,
allowUnsafePrCheckout: false
})
).resolves.toBeUndefined()
).not.toThrow()
})
})
+7 -58
View File
@@ -35913,7 +35913,7 @@ class GitCommandManager {
else {
args.push(globalConfig ? '--global' : '--local');
}
args.push('--unset', configKey, regexp_helper_escape(configValue));
args.push('--unset', configKey, configValue);
const output = await this.execGit(args, true);
return output.exitCode === 0;
}
@@ -41970,7 +41970,7 @@ async function getGitCommandManager(settings) {
const PR_REF_PATTERN = /^refs\/pull\/[0-9]+\/(?:head|merge)$/;
async function assertSafePrCheckout(input, authToken) {
function assertSafePrCheckout(input) {
if (input.allowUnsafePrCheckout) {
return;
}
@@ -42014,20 +42014,10 @@ async function assertSafePrCheckout(input, authToken) {
const repositoryMatchesPrHead = typeof prHeadRepoFullName === 'string' &&
input.qualifiedRepository.toLowerCase() === prHeadRepoFullName.toLowerCase();
const refMatchesPullPattern = PR_REF_PATTERN.test(input.ref);
const commit = input.commit?.toLowerCase();
const commitMatchesPrHeadSha = !!commit && prShas.includes(commit);
const commitMatchesPrHeadSha = !!input.commit && prShas.includes(input.commit.toLowerCase());
if (!repositoryMatchesPrHead &&
!refMatchesPullPattern &&
!commitMatchesPrHeadSha) {
if (eventName === 'workflow_run' && !input.ref && commit) {
const { owner, repo } = github_context.repo;
if (input.qualifiedRepository.toLowerCase() ===
`${owner}/${repo}`.toLowerCase() &&
!(await commitIsInWorkflowHistory(authToken, owner, repo, commit))) {
throw new Error('Refusing to check out the requested commit for this fork pull request. ' +
'The commit is not verified to be in the workflow commit history. Use a trusted branch ref.');
}
}
return;
}
throw new Error(`Refusing to check out fork pull request code from a '${eventName}' workflow. ` +
@@ -42037,31 +42027,6 @@ async function assertSafePrCheckout(input, authToken) {
`at https://gh.io/securely-using-pull_request_target and set 'allow-unsafe-pr-checkout: true' ` +
`on the actions/checkout step.`);
}
async function commitIsInWorkflowHistory(authToken, owner, repo, commit) {
const workflowSha = github_context.sha?.toLowerCase() || '';
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(workflowSha)) {
throw new Error('Unable to verify the requested commit: the workflow commit SHA is missing or invalid.');
}
if (commit === workflowSha) {
return true;
}
try {
// Compare immutable commits so the result does not depend on current PR metadata.
const { data } = await getOctokit(authToken)
.rest.repos.compareCommitsWithBasehead({
owner,
repo,
basehead: `${workflowSha}...${commit}`,
per_page: 1
});
return (data?.base_commit?.sha === workflowSha &&
data?.merge_base_commit?.sha === commit);
}
catch (error) {
throw new Error('Unable to verify the requested commit against the workflow commit history. ' +
'Check that the checkout token has contents: read, or use a trusted branch ref.', { cause: error });
}
}
function pushIfSha(target, value) {
if (typeof value === 'string' && value.length > 0) {
target.push(value.toLowerCase());
@@ -42135,22 +42100,6 @@ async function getInputs() {
`${github_context.repo.owner}/${github_context.repo.repo}`.toUpperCase();
// Source branch, source version
result.ref = getInput('ref');
// core.getInput()'s default trim strips a range of Unicode characters such as a
// leading BOM (U+FEFF) or NBSP (U+00A0). Those are valid in a git ref name, so
// a fork branch named "<BOM>" + 40 hex chars would trim down to a bare SHA and
// be silently reclassified as a commit, bypassing the unsafe fork PR checkout
// guard.
//
// The trim below strips only the ASCII whitespace characters which are all forbidden
// in a git branch name.
// \t U+0009 horizontal tab - ASCII control, forbidden in ref names
// \n U+000A line feed - ASCII control, forbidden in ref names
// \v U+000B vertical tab - ASCII control, forbidden in ref names
// \f U+000C form feed - ASCII control, forbidden in ref names
// \r U+000D carriage return - ASCII control, forbidden in ref names
// ' ' U+0020 space - forbidden in ref names
const asciiTrimmedRef = getInput('ref', { trimWhitespace: false })
.replace(/^[\t\n\v\f\r ]+|[\t\n\v\f\r ]+$/g, '');
if (!result.ref) {
if (isWorkflowRepository) {
result.ref = github_context.ref;
@@ -42163,8 +42112,8 @@ async function getInputs() {
}
}
// SHA?
else if (asciiTrimmedRef.match(/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/)) {
result.commit = asciiTrimmedRef;
else if (result.ref.match(/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/)) {
result.commit = result.ref;
result.ref = '';
}
core_debug(`ref = '${result.ref}'`);
@@ -42248,12 +42197,12 @@ async function getInputs() {
// repository or ref.
const isDefaultCheckout = isWorkflowRepository && !getInput('ref');
if (!isDefaultCheckout) {
await assertSafePrCheckout({
assertSafePrCheckout({
qualifiedRepository,
ref: result.ref,
commit: result.commit,
allowUnsafePrCheckout: result.allowUnsafePrCheckout
}, result.authToken);
});
}
return result;
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "checkout",
"version": "7.0.1",
"version": "7.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "checkout",
"version": "7.0.1",
"version": "7.0.0",
"license": "MIT",
"dependencies": {
"@actions/core": "^3.0.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "checkout",
"version": "7.0.1",
"version": "7.0.0",
"description": "checkout action",
"type": "module",
"main": "lib/main.js",
+1 -1
View File
@@ -510,7 +510,7 @@ class GitCommandManager {
} else {
args.push(globalConfig ? '--global' : '--local')
}
args.push('--unset', configKey, regexpHelper.escape(configValue))
args.push('--unset', configKey, configValue)
const output = await this.execGit(args, true)
return output.exitCode === 0
+8 -28
View File
@@ -59,23 +59,6 @@ export async function getInputs(): Promise<IGitSourceSettings> {
// Source branch, source version
result.ref = core.getInput('ref')
// core.getInput()'s default trim strips a range of Unicode characters such as a
// leading BOM (U+FEFF) or NBSP (U+00A0). Those are valid in a git ref name, so
// a fork branch named "<BOM>" + 40 hex chars would trim down to a bare SHA and
// be silently reclassified as a commit, bypassing the unsafe fork PR checkout
// guard.
//
// The trim below strips only the ASCII whitespace characters which are all forbidden
// in a git branch name.
// \t U+0009 horizontal tab - ASCII control, forbidden in ref names
// \n U+000A line feed - ASCII control, forbidden in ref names
// \v U+000B vertical tab - ASCII control, forbidden in ref names
// \f U+000C form feed - ASCII control, forbidden in ref names
// \r U+000D carriage return - ASCII control, forbidden in ref names
// ' ' U+0020 space - forbidden in ref names
const asciiTrimmedRef = core
.getInput('ref', {trimWhitespace: false})
.replace(/^[\t\n\v\f\r ]+|[\t\n\v\f\r ]+$/g, '')
if (!result.ref) {
if (isWorkflowRepository) {
result.ref = github.context.ref
@@ -89,8 +72,8 @@ export async function getInputs(): Promise<IGitSourceSettings> {
}
}
// SHA?
else if (asciiTrimmedRef.match(/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/)) {
result.commit = asciiTrimmedRef
else if (result.ref.match(/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/)) {
result.commit = result.ref
result.ref = ''
}
core.debug(`ref = '${result.ref}'`)
@@ -191,15 +174,12 @@ export async function getInputs(): Promise<IGitSourceSettings> {
// repository or ref.
const isDefaultCheckout = isWorkflowRepository && !core.getInput('ref')
if (!isDefaultCheckout) {
await unsafePrCheckoutHelper.assertSafePrCheckout(
{
qualifiedRepository,
ref: result.ref,
commit: result.commit,
allowUnsafePrCheckout: result.allowUnsafePrCheckout
},
result.authToken
)
unsafePrCheckoutHelper.assertSafePrCheckout({
qualifiedRepository,
ref: result.ref,
commit: result.commit,
allowUnsafePrCheckout: result.allowUnsafePrCheckout
})
}
return result
+3 -58
View File
@@ -10,10 +10,7 @@ export interface IUnsafePrCheckoutInput {
allowUnsafePrCheckout: boolean
}
export async function assertSafePrCheckout(
input: IUnsafePrCheckoutInput,
authToken: string
): Promise<void> {
export function assertSafePrCheckout(input: IUnsafePrCheckoutInput): void {
if (input.allowUnsafePrCheckout) {
return
}
@@ -63,27 +60,14 @@ export async function assertSafePrCheckout(
typeof prHeadRepoFullName === 'string' &&
input.qualifiedRepository.toLowerCase() === prHeadRepoFullName.toLowerCase()
const refMatchesPullPattern = PR_REF_PATTERN.test(input.ref)
const commit = input.commit?.toLowerCase()
const commitMatchesPrHeadSha = !!commit && prShas.includes(commit)
const commitMatchesPrHeadSha =
!!input.commit && prShas.includes(input.commit.toLowerCase())
if (
!repositoryMatchesPrHead &&
!refMatchesPullPattern &&
!commitMatchesPrHeadSha
) {
if (eventName === 'workflow_run' && !input.ref && commit) {
const {owner, repo} = github.context.repo
if (
input.qualifiedRepository.toLowerCase() ===
`${owner}/${repo}`.toLowerCase() &&
!(await commitIsInWorkflowHistory(authToken, owner, repo, commit))
) {
throw new Error(
'Refusing to check out the requested commit for this fork pull request. ' +
'The commit is not verified to be in the workflow commit history. Use a trusted branch ref.'
)
}
}
return
}
@@ -97,45 +81,6 @@ export async function assertSafePrCheckout(
)
}
async function commitIsInWorkflowHistory(
authToken: string,
owner: string,
repo: string,
commit: string
): Promise<boolean> {
const workflowSha = github.context.sha?.toLowerCase() || ''
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(workflowSha)) {
throw new Error(
'Unable to verify the requested commit: the workflow commit SHA is missing or invalid.'
)
}
if (commit === workflowSha) {
return true
}
try {
// Compare immutable commits so the result does not depend on current PR metadata.
const {data} = await github
.getOctokit(authToken)
.rest.repos.compareCommitsWithBasehead({
owner,
repo,
basehead: `${workflowSha}...${commit}`,
per_page: 1
})
return (
data?.base_commit?.sha === workflowSha &&
data?.merge_base_commit?.sha === commit
)
} catch (error) {
throw new Error(
'Unable to verify the requested commit against the workflow commit history. ' +
'Check that the checkout token has contents: read, or use a trusted branch ref.',
{cause: error}
)
}
}
function pushIfSha(target: string[], value: unknown): void {
if (typeof value === 'string' && value.length > 0) {
target.push(value.toLowerCase())