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
25 changes: 25 additions & 0 deletions powershell/internal/packs/Get-MtGitHubCliToken.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
function Get-MtGitHubCliToken {
<#
.SYNOPSIS
Asks the GitHub CLI for the github.com token it is signed in with, or returns $null.

.DESCRIPTION
Runs `gh auth token --hostname github.com` when the gh CLI is installed. The token is returned to the
caller and kept nowhere. Returns $null when gh is not installed, is not signed in, or fails.
#>
[CmdletBinding()]
[OutputType([string])]
param()

$gh = Get-Command -Name 'gh' -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $gh) { return $null }
try {
$output = & $gh.Source auth token --hostname github.com 2>$null
if ($LASTEXITCODE -ne 0) { return $null }
$token = ([string]($output | Select-Object -First 1)).Trim()
if ($token) { $token } else { $null }
} catch {
Write-Debug "gh auth token failed: $_"
$null
}
}
11 changes: 8 additions & 3 deletions powershell/internal/packs/Get-MtPackCandidate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,14 @@
# Fetch exactly this commit (Restore-MtPack), skipping release selection.
[Parameter()] [string] $Commit,
# The branch or tag the commit was installed from (the lock file's Ref), which it may be reachable from.
[Parameter()] [string] $CommitRef
[Parameter()] [string] $CommitRef,
# The -Token of the pack command, passed on to Invoke-MtPackGitHubRequest.
[Parameter()] [AllowNull()] [securestring] $Token
)

$auth = @{}
if ($Token) { $auth.Token = $Token }

# Staging is only a temporary copy to read, so it happens under -WhatIf too.
$WhatIfPreference = $false
$parsed = ConvertFrom-MtPackSource -Source $Source
Expand All @@ -52,14 +57,14 @@
}
'GitHub' {
if ($Commit) { $parsed.Ref = $Commit }
$resolved = Resolve-MtPackGitHubSource -Source $parsed -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $CooldownHours -ReachableFrom @($CommitRef | Where-Object { $_ })
$resolved = Resolve-MtPackGitHubSource @auth -Source $parsed -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $CooldownHours -ReachableFrom @($CommitRef | Where-Object { $_ })
foreach ($p in $resolved.PSObject.Properties) { if ($candidate.Contains($p.Name)) { $candidate[$p.Name] = $p.Value } }
$candidate.Source = "github.com/$($resolved.Owner)/$($resolved.Repo)$(if ($resolved.Folder) { "/$($resolved.Folder)" })"
$staging = Join-Path ([System.IO.Path]::GetTempPath()) "maester-pack-$([guid]::NewGuid().ToString('n'))"
$candidate.Staging = $staging
$null = New-Item -Path $staging -ItemType Directory -Force
$archive = Join-Path $staging 'archive.zip'
$null = Invoke-MtPackGitHubRequest -Path "repos/$($resolved.Owner)/$($resolved.Repo)/zipball/$($resolved.Commit)" -OutFile $archive
$null = Invoke-MtPackGitHubRequest @auth -Path "repos/$($resolved.Owner)/$($resolved.Repo)/zipball/$($resolved.Commit)" -OutFile $archive
$root = Join-Path $staging 'pack'
Expand-MtPackArchive -Archive $archive -Destination $root -Folder $resolved.Folder
Remove-Item -LiteralPath $archive -Force
Expand Down
50 changes: 50 additions & 0 deletions powershell/internal/packs/Get-MtPackGitHubToken.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
function Get-MtPackGitHubToken {
<#
.SYNOPSIS
Reads the GitHub token one source holds for pack installs, or returns $null.

.DESCRIPTION
Invoke-MtPackGitHubRequest asks each source in turn, at the moment of a request, and keeps none of the
answers:

- Parameter: the -Token a person passed to Install-MtPack, Update-MtPack or Restore-MtPack.
- Session: the sign-in Connect-MtGitHub holds for this session. It is used only when that connection is
to https://api.github.com and has not expired, so a token for a GitHub Enterprise Cloud tenant with
data residency (api.<name>.ghe.com) is never sent to github.com.
- GitHubCli: `gh auth token`, when the gh CLI is installed and signed in (Get-MtGitHubCliToken).
- GH_TOKEN and GITHUB_TOKEN: the environment variables, which pipelines set.
#>
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory)]
[ValidateSet('Parameter', 'Session', 'GitHubCli', 'GH_TOKEN', 'GITHUB_TOKEN')]
[string] $Source,

# The -Token parameter of the pack command, for the Parameter source.
[Parameter()]
[AllowNull()]
[securestring] $Token
)

switch ($Source) {
'Parameter' {
if (-not $Token -or $Token.Length -eq 0) { return $null }
return [System.Net.NetworkCredential]::new('', $Token).Password
}
'Session' {
$connection = $__MtSession.GitHubConnection
$header = $__MtSession.GitHubAuthHeader
if (-not $connection -or -not $connection.Connected -or $header -isnot [System.Collections.IDictionary]) { return $null }
if ([string]$connection.ApiBaseUri -ne 'https://api.github.com') { return $null }
$expires = if ($connection.PSObject.Properties['TokenExpiresAt']) { $connection.TokenExpiresAt }
if ($expires -and ([datetimeoffset]$expires) -le [datetimeoffset]::UtcNow) { return $null }
$value = [string]$header['Authorization']
if ($value -match '^Bearer\s+(\S+)$') { return $Matches[1] }
return $null
}
'GitHubCli' { return Get-MtGitHubCliToken }
'GH_TOKEN' { if ($env:GH_TOKEN) { return $env:GH_TOKEN } return $null }
'GITHUB_TOKEN' { if ($env:GITHUB_TOKEN) { return $env:GITHUB_TOKEN } return $null }
}
}
127 changes: 99 additions & 28 deletions powershell/internal/packs/Invoke-MtPackGitHubRequest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,28 @@
Calls the GitHub REST API for pack installs (Maester Packs design, section 5.1).

.DESCRIPTION
Sends GH_TOKEN or GITHUB_TOKEN, when one is set, to api.github.com only: a private repository needs it,
and it lifts GitHub's limit of 60 anonymous requests an hour. With -OutFile the response is saved to a
file (an archive download); GitHub redirects those to codeload.github.com, which receives no token.
A private repository needs a GitHub token, and a token lifts GitHub's limit of 60 anonymous requests an
hour. The token is read at the moment of the request (Get-MtPackGitHubToken), is sent to api.github.com
only, and is kept nowhere. With -OutFile the response is saved to a file (an archive download); GitHub
redirects those to codeload.github.com, which receives no token.

With -Token, that token is the only one used. Without it, each source is asked in turn and the first
that can read the repository is used:

1. the sign-in Connect-MtGitHub holds for this session, when it is to github.com;
2. `gh auth token`, when the GitHub CLI is installed and signed in;
3. the GH_TOKEN environment variable, then GITHUB_TOKEN;
4. no token.

A source GitHub answers with 401, 403 or 404 is passed over for the next one, since GitHub answers 404
for a private repository a token cannot read. Only the name of the source that worked is remembered, for
each repository, so later requests start with it.

Returns the parsed JSON, or $null for 404 with -AllowNotFound. Other failures throw with GitHub's
message and, when the rate limit was reached, how to raise it. -UsedToken says whether a token was sent.
#>
[CmdletBinding()]
[OutputType([object], [string])]
[OutputType([object], [object[]], [string])]
param(
# The path after https://api.github.com/, such as 'repos/contoso/pack'.
[Parameter(Mandatory)]
Expand All @@ -28,35 +41,93 @@

# Receives whether a token was sent (a [ref] to a bool).
[Parameter()]
[ref] $UsedToken
[ref] $UsedToken,

# The -Token of the pack command. When given, no other source is asked.
[Parameter()]
[AllowNull()]
[securestring] $Token
)

$token = if ($env:GH_TOKEN) { $env:GH_TOKEN } elseif ($env:GITHUB_TOKEN) { $env:GITHUB_TOKEN } else { $null }
if ($UsedToken) { $UsedToken.Value = [bool]$token }
$headers = @{ Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28'; 'User-Agent' = 'Maester' }
if ($token) { $headers['Authorization'] = "Bearer $token" }
$uri = "https://api.github.com/$($Path.TrimStart('/'))"
try {
if ($OutFile) {
$null = Invoke-WebRequest -Uri $uri -Headers $headers -OutFile $OutFile -MaximumRedirection 5 -ErrorAction Stop
return $OutFile
$labels = @{
Parameter = 'the -Token parameter'
Session = 'the Connect-MtGitHub sign-in'
GitHubCli = 'the GitHub CLI (gh auth token)'
GH_TOKEN = 'GH_TOKEN'
GITHUB_TOKEN = 'GITHUB_TOKEN'
}
$explicit = $Token -and $Token.Length -gt 0
$order = if ($explicit) { @('Parameter') } else { @('Session', 'GitHubCli', 'GH_TOKEN', 'GITHUB_TOKEN', 'Anonymous') }

# The source that last read this repository goes first. Its name is remembered, never its token.
if (-not $script:__MtPackGitHubTokenSource) { $script:__MtPackGitHubTokenSource = @{} }
$repository = if ($Path.TrimStart('/') -match '^repos/([^/?]+/[^/?]+)') { $Matches[1].ToLowerInvariant() }
$proven = if (-not $explicit -and $repository) { $script:__MtPackGitHubTokenSource[$repository] }
if ($proven) { $order = @($proven) + @($order | Where-Object { $_ -ne $proven }) }

$sent = [System.Collections.Generic.List[string]]::new()
$tried = [System.Collections.Generic.List[string]]::new()
$failure = $null
foreach ($source in $order) {
$value = $null
if ($source -ne 'Anonymous') {
$value = Get-MtPackGitHubToken -Source $source -Token $Token
# gh answers with GH_TOKEN when it is set, so the same token is not sent twice.
if (-not $value -or $sent.Contains($value)) { continue }
$sent.Add($value)
$tried.Add($labels[$source])
}
Invoke-RestMethod -Uri $uri -Headers $headers -ErrorAction Stop
} catch {
$status = $null
if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
if ($status -eq 404 -and $AllowNotFound) { return $null }
$message = $_.ErrorDetails.Message
try { if ($message) { $message = ($message | ConvertFrom-Json -ErrorAction Stop).message } } catch { Write-Debug $_ }
if (-not $message) { $message = $_.Exception.Message }
if ($status -in 403, 429 -and $message -match 'rate limit') {
$hint = if ($token) { 'Wait for the limit to reset.' } else { 'Set GH_TOKEN (for example from `gh auth token`) to raise the limit.' }
throw "GitHub's API rate limit was reached while reading $uri. $hint"
$headers = @{ Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28'; 'User-Agent' = 'Maester' }
if ($value) { $headers['Authorization'] = "Bearer $value" }
try {
if ($OutFile) {
$null = Invoke-WebRequest -Uri $uri -Headers $headers -OutFile $OutFile -MaximumRedirection 5 -ErrorAction Stop
$result = $OutFile
} else {
$result = Invoke-RestMethod -Uri $uri -Headers $headers -ErrorAction Stop
}
} catch {
$status = $null
if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
$message = $_.ErrorDetails.Message
try { if ($message) { $message = ($message | ConvertFrom-Json -ErrorAction Stop).message } } catch { Write-Debug $_ }
if (-not $message) { $message = $_.Exception.Message }
if ($status -in 403, 429 -and $message -match 'rate limit') {
$hint = if ($value) { 'Wait for the limit to reset.' } else { 'Sign in with `gh auth login` or Connect-MtGitHub, or pass -Token, to raise the limit.' }
throw "GitHub's API rate limit was reached while reading $uri. $hint"
}
$failure = [pscustomobject]@{ Status = $status; Message = $message }
# The source that already read this repository says a path is missing: no other source will find it.
if ($status -eq 404 -and $source -eq $proven) { break }
if ($status -in 401, 403, 404) {
if ($source -eq $proven) { $script:__MtPackGitHubTokenSource.Remove($repository) }
Write-Verbose "GitHub answered $status for $uri with $(if ($value) { $labels[$source] } else { 'no token' })."
continue
}
break
} finally {
$headers.Remove('Authorization')
$value = $null
}
if ($status -eq 404) {
$hint = if ($token) { '' } else { ' If it is a private repository, set GH_TOKEN to a token that can read it.' }
throw "GitHub returned 404 Not Found for $uri.$hint"
if ($UsedToken) { $UsedToken.Value = $source -ne 'Anonymous' }
if (-not $explicit -and $repository) { $script:__MtPackGitHubTokenSource[$repository] = $source }
Write-Verbose "Read $uri with $(if ($source -eq 'Anonymous') { 'no token' } else { $labels[$source] })."
if ($result -is [array]) { return , $result }
return $result
}

if ($UsedToken) { $UsedToken.Value = $tried.Count -gt 0 }
if ($failure.Status -eq 404) {
if ($AllowNotFound) { return $null }
$hint = if ($explicit) {
' It does not exist, or the token passed to -Token cannot read it. A fine-grained token needs read-only Contents access to the repository.'
} elseif ($tried.Count -gt 0) {
" It does not exist, or it is a private repository that $($tried -join ' and ') cannot read. Pass -Token with a token that can read it."
} else {
' If it is a private repository, sign in with `gh auth login`, or pass -Token with a token that can read it.'
}
throw "GitHub request $uri failed$(if ($status) { " ($status)" }): $message"
throw "GitHub returned 404 Not Found for $uri.$hint"
}
throw "GitHub request $uri failed$(if ($failure.Status) { " ($($failure.Status))" }): $($failure.Message)"
}
11 changes: 8 additions & 3 deletions powershell/internal/packs/Invoke-MtPackInstall.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,15 @@
# The pack IDs being installed above this one, to refuse cycles.
[Parameter()] [string[]] $Stack = @(),
# Return -Previous when the fetched files have its digest, without asking again.
[Parameter()] [switch] $SkipUnchanged
[Parameter()] [switch] $SkipUnchanged,
# The -Token of the pack command, used for this pack and the packs it requires.
[Parameter()] [AllowNull()] [securestring] $Token
)

$candidate = Get-MtPackCandidate -Source $Source -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $Policy.CooldownHours
$auth = @{}
if ($Token) { $auth.Token = $Token }

$candidate = Get-MtPackCandidate @auth -Source $Source -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $Policy.CooldownHours
try {
if ($candidate.Errors.Count -gt 0) {
$list = @($candidate.Errors | Select-Object -First 15 | ForEach-Object { " $($_.Code): $(ConvertTo-MtPackSafeText $_.Message -MaxLength 300)" }) -join [Environment]::NewLine
Expand Down Expand Up @@ -77,7 +82,7 @@
}
if (-not ($r.PSObject.Properties['Source'] -and $r.Source)) { throw "The pack $id requires $($r.Id), which is not installed and has no Source to install it from." }
Write-Host "The pack $id requires $($r.Id)$(if ($range) { " $range" }); installing it first."
$entry = Invoke-MtPackInstall -Source $r.Source -Lock $Lock -Policy $Policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$NonInteractive -Stack @($Stack + $id)
$entry = Invoke-MtPackInstall @auth -Source $r.Source -Lock $Lock -Policy $Policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$NonInteractive -Stack @($Stack + $id)
if ($entry.Id -ne $r.Id) { throw "The pack $id requires $($r.Id) from $($r.Source), but that source holds $($entry.Id)." }
if ($range -and -not (Test-MtVersionRange -Range $range -Version $entry.Version)) { throw "The pack $id requires $($r.Id) $range, but $($r.Source) has version $($entry.Version)." }
foreach ($s in @($entry.Services)) { $requiredServices.Add($s) }
Expand Down
Loading
Loading