-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeploy-FromRelease.ps1
More file actions
428 lines (373 loc) · 19.5 KB
/
Copy pathDeploy-FromRelease.ps1
File metadata and controls
428 lines (373 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<#
.SYNOPSIS
Deploys BitLockerKeyMonitor to a remote Windows Server using PRE-BUILT
binaries from a GitHub Release (no source code or .NET SDK required).
.DESCRIPTION
Thin wrapper around Deploy-Remote.ps1 that:
1. Resolves a release tag on github.com/robgrame/BitLockerKeyMonitor
(defaults to the latest published release).
2. Auto-fetches Deploy-Remote.ps1 from the resolved tag if it's not
already next to this script — so the operator can deploy with a
single .ps1 file in hand.
3. Downloads the Worker and Web ZIP assets for that release
(prefers `gh release download`; falls back to the public REST API).
4. Extracts them into .\artifacts\Worker and .\artifacts\Web — wiping any
stale contents first so a version downgrade cannot leave orphan DLLs.
5. Sanity-checks the Worker publish layout (the 92 KB Windows impl of
System.ServiceProcess.ServiceController.dll must be at the publish
root, NOT the netstandard stub — see Deploy-Remote.ps1 notes).
6. Invokes Deploy-Remote.ps1 -SkipPublish with all pass-through params.
Use this for air-gapped or build-server-less deploys, or when you simply
want to pin a deployment to a known-good release.
Prerequisites on the DEPLOY machine:
- Windows PowerShell 5.1 or PowerShell 7+
- Either:
* GitHub CLI (`gh`) on PATH AND authenticated (`gh auth status`), OR
* Outbound HTTPS to github.com / api.github.com /
raw.githubusercontent.com / objects.githubusercontent.com
- That's it. No .NET SDK, no source code, no second .ps1 file required.
.PARAMETER TargetServer
Hostname or FQDN of the target server. Required.
.PARAMETER Version
Release tag to deploy (e.g. "v1.5.2"). Default: "latest" (resolves to the
most recent non-draft, non-prerelease release).
.PARAMETER Repository
GitHub repository in OWNER/NAME form. Default: robgrame/BitLockerKeyMonitor.
.PARAMETER LocalZipDir
Air-gapped mode: skip download and use Worker/Web ZIP files already present
in this folder. The script picks the first file matching
*Worker*win-x64.zip and *Web*win-x64.zip respectively.
.PARAMETER Credential
PSCredential for the target server. Forwarded to Deploy-Remote.ps1.
.PARAMETER InstallRoot
Installation folder on the target. Default: C:\Program Files\BitLockerKeyMonitor
.PARAMETER SqlInstanceName
SQL Server instance name on the target. Default: SQLEXPRESS
.PARAMETER SkipServiceRestart
Deploy binaries but do not restart services.
.PARAMETER GraphCertificateThumbprint
SHA-1 thumbprint merged in-place into BOTH Worker and Web appsettings.json
under Authentication:CertificateThumbprint. See Deploy-Remote.ps1.
.PARAMETER HttpsCertificateThumbprint
SHA-1 thumbprint merged in-place into Web appsettings.json under
WebServer:CertificateThumbprint. See Deploy-Remote.ps1.
.PARAMETER GitHubToken
Optional Personal Access Token (or GITHUB_TOKEN). Use when:
- Deploying from a PRIVATE repo (required), or
- The unauthenticated REST API rate limit (60 req/hr/IP) is hit.
Falls back to the GITHUB_TOKEN environment variable if not supplied.
Has no effect when gh is available AND already authenticated.
.PARAMETER NoGh
Force the REST API path even if the GitHub CLI is installed. Useful for
testing the fallback or when you don't want gh's stored credentials used.
.PARAMETER KeepArtifacts
Do not delete .\artifacts after a successful deploy (useful for debugging).
.EXAMPLE
# Deploy the latest release
.\Deploy-FromRelease.ps1 -TargetServer SRVBLKMON01
.EXAMPLE
# Pin to a specific version with cert thumbprints
.\Deploy-FromRelease.ps1 -TargetServer srvblkmon01.mslabs.local `
-Version v1.5.2 `
-GraphCertificateThumbprint 855CDF6182DE9CBD6C7D3C95340B5CAA7222D2BA `
-HttpsCertificateThumbprint AABBCCDDEEFF00112233445566778899AABBCCDD
.EXAMPLE
# Air-gapped: zips already on a USB stick at D:\Releases\v1.5.2
.\Deploy-FromRelease.ps1 -TargetServer SRVBLKMON01 -LocalZipDir D:\Releases\v1.5.2
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$TargetServer,
[string]$Version = "latest",
[string]$Repository = "robgrame/BitLockerKeyMonitor",
[string]$LocalZipDir,
[PSCredential]$Credential,
[string]$InstallRoot = "C:\Program Files\BitLockerKeyMonitor",
[string]$SqlInstanceName = "SQLEXPRESS",
[switch]$SkipServiceRestart,
[ValidateScript({
if ($_ -match '^[A-Fa-f0-9]{40}$') { return $true }
throw "GraphCertificateThumbprint must be a 40-character hex SHA-1 thumbprint (got '$_')."
})]
[string]$GraphCertificateThumbprint,
[ValidateScript({
if ($_ -match '^[A-Fa-f0-9]{40}$') { return $true }
throw "HttpsCertificateThumbprint must be a 40-character hex SHA-1 thumbprint (got '$_')."
})]
[string]$HttpsCertificateThumbprint,
[string]$GitHubToken = $env:GITHUB_TOKEN,
[switch]$NoGh,
[switch]$KeepArtifacts
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Force TLS 1.2 for Windows PowerShell 5.1 — github.com refuses TLS 1.0/1.1.
# Harmless no-op on PS 7+ which already defaults to system protocols.
try {
[Net.ServicePointManager]::SecurityProtocol =
[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
} catch { }
# ── UX helpers (mirrors Deploy-Remote.ps1) ──────────────────────────────────
function Write-Step { param([string]$msg) Write-Host "`n▶ $msg" -ForegroundColor Cyan }
function Write-Ok { param([string]$msg) Write-Host " ✓ $msg" -ForegroundColor Green }
function Write-Warn { param([string]$msg) Write-Host " ⚠ $msg" -ForegroundColor Yellow }
function Write-Err { param([string]$msg) Write-Host " ✗ $msg" -ForegroundColor Red }
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$DeployRemoteSrc = Join-Path $ScriptDir "Deploy-Remote.ps1"
$ArtifactsDir = Join-Path $ScriptDir "artifacts"
$WorkerPubDir = Join-Path $ArtifactsDir "Worker"
$WebPubDir = Join-Path $ArtifactsDir "Web"
$DownloadDir = Join-Path $ArtifactsDir "_download"
# Deploy-Remote.ps1 is auto-fetched from the resolved release tag if not
# present locally — see the resolution section below. The strict check happens
# right before we hand off, so the operator can deploy with ONLY this script.
# ── GitHub REST helpers (work without gh) ───────────────────────────────────
# These cover the case where the operator's deploy box does NOT have the
# GitHub CLI installed. Only PowerShell's built-in Invoke-RestMethod /
# Invoke-WebRequest is used. For PUBLIC repos no token is required (60 unauth
# requests/hr/IP is plenty for a deploy). For PRIVATE repos or to dodge rate
# limits, pass -GitHubToken or set $env:GITHUB_TOKEN.
function Get-GitHubHeaders {
param([string]$Token)
$h = @{
"User-Agent" = "BitLockerKeyMonitor-Deploy"
"Accept" = "application/vnd.github+json"
}
if ($Token) { $h["Authorization"] = "Bearer $Token" }
return $h
}
function Get-ReleaseInfo {
param(
[string]$Repo,
[string]$Tag, # "latest" or explicit, e.g. "v1.5.2"
[string]$Token
)
$url = if ($Tag -eq "latest") {
"https://api.github.com/repos/$Repo/releases/latest"
} else {
"https://api.github.com/repos/$Repo/releases/tags/$Tag"
}
try {
return Invoke-RestMethod -Uri $url -Headers (Get-GitHubHeaders $Token) -UseBasicParsing
} catch {
$status = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 }
if ($status -eq 404) { throw "Release '$Tag' not found in $Repo (HTTP 404). For private repos pass -GitHubToken." }
elseif ($status -eq 401) { throw "GitHub returned 401 Unauthorized. Check -GitHubToken / `$env:GITHUB_TOKEN." }
elseif ($status -eq 403) { throw "GitHub returned 403 (likely rate-limited). Pass -GitHubToken to authenticate." }
else { throw }
}
}
function Save-ReleaseAsset {
param(
[Parameter(Mandatory)] $Asset, # asset object from /releases API
[Parameter(Mandatory)] [string]$OutFile,
[string]$Token
)
# PowerShell 5.1 Invoke-WebRequest shows a progress bar by default that can
# slow large downloads by ~100x. Silence it just for this call.
$prevProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
# browser_download_url works without auth for public repos. For private
# repos we hit the asset API endpoint with Accept: application/octet-stream.
if ($Token) {
$url = "https://api.github.com/repos/$Repository/releases/assets/$($Asset.id)"
$h = Get-GitHubHeaders $Token
$h["Accept"] = "application/octet-stream"
Invoke-WebRequest -Uri $url -OutFile $OutFile -Headers $h -UseBasicParsing
} else {
Invoke-WebRequest -Uri $Asset.browser_download_url -OutFile $OutFile `
-Headers (Get-GitHubHeaders $null) -UseBasicParsing
}
} finally {
$ProgressPreference = $prevProgress
}
}
# Detect whether to use gh — it's an OPTIMIZATION, not a requirement.
$ghAvailable = (-not $NoGh) -and [bool](Get-Command gh -ErrorAction SilentlyContinue)
# ── Resolve release tag ─────────────────────────────────────────────────────
if (-not $LocalZipDir) {
Write-Step "Resolving release"
if ($Version -eq "latest") {
if ($ghAvailable) {
$json = gh release view --repo $Repository --json tagName 2>$null
if ($LASTEXITCODE -eq 0 -and $json) {
$Version = (ConvertFrom-Json $json).tagName
} else {
$Version = (Get-ReleaseInfo -Repo $Repository -Tag "latest" -Token $GitHubToken).tag_name
}
} else {
$Version = (Get-ReleaseInfo -Repo $Repository -Tag "latest" -Token $GitHubToken).tag_name
}
if (-not $Version) { Write-Err "Failed to resolve latest release tag for $Repository"; exit 1 }
}
Write-Ok "Will deploy $Repository @ $Version (gh=$ghAvailable, token=$([bool]$GitHubToken))"
}
# ── Ensure Deploy-Remote.ps1 is available (auto-fetch if missing) ───────────
# Pin to the resolved release tag so the orchestrator and the deploy script
# always come from the SAME commit — no risk of a master-branch fetch drifting
# from the release behavior. raw.githubusercontent.com at a tag is immutable.
if (-not (Test-Path $DeployRemoteSrc)) {
if ($LocalZipDir) {
# In air-gapped mode we cannot reach github; Deploy-Remote.ps1 MUST be local.
Write-Err "Deploy-Remote.ps1 not found next to this script: $DeployRemoteSrc"
Write-Err "In -LocalZipDir mode the deploy script cannot be auto-fetched. Copy it from the repo."
exit 1
}
Write-Step "Fetching Deploy-Remote.ps1 from $Repository @ $Version"
$rawUrl = "https://raw.githubusercontent.com/$Repository/$Version/Deploy-Remote.ps1"
$prevProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
Invoke-WebRequest -Uri $rawUrl -OutFile $DeployRemoteSrc `
-Headers (Get-GitHubHeaders $GitHubToken) -UseBasicParsing
} catch {
Write-Err "Failed to download Deploy-Remote.ps1 from $rawUrl"
Write-Err $_.Exception.Message
Write-Err "Place Deploy-Remote.ps1 next to this script and retry, or pass -GitHubToken for private repos."
exit 1
} finally {
$ProgressPreference = $prevProgress
}
$sz = (Get-Item $DeployRemoteSrc).Length
if ($sz -lt 1000) {
Write-Err "Downloaded Deploy-Remote.ps1 is suspiciously small ($sz bytes) — aborting."
Remove-Item -Force $DeployRemoteSrc -ErrorAction SilentlyContinue
exit 1
}
Write-Ok "Deploy-Remote.ps1 fetched ($sz bytes) — pinned to $Version"
}
# ── Acquire ZIPs (download or local) ────────────────────────────────────────
$workerZip = $null
$webZip = $null
if ($LocalZipDir) {
Write-Step "Locating ZIPs in $LocalZipDir"
if (-not (Test-Path $LocalZipDir)) {
Write-Err "LocalZipDir does not exist: $LocalZipDir"
exit 1
}
$workerZip = Get-ChildItem -Path $LocalZipDir -Filter "*Worker*win-x64.zip" -File |
Select-Object -First 1 -ExpandProperty FullName
$webZip = Get-ChildItem -Path $LocalZipDir -Filter "*Web*win-x64.zip" -File |
Select-Object -First 1 -ExpandProperty FullName
if (-not $workerZip) { Write-Err "No Worker ZIP found in $LocalZipDir (expected *Worker*win-x64.zip)"; exit 1 }
if (-not $webZip) { Write-Err "No Web ZIP found in $LocalZipDir (expected *Web*win-x64.zip)"; exit 1 }
Write-Ok "Worker → $workerZip"
Write-Ok "Web → $webZip"
} else {
Write-Step "Downloading release assets"
if (Test-Path $DownloadDir) { Remove-Item -Recurse -Force $DownloadDir }
New-Item -ItemType Directory -Path $DownloadDir | Out-Null
$patternWorker = "*Worker*win-x64.zip"
$patternWeb = "*Web*win-x64.zip"
$usedGh = $false
if ($ghAvailable) {
# `gh release download` validates auth + handles private repos transparently.
& gh release download $Version `
--repo $Repository `
--pattern $patternWorker `
--pattern $patternWeb `
--dir $DownloadDir 2>&1 | Write-Host
if ($LASTEXITCODE -eq 0) {
$usedGh = $true
} else {
Write-Warn "gh release download failed (exit $LASTEXITCODE) — falling back to REST API"
}
}
if (-not $usedGh) {
$rel = Get-ReleaseInfo -Repo $Repository -Tag $Version -Token $GitHubToken
$matched = $rel.assets | Where-Object {
$_.name -like $patternWorker -or $_.name -like $patternWeb
}
if (-not $matched) {
Write-Err "Release $Version contains no assets matching $patternWorker / $patternWeb"
exit 1
}
foreach ($asset in $matched) {
$dest = Join-Path $DownloadDir $asset.name
Write-Host (" ↓ {0} ({1:N1} MB)" -f $asset.name, ($asset.size/1MB)) -ForegroundColor DarkGray
$sw = [Diagnostics.Stopwatch]::StartNew()
Save-ReleaseAsset -Asset $asset -OutFile $dest -Token $GitHubToken
$sw.Stop()
$got = (Get-Item $dest).Length
if ($got -ne $asset.size) {
Write-Err "Size mismatch for $($asset.name): got $got, expected $($asset.size)"
exit 1
}
Write-Host (" done in {0:N1}s" -f $sw.Elapsed.TotalSeconds) -ForegroundColor DarkGray
}
}
$workerZip = Get-ChildItem -Path $DownloadDir -Filter $patternWorker -File |
Select-Object -First 1 -ExpandProperty FullName
$webZip = Get-ChildItem -Path $DownloadDir -Filter $patternWeb -File |
Select-Object -First 1 -ExpandProperty FullName
if (-not $workerZip) { Write-Err "Worker ZIP not downloaded — does release $Version include a $patternWorker asset?"; exit 1 }
if (-not $webZip) { Write-Err "Web ZIP not downloaded — does release $Version include a $patternWeb asset?"; exit 1 }
Write-Ok "Worker ZIP: $(Split-Path -Leaf $workerZip)"
Write-Ok "Web ZIP: $(Split-Path -Leaf $webZip)"
}
# ── Extract ─────────────────────────────────────────────────────────────────
Write-Step "Extracting artifacts"
foreach ($pair in @(@{ Zip = $workerZip; Dest = $WorkerPubDir; Label = "Worker" },
@{ Zip = $webZip; Dest = $WebPubDir; Label = "Web" })) {
if (Test-Path $pair.Dest) { Remove-Item -Recurse -Force $pair.Dest }
New-Item -ItemType Directory -Path $pair.Dest | Out-Null
Expand-Archive -Path $pair.Zip -DestinationPath $pair.Dest -Force
$fileCount = (Get-ChildItem -Path $pair.Dest -Recurse -File).Count
Write-Ok "$($pair.Label) → $($pair.Dest) ($fileCount files)"
}
# ── Sanity check: Worker must have the WINDOWS ServiceController impl ───────
# Without -r win-x64 in the publish, a 35 KB netstandard stub of
# System.ServiceProcess.ServiceController.dll ends up at the publish root and
# overrides the 92 KB Windows impl in runtimes\win\lib\net10.0\, causing the
# service to crash at startup with PlatformNotSupportedException.
$svcDll = Join-Path $WorkerPubDir "System.ServiceProcess.ServiceController.dll"
if (Test-Path $svcDll) {
$sz = (Get-Item $svcDll).Length
if ($sz -lt 80000) {
Write-Err ("System.ServiceProcess.ServiceController.dll at Worker root is only $sz bytes " +
"(expected ~92 KB Windows impl). The release asset was built without -r win-x64; " +
"the Worker service WILL crash on start with PlatformNotSupportedException.")
exit 1
}
Write-Ok "ServiceController.dll OK ($sz bytes, Windows impl)"
} else {
Write-Warn "ServiceController.dll not found at Worker root — Worker may fail to install as a service"
}
# Show version of the published Worker so the operator can confirm what's being deployed
$workerExe = Join-Path $WorkerPubDir "BitLockerKeyMonitor.Worker.exe"
if (Test-Path $workerExe) {
$vi = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($workerExe)
Write-Ok "Deploying Worker ProductVersion=$($vi.ProductVersion) FileVersion=$($vi.FileVersion)"
}
# ── Hand off to Deploy-Remote.ps1 ───────────────────────────────────────────
# Deploy-Remote.ps1 has no explicit `exit 0` at the end — on success the script
# returns normally; on failure it calls `exit 1` which terminates THIS host
# process too. So any code below the invocation only runs on success, and we
# don't need to inspect $LASTEXITCODE (which is unreliable after a .ps1 with
# no explicit exit).
Write-Step "Invoking Deploy-Remote.ps1 -SkipPublish"
$deployArgs = @{
TargetServer = $TargetServer
InstallRoot = $InstallRoot
SqlInstanceName = $SqlInstanceName
SkipPublish = $true
}
if ($Credential) { $deployArgs.Credential = $Credential }
if ($SkipServiceRestart) { $deployArgs.SkipServiceRestart = $true }
if ($GraphCertificateThumbprint) { $deployArgs.GraphCertificateThumbprint = $GraphCertificateThumbprint }
if ($HttpsCertificateThumbprint) { $deployArgs.HttpsCertificateThumbprint = $HttpsCertificateThumbprint }
& $DeployRemoteSrc @deployArgs
# ── Cleanup (only reached on Deploy-Remote success) ─────────────────────────
if (-not $KeepArtifacts) {
Write-Step "Cleaning up downloaded artifacts"
Remove-Item -Recurse -Force $WorkerPubDir -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force $WebPubDir -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force $DownloadDir -ErrorAction SilentlyContinue
# Remove artifacts/ only if empty (don't clobber unrelated files a user may have placed there)
if ((Test-Path $ArtifactsDir) -and -not (Get-ChildItem -Path $ArtifactsDir -Force)) {
Remove-Item -Force $ArtifactsDir
}
Write-Ok "Cleaned (use -KeepArtifacts to preserve)"
}