Files
mtusi2026lab7/scripts/rotate-grafana-admin-password.ps1
T

133 lines
5.5 KiB
PowerShell

[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[int]$Port = 3000
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
$envPath = Join-Path $projectRoot $EnvFile
$caCertificate = Join-Path $projectRoot 'secrets\pki\service-ca\ca.crt'
if (-not (Test-Path -LiteralPath $envPath)) { throw "Missing env file: $EnvFile" }
if (-not (Test-Path -LiteralPath $caCertificate)) { throw "Missing service CA: $caCertificate" }
function Get-EnvValue([string]$Name) {
foreach ($line in [System.IO.File]::ReadAllLines($envPath)) {
if ($line -match "^\s*$([regex]::Escape($Name))=(.*)$") {
return $Matches[1].Trim().Trim('"')
}
}
return $null
}
function Set-EnvValue([string]$Name, [string]$Value) {
$lines = [System.IO.File]::ReadAllLines($envPath)
$updated = $false
for ($index = 0; $index -lt $lines.Count; $index++) {
if ($lines[$index] -match "^\s*$([regex]::Escape($Name))=") {
$lines[$index] = "$Name=$Value"
$updated = $true
break
}
}
if (-not $updated) { throw "$Name is missing from $EnvFile" }
[System.IO.File]::WriteAllLines($envPath, $lines, [System.Text.UTF8Encoding]::new($false))
}
function Invoke-Grafana([string]$User, [string]$Password, [string]$Path,
[string]$Method = 'GET', [string]$Body = '') {
$arguments = @('-sS','-o','NUL','-w','%{http_code}','--cacert',$caCertificate,
'--ssl-no-revoke','--connect-timeout','5','--max-time','15','-u',"$User`:$Password")
if ($Method -ne 'GET') { $arguments += @('-X',$Method) }
$bodyFile = $null
if ($Body) {
# curl.exe on Windows must receive JSON from a file: inline arguments
# are quote-stripped, and PowerShell's default UTF-8 writer adds a BOM.
$bodyFile = Join-Path ([System.IO.Path]::GetTempPath()) ("grafana-rotation-" + [guid]::NewGuid().ToString('N') + '.json')
[System.IO.File]::WriteAllText($bodyFile, $Body, [System.Text.UTF8Encoding]::new($false))
$arguments += @('-H','Content-Type: application/json','--data-binary',"@$bodyFile")
}
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$code = (& curl.exe @arguments "https://localhost:$Port$Path" 2>$null | Out-String).Trim()
} finally {
$ErrorActionPreference = $previous
if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -Force -ErrorAction SilentlyContinue }
}
return $code
}
function Invoke-ComposeQuiet([string[]]$Arguments) {
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& docker compose @Arguments 2>&1 | Out-Null
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if ($code -ne 0) { throw "docker compose failed with exit code $code" }
}
function New-RotationPassword {
$bytes = New-Object byte[] 24
$generator = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try { $generator.GetBytes($bytes) } finally { $generator.Dispose() }
return [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=')
}
$user = Get-EnvValue 'GRAFANA_ADMIN_USER'
if ([string]::IsNullOrWhiteSpace($user)) { $user = 'admin' }
$oldPassword = Get-EnvValue 'GRAFANA_ADMIN_PASSWORD'
if ([string]::IsNullOrWhiteSpace($oldPassword)) { throw 'GRAFANA_ADMIN_PASSWORD is missing from the env file' }
$newPassword = New-RotationPassword
$imageBefore = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim()
if ((Invoke-Grafana $user $oldPassword '/api/user') -ne '200') {
throw 'Current Grafana admin credentials were not accepted before rotation'
}
$body = @{
oldPassword = $oldPassword
newPassword = $newPassword
confirmNew = $newPassword
} | ConvertTo-Json -Compress
$rotationStatus = Invoke-Grafana $user $oldPassword '/api/user/password' 'PUT' $body
if ($rotationStatus -ne '200' -and $rotationStatus -ne '204') {
throw "Grafana password API returned an unexpected status: $rotationStatus"
}
$envBackup = [System.IO.File]::ReadAllBytes($envPath)
try {
Set-EnvValue 'GRAFANA_ADMIN_PASSWORD' $newPassword
Invoke-ComposeQuiet @('--env-file',$EnvFile,'up','-d','--no-deps','--force-recreate','grafana')
$ready = $false
for ($attempt = 0; $attempt -lt 30; $attempt++) {
if ((Invoke-Grafana $user $newPassword '/api/user') -eq '200') { $ready = $true; break }
Start-Sleep -Seconds 2
}
if (-not $ready) { throw 'Rotated Grafana credentials were not accepted after container recreate' }
if ((Invoke-Grafana $user $oldPassword '/api/user') -eq '200') {
throw 'Old Grafana password is still accepted after rotation'
}
} catch {
[System.IO.File]::WriteAllBytes($envPath, $envBackup)
$rollbackBody = @{
oldPassword = $newPassword
newPassword = $oldPassword
confirmNew = $oldPassword
} | ConvertTo-Json -Compress
Invoke-Grafana $user $newPassword '/api/user/password' 'PUT' $rollbackBody | Out-Null
throw
}
$imageAfter = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim()
if ($imageBefore -ne $imageAfter) { throw 'Grafana image changed during rotation' }
Write-Host 'PASS: Grafana admin password rotated through the API and .env without rebuilding images.'
Write-Host "old_password_accepted_after=false"
Write-Host "new_password_accepted_after=true"
Write-Host "grafana_image=$imageAfter"