conocimientocicd-architecttemplates/8205 B
Provision-QualityCiKey.github.ps1.template
Fichero que /hv:cicd-architect usa o materializa en el proyecto. Se muestra tal cual está en el plugin.
#Requires -Version 5.1
<#
.SYNOPSIS
Zero-touch de la HUB_SERVICE_KEY del QR de calidad en un repositorio de GitHub.
.DESCRIPTION
Homologo de Provision-QualityCiKey.ps1.template para cicd.platform = github-actions.
Aprovisiona la service-key del dashboard de calidad SIN intervencion manual:
1. Resuelve la apiKey per-dev del consumidor (_hilo/.mcp-credentials.json).
2. Pide al Hub que EMITA/ROTE la service-key del proyecto (POST /v2/sync/emit-service-key).
La key viaja en memoria; NUNCA se imprime ni se pasa por linea de comandos.
3. La guarda como secret de GitHub Actions (HUB_SERVICE_KEY) con `gh secret set` leyendo de STDIN
(nunca con --body: quedaria en el historial de la shell). Secret de repositorio por defecto;
con -Env, secret del environment indicado.
4. Publica HUB_PROJECT_ID como variable (no secreta) con `gh variable set`.
Lo invoca /cicd-init FASE 2.7 (opcion Auto) en proyectos GitHub. Degrada con elegancia: si falla,
/cicd-init cae al flujo manual (admin emite por SQL + `gh secret set HUB_SERVICE_KEY < key.txt`) y la
composite action quality-sync sigue siendo best-effort (sin key -> avisa, no rompe el workflow).
No hay "autorizacion del Variable Group": los secrets de repositorio los lee cualquier workflow del repo;
los de environment, solo los jobs con ese `environment:`. Requiere `gh` autenticado con scope `repo` y
permiso de administracion sobre el repositorio (secrets). Rotacion: -Rotate.
NUNCA imprime la service-key (stdout solo [OK]/[WARN] + nombres).
.PARAMETER ProjectId GUID del proyecto en el Hub (default: el de .mcp-credentials.json).
.PARAMETER ServerUrl Base del Hub (default: el de .mcp-credentials.json; se normaliza /mcp -> /hub).
.PARAMETER Repo owner/repo de GitHub (default: el del remoto, via `gh repo view`).
.PARAMETER Env Environment de GitHub donde guardar el secret (vacio = secret de repositorio).
.PARAMETER Label Etiqueta de la service-key (default ci-quality).
.PARAMETER Rotate Fuerza nueva emision aunque el secret ya exista.
.PARAMETER WhatIf Muestra lo que haria sin emitir ni escribir nada.
.OUTPUTS
exit 0 = OK | 3 = sin apiKey (-> manual)
exit 4 = 401 del Hub (apiKey rotada) | 5 = 404 del Hub (< 1.7.0 -> manual)
exit 6 = gh no autenticado / sin permiso / fallo al escribir el secret (-> manual)
#>
[CmdletBinding()]
param(
[string] $ProjectId = '{{HUB_PROJECT_ID}}',
[string] $ServerUrl = '{{HUB_SERVER_URL}}',
[string] $Repo = '{{GITHUB_REPO}}',
[string] $Env = '',
[string] $Label = 'ci-quality',
[switch] $Rotate,
[switch] $WhatIf
)
$ErrorActionPreference = 'Stop'
try {
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13
} catch { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 }
function Get-HttpStatus($err) {
try { return [int]$err.Exception.Response.StatusCode } catch { return 0 }
}
# --- 0. gh autenticado y repo resuelto ---
if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { Write-Host "[ERR] gh (GitHub CLI) no esta instalado (https://cli.github.com). -> manual"; exit 6 }
$auth = (& gh auth status 2>&1 | Out-String)
if ($auth -notmatch 'Logged in') { Write-Host "[ERR] gh sin sesion. Ejecuta 'gh auth login'. -> manual"; exit 6 }
if ([string]::IsNullOrWhiteSpace($Repo) -or $Repo -like '{{*}}') {
try { $Repo = (& gh repo view --json nameWithOwner --jq .nameWithOwner 2>$null | Out-String).Trim() } catch { $Repo = '' }
}
if ([string]::IsNullOrWhiteSpace($Repo)) { Write-Host "[ERR] No se pudo resolver owner/repo (pasa -Repo). -> manual"; exit 6 }
# --- 1. Resolver apiKey per-dev + serverUrl + projectId (NO imprimir la apiKey) ---
$credPath = Join-Path (Get-Location) '_hilo/.mcp-credentials.json'
if (-not (Test-Path $credPath)) {
Write-Host "[ERR] No existe _hilo/.mcp-credentials.json. Ejecuta /hv:mcp-register en este repo, o usa el flujo manual (FASE 2.7)."
exit 3
}
$cred = Get-Content $credPath -Raw | ConvertFrom-Json
$apiKey = $cred.apiKey
if ([string]::IsNullOrWhiteSpace($apiKey)) { Write-Host "[ERR] .mcp-credentials.json sin apiKey -> flujo manual."; exit 3 }
if ([string]::IsNullOrWhiteSpace($ProjectId) -or $ProjectId -like '{{*}}') { $ProjectId = $cred.projectId }
if ([string]::IsNullOrWhiteSpace($ServerUrl) -or $ServerUrl -like '{{*}}') { $ServerUrl = $cred.serverUrl }
if ($cred.projectId -and $ProjectId -and ($cred.projectId -ne $ProjectId)) {
Write-Host "[ERR] El projectId pedido ($ProjectId) no coincide con el de tus credenciales ($($cred.projectId)). Abortando por seguridad."
exit 3
}
$hub = ($ServerUrl -replace '/+$','') -replace '/mcp$','/hub'
# --- 2. Ya existe el secret? (sin -Rotate, no re-emitir) ---
$secretArgs = @('secret', 'list', '-R', $Repo, '--json', 'name', '--jq', '.[].name')
if ($Env) { $secretArgs += @('-e', $Env) }
$existing = @()
try { $existing = @((& gh @secretArgs 2>$null | Out-String) -split "`r?`n" | Where-Object { $_ }) } catch { $existing = @() }
$yaExiste = $existing -contains 'HUB_SERVICE_KEY'
if ($yaExiste -and -not $Rotate) {
Write-Host "[OK] HUB_SERVICE_KEY ya existe en $Repo$(if ($Env) { " (environment $Env)" }). Nada que hacer (usa -Rotate para reemitir)."
exit 0
}
# --- 3. Emitir/rotar la service-key via Hub (en memoria) ---
$svcKey = $null; $revoked = 0
if ($WhatIf) {
Write-Host "[WHATIF] Emitiria service-key (label '$Label') para $ProjectId via $hub/v2/sync/emit-service-key"
Write-Host "[WHATIF] gh secret set HUB_SERVICE_KEY -R $Repo$(if ($Env) { " -e $Env" }) (valor por STDIN) | gh variable set HUB_PROJECT_ID -R $Repo --body <GUID>"
exit 0
}
$emitBody = @{ projectId = $ProjectId; label = $Label } | ConvertTo-Json
try {
$resp = Invoke-RestMethod "$hub/v2/sync/emit-service-key" -Method POST `
-Headers @{ 'X-Hub-Api-Key' = $apiKey; 'Content-Type' = 'application/json' } `
-Body $emitBody -TimeoutSec 30
$svcKey = $resp.serviceKey
$revoked = [int]$resp.revokedPrevious
} catch {
$code = Get-HttpStatus $_
if ($code -eq 401) { Write-Host "[ERR] Hub 401: tu apiKey per-dev no autentica (rotada?). Re-ejecuta /hv:mcp-register. -> manual"; exit 4 }
if ($code -eq 404) { Write-Host "[ERR] Hub 404: el endpoint emit-service-key no existe (Hub < 1.7.0). -> manual"; exit 5 }
Write-Host "[ERR] Hub emit-service-key fallo (HTTP $code): $($_.Exception.Message) -> manual"; exit 5
}
if ([string]::IsNullOrWhiteSpace($svcKey)) { Write-Host "[ERR] El Hub no devolvio service-key. -> manual"; exit 5 }
# --- 4. Guardar el secret por STDIN (gh recorta el salto de linea final) ---
$setArgs = @('secret', 'set', 'HUB_SERVICE_KEY', '-R', $Repo)
if ($Env) { $setArgs += @('-e', $Env) }
try {
$out = ($svcKey | & gh @setArgs 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0) { throw "gh secret set exit ${LASTEXITCODE}: $out" }
} catch {
Write-Host "[ERR] No se pudo escribir el secret en GitHub: $($_.Exception.Message -replace [regex]::Escape($svcKey), '***'). Comprueba permisos de admin sobre $Repo. -> manual"
Write-Host " La service-key YA fue emitida en el Hub ($revoked anteriores revocadas); reintenta este script con -Rotate o pega la key a mano: gh secret set HUB_SERVICE_KEY -R $Repo < key.txt"
exit 6
}
$svcKey = $null # soltar la referencia cuanto antes
# --- 5. Variable no secreta con el projectId ---
try {
& gh variable set HUB_PROJECT_ID -R $Repo --body $ProjectId 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) { Write-Host "[WARN] gh variable set HUB_PROJECT_ID fallo; la composite action quality-sync avisara hasta que exista." }
} catch { Write-Host "[WARN] gh variable set HUB_PROJECT_ID fallo: $($_.Exception.Message)" }
Write-Host "[OK] HUB_SERVICE_KEY guardada en $Repo$(if ($Env) { " (environment $Env)" }) (label '$Label'; $revoked key(s) anteriores revocadas). HUB_PROJECT_ID publicada como variable."
Write-Host " Verifica: gh secret list -R $Repo | gh variable list -R $Repo. La proxima run del workflow ya publica el QR."
exit 0