#
.SYNOPSIS
Creates/updates the Gitea Actions repository secrets and variables that CI/CD
needs, using the Gitea REST API. Idempotent: re-running overwrites values.
.DESCRIPTION
Secrets are read from the local .env / secrets directory (or parameters) and
pushed with:
PUT /api/v1/repos/{owner}/{repo}/actions/secrets/{name}
PUT /api/v1/repos/{owner}/{repo}/actions/variables/{name}
Secret VALUES are never printed — only names and the resulting status.
.EXAMPLE
$env:GITEA_URL='https://git.example.com'; $env:GITEA_API_TOKEN='...'
./scripts/Initialize-GiteaSecrets.ps1 -Owner platform -Repository ExecuteR
.NOTES
The token needs repository admin scope (write:repository) to manage secrets.
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[string]$GiteaUrl = $env:GITEA_URL,
[string]$Token = $(if ($env:GITEA_TOKEN) { $env:GITEA_TOKEN } else { $env:GITEA_API_TOKEN }),
[string]$Owner = $env:GITEA_OWNER,
[string]$Repository = $env:GITEA_REPOSITORY,
[string]$RegistryUsername,
[string]$RegistryPassword,
# Publish to a registry other than this Gitea instance's built-in one.
# Without this switch no registry credentials are written at all — CI uses
# the token Gitea Actions injects automatically.
[switch]$ExternalRegistry,
[switch]$SkipNats
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
# ── Resolve context from git when not supplied ──────────────────────────────
if (-not $GiteaUrl -or -not $Owner -or -not $Repository) {
$remote = (git -C $repoRoot remote get-url origin 2>$null)
if ($remote -match '^(?https?://[^/]+)/(?[^/]+)/(?[^/]+?)(\.git)?$') {
if (-not $GiteaUrl) { $GiteaUrl = $Matches.base }
if (-not $Owner) { $Owner = $Matches.owner }
if (-not $Repository) { $Repository = $Matches.repo }
Write-Host "Derived from git remote: $GiteaUrl/$Owner/$Repository"
}
}
if (-not $GiteaUrl) { throw 'GITEA_URL is required (or a git remote to derive it from).' }
if (-not $Token) { throw 'GITEA_TOKEN / GITEA_API_TOKEN is required.' }
if (-not $Owner) { throw 'GITEA_OWNER is required.' }
if (-not $Repository) { throw 'GITEA_REPOSITORY is required.' }
$apiBase = "$($GiteaUrl.TrimEnd('/'))/api/v1/repos/$Owner/$Repository"
$headers = @{ Authorization = "token $Token" }
# ── Collect values: .env first, then generated secrets, then parameters ─────
$values = @{}
$envFile = Join-Path $repoRoot '.env'
if (Test-Path $envFile) {
foreach ($line in Get-Content $envFile) {
if ($line -match '^\s*([A-Z0-9_]+)\s*=\s*(.*)$') {
$values[$Matches[1]] = $Matches[2].Trim()
}
}
}
$natsDir = Join-Path $repoRoot 'secrets/nats'
if (-not $SkipNats -and (Test-Path $natsDir)) {
$signing = Join-Path $natsDir 'account-signing.nk'
$accountPub = Join-Path $natsDir 'account.pub'
if (Test-Path $signing) { $values['NATS_ACCOUNT_SIGNING_SEED'] = (Get-Content $signing -Raw).Trim() }
if (Test-Path $accountPub) { $values['NATS_ACCOUNT_PUBLIC_KEY'] = (Get-Content $accountPub -Raw).Trim() }
}
# The registry credentials CI uses to push images. Default to the API token,
# which Gitea accepts as a container-registry password.
if (-not $RegistryUsername) { $RegistryUsername = if ($values['GITEA_ACTOR']) { $values['GITEA_ACTOR'] } else { $Owner } }
if (-not $RegistryPassword) { $RegistryPassword = $Token }
$registryHost = ([Uri]$GiteaUrl).Host
# ── Secrets (encrypted, never readable back) ────────────────────────────────
# NOTE: Gitea reserves the GITEA_ and GITHUB_ prefixes for Actions secret
# names and rejects them with HTTP 400, so these use neutral names.
#
# Nothing here is needed for Gitea's OWN container registry: Actions injects a
# GITEA_TOKEN per run which the registry accepts as the actor's password, and
# the host is derived from the instance URL. REGISTRY_HOST/USERNAME/PASSWORD
# are written only with -ExternalRegistry, to publish somewhere else.
$secrets = @{}
if ($ExternalRegistry) {
$secrets['REGISTRY_HOST'] = $registryHost
$secrets['REGISTRY_USERNAME'] = $RegistryUsername
$secrets['REGISTRY_PASSWORD'] = $RegistryPassword
}
foreach ($name in @('NATS_ACCOUNT_SIGNING_SEED', 'INITIAL_ADMIN_PASSWORD', 'OIDC_CLIENT_SECRET', 'S3_SECRET_KEY')) {
if ($values[$name]) { $secrets[$name] = $values[$name] }
}
# ── Variables (plain, readable in the UI) ───────────────────────────────────
$variables = @{
'REGISTRY' = "$registryHost/$($Owner.ToLowerInvariant())"
'SERVER_URL' = $GiteaUrl.TrimEnd('/')
}
foreach ($name in @('NATS_ACCOUNT_PUBLIC_KEY', 'NATS_OPERATOR_PUBLIC_KEY')) {
if ($values[$name]) { $variables[$name] = $values[$name] }
}
function Set-GiteaItem {
param([string]$Kind, [string]$Name, [string]$Value)
$uri = "$apiBase/actions/$Kind/$([uri]::EscapeDataString($Name))"
# The two endpoints disagree on the payload field: secrets take "data",
# variables take "value". Sending the wrong one returns HTTP 422.
$body = if ($Kind -eq 'secrets') {
@{ data = $Value } | ConvertTo-Json -Compress
}
else {
@{ value = $Value } | ConvertTo-Json -Compress
}
if (-not $PSCmdlet.ShouldProcess("$Kind/$Name", 'PUT')) { return }
try {
Invoke-RestMethod -Method Put -Uri $uri -Headers $headers -ContentType 'application/json' -Body $body | Out-Null
Write-Host (" {0,-36} set" -f $Name)
}
catch {
$status = $_.Exception.Response.StatusCode.value__
if ($status -eq 404 -and $Kind -eq 'variables') {
# Older Gitea: variables endpoint may need POST to create.
try {
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType 'application/json' -Body $body | Out-Null
Write-Host (" {0,-36} created" -f $Name)
return
}
catch { }
}
Write-Warning (" {0,-36} FAILED (HTTP {1})" -f $Name, $status)
}
}
Write-Host "Configuring Actions secrets on $Owner/$Repository"
if (-not $ExternalRegistry) {
Write-Host ' (built-in Gitea registry: no registry credentials needed)'
}
foreach ($entry in $secrets.GetEnumerator() | Sort-Object Name) {
if ([string]::IsNullOrWhiteSpace($entry.Value)) {
Write-Host (" {0,-36} skipped (no value)" -f $entry.Name)
continue
}
Set-GiteaItem -Kind 'secrets' -Name $entry.Name -Value $entry.Value
}
Write-Host "Configuring Actions variables"
foreach ($entry in $variables.GetEnumerator() | Sort-Object Name) {
if ([string]::IsNullOrWhiteSpace($entry.Value)) { continue }
Set-GiteaItem -Kind 'variables' -Name $entry.Name -Value $entry.Value
}
Write-Host ''
Write-Host 'Done. CI can now log in to the registry and publish images.'
Write-Host 'No secret values were printed.'