Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,12 @@ Create a `release.config.json` file at the root of your project. Open the newly

### Generate GitHub Personal Access Token

Generate a [Personal Access Token](https://github.com/settings/tokens/new?scopes=repo,admin:repo_hook,admin:org_hook) for your GitHub user with the following permissions:
Generate a [fine-grained Personal Access Token](https://github.com/settings/personal-access-tokens/new?contents=write&issues=write) for your GitHub user. Grant the token access to your repository and the following repository permissions:

- `Contents`: Read and write (create release commits, tags, and GitHub releases)
- `Issues`: Read and write (comment on the issues referenced by the release)

Alternatively, you can use a classic [Personal Access Token](https://github.com/settings/tokens/new?scopes=repo,admin:repo_hook,admin:org_hook) with the following scopes:

- `repo`
- `admin:repo_hook`
Expand Down
170 changes: 170 additions & 0 deletions src/utils/github/__test__/validate-fine-grained-access-token.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { http, HttpResponse } from 'msw'
import { api } from '#/test/env.js'
import {
getGitHubTokenType,
validateAccessToken,
validateFineGrainedAccessToken,
GITHUB_NEW_FINE_GRAINED_TOKEN_URL,
} from '#/src/utils/github/validate-access-token.js'

const repo = {
owner: 'octocat',
name: 'example',
}

describe(getGitHubTokenType, () => {
it('returns "fine-grained" for tokens with the "github_pat_" prefix', () => {
expect(getGitHubTokenType('github_pat_11ABC')).toBe('fine-grained')
})

it('returns "classic" for tokens with the "ghp_" prefix', () => {
expect(getGitHubTokenType('ghp_ABC')).toBe('classic')
})

it('returns "classic" for legacy 40-character tokens', () => {
expect(getGitHubTokenType('a'.repeat(40))).toBe('classic')
})
})

describe(validateFineGrainedAccessToken, () => {
it('resolves given a token with sufficient permissions', async () => {
api.use(
http.get('https://api.github.com/repos/octocat/example', () => {
return HttpResponse.json({})
}),
http.post('https://api.github.com/repos/octocat/example/releases', () => {
return new HttpResponse(null, { status: 422 })
}),
http.post(
'https://api.github.com/repos/octocat/example/issues/0/comments',
() => {
return new HttpResponse(null, { status: 404 })
},
),
)

await expect(
validateFineGrainedAccessToken('github_pat_TOKEN', repo),
).resolves.toBeUndefined()
})

it('throws an error given a token that cannot access the repository', async () => {
api.use(
http.get('https://api.github.com/repos/octocat/example', () => {
return new HttpResponse(null, { status: 404 })
}),
)

await expect(
validateFineGrainedAccessToken('github_pat_TOKEN', repo),
).rejects.toThrow(
`Failed to verify GitHub token permissions: the provided fine-grained "GITHUB_TOKEN" cannot access the "octocat/example" repository. Please make sure that the repository access of the token includes that repository and try again.`,
)
})

it('throws an error given a generic error response from the API', async () => {
api.use(
http.get('https://api.github.com/repos/octocat/example', () => {
return new HttpResponse(null, { status: 500 })
}),
)

await expect(
validateFineGrainedAccessToken('github_pat_TOKEN', repo),
).rejects.toThrow(
`Failed to verify GitHub token permissions: GitHub API responded with 500 Internal Server Error. Please double-check your "GITHUB_TOKEN" environmental variable and try again.`,
)
})

it('throws an error given a token without the "contents: write" permission', async () => {
api.use(
http.get('https://api.github.com/repos/octocat/example', () => {
return HttpResponse.json({})
}),
http.post('https://api.github.com/repos/octocat/example/releases', () => {
return new HttpResponse(null, { status: 403 })
}),
http.post(
'https://api.github.com/repos/octocat/example/issues/0/comments',
() => {
return new HttpResponse(null, { status: 404 })
},
),
)

await expect(
validateFineGrainedAccessToken('github_pat_TOKEN', repo),
).rejects.toThrow(
`Provided "GITHUB_TOKEN" environment variable has insufficient permissions: missing permissions "contents: write". Please generate a new GitHub fine-grained personal access token from this URL: ${GITHUB_NEW_FINE_GRAINED_TOKEN_URL}`,
)
})

it('throws an error given a token without the "issues: write" permission', async () => {
api.use(
http.get('https://api.github.com/repos/octocat/example', () => {
return HttpResponse.json({})
}),
http.post('https://api.github.com/repos/octocat/example/releases', () => {
return new HttpResponse(null, { status: 422 })
}),
http.post(
'https://api.github.com/repos/octocat/example/issues/0/comments',
() => {
return new HttpResponse(null, { status: 403 })
},
),
)

await expect(
validateFineGrainedAccessToken('github_pat_TOKEN', repo),
).rejects.toThrow(
`Provided "GITHUB_TOKEN" environment variable has insufficient permissions: missing permissions "issues: write". Please generate a new GitHub fine-grained personal access token from this URL: ${GITHUB_NEW_FINE_GRAINED_TOKEN_URL}`,
)
})

it('throws an error given a token with missing multiple permissions', async () => {
api.use(
http.get('https://api.github.com/repos/octocat/example', () => {
return HttpResponse.json({})
}),
http.post('https://api.github.com/repos/octocat/example/releases', () => {
return new HttpResponse(null, { status: 403 })
}),
http.post(
'https://api.github.com/repos/octocat/example/issues/0/comments',
() => {
return new HttpResponse(null, { status: 403 })
},
),
)

await expect(
validateFineGrainedAccessToken('github_pat_TOKEN', repo),
).rejects.toThrow(
`Provided "GITHUB_TOKEN" environment variable has insufficient permissions: missing permissions "contents: write", "issues: write". Please generate a new GitHub fine-grained personal access token from this URL: ${GITHUB_NEW_FINE_GRAINED_TOKEN_URL}`,
)
})
})

describe(validateAccessToken, () => {
it('validates fine-grained tokens against the repository from Git info', async () => {
api.use(
http.get('https://api.github.com/repos/:owner/:name', () => {
return HttpResponse.json({})
}),
http.post('https://api.github.com/repos/:owner/:name/releases', () => {
return new HttpResponse(null, { status: 422 })
}),
http.post(
'https://api.github.com/repos/:owner/:name/issues/0/comments',
() => {
return new HttpResponse(null, { status: 404 })
},
),
)

await expect(
validateAccessToken('github_pat_TOKEN'),
).resolves.toBeUndefined()
})
})
165 changes: 164 additions & 1 deletion src/utils/github/validate-access-token.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import { invariant } from 'outvariant'
import { getInfo, type GitInfo } from '#/src/utils/git/get-info.js'

export const requiredGitHubTokenScopes: string[] = [
export type GitHubTokenType = 'classic' | 'fine-grained'

export type GitHubRepo = Pick<GitInfo, 'owner' | 'name'>

const FINE_GRAINED_TOKEN_PREFIX = 'github_pat_'

export function getGitHubTokenType(accessToken: string): GitHubTokenType {
if (accessToken.startsWith(FINE_GRAINED_TOKEN_PREFIX)) {
return 'fine-grained'
}

return 'classic'
}

export const requiredGitHubTokenScopes: Array<string> = [
'repo',
'admin:repo_hook',
'admin:org_hook',
Expand All @@ -10,11 +25,93 @@ export const GITHUB_NEW_TOKEN_URL = `https://github.com/settings/tokens/new?scop
',',
)}`

export interface FineGrainedTokenPermission {
permission: string
access: 'read' | 'write'
/**
* Check whether the given access token is granted this permission.
*/
probe: (accessToken: string, repo: GitHubRepo) => Promise<boolean>
}

export const requiredFineGrainedTokenPermissions: Array<FineGrainedTokenPermission> =
[
{
permission: 'contents',
access: 'write',
async probe(accessToken, repo) {
/**
* Attempt to create a release without any payload.
* GitHub checks the token permissions before validating
* the payload: a validation error (422) means the token can
* create releases while 403/404 mean the permission is missing.
*/
const response = await fetch(
`https://api.github.com/repos/${repo.owner}/${repo.name}/releases`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({}),
},
)

return response.status === 422
},
},
{
permission: 'issues',
access: 'write',
async probe(accessToken, repo) {
/**
* Attempt to comment on an issue that can never exist (#0).
* A 404/422 response means the token has passed the permission
* check while 403 means the permission is missing.
*/
const response = await fetch(
`https://api.github.com/repos/${repo.owner}/${repo.name}/issues/0/comments`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({}),
},
)

return response.status === 404 || response.status === 422
},
},
]

export const GITHUB_NEW_FINE_GRAINED_TOKEN_URL = `https://github.com/settings/personal-access-tokens/new?${requiredFineGrainedTokenPermissions
.map((requiredPermission) => {
return `${requiredPermission.permission}=${requiredPermission.access}`
})
.join('&')}`

/**
* Check whether the given GitHub access token has sufficient permissions
* for this library to create and publish a new release.
*/
export async function validateAccessToken(accessToken: string): Promise<void> {
if (getGitHubTokenType(accessToken) === 'fine-grained') {
const repo = await getInfo()
await validateFineGrainedAccessToken(accessToken, repo)
return
}

await validateClassicAccessToken(accessToken)
}

/**
* Check whether the given classic GitHub access token (OAuth)
* has sufficient permission scopes.
*/
export async function validateClassicAccessToken(
accessToken: string,
): Promise<void> {
const response = await fetch('https://api.github.com', {
headers: {
Authorization: `Bearer ${accessToken}`,
Expand Down Expand Up @@ -52,3 +149,69 @@ export async function validateAccessToken(accessToken: string): Promise<void> {
)
}
}

/**
* Check whether the given fine-grained GitHub access token has
* sufficient permissions for the given repository.
*/
export async function validateFineGrainedAccessToken(
accessToken: string,
repo: GitHubRepo,
): Promise<void> {
const repoResponse = await fetch(
`https://api.github.com/repos/${repo.owner}/${repo.name}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
)

invariant(
repoResponse.status !== 404,
'Failed to verify GitHub token permissions: the provided fine-grained "GITHUB_TOKEN" cannot access the "%s/%s" repository. Please make sure that the repository access of the token includes that repository and try again.',
repo.owner,
repo.name,
)

// Handle generic error responses.
invariant(
repoResponse.ok,
'Failed to verify GitHub token permissions: GitHub API responded with %d %s. Please double-check your "GITHUB_TOKEN" environmental variable and try again.',
repoResponse.status,
repoResponse.statusText,
)

/**
* @note GitHub provides no API to list the permissions granted
* to a fine-grained token so probe the endpoints behind the
* required permissions instead.
*/
const probedPermissions = await Promise.all(
requiredFineGrainedTokenPermissions.map(async (requiredPermission) => {
const isGranted = await requiredPermission.probe(accessToken, repo)

return {
requiredPermission,
isGranted,
}
}),
)

const missingPermissions = probedPermissions
.filter((probedPermission) => {
return !probedPermission.isGranted
})
.map((probedPermission) => {
return `${probedPermission.requiredPermission.permission}: ${probedPermission.requiredPermission.access}`
})

if (missingPermissions.length > 0) {
invariant(
false,
'Provided "GITHUB_TOKEN" environment variable has insufficient permissions: missing permissions "%s". Please generate a new GitHub fine-grained personal access token from this URL: %s',
missingPermissions.join(`", "`),
GITHUB_NEW_FINE_GRAINED_TOKEN_URL,
)
}
}
Loading