|
| 1 | +# Mints a short-lived GitHub App installation access token by signing a JWT |
| 2 | +# with a private key stored in Azure Key Vault (RSA, RS256). The signed JWT is |
| 3 | +# exchanged with the GitHub API for a token scoped to a single installation. |
| 4 | +# |
| 5 | +# Requirements: |
| 6 | +# - A GitHub App whose private key has been uploaded into Key Vault as an RSA |
| 7 | +# key (the PEM converted to a Key Vault *key*, NOT stored as a secret). |
| 8 | +# - The caller (the federated Azure service connection used to run this script) |
| 9 | +# must have the `Key Vault Crypto User` role (or at minimum the `Sign` |
| 10 | +# action) on that key. |
| 11 | +# - The App must be installed on the target organization/account |
| 12 | +# (`InstallationOwner`) with the permissions/repositories it needs. |
| 13 | +# |
| 14 | +# Installation tokens (ghs_*) are exempt from the enterprise classic-PAT |
| 15 | +# lifetime policy, which is why this replaces the long-lived PAT. |
| 16 | + |
| 17 | +[CmdletBinding()] |
| 18 | +param( |
| 19 | + # Name of the Key Vault that holds the GitHub App's RSA signing key. |
| 20 | + [Parameter(Mandatory = $true)] |
| 21 | + [string] $KeyVaultName, |
| 22 | + |
| 23 | + # Name of the RSA key inside the Key Vault (the App's private key). |
| 24 | + [Parameter(Mandatory = $true)] |
| 25 | + [string] $KeyName, |
| 26 | + |
| 27 | + # The GitHub App's Client ID (the value to put in the `iss` JWT claim). |
| 28 | + [Parameter(Mandatory = $true)] |
| 29 | + [string] $AppClientId, |
| 30 | + |
| 31 | + # Login of the organization or user account whose installation we should |
| 32 | + # mint the token for (e.g. `dotnet`, `microsoft`). |
| 33 | + [Parameter(Mandatory = $true)] |
| 34 | + [string] $InstallationOwner, |
| 35 | + |
| 36 | + # Optional Azure DevOps pipeline variable name to set with the installation |
| 37 | + # token (marked as a secret). When not specified, the token is written to |
| 38 | + # stdout instead. |
| 39 | + [Parameter(Mandatory = $false)] |
| 40 | + [string] $OutputVariableName |
| 41 | +) |
| 42 | + |
| 43 | +$ErrorActionPreference = 'Stop' |
| 44 | +$PSNativeCommandUseErrorActionPreference = $true |
| 45 | + |
| 46 | +. $PSScriptRoot\pipeline-logging-functions.ps1 |
| 47 | + |
| 48 | +function ConvertTo-Base64Url([byte[]] $bytes) { |
| 49 | + return [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_') |
| 50 | +} |
| 51 | + |
| 52 | +# Build JWT header and payload. Use [ordered] hashtables so JSON |
| 53 | +# serialization is deterministic. |
| 54 | +$jwtHeader = [ordered]@{ |
| 55 | + alg = 'RS256' |
| 56 | + typ = 'JWT' |
| 57 | +} |
| 58 | +$now = [System.DateTimeOffset]::UtcNow |
| 59 | +$jwtPayload = [ordered]@{ |
| 60 | + iat = $now.AddMinutes(-1).ToUnixTimeSeconds() |
| 61 | + exp = $now.AddMinutes(5).ToUnixTimeSeconds() |
| 62 | + iss = $AppClientId |
| 63 | +} |
| 64 | + |
| 65 | +$headerEncoded = ConvertTo-Base64Url ([System.Text.Encoding]::UTF8.GetBytes(($jwtHeader | ConvertTo-Json -Compress))) |
| 66 | +$payloadEncoded = ConvertTo-Base64Url ([System.Text.Encoding]::UTF8.GetBytes(($jwtPayload | ConvertTo-Json -Compress))) |
| 67 | +$signingInput = "$headerEncoded.$payloadEncoded" |
| 68 | + |
| 69 | +# Key Vault `sign` expects the *digest* (base64), not the raw bytes. |
| 70 | +$sha256 = [System.Security.Cryptography.SHA256]::Create() |
| 71 | +$digestBytes = $sha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($signingInput)) |
| 72 | +$digestBase64 = [Convert]::ToBase64String($digestBytes) |
| 73 | + |
| 74 | +Write-Host "Signing JWT with key '$KeyName' in vault '$KeyVaultName'..." |
| 75 | +try { |
| 76 | + $signatureUrl = az keyvault key sign ` |
| 77 | + --vault-name $KeyVaultName ` |
| 78 | + --name $KeyName ` |
| 79 | + --algorithm RS256 ` |
| 80 | + --digest $digestBase64 ` |
| 81 | + --query value ` |
| 82 | + --output tsv ` |
| 83 | + --only-show-errors |
| 84 | +} |
| 85 | +catch { |
| 86 | + Write-PipelineTelemetryError -Category 'Build' -Message "Failed to sign the JWT via Key Vault (key '$KeyName', vault '$KeyVaultName'): $_. Verify the service connection identity has the 'Key Vault Crypto User' role (Sign action) on the key." |
| 87 | + exit 1 |
| 88 | +} |
| 89 | +if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($signatureUrl)) { |
| 90 | + Write-PipelineTelemetryError -Category 'Build' -Message "'az keyvault key sign' exited with code $LASTEXITCODE for key '$KeyName' in vault '$KeyVaultName'. Verify the service connection identity has the 'Key Vault Crypto User' role (Sign action) on the key." |
| 91 | + exit 1 |
| 92 | +} |
| 93 | +$jwt = "$signingInput.$($signatureUrl.Trim())" |
| 94 | + |
| 95 | +$headers = @{ |
| 96 | + Authorization = "Bearer $jwt" |
| 97 | + 'X-GitHub-Api-Version' = '2022-11-28' |
| 98 | + Accept = 'application/vnd.github+json' |
| 99 | + 'User-Agent' = 'dotnet-arcade-onelocbuild' |
| 100 | +} |
| 101 | + |
| 102 | +Write-Host "Looking up installation for '$InstallationOwner'..." |
| 103 | +try { |
| 104 | + $installations = @() |
| 105 | + $page = 1 |
| 106 | + do { |
| 107 | + $pageInstallations = @(Invoke-RestMethod ` |
| 108 | + -Uri "https://api.github.com/app/installations?per_page=100&page=$page" ` |
| 109 | + -Headers $headers ` |
| 110 | + -Method Get) |
| 111 | + $installations += $pageInstallations |
| 112 | + $page++ |
| 113 | + } while ($pageInstallations.Count -eq 100) |
| 114 | +} |
| 115 | +catch { |
| 116 | + Write-PipelineTelemetryError -Category 'Build' -Message "Failed to list GitHub App installations: $_. The signed JWT may be invalid or the App's Client ID ('$AppClientId') may be incorrect." |
| 117 | + exit 1 |
| 118 | +} |
| 119 | +$installation = $installations | Where-Object { $_.account.login -ieq $InstallationOwner } | Select-Object -First 1 |
| 120 | +if (-not $installation) { |
| 121 | + $found = ($installations | ForEach-Object { $_.account.login }) -join ', ' |
| 122 | + Write-PipelineTelemetryError -Category 'Build' -Message "No installation found for '$InstallationOwner'. App is installed on: $found" |
| 123 | + exit 1 |
| 124 | +} |
| 125 | + |
| 126 | +try { |
| 127 | + $tokenResponse = Invoke-RestMethod ` |
| 128 | + -Uri "https://api.github.com/app/installations/$($installation.id)/access_tokens" ` |
| 129 | + -Headers $headers ` |
| 130 | + -Method Post ` |
| 131 | + -ContentType 'application/json' |
| 132 | +} |
| 133 | +catch { |
| 134 | + Write-PipelineTelemetryError -Category 'Build' -Message "Failed to mint an installation access token for '$InstallationOwner' (installation $($installation.id)): $_" |
| 135 | + exit 1 |
| 136 | +} |
| 137 | + |
| 138 | +Write-Host "Got installation token for '$InstallationOwner' (expires $($tokenResponse.expires_at))." |
| 139 | +if ($OutputVariableName) { |
| 140 | + Write-Host "Setting pipeline variable '$OutputVariableName'." |
| 141 | + Write-Host "##vso[task.setvariable variable=$OutputVariableName;issecret=true]$($tokenResponse.token)" |
| 142 | +} |
| 143 | +else { |
| 144 | + Write-Host $tokenResponse.token -ForegroundColor Green |
| 145 | +} |
0 commit comments