|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +const crypto = require('node:crypto'); |
| 4 | +const { execFileSync } = require('node:child_process'); |
| 5 | + |
| 6 | +const PERMISSION_PROFILES = Object.freeze({ |
| 7 | + issues: Object.freeze({ |
| 8 | + issues: 'write', |
| 9 | + }), |
| 10 | + 'pull-requests': Object.freeze({ |
| 11 | + contents: 'read', |
| 12 | + pull_requests: 'write', |
| 13 | + }), |
| 14 | + devflow: Object.freeze({ |
| 15 | + contents: 'read', |
| 16 | + issues: 'write', |
| 17 | + pull_requests: 'write', |
| 18 | + }), |
| 19 | +}); |
| 20 | + |
| 21 | +function base64Url(value) { |
| 22 | + return Buffer.from(value).toString('base64url'); |
| 23 | +} |
| 24 | + |
| 25 | +function base64ToBase64Url(value) { |
| 26 | + return Buffer.from(value, 'base64').toString('base64url'); |
| 27 | +} |
| 28 | + |
| 29 | +function createJwtSigningInput(clientId, nowSeconds) { |
| 30 | + const header = base64Url(JSON.stringify({ alg: 'RS256', typ: 'JWT' })); |
| 31 | + const payload = base64Url(JSON.stringify({ |
| 32 | + iat: nowSeconds - 60, |
| 33 | + exp: nowSeconds + 540, |
| 34 | + iss: clientId, |
| 35 | + })); |
| 36 | + return `${header}.${payload}`; |
| 37 | +} |
| 38 | + |
| 39 | +function signJwt(signingInput, config, execute = execFileSync) { |
| 40 | + const digest = crypto.createHash('sha256').update(signingInput).digest('base64'); |
| 41 | + const signature = execute( |
| 42 | + 'az', |
| 43 | + [ |
| 44 | + 'keyvault', 'key', 'sign', |
| 45 | + '--subscription', config.azureSubscriptionId, |
| 46 | + '--vault-name', config.keyVaultName, |
| 47 | + '--name', config.keyName, |
| 48 | + '--algorithm', 'RS256', |
| 49 | + '--digest', digest, |
| 50 | + '--query', 'signature', |
| 51 | + '--output', 'tsv', |
| 52 | + '--only-show-errors', |
| 53 | + ], |
| 54 | + { encoding: 'utf8' }, |
| 55 | + ).trim(); |
| 56 | + |
| 57 | + if (!signature) { |
| 58 | + throw new Error('Key Vault returned an empty signature.'); |
| 59 | + } |
| 60 | + |
| 61 | + return `${signingInput}.${base64ToBase64Url(signature)}`; |
| 62 | +} |
| 63 | + |
| 64 | +async function createInstallationToken(config, dependencies = {}) { |
| 65 | + const execute = dependencies.execute ?? execFileSync; |
| 66 | + const request = dependencies.fetch ?? fetch; |
| 67 | + const nowSeconds = dependencies.nowSeconds ?? Math.floor(Date.now() / 1000); |
| 68 | + const repositoryParts = config.targetRepository.split('/'); |
| 69 | + |
| 70 | + if (repositoryParts.length !== 2 || repositoryParts.some((part) => part.length === 0)) { |
| 71 | + throw new Error('TARGET_REPOSITORY must use the owner/repository format.'); |
| 72 | + } |
| 73 | + if (!Object.hasOwn(PERMISSION_PROFILES, config.permissionProfile)) { |
| 74 | + throw new Error('PERMISSION_PROFILE must be issues, pull-requests, or devflow.'); |
| 75 | + } |
| 76 | + const permissions = PERMISSION_PROFILES[config.permissionProfile]; |
| 77 | + |
| 78 | + const [, repository] = repositoryParts; |
| 79 | + const signingInput = createJwtSigningInput(config.githubAppClientId, nowSeconds); |
| 80 | + const jwt = signJwt(signingInput, config, execute); |
| 81 | + |
| 82 | + const response = await request( |
| 83 | + `https://api.github.com/app/installations/${config.githubAppInstallationId}/access_tokens`, |
| 84 | + { |
| 85 | + method: 'POST', |
| 86 | + headers: { |
| 87 | + Accept: 'application/vnd.github+json', |
| 88 | + Authorization: `Bearer ${jwt}`, |
| 89 | + 'X-GitHub-Api-Version': '2022-11-28', |
| 90 | + }, |
| 91 | + body: JSON.stringify({ |
| 92 | + repositories: [repository], |
| 93 | + permissions, |
| 94 | + }), |
| 95 | + }, |
| 96 | + ); |
| 97 | + |
| 98 | + if (!response.ok) { |
| 99 | + throw new Error(`GitHub installation token request failed with HTTP ${response.status}.`); |
| 100 | + } |
| 101 | + |
| 102 | + const result = await response.json(); |
| 103 | + if (typeof result.token !== 'string' || result.token.length === 0) { |
| 104 | + throw new Error('GitHub returned an empty installation token.'); |
| 105 | + } |
| 106 | + |
| 107 | + return result.token; |
| 108 | +} |
| 109 | + |
| 110 | +function readConfig(environment) { |
| 111 | + const config = { |
| 112 | + azureSubscriptionId: environment.AZURE_SUBSCRIPTION_ID, |
| 113 | + keyVaultName: environment.KEY_VAULT_NAME, |
| 114 | + keyName: environment.KEY_NAME, |
| 115 | + githubAppClientId: environment.GITHUB_APP_CLIENT_ID, |
| 116 | + githubAppInstallationId: environment.GITHUB_APP_INSTALLATION_ID, |
| 117 | + targetRepository: environment.TARGET_REPOSITORY, |
| 118 | + permissionProfile: environment.PERMISSION_PROFILE, |
| 119 | + }; |
| 120 | + |
| 121 | + if (Object.values(config).some((value) => !value)) { |
| 122 | + throw new Error('Required GitHub App authentication configuration is missing.'); |
| 123 | + } |
| 124 | + |
| 125 | + return config; |
| 126 | +} |
| 127 | + |
| 128 | +async function main() { |
| 129 | + try { |
| 130 | + const token = await createInstallationToken(readConfig(process.env)); |
| 131 | + process.stdout.write(token); |
| 132 | + } catch { |
| 133 | + console.error('GitHub App token generation failed.'); |
| 134 | + process.exitCode = 1; |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +if (require.main === module) { |
| 139 | + void main(); |
| 140 | +} |
| 141 | + |
| 142 | +module.exports = { |
| 143 | + base64ToBase64Url, |
| 144 | + createInstallationToken, |
| 145 | + createJwtSigningInput, |
| 146 | + readConfig, |
| 147 | + signJwt, |
| 148 | + PERMISSION_PROFILES, |
| 149 | +}; |
0 commit comments