Защита стенда и управление секретами через OpenBao
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) {
|
||||
throw 'Set BAO_TOKEN to the operator root token only for this bootstrap process.'
|
||||
}
|
||||
|
||||
$values = @{}
|
||||
foreach($line in [System.IO.File]::ReadAllLines((Resolve-Path $EnvFile))) {
|
||||
if($line -match '^(?<name>[A-Z][A-Z0-9_]*)=(?<value>.*)$') { $values[$Matches.name]=$Matches.value }
|
||||
}
|
||||
function Require-Value([string]$Name) {
|
||||
if(-not $values.ContainsKey($Name) -or [string]::IsNullOrWhiteSpace($values[$Name])) {
|
||||
throw "Missing $Name in $EnvFile"
|
||||
}
|
||||
return $values[$Name]
|
||||
}
|
||||
function Bao([Parameter(ValueFromRemainingArguments=$true)][string[]]$Arguments) {
|
||||
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao @Arguments
|
||||
if($LASTEXITCODE -ne 0){ throw "OpenBao command failed: bao $($Arguments -join ' ')" }
|
||||
}
|
||||
|
||||
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao secrets enable -path=secret -version=2 kv 2>$null
|
||||
if($LASTEXITCODE -ne 0) { Bao secrets list | Select-String 'secret/' | Out-Null }
|
||||
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao auth enable approle 2>$null
|
||||
if($LASTEXITCODE -ne 0) { Bao auth list | Select-String 'approle/' | Out-Null }
|
||||
|
||||
Bao policy write messenger-api /openbao/config/api-policy.hcl | Out-Null
|
||||
Bao policy write messenger-worker /openbao/config/worker-policy.hcl | Out-Null
|
||||
Bao write auth/approle/role/messenger-api token_policies=messenger-api token_ttl=15m token_max_ttl=1h token_num_uses=0 secret_id_ttl=24h secret_id_num_uses=0 | Out-Null
|
||||
Bao write auth/approle/role/messenger-worker token_policies=messenger-worker token_ttl=15m token_max_ttl=1h token_num_uses=0 secret_id_ttl=24h secret_id_num_uses=0 | Out-Null
|
||||
|
||||
$api = @{
|
||||
database_password = Require-Value DATABASE_API_PASSWORD
|
||||
redis_password = Require-Value REDIS_API_PASSWORD
|
||||
rabbitmq_password = Require-Value RABBITMQ_API_PASSWORD
|
||||
s3_access_key_id = Require-Value S3_ACCESS_KEY_ID
|
||||
s3_secret_access_key = Require-Value S3_SECRET_ACCESS_KEY
|
||||
} | ConvertTo-Json -Compress
|
||||
$worker = @{
|
||||
database_password = Require-Value DATABASE_WORKER_PASSWORD
|
||||
redis_password = Require-Value REDIS_WORKER_PASSWORD
|
||||
rabbitmq_password = Require-Value RABBITMQ_WORKER_PASSWORD
|
||||
s3_access_key_id = Require-Value S3_WORKER_ACCESS_KEY_ID
|
||||
s3_secret_access_key = Require-Value S3_WORKER_SECRET_ACCESS_KEY
|
||||
} | ConvertTo-Json -Compress
|
||||
$api | & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao kv put -mount=secret messenger/api - | Out-Null
|
||||
if($LASTEXITCODE -ne 0){ throw 'Failed to write API secrets' }
|
||||
$worker | & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao kv put -mount=secret messenger/worker - | Out-Null
|
||||
if($LASTEXITCODE -ne 0){ throw 'Failed to write worker secrets' }
|
||||
|
||||
foreach($role in 'api','worker') {
|
||||
$roleName = "messenger-$role"
|
||||
$dir = Join-Path 'secrets\openbao' $role
|
||||
New-Item -ItemType Directory -Path $dir -Force | Out-Null
|
||||
$roleId = (Bao read -field=role_id "auth/approle/role/$roleName/role-id" | Out-String).Trim()
|
||||
$secretId = (Bao write -field=secret_id -f "auth/approle/role/$roleName/secret-id" | Out-String).Trim()
|
||||
[System.IO.File]::WriteAllText((Join-Path $dir 'role-id'),$roleId,[System.Text.Encoding]::ASCII)
|
||||
[System.IO.File]::WriteAllText((Join-Path $dir 'secret-id'),$secretId,[System.Text.Encoding]::ASCII)
|
||||
}
|
||||
|
||||
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao audit enable file file_path=/openbao/data/audit.log 2>$null
|
||||
if($LASTEXITCODE -ne 0) { Bao audit list | Select-String 'file/' | Out-Null }
|
||||
Write-Host 'OpenBao policies, AppRoles, KV secrets and agent bootstrap files are ready. Secret values were not printed.'
|
||||
@@ -0,0 +1,104 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$OutputDirectory, [int]$LeafValidityDays = 30)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ([string]::IsNullOrWhiteSpace($OutputDirectory)) {
|
||||
$OutputDirectory = Join-Path $PSScriptRoot '..\secrets\pki'
|
||||
}
|
||||
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
|
||||
$OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).Path
|
||||
$script:Cas = @{}
|
||||
|
||||
function Write-Pem([string]$Path, [string]$Label, [byte[]]$Value) {
|
||||
$base64 = [Convert]::ToBase64String($Value)
|
||||
$lines = for($offset=0; $offset -lt $base64.Length; $offset+=64){
|
||||
$base64.Substring($offset,[Math]::Min(64,$base64.Length-$offset))
|
||||
}
|
||||
$pem = "-----BEGIN $Label-----`n" + ($lines -join "`n") + "`n-----END $Label-----`n"
|
||||
[System.IO.File]::WriteAllText($Path, $pem, [System.Text.Encoding]::ASCII)
|
||||
}
|
||||
|
||||
function Export-PrivateKey($Rsa) {
|
||||
if ($null -ne $Rsa.PSObject.Methods['ExportPkcs8PrivateKey']) {
|
||||
return $Rsa.ExportPkcs8PrivateKey()
|
||||
}
|
||||
return $Rsa.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)
|
||||
}
|
||||
|
||||
function New-Ca([string]$Name) {
|
||||
$rsa = [System.Security.Cryptography.RSA]::Create(3072)
|
||||
$request = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new(
|
||||
"CN=HLA Lab 7 $Name", $rsa,
|
||||
[System.Security.Cryptography.HashAlgorithmName]::SHA256,
|
||||
[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
|
||||
$request.CertificateExtensions.Add(
|
||||
[System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($true,$false,0,$true))
|
||||
$request.CertificateExtensions.Add(
|
||||
[System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new(
|
||||
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyCertSign -bor
|
||||
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::CrlSign,$true))
|
||||
$certificate = $request.CreateSelfSigned([DateTimeOffset]::UtcNow.AddMinutes(-5),[DateTimeOffset]::UtcNow.AddDays(365))
|
||||
$dir = Join-Path $OutputDirectory $Name
|
||||
New-Item -ItemType Directory -Path $dir -Force | Out-Null
|
||||
Write-Pem (Join-Path $dir 'ca.crt') 'CERTIFICATE' $certificate.Export(
|
||||
[System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
|
||||
Write-Pem (Join-Path $dir 'ca.key') 'PRIVATE KEY' (Export-PrivateKey $rsa)
|
||||
$script:Cas[$Name] = $certificate
|
||||
}
|
||||
|
||||
function New-Leaf(
|
||||
[string]$Name, [string]$CaName, [bool]$ServerAuth,
|
||||
[string[]]$DnsNames, [string[]]$IpAddresses, [string[]]$Uris) {
|
||||
$rsa = [System.Security.Cryptography.RSA]::Create(3072)
|
||||
$request = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new(
|
||||
"CN=$Name",$rsa,[System.Security.Cryptography.HashAlgorithmName]::SHA256,
|
||||
[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
|
||||
$request.CertificateExtensions.Add(
|
||||
[System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($false,$false,0,$true))
|
||||
$request.CertificateExtensions.Add(
|
||||
[System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new(
|
||||
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DigitalSignature -bor
|
||||
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyEncipherment,$true))
|
||||
$eku = [System.Security.Cryptography.OidCollection]::new()
|
||||
[void]$eku.Add([System.Security.Cryptography.Oid]::new($(if($ServerAuth){'1.3.6.1.5.5.7.3.1'}else{'1.3.6.1.5.5.7.3.2'})))
|
||||
$request.CertificateExtensions.Add(
|
||||
[System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new($eku,$false))
|
||||
$san = [System.Security.Cryptography.X509Certificates.SubjectAlternativeNameBuilder]::new()
|
||||
foreach($dns in $DnsNames){ $san.AddDnsName($dns) }
|
||||
foreach($ip in $IpAddresses){ $san.AddIpAddress([System.Net.IPAddress]::Parse($ip)) }
|
||||
foreach($uri in $Uris){ $san.AddUri([Uri]::new($uri)) }
|
||||
$request.CertificateExtensions.Add($san.Build($true))
|
||||
$serial = [byte[]]::new(16)
|
||||
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
$rng.GetBytes($serial)
|
||||
$rng.Dispose()
|
||||
$serial[0] = $serial[0] -band 0x7f
|
||||
$signed = $request.Create($script:Cas[$CaName],[DateTimeOffset]::UtcNow.AddMinutes(-5),
|
||||
[DateTimeOffset]::UtcNow.AddDays($LeafValidityDays),$serial)
|
||||
$certificate = $signed
|
||||
$dir = Join-Path $OutputDirectory $Name
|
||||
New-Item -ItemType Directory -Path $dir -Force | Out-Null
|
||||
Write-Pem (Join-Path $dir 'tls.crt') 'CERTIFICATE' $certificate.Export(
|
||||
[System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
|
||||
Write-Pem (Join-Path $dir 'tls.key') 'PRIVATE KEY' (Export-PrivateKey $rsa)
|
||||
Copy-Item (Join-Path $OutputDirectory "$CaName\ca.crt") (Join-Path $dir 'ca.crt') -Force
|
||||
}
|
||||
|
||||
foreach($name in 'public-ca','service-ca','lb-client-ca','workload-client-ca','telemetry-client-ca'){ New-Ca $name }
|
||||
New-Leaf 'ingress' 'public-ca' $true @('localhost') @('127.0.0.1') @()
|
||||
foreach($name in 'api','postgres','redis','rabbitmq','minio','otel-collector','prometheus','loki','tempo'){
|
||||
New-Leaf $name 'service-ca' $true @($name) @() @("spiffe://hla-lab7/$name")
|
||||
}
|
||||
New-Leaf 'openbao' 'service-ca' $true @('openbao','localhost') @('127.0.0.1') @('spiffe://hla-lab7/openbao')
|
||||
New-Leaf 'grafana' 'service-ca' $true @('grafana','localhost') @('127.0.0.1') @('spiffe://hla-lab7/grafana')
|
||||
New-Leaf 'lb' 'lb-client-ca' $false @() @() @('spiffe://hla-lab7/lb')
|
||||
New-Leaf 'wrong-lb-client' 'lb-client-ca' $false @() @() @('spiffe://hla-lab7/worker')
|
||||
New-Leaf 'api-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/api')
|
||||
New-Leaf 'worker-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/worker')
|
||||
New-Leaf 'migration-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/migration')
|
||||
New-Leaf 'collector-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/otel-collector')
|
||||
New-Leaf 'prometheus-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/prometheus')
|
||||
New-Leaf 'grafana-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/grafana')
|
||||
|
||||
Write-Host "Created private PKI in $OutputDirectory"
|
||||
Write-Host "Public test CA: $(Join-Path $OutputDirectory 'public-ca\ca.crt')"
|
||||
@@ -0,0 +1,28 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$Destination, [switch]$Force)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ([string]::IsNullOrWhiteSpace($Destination)) {
|
||||
$Destination = Join-Path $PSScriptRoot '..\.env'
|
||||
}
|
||||
if ((Test-Path -LiteralPath $Destination) -and -not $Force) {
|
||||
throw "$Destination already exists; use -Force only for an intentional full credential rotation"
|
||||
}
|
||||
$template = Join-Path $PSScriptRoot '..\.env.example'
|
||||
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
try {
|
||||
$lines = foreach($line in [System.IO.File]::ReadAllLines($template)) {
|
||||
if ($line -match '^(?<name>[A-Z][A-Z0-9_]*)=replace-with-') {
|
||||
$bytes = [byte[]]::new(32)
|
||||
$rng.GetBytes($bytes)
|
||||
$secret = [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_')
|
||||
"$($Matches.name)=$secret"
|
||||
} else {
|
||||
$line
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$rng.Dispose()
|
||||
}
|
||||
[System.IO.File]::WriteAllLines($Destination,$lines,[System.Text.UTF8Encoding]::new($false))
|
||||
Write-Host "Created local stand credentials in $Destination; values were not printed."
|
||||
@@ -0,0 +1,40 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$OutputDirectory = (Join-Path $PSScriptRoot '..\secrets\tls'),
|
||||
[int]$ValidityDays = 30
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if (-not (Get-Command openssl -ErrorAction SilentlyContinue)) {
|
||||
throw 'openssl is required and was not found in PATH'
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
|
||||
$OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).Path
|
||||
|
||||
$caKey = Join-Path $OutputDirectory 'ca.key'
|
||||
$caCert = Join-Path $OutputDirectory 'ca.crt'
|
||||
$serverKey = Join-Path $OutputDirectory 'server.key'
|
||||
$serverCsr = Join-Path $OutputDirectory 'server.csr'
|
||||
$serverCert = Join-Path $OutputDirectory 'server.crt'
|
||||
$extensions = Join-Path $OutputDirectory 'server.ext'
|
||||
|
||||
@'
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=serverAuth
|
||||
subjectAltName=DNS:localhost,IP:127.0.0.1
|
||||
'@ | Set-Content -LiteralPath $extensions -Encoding ascii
|
||||
|
||||
& openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out $caKey
|
||||
& openssl req -x509 -new -sha256 -key $caKey -days $ValidityDays `
|
||||
-subj '/CN=HLA Lab 7 Local CA' -out $caCert
|
||||
& openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out $serverKey
|
||||
& openssl req -new -sha256 -key $serverKey -subj '/CN=localhost' -out $serverCsr
|
||||
& openssl x509 -req -sha256 -in $serverCsr -CA $caCert -CAkey $caKey `
|
||||
-CAcreateserial -days $ValidityDays -extfile $extensions -out $serverCert
|
||||
|
||||
Remove-Item -LiteralPath $serverCsr, $extensions, (Join-Path $OutputDirectory 'ca.srl') -Force -ErrorAction SilentlyContinue
|
||||
Write-Host "Created local TLS material in $OutputDirectory"
|
||||
Write-Host "Trust this CA only for the lab: $caCert"
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
out_dir=${1:-"$repo_dir/secrets/tls"}
|
||||
days=${TLS_VALIDITY_DAYS:-30}
|
||||
|
||||
command -v openssl >/dev/null 2>&1 || {
|
||||
echo 'openssl is required and was not found in PATH' >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
mkdir -p "$out_dir"
|
||||
umask 077
|
||||
|
||||
cat >"$out_dir/server.ext" <<'EOF'
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=serverAuth
|
||||
subjectAltName=DNS:localhost,IP:127.0.0.1
|
||||
EOF
|
||||
|
||||
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$out_dir/ca.key"
|
||||
openssl req -x509 -new -sha256 -key "$out_dir/ca.key" -days "$days" \
|
||||
-subj '/CN=HLA Lab 7 Local CA' -out "$out_dir/ca.crt"
|
||||
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$out_dir/server.key"
|
||||
openssl req -new -sha256 -key "$out_dir/server.key" -subj '/CN=localhost' -out "$out_dir/server.csr"
|
||||
openssl x509 -req -sha256 -in "$out_dir/server.csr" -CA "$out_dir/ca.crt" \
|
||||
-CAkey "$out_dir/ca.key" -CAcreateserial -days "$days" \
|
||||
-extfile "$out_dir/server.ext" -out "$out_dir/server.crt"
|
||||
|
||||
rm -f "$out_dir/server.csr" "$out_dir/server.ext" "$out_dir/ca.srl"
|
||||
printf 'Created local TLS material in %s\n' "$out_dir"
|
||||
printf 'Trust this CA only for the lab: %s/ca.crt\n' "$out_dir"
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
cd /d "%~dp0\.."
|
||||
if not defined ENV_FILE set "ENV_FILE=.env"
|
||||
|
||||
docker compose --env-file "%ENV_FILE%" stop nginx api redis postgres minio || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 postgres redis minio || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" run --rm minio-init || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" up -d --no-deps nginx || exit /b 1
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
|
||||
cd "$PROJECT_DIR"
|
||||
: "${ENV_FILE:=.env}"
|
||||
|
||||
# Preserve named volumes and the network. The migration job is intentionally
|
||||
# not re-run during a same-version restart.
|
||||
docker compose --env-file "$ENV_FILE" stop nginx api redis postgres minio
|
||||
docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 postgres redis minio
|
||||
docker compose --env-file "$ENV_FILE" run --rm minio-init
|
||||
docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api
|
||||
docker compose --env-file "$ENV_FILE" up -d --no-deps nginx
|
||||
@@ -0,0 +1,13 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) { throw 'Set BAO_TOKEN for this operator action.' }
|
||||
foreach($role in 'api','worker') {
|
||||
$roleName = "messenger-$role"
|
||||
$secretId = (& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao write -field=secret_id -f "auth/approle/role/$roleName/secret-id" | Out-String).Trim()
|
||||
if($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($secretId)){ throw "Failed to rotate $roleName SecretID" }
|
||||
[System.IO.File]::WriteAllText((Join-Path "secrets\openbao\$role" 'secret-id'),$secretId,[System.Text.Encoding]::ASCII)
|
||||
}
|
||||
Write-Host 'AppRole SecretIDs rotated without printing their values.'
|
||||
@@ -0,0 +1,26 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions EnableDelayedExpansion
|
||||
|
||||
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
|
||||
cd /d "%~dp0\.."
|
||||
if not defined ENV_FILE set "ENV_FILE=.env"
|
||||
|
||||
set "TARGET_CONTAINER="
|
||||
set /a MATCHES=0
|
||||
for /f "usebackq delims=" %%C in (`docker compose --env-file "%ENV_FILE%" ps -q api`) do (
|
||||
set "CONTAINER_ID=%%C"
|
||||
set "SHORT_ID=!CONTAINER_ID:~0,12!"
|
||||
set "HOSTNAME_VALUE="
|
||||
for /f "usebackq delims=" %%H in (`docker inspect --format "{{.Config.Hostname}}" %%C`) do set "HOSTNAME_VALUE=%%H"
|
||||
if "!HOSTNAME_VALUE!"=="%TARGET_INSTANCE_ID%" (
|
||||
set "TARGET_CONTAINER=%%C"
|
||||
set /a MATCHES+=1
|
||||
) else if "!SHORT_ID!"=="%TARGET_INSTANCE_ID%" (
|
||||
set "TARGET_CONTAINER=%%C"
|
||||
set /a MATCHES+=1
|
||||
)
|
||||
)
|
||||
|
||||
if not "!MATCHES!"=="1" exit /b 2
|
||||
docker stop --time 5 "!TARGET_CONTAINER!" >nul
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
|
||||
cd "$PROJECT_DIR"
|
||||
: "${ENV_FILE:=.env}"
|
||||
|
||||
target=""
|
||||
matches=0
|
||||
for container_id in $(docker compose --env-file "$ENV_FILE" ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
|
||||
short_id=$(printf '%s' "$container_id" | cut -c1-12)
|
||||
if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$short_id" ]; then
|
||||
target=$container_id
|
||||
matches=$((matches + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$matches" -ne 1 ]; then
|
||||
printf '%s\n' "Expected one API replica for X-Instance-Id, found $matches" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Five seconds keeps the operator hook below the test's ten-second budget while
|
||||
# still delivering SIGTERM and allowing Spring's graceful shutdown phase.
|
||||
docker stop --time 5 "$target" >/dev/null
|
||||
@@ -0,0 +1,25 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
|
||||
function Invoke-Probe([string]$TlsArguments) {
|
||||
$script = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -connect api:8443 -servername api -CAfile /run/pki/service-ca/ca.crt $TlsArguments 2>&1"
|
||||
$output = docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $script
|
||||
return ($output -join "`n")
|
||||
}
|
||||
|
||||
$noCertificate = Invoke-Probe ''
|
||||
if ($noCertificate -match 'HTTP/1.1 200') { throw 'mTLS failure: API accepted a client without a certificate' }
|
||||
|
||||
$foreignCa = Invoke-Probe '-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key'
|
||||
if ($foreignCa -match 'HTTP/1.1 200') { throw 'mTLS failure: API accepted a foreign client CA' }
|
||||
|
||||
$wrongIdentity = Invoke-Probe '-cert /run/pki/wrong-lb-client/tls.crt -key /run/pki/wrong-lb-client/tls.key'
|
||||
if ($wrongIdentity -notmatch 'HTTP/1.1 403') { throw 'mTLS failure: trusted CA with forbidden SAN was not rejected with 403' }
|
||||
|
||||
$allowed = Invoke-Probe '-cert /run/pki/lb/tls.crt -key /run/pki/lb/tls.key'
|
||||
if ($allowed -notmatch 'HTTP/1.1 200') { throw 'mTLS failure: allowed LB identity did not reach API health' }
|
||||
|
||||
Write-Host 'PASS: no cert, foreign CA and forbidden SAN rejected; LB identity accepted.'
|
||||
@@ -0,0 +1,30 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
|
||||
function Get-AppRoleToken([string]$Role) {
|
||||
$dir = Join-Path 'secrets\openbao' $Role
|
||||
$roleId = [System.IO.File]::ReadAllText((Join-Path $dir 'role-id')).Trim()
|
||||
$secretId = [System.IO.File]::ReadAllText((Join-Path $dir 'secret-id')).Trim()
|
||||
$body = @{ role_id = $roleId; secret_id = $secretId } | ConvertTo-Json -Compress
|
||||
$token = ($body | & docker compose --env-file $EnvFile exec -T openbao bao write -field=token auth/approle/login - | Out-String).Trim()
|
||||
if($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) { throw "AppRole login failed for $Role" }
|
||||
return $token
|
||||
}
|
||||
|
||||
function Bao-WithToken([string]$Token,[Parameter(ValueFromRemainingArguments=$true)][string[]]$Arguments) {
|
||||
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$Token" openbao bao @Arguments 2>$null | Out-Null
|
||||
return $LASTEXITCODE
|
||||
}
|
||||
|
||||
foreach($role in 'api','worker') {
|
||||
$other = if($role -eq 'api'){'worker'}else{'api'}
|
||||
$token = Get-AppRoleToken $role
|
||||
if((Bao-WithToken $token kv get -mount=secret "messenger/$role") -ne 0) { throw "$role cannot read its own KV path" }
|
||||
if((Bao-WithToken $token kv get -mount=secret "messenger/$other") -eq 0) { throw "$role unexpectedly read the $other KV path" }
|
||||
if((Bao-WithToken $token policy write forbidden /openbao/config/api-policy.hcl) -eq 0) { throw "$role unexpectedly changed an OpenBao policy" }
|
||||
}
|
||||
|
||||
Write-Host 'OpenBao policy checks passed: own path allowed; foreign path and policy changes denied.'
|
||||
Reference in New Issue
Block a user