From 09c249ba5f9d484ed246330383a748efc5395e65 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Wed, 6 Nov 2024 19:51:15 +0100 Subject: [PATCH 01/11] refactor to make token a parameter to pass --- .../Commands/Initialize-RunnerEnvironment.ps1 | 16 ++- .../public/Auth/Connect-GitHubAccount.ps1 | 110 ++++++++---------- 2 files changed, 61 insertions(+), 65 deletions(-) diff --git a/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 b/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 index d8c13cf71..0bdffec51 100644 --- a/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 +++ b/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 @@ -19,10 +19,16 @@ Set-GitHubEnv -Name 'GITHUB_REPOSITORY_NAME' -Value $env:GITHUB_REPOSITORY_NAME # Autologon if a token is present in environment variables - Write-Verbose (Get-ChildItem -Path 'Env:' | Where-Object Name -In 'GH_TOKEN', 'GITHUB_TOKEN' | Out-String) - $tokenVar = Get-ChildItem -Path 'Env:' | Where-Object Name -In 'GH_TOKEN', 'GITHUB_TOKEN' | Select-Object -First 1 -ExpandProperty Value - $tokenVarPresent = $tokenVar.count -gt 0 -and -not [string]::IsNullOrEmpty($tokenVar) - if ($tokenVarPresent) { - Connect-GitHubAccount -Repo $env:GITHUB_REPOSITORY_NAME -Owner $env:GITHUB_REPOSITORY_OWNER -Server $env:GITHUB_SERVER_URL + $gitHubToken = Get-ChildItem -Path 'Env:' | Where-Object Name -In 'GH_TOKEN', 'GITHUB_TOKEN' | Select-Object -First 1 -ExpandProperty Value + $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) + Write-Debug "GitHub token present: [$gitHubTokenPresent]" + if ($gitHubTokenPresent) { + $params = @{ + AccessToken = $gitHubToken + Owner = $env:GITHUB_REPOSITORY_OWNER + Repo = $env:GITHUB_REPOSITORY_NAME + Server = $env:GITHUB_SERVER_URL + } + Connect-GitHubAccount @params } } diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 3cbe84c88..6f2460e4e 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -71,14 +71,16 @@ [Parameter(ParameterSetName = 'UAT')] [string] $Scope = 'gist read:org repo workflow', - # The personal access token to use for authentication. + # An access token to use for authentication. [Parameter( Mandatory, - ParameterSetName = 'PAT' + ParameterSetName = 'Token' )] + [AllowNull()] [Alias('Token')] [Alias('PAT')] - [switch] $AccessToken, + [Alias('IAT')] + [string] $AccessToken, # The client ID for the GitHub App to use for authentication. [Parameter(ParameterSetName = 'UAT')] @@ -128,14 +130,7 @@ $HostName = $HostName -replace '^https?://' $ApiBaseUri = "https://api.$HostName" - $envVars = Get-ChildItem -Path 'Env:' - Write-Debug 'Environment variables:' - Write-Debug ($envVars | Format-Table -AutoSize | Out-String) - $gitHubToken = $envVars | Where-Object Name -In 'GH_TOKEN', 'GITHUB_TOKEN' | Select-Object -First 1 -ExpandProperty Value - Write-Debug "GitHub token: [$gitHubToken]" - $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) - Write-Debug "GitHub token present: [$gitHubTokenPresent]" - $AuthType = if ($gitHubTokenPresent) { 'IAT' } else { $PSCmdlet.ParameterSetName } + $AuthType = $PSCmdlet.ParameterSetName Write-Verbose "AuthType: [$AuthType]" switch ($AuthType) { 'UAT' { @@ -213,29 +208,8 @@ } } Set-GitHubConfig @settings - break - } - 'PAT' { - Write-Verbose 'Logging in using personal access token...' - Reset-GitHubConfig -Scope 'Auth' - Write-Host '! ' -ForegroundColor DarkYellow -NoNewline - Start-Process "https://$HostName/settings/tokens" - $accessTokenValue = Read-Host -Prompt 'Enter your personal access token' -AsSecureString - $accessTokenType = (ConvertFrom-SecureString $accessTokenValue -AsPlainText) -replace '_.*$', '_*' - if ($accessTokenType -notmatch '^ghp_|^github_pat_') { - Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline - Write-Host "Unexpected access token format: $accessTokenType" - } - $settings = @{ - AccessToken = $accessTokenValue - AccessTokenType = $accessTokenType - ApiBaseUri = $ApiBaseUri - ApiVersion = $ApiVersion - AuthType = $AuthType - HostName = $HostName - } - Set-GitHubConfig @settings - break + $user = Get-GitHubUser + $username = $user.login } 'App' { Write-Verbose 'Logging in as a GitHub App...' @@ -251,35 +225,51 @@ HostName = $HostName } Set-GitHubConfig @settings - } - 'IAT' { - Write-Verbose 'Logging in using GitHub access token...' - Reset-GitHubConfig -Scope 'Auth' - $prefix = $gitHubToken -replace '_.*$', '_*' - $settings = @{ - AccessToken = ConvertTo-SecureString -AsPlainText $gitHubToken - AccessTokenType = $prefix - ApiBaseUri = $ApiBaseUri - ApiVersion = $ApiVersion - AuthType = 'IAT' - ClientID = $ClientID - HostName = $HostName - } - Set-GitHubConfig @settings - } - } - - switch ($AuthType) { - 'App' { $app = Get-GitHubApp $username = $app.slug } - 'IAT' { - $username = 'system' - } - default { - $user = Get-GitHubUser - $username = $user.login + 'Token' { + if ([string]::IsNullOrEmpty($AccessToken)) { + Write-Verbose 'Logging in using personal access token...' + Write-Host '! ' -ForegroundColor DarkYellow -NoNewline + Start-Process "https://$HostName/settings/tokens" + $accessTokenValue = Read-Host -Prompt 'Enter your personal access token' -AsSecureString + $AccessToken = ConvertFrom-SecureString $accessTokenValue -AsPlainText + } + $accessTokenType = $AccessToken -replace '_.*$', '_*' + switch -Regex ($accessTokenType) { + '^ghp_|^github_pat_' { + Reset-GitHubConfig -Scope 'Auth' + $settings = @{ + AccessToken = $accessTokenValue + AccessTokenType = $accessTokenType + ApiBaseUri = $ApiBaseUri + ApiVersion = $ApiVersion + AuthType = 'PAT' + HostName = $HostName + } + Set-GitHubConfig @settings + } + '^ghs_' { + Write-Verbose 'Logging in using GitHub access token...' + Reset-GitHubConfig -Scope 'Auth' + $settings = @{ + AccessToken = ConvertTo-SecureString -AsPlainText $AccessToken + AccessTokenType = $accessTokenType + ApiBaseUri = $ApiBaseUri + ApiVersion = $ApiVersion + AuthType = 'IAT' + ClientID = $ClientID + HostName = $HostName + } + Set-GitHubConfig @settings + $username = 'system' + } + default { + Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline + Write-Host "Unexpected access token format: $accessTokenType" + } + } } } From 8b8da42b96358ced628081df885506f6539c022d Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Wed, 6 Nov 2024 20:14:20 +0100 Subject: [PATCH 02/11] Allow null on ClientID --- src/functions/public/Config/Set-GitHubConfig.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/src/functions/public/Config/Set-GitHubConfig.ps1 b/src/functions/public/Config/Set-GitHubConfig.ps1 index ae346f9eb..3c2a70674 100644 --- a/src/functions/public/Config/Set-GitHubConfig.ps1 +++ b/src/functions/public/Config/Set-GitHubConfig.ps1 @@ -50,6 +50,7 @@ function Set-GitHubConfig { [string] $AuthType, # Set the client ID. + [AllowNull()] [string] $ClientID, # Set the device flow type. From 5a0f4ca87413d21672937dc006d79fe5025fb144 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Wed, 6 Nov 2024 20:58:35 +0100 Subject: [PATCH 03/11] Test connect-github --- tests/Commands.Tests.ps1 | 21 --------------------- tests/GitHub.Tests.ps1 | 31 ++++++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 26 deletions(-) delete mode 100644 tests/Commands.Tests.ps1 diff --git a/tests/Commands.Tests.ps1 b/tests/Commands.Tests.ps1 deleted file mode 100644 index 92dae9282..000000000 --- a/tests/Commands.Tests.ps1 +++ /dev/null @@ -1,21 +0,0 @@ -Describe 'Commands' { - It "Start-LogGroup 'MyGroup' should not throw" { - { - Start-LogGroup 'MyGroup' - } | Should -Not -Throw - } - - It 'Stop-LogGroup should not throw' { - { - Stop-LogGroup - } | Should -Not -Throw - } - - It "LogGroup 'MyGroup' should not throw" { - { - LogGroup 'MyGroup' { - Get-ChildItem env: | Select-Object Name, Value | Format-Table -AutoSize - } - } | Should -Not -Throw - } -} diff --git a/tests/GitHub.Tests.ps1 b/tests/GitHub.Tests.ps1 index 94f3d1f97..c08de14b6 100644 --- a/tests/GitHub.Tests.ps1 +++ b/tests/GitHub.Tests.ps1 @@ -1,8 +1,7 @@ -BeforeAll { - Connect-GitHub -} - -Describe 'GitHub' { +Describe 'GitHub' { + Context 'Connect-GitHub' { + { Connect-GitHub } | Should -Not -Throw + } Context 'Invoke-GitHubAPI' { It 'Invoke-GitHubAPI function exists' { Get-Command Invoke-GitHubAPI | Should -Not -BeNullOrEmpty @@ -29,3 +28,25 @@ Describe 'GitHub' { } } } + +Describe 'Commands' { + It "Start-LogGroup 'MyGroup' should not throw" { + { + Start-LogGroup 'MyGroup' + } | Should -Not -Throw + } + + It 'Stop-LogGroup should not throw' { + { + Stop-LogGroup + } | Should -Not -Throw + } + + It "LogGroup 'MyGroup' should not throw" { + { + LogGroup 'MyGroup' { + Get-ChildItem env: | Select-Object Name, Value | Format-Table -AutoSize + } + } | Should -Not -Throw + } +} From c130d1cef5620a924e33e14b8db3a9253a24cc7d Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Wed, 6 Nov 2024 21:59:28 +0100 Subject: [PATCH 04/11] Fix --- src/functions/public/Auth/Connect-GitHubAccount.ps1 | 1 - src/functions/public/Config/Set-GitHubConfig.ps1 | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 6f2460e4e..83c9e0e43 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -52,7 +52,6 @@ [Alias('Login-GH')] [OutputType([void])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidLongLines', '', Justification = 'Long links for documentation.')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'AccessToken', Justification = 'Required for parameter set')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Is the CLI part of the module.')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification = 'The tokens are recieved as clear text. Mitigating exposure by removing variables and performing garbage collection.')] [CmdletBinding(DefaultParameterSetName = 'UAT')] diff --git a/src/functions/public/Config/Set-GitHubConfig.ps1 b/src/functions/public/Config/Set-GitHubConfig.ps1 index 3c2a70674..6f62023cb 100644 --- a/src/functions/public/Config/Set-GitHubConfig.ps1 +++ b/src/functions/public/Config/Set-GitHubConfig.ps1 @@ -51,6 +51,7 @@ function Set-GitHubConfig { # Set the client ID. [AllowNull()] + [AllowEmptyString()] [string] $ClientID, # Set the device flow type. From b0bfb81f70b8b6d61444d1a944fff9ca0195ace2 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Wed, 6 Nov 2024 22:02:08 +0100 Subject: [PATCH 05/11] Fix --- src/functions/public/Auth/Connect-GitHubAccount.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 83c9e0e43..28315ba3d 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -258,7 +258,6 @@ ApiBaseUri = $ApiBaseUri ApiVersion = $ApiVersion AuthType = 'IAT' - ClientID = $ClientID HostName = $HostName } Set-GitHubConfig @settings From 994e3997e21255b86adbe3f15625834606646b07 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Wed, 6 Nov 2024 23:46:40 +0100 Subject: [PATCH 06/11] test --- .../public/Auth/Connect-GitHubAccount.ps1 | 288 +++++++++--------- 1 file changed, 145 insertions(+), 143 deletions(-) diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 28315ba3d..14cbd179f 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -125,167 +125,169 @@ [Alias('s')] [switch] $Silent ) + try { + $HostName = $HostName -replace '^https?://' + $ApiBaseUri = "https://api.$HostName" - $HostName = $HostName -replace '^https?://' - $ApiBaseUri = "https://api.$HostName" - - $AuthType = $PSCmdlet.ParameterSetName - Write-Verbose "AuthType: [$AuthType]" - switch ($AuthType) { - 'UAT' { - Write-Verbose 'Logging in using device flow...' - $authClientID = $ClientID ?? (Get-GitHubConfig -Name 'AuthClientID') ?? $script:Auth.$Mode.ClientID - if ($Mode -ne (Get-GitHubConfig -Name 'DeviceFlowType' -ErrorAction SilentlyContinue)) { - Write-Verbose "Using $Mode authentication..." - $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -Scope $Scope -HostName $HostName - } else { - $accessTokenValidity = [datetime](Get-GitHubConfig -Name 'AccessTokenExpirationDate') - (Get-Date) - $accessTokenIsValid = $accessTokenValidity.Seconds -gt 0 - $hours = $accessTokenValidity.Hours.ToString().PadLeft(2, '0') - $minutes = $accessTokenValidity.Minutes.ToString().PadLeft(2, '0') - $seconds = $accessTokenValidity.Seconds.ToString().PadLeft(2, '0') - $accessTokenValidityText = "$hours`:$minutes`:$seconds" - if ($accessTokenIsValid) { - if ($accessTokenValidity.TotalHours -gt $script:Auth.AccessTokenGracePeriodInHours) { - if (-not $Silent) { - Write-Host '✓ ' -ForegroundColor Green -NoNewline - Write-Host "Access token is still valid for $accessTokenValidityText ..." - } - break - } else { - if (-not $Silent) { - Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline - Write-Host "Access token remaining validity $accessTokenValidityText. Refreshing access token..." - } - $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken (Get-GitHubConfig -Name 'RefreshToken') -HostName $HostName - } + $AuthType = $PSCmdlet.ParameterSetName + Write-Verbose "AuthType: [$AuthType]" + switch ($AuthType) { + 'UAT' { + Write-Verbose 'Logging in using device flow...' + $authClientID = $ClientID ?? (Get-GitHubConfig -Name 'AuthClientID') ?? $script:Auth.$Mode.ClientID + if ($Mode -ne (Get-GitHubConfig -Name 'DeviceFlowType' -ErrorAction SilentlyContinue)) { + Write-Verbose "Using $Mode authentication..." + $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -Scope $Scope -HostName $HostName } else { - $refreshTokenValidity = [datetime](Get-GitHubConfig -Name 'RefreshTokenExpirationDate') - (Get-Date) - $refreshTokenIsValid = $refreshTokenValidity.Seconds -gt 0 - if ($refreshTokenIsValid) { - if (-not $Silent) { - Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline - Write-Host 'Access token expired. Refreshing access token...' + $accessTokenValidity = [datetime](Get-GitHubConfig -Name 'AccessTokenExpirationDate') - (Get-Date) + $accessTokenIsValid = $accessTokenValidity.Seconds -gt 0 + $hours = $accessTokenValidity.Hours.ToString().PadLeft(2, '0') + $minutes = $accessTokenValidity.Minutes.ToString().PadLeft(2, '0') + $seconds = $accessTokenValidity.Seconds.ToString().PadLeft(2, '0') + $accessTokenValidityText = "$hours`:$minutes`:$seconds" + if ($accessTokenIsValid) { + if ($accessTokenValidity.TotalHours -gt $script:Auth.AccessTokenGracePeriodInHours) { + if (-not $Silent) { + Write-Host '✓ ' -ForegroundColor Green -NoNewline + Write-Host "Access token is still valid for $accessTokenValidityText ..." + } + break + } else { + if (-not $Silent) { + Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline + Write-Host "Access token remaining validity $accessTokenValidityText. Refreshing access token..." + } + $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken (Get-GitHubConfig -Name 'RefreshToken') -HostName $HostName } - $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken (Get-GitHubConfig -Name 'RefreshToken') -HostName $HostName } else { - Write-Verbose "Using $Mode authentication..." - $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -Scope $Scope -HostName $HostName + $refreshTokenValidity = [datetime](Get-GitHubConfig -Name 'RefreshTokenExpirationDate') - (Get-Date) + $refreshTokenIsValid = $refreshTokenValidity.Seconds -gt 0 + if ($refreshTokenIsValid) { + if (-not $Silent) { + Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline + Write-Host 'Access token expired. Refreshing access token...' + } + $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken (Get-GitHubConfig -Name 'RefreshToken') -HostName $HostName + } else { + Write-Verbose "Using $Mode authentication..." + $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -Scope $Scope -HostName $HostName + } } } - } - Reset-GitHubConfig -Scope 'Auth' - switch ($Mode) { - 'GitHubApp' { - $settings = @{ - AccessToken = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token - AccessTokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.expires_in) - AccessTokenType = $tokenResponse.access_token -replace '_.*$', '_*' - ApiBaseUri = $ApiBaseUri - ApiVersion = $ApiVersion - AuthClientID = $authClientID - AuthType = $AuthType - DeviceFlowType = $Mode - HostName = $HostName - RefreshToken = ConvertTo-SecureString -AsPlainText $tokenResponse.refresh_token - RefreshTokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.refresh_token_expires_in) - Scope = $tokenResponse.scope + Reset-GitHubConfig -Scope 'Auth' + switch ($Mode) { + 'GitHubApp' { + $settings = @{ + AccessToken = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token + AccessTokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.expires_in) + AccessTokenType = $tokenResponse.access_token -replace '_.*$', '_*' + ApiBaseUri = $ApiBaseUri + ApiVersion = $ApiVersion + AuthClientID = $authClientID + AuthType = $AuthType + DeviceFlowType = $Mode + HostName = $HostName + RefreshToken = ConvertTo-SecureString -AsPlainText $tokenResponse.refresh_token + RefreshTokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.refresh_token_expires_in) + Scope = $tokenResponse.scope + } } - } - 'OAuthApp' { - $settings = @{ - AccessToken = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token - AccessTokenType = $tokenResponse.access_token -replace '_.*$', '_*' - ApiBaseUri = $ApiBaseUri - ApiVersion = $ApiVersion - AuthClientID = $authClientID - AuthType = $AuthType - DeviceFlowType = $Mode - HostName = $HostName - Scope = $tokenResponse.scope + 'OAuthApp' { + $settings = @{ + AccessToken = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token + AccessTokenType = $tokenResponse.access_token -replace '_.*$', '_*' + ApiBaseUri = $ApiBaseUri + ApiVersion = $ApiVersion + AuthClientID = $authClientID + AuthType = $AuthType + DeviceFlowType = $Mode + HostName = $HostName + Scope = $tokenResponse.scope + } } } + Set-GitHubConfig @settings + $user = Get-GitHubUser + $username = $user.login } - Set-GitHubConfig @settings - $user = Get-GitHubUser - $username = $user.login - } - 'App' { - Write-Verbose 'Logging in as a GitHub App...' - Reset-GitHubConfig -Scope 'Auth' - $jwt = Get-GitHubAppJWT -ClientId $ClientID -PrivateKey $PrivateKey - $settings = @{ - AccessToken = ConvertTo-SecureString -AsPlainText $jwt - AccessTokenType = 'JWT' - ApiBaseUri = $ApiBaseUri - ApiVersion = $ApiVersion - AuthType = $AuthType - ClientID = $ClientID - HostName = $HostName - } - Set-GitHubConfig @settings - $app = Get-GitHubApp - $username = $app.slug - } - 'Token' { - if ([string]::IsNullOrEmpty($AccessToken)) { - Write-Verbose 'Logging in using personal access token...' - Write-Host '! ' -ForegroundColor DarkYellow -NoNewline - Start-Process "https://$HostName/settings/tokens" - $accessTokenValue = Read-Host -Prompt 'Enter your personal access token' -AsSecureString - $AccessToken = ConvertFrom-SecureString $accessTokenValue -AsPlainText + 'App' { + Write-Verbose 'Logging in as a GitHub App...' + Reset-GitHubConfig -Scope 'Auth' + $jwt = Get-GitHubAppJWT -ClientId $ClientID -PrivateKey $PrivateKey + $settings = @{ + AccessToken = ConvertTo-SecureString -AsPlainText $jwt + AccessTokenType = 'JWT' + ApiBaseUri = $ApiBaseUri + ApiVersion = $ApiVersion + AuthType = $AuthType + ClientID = $ClientID + HostName = $HostName + } + Set-GitHubConfig @settings + $app = Get-GitHubApp + $username = $app.slug } - $accessTokenType = $AccessToken -replace '_.*$', '_*' - switch -Regex ($accessTokenType) { - '^ghp_|^github_pat_' { - Reset-GitHubConfig -Scope 'Auth' - $settings = @{ - AccessToken = $accessTokenValue - AccessTokenType = $accessTokenType - ApiBaseUri = $ApiBaseUri - ApiVersion = $ApiVersion - AuthType = 'PAT' - HostName = $HostName - } - Set-GitHubConfig @settings + 'Token' { + if ([string]::IsNullOrEmpty($AccessToken)) { + Write-Verbose 'Logging in using personal access token...' + Write-Host '! ' -ForegroundColor DarkYellow -NoNewline + Start-Process "https://$HostName/settings/tokens" + $accessTokenValue = Read-Host -Prompt 'Enter your personal access token' -AsSecureString + $AccessToken = ConvertFrom-SecureString $accessTokenValue -AsPlainText } - '^ghs_' { - Write-Verbose 'Logging in using GitHub access token...' - Reset-GitHubConfig -Scope 'Auth' - $settings = @{ - AccessToken = ConvertTo-SecureString -AsPlainText $AccessToken - AccessTokenType = $accessTokenType - ApiBaseUri = $ApiBaseUri - ApiVersion = $ApiVersion - AuthType = 'IAT' - HostName = $HostName + $accessTokenType = $AccessToken -replace '_.*$', '_*' + switch -Regex ($accessTokenType) { + '^ghp_|^github_pat_' { + Reset-GitHubConfig -Scope 'Auth' + $settings = @{ + AccessToken = $accessTokenValue + AccessTokenType = $accessTokenType + ApiBaseUri = $ApiBaseUri + ApiVersion = $ApiVersion + AuthType = 'PAT' + HostName = $HostName + } + Set-GitHubConfig @settings + } + '^ghs_' { + Write-Verbose 'Logging in using GitHub access token...' + Reset-GitHubConfig -Scope 'Auth' + $settings = @{ + AccessToken = ConvertTo-SecureString -AsPlainText $AccessToken + AccessTokenType = $accessTokenType + ApiBaseUri = $ApiBaseUri + ApiVersion = $ApiVersion + AuthType = 'IAT' + HostName = $HostName + } + Set-GitHubConfig @settings + $username = 'system' + } + default { + Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline + Write-Host "Unexpected access token format: $accessTokenType" } - Set-GitHubConfig @settings - $username = 'system' - } - default { - Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline - Write-Host "Unexpected access token format: $accessTokenType" } } } - } - - if (-not $Silent) { - Write-Host '✓ ' -ForegroundColor Green -NoNewline - Write-Host "Logged in as $username!" - } - if ($Owner) { - Set-GitHubConfig -Owner $Owner - } + if (-not $Silent) { + Write-Host '✓ ' -ForegroundColor Green -NoNewline + Write-Host "Logged in as $username!" + } - if ($Repo) { - Set-GitHubConfig -Repo $Repo - } + if ($Owner) { + Set-GitHubConfig -Owner $Owner + } - Remove-Variable -Name tokenResponse -ErrorAction SilentlyContinue - Remove-Variable -Name settings -ErrorAction SilentlyContinue - [System.GC]::Collect() + if ($Repo) { + Set-GitHubConfig -Repo $Repo + } + Remove-Variable -Name tokenResponse -ErrorAction SilentlyContinue + Remove-Variable -Name settings -ErrorAction SilentlyContinue + [System.GC]::Collect() + } catch { + throw $_ + } } From 9345e673f7783d19ab52d5cee87298470ec9da61 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Thu, 7 Nov 2024 14:27:09 +0100 Subject: [PATCH 07/11] test auto login --- .../Commands/Initialize-RunnerEnvironment.ps1 | 17 ++++---------- .../public/Auth/Connect-GitHubAccount.ps1 | 23 +++++++++++++++---- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 b/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 index 0bdffec51..254f8b59d 100644 --- a/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 +++ b/src/functions/private/Commands/Initialize-RunnerEnvironment.ps1 @@ -18,17 +18,10 @@ $env:GITHUB_REPOSITORY_NAME = $env:GITHUB_REPOSITORY -replace '.+/' Set-GitHubEnv -Name 'GITHUB_REPOSITORY_NAME' -Value $env:GITHUB_REPOSITORY_NAME - # Autologon if a token is present in environment variables - $gitHubToken = Get-ChildItem -Path 'Env:' | Where-Object Name -In 'GH_TOKEN', 'GITHUB_TOKEN' | Select-Object -First 1 -ExpandProperty Value - $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) - Write-Debug "GitHub token present: [$gitHubTokenPresent]" - if ($gitHubTokenPresent) { - $params = @{ - AccessToken = $gitHubToken - Owner = $env:GITHUB_REPOSITORY_OWNER - Repo = $env:GITHUB_REPOSITORY_NAME - Server = $env:GITHUB_SERVER_URL - } - Connect-GitHubAccount @params + $params = @{ + Owner = $env:GITHUB_REPOSITORY_OWNER + Repo = $env:GITHUB_REPOSITORY_NAME + Server = $env:GITHUB_SERVER_URL } + Connect-GitHubAccount @params } diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 14cbd179f..094e3129f 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -70,7 +70,10 @@ [Parameter(ParameterSetName = 'UAT')] [string] $Scope = 'gist read:org repo workflow', - # An access token to use for authentication. + # An access token to use for authentication. If left enpty, the user will be prompted to enter the token. + # Supports both personal access tokens and GitHub App installation access tokens. + # Example: 'ghp_1234567890abcdef' + # Example: 'ghs_1234567890abcdef' [Parameter( Mandatory, ParameterSetName = 'Token' @@ -100,12 +103,12 @@ [Parameter()] [Alias('Organization')] [Alias('Org')] - [string] $Owner, + [string] $Owner = $env:GITHUB_REPOSITORY_OWNER, # Set the default repository to use in commands. [Parameter()] [Alias('Repository')] - [string] $Repo, + [string] $Repo = $env:GITHUB_REPOSITORY_NAME, # API version used for API requests. [Parameter()] @@ -116,7 +119,7 @@ [Parameter()] [Alias('Host')] [Alias('Server')] - [string] $HostName = 'github.com', + [string] $HostName = $env:GITHUB_SERVER_URL ?? 'github.com', # Suppresses the output of the function. [Parameter()] @@ -129,7 +132,19 @@ $HostName = $HostName -replace '^https?://' $ApiBaseUri = "https://api.$HostName" + # First assume interactive logon $AuthType = $PSCmdlet.ParameterSetName + + if ($AuthType -ne 'Token' -and $env:GITHUB_ACTION -eq 'true') { + # Autologon if a token is present in environment variables + $gitHubToken = $env:GH_TOKEN ?? $env:GITHUB_TOKEN + $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) + Write-Debug "GitHub token present: [$gitHubTokenPresent]" + if ($gitHubTokenPresent) { + $AccessToken = $gitHubToken + } + } + Write-Verbose "AuthType: [$AuthType]" switch ($AuthType) { 'UAT' { From ddcdf0771b6e3a60e4d07de5fa797b7c81e3f0e6 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Thu, 7 Nov 2024 14:59:59 +0100 Subject: [PATCH 08/11] Override authtype --- src/functions/public/Auth/Connect-GitHubAccount.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 094e3129f..4978d2371 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -141,6 +141,7 @@ $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) Write-Debug "GitHub token present: [$gitHubTokenPresent]" if ($gitHubTokenPresent) { + $AuthType = 'Token' $AccessToken = $gitHubToken } } From 10a28c939655793029fe692cd4afeb0037b25017 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Thu, 7 Nov 2024 15:18:04 +0100 Subject: [PATCH 09/11] test --- src/functions/public/Auth/Connect-GitHubAccount.ps1 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 4978d2371..978b078fd 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -135,7 +135,9 @@ # First assume interactive logon $AuthType = $PSCmdlet.ParameterSetName - if ($AuthType -ne 'Token' -and $env:GITHUB_ACTION -eq 'true') { + Write-Verbose "Running on GitHub Actions: [$env:GITHUB_ACTION]" + + if ($env:GITHUB_ACTION -eq 'true') { # Autologon if a token is present in environment variables $gitHubToken = $env:GH_TOKEN ?? $env:GITHUB_TOKEN $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) From bc85c9af8475d7d4f3212e67c5dcb5326f11d588 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Thu, 7 Nov 2024 15:32:33 +0100 Subject: [PATCH 10/11] test --- src/functions/public/Auth/Connect-GitHubAccount.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index 978b078fd..cff855aac 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -135,9 +135,9 @@ # First assume interactive logon $AuthType = $PSCmdlet.ParameterSetName - Write-Verbose "Running on GitHub Actions: [$env:GITHUB_ACTION]" + Write-Verbose "Running on GitHub Actions: [$env:GITHUB_ACTIONS]" - if ($env:GITHUB_ACTION -eq 'true') { + if ($env:GITHUB_ACTIONS -eq 'true') { # Autologon if a token is present in environment variables $gitHubToken = $env:GH_TOKEN ?? $env:GITHUB_TOKEN $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) From e094935eedcaefc979015b8e7a5bec09eac3759a Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Thu, 7 Nov 2024 15:52:28 +0100 Subject: [PATCH 11/11] Fix --- src/functions/public/Auth/Connect-GitHubAccount.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/functions/public/Auth/Connect-GitHubAccount.ps1 b/src/functions/public/Auth/Connect-GitHubAccount.ps1 index cff855aac..a81c9f133 100644 --- a/src/functions/public/Auth/Connect-GitHubAccount.ps1 +++ b/src/functions/public/Auth/Connect-GitHubAccount.ps1 @@ -137,8 +137,8 @@ Write-Verbose "Running on GitHub Actions: [$env:GITHUB_ACTIONS]" - if ($env:GITHUB_ACTIONS -eq 'true') { - # Autologon if a token is present in environment variables + # Autologon if running on GitHub Actions and no access token is provided + if ($env:GITHUB_ACTIONS -eq 'true' -and [string]::IsNullOrEmpty($AccessToken)) { $gitHubToken = $env:GH_TOKEN ?? $env:GITHUB_TOKEN $gitHubTokenPresent = $gitHubToken.count -gt 0 -and -not [string]::IsNullOrEmpty($gitHubToken) Write-Debug "GitHub token present: [$gitHubTokenPresent]"