Усиление контейнеров и проверка отказоустойчивости

This commit is contained in:
EgorAnti
2026-11-26 17:26:19 +03:00
parent d23847f953
commit 60fa12ce6e
24 changed files with 418 additions and 68 deletions
+39 -10
View File
@@ -2,7 +2,9 @@
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$PSNativeCommandUseErrorActionPreference = $false
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) {
throw 'Set BAO_TOKEN to the operator root token only for this bootstrap process.'
}
@@ -21,14 +23,40 @@ 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 ' ')" }
}
function Revoke-AppRoleSecretIds([string]$RoleName) {
# Windows PowerShell 5 wraps native stderr as NativeCommandError. OpenBao
# legitimately returns exit code 2 when this LIST collection is empty, so
# suppress only that invocation and inspect its exit code explicitly.
$previousErrorAction = $ErrorActionPreference
try {
$ErrorActionPreference = 'SilentlyContinue'
$json = (& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao list -format=json "auth/approle/role/$RoleName/secret-id" 2>$null | Out-String).Trim()
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previousErrorAction
}
if($code -eq 2){ return } # OpenBao returns 2 when the collection is empty.
if($code -ne 0){ throw "Failed to list existing SecretID accessors for $RoleName" }
$parsed = $json | ConvertFrom-Json
$accessors = if($parsed.PSObject.Properties.Name -contains 'keys'){ @($parsed.keys) } else { @($parsed) }
foreach($accessor in $accessors) {
if(-not [string]::IsNullOrWhiteSpace($accessor)) {
Bao write "auth/approle/role/$RoleName/secret-id-accessor/destroy" "secret_id_accessor=$accessor" | Out-Null
}
}
}
& 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 }
$secretMounts = (Bao secrets list -format=json | Out-String) | ConvertFrom-Json
if($secretMounts.PSObject.Properties.Name -notcontains 'secret/') {
Bao secrets enable -path=secret -version=2 kv | Out-Null
}
$authMounts = (Bao auth list -format=json | Out-String) | ConvertFrom-Json
if($authMounts.PSObject.Properties.Name -notcontains 'approle/') {
Bao auth enable 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 policy write messenger-api /openbao/policies/api-policy.hcl | Out-Null
Bao policy write messenger-worker /openbao/policies/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
@@ -53,14 +81,15 @@ if($LASTEXITCODE -ne 0){ throw 'Failed to write worker secrets' }
foreach($role in 'api','worker') {
$roleName = "messenger-$role"
$dir = Join-Path 'secrets\openbao' $role
$dir = Join-Path $projectRoot "secrets\openbao\$role"
New-Item -ItemType Directory -Path $dir -Force | Out-Null
# A previous interrupted bootstrap may have issued a SecretID without
# persisting it. Revoke each old credential by its non-secret accessor.
Revoke-AppRoleSecretIds $roleName
$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.'
+9
View File
@@ -37,6 +37,9 @@ function New-Ca([string]$Name) {
[System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new(
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyCertSign -bor
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::CrlSign,$true))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new(
$request.PublicKey,$false))
$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
@@ -63,6 +66,12 @@ function New-Leaf(
[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))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new(
$request.PublicKey,$false))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509AuthorityKeyIdentifierExtension]::CreateFromCertificate(
$script:Cas[$CaName],$true,$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)) }
+44
View File
@@ -0,0 +1,44 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$json = & docker compose --profile verification --env-file $EnvFile config --format json
if($LASTEXITCODE -ne 0){ throw 'docker compose config failed' }
$config = $json | ConvertFrom-Json
$allowedPublished = @{ nginx = 8443; openbao = 8200; grafana = 3000 }
$statefulWritableRoots = @('postgres','redis','rabbitmq','minio')
foreach($property in $config.services.PSObject.Properties) {
$name = $property.Name
$service = $property.Value
if($service.privileged -eq $true){ throw "$name is privileged" }
if($service.network_mode -eq 'host'){ throw "$name uses host networking" }
if(-not $service.pids_limit -or -not $service.cpus -or -not $service.mem_limit){
throw "$name is missing pids/cpu/memory limits"
}
if(-not ($service.security_opt -contains 'no-new-privileges:true')){
throw "$name is missing no-new-privileges"
}
if(-not $service.cap_drop -or $service.cap_drop.Count -eq 0){ throw "$name has no capability drop policy" }
if($name -notin $statefulWritableRoots -and $service.read_only -ne $true){
throw "$name must use a read-only root filesystem"
}
foreach($volume in @($service.volumes) | Where-Object { $null -ne $_ }) {
if($volume.source -match 'docker\.sock' -or $volume.target -match 'docker\.sock'){
throw "$name mounts the Docker socket"
}
}
foreach($port in @($service.ports) | Where-Object { $null -ne $_ }) {
if(-not $allowedPublished.ContainsKey($name) -or [int]$port.target -ne $allowedPublished[$name]){
throw "$name publishes unexpected port $($port.published):$($port.target)"
}
if($port.host_ip -notin @('127.0.0.1','::1')){ throw "$name port is not loopback-bound" }
}
}
foreach($expected in $allowedPublished.Keys){
if(-not $config.services.$expected.ports){ throw "$expected operator/public port is missing" }
}
Write-Host 'PASS: ports, privileges, capabilities, filesystems and resource limits satisfy the local hardening contract.'
+68
View File
@@ -0,0 +1,68 @@
[CmdletBinding()]
param(
[string]$PkiDirectory,
[int]$MinimumRemainingDays = 7,
[int]$MaximumLeafValidityDays = 31,
[int]$MaximumSecretIdAgeHours = 24
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
if([string]::IsNullOrWhiteSpace($PkiDirectory)){ $PkiDirectory = 'secrets\pki' }
$pki = (Resolve-Path -LiteralPath $PkiDirectory).Path
$now = [DateTimeOffset]::UtcNow
$leafCount = 0
foreach($certificateFile in Get-ChildItem -LiteralPath $pki -Recurse -Filter tls.crt) {
$keyFile = Join-Path $certificateFile.DirectoryName 'tls.key'
$caFile = Join-Path $certificateFile.DirectoryName 'ca.crt'
if(-not (Test-Path -LiteralPath $keyFile) -or -not (Test-Path -LiteralPath $caFile)){
throw "Incomplete certificate bundle: $($certificateFile.Directory.Name)"
}
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certificateFile.FullName)
if([DateTimeOffset]$certificate.NotBefore -gt $now.AddMinutes(1)){ throw "$($certificateFile.Directory.Name) certificate is not valid yet" }
if([DateTimeOffset]$certificate.NotAfter -le $now.AddDays($MinimumRemainingDays)){ throw "$($certificateFile.Directory.Name) certificate expires too soon" }
if(($certificate.NotAfter.ToUniversalTime() - $certificate.NotBefore.ToUniversalTime()).TotalDays -gt ($MaximumLeafValidityDays + 1)){
throw "$($certificateFile.Directory.Name) leaf validity exceeds the contract"
}
if(-not ($certificate.Extensions | Where-Object { $_.Oid.Value -eq '2.5.29.17' })){
throw "$($certificateFile.Directory.Name) certificate has no SAN"
}
$privateKey = [System.Security.Cryptography.RSA]::Create()
$publicKey = $null
try {
$privateKey.ImportFromPem([System.IO.File]::ReadAllText($keyFile))
$privatePublic = [Convert]::ToBase64String($privateKey.ExportSubjectPublicKeyInfo())
$publicKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPublicKey($certificate)
$certificatePublic = [Convert]::ToBase64String($publicKey.ExportSubjectPublicKeyInfo())
if($privatePublic -ne $certificatePublic){ throw "$($certificateFile.Directory.Name) private key does not match certificate" }
} finally {
if($null -ne $publicKey){ $publicKey.Dispose() }
$privateKey.Dispose()
$certificate.Dispose()
}
$leafCount++
}
if($leafCount -eq 0){ throw 'No leaf certificates found' }
$trackedPrivate = & git ls-files -- .env secrets '*.key' '*.p12' '*.pfx' '*.jks' '*.pem'
if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' }
if($trackedPrivate){ throw 'Private material is tracked by Git' }
foreach($path in '.env','secrets/pki/openbao/tls.key'){
& git check-ignore --quiet -- $path
if($LASTEXITCODE -ne 0){ throw "$path is not ignored by Git" }
}
$operatorArtifacts = Get-ChildItem -LiteralPath secrets -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '(?i)unseal|root[-_.]?token|\.vault-token' }
if($operatorArtifacts){ throw 'Root token or unseal-named operator artifact exists inside the project secrets directory' }
foreach($role in 'api','worker'){
$secretId = Join-Path "secrets\openbao\$role" 'secret-id'
if(Test-Path -LiteralPath $secretId){
$age = $now - [DateTimeOffset](Get-Item -LiteralPath $secretId).LastWriteTimeUtc
if($age.TotalHours -ge $MaximumSecretIdAgeHours){ throw "$role AppRole SecretID reached its rotation deadline" }
}
}
Write-Host "PASS: $leafCount certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL."
+4 -4
View File
@@ -8,8 +8,8 @@ import re
ROOT = Path(__file__).resolve().parents[1]
def main():
lab = json.loads((ROOT/'lab.json').read_text())['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
assert spec['openapi']=='3.1.0'
assert spec['info']['version']=='1.%d.0'%lab
operation_ids = set()
@@ -41,11 +41,11 @@ def main():
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
ast.parse(file.read_text(),filename=str(file))
ast.parse(file.read_text(encoding='utf-8'),filename=str(file))
for file in ROOT.rglob('*.json'):
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
continue
json.loads(file.read_text())
json.loads(file.read_text(encoding='utf-8'))
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
assert (ROOT/required).is_file(), 'missing '+required
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
+5 -3
View File
@@ -3,8 +3,10 @@ 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%" stop nginx api worker redis postgres minio rabbitmq || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 postgres redis minio rabbitmq || 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%" run --rm rabbitmq-init || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --no-deps worker || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --no-deps --scale api=2 api || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --no-deps nginx || exit /b 1
+5 -3
View File
@@ -8,8 +8,10 @@ cd "$PROJECT_DIR"
# 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" stop nginx api worker redis postgres minio rabbitmq
docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 postgres redis minio rabbitmq
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" run --rm rabbitmq-init
docker compose --env-file "$ENV_FILE" up -d --no-deps worker
docker compose --env-file "$ENV_FILE" up -d --no-deps --scale api=2 api
docker compose --env-file "$ENV_FILE" up -d --no-deps nginx
+5 -2
View File
@@ -2,12 +2,15 @@
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) { throw 'Set BAO_TOKEN for this operator action.' }
foreach($role in 'api','worker') {
$roleName = "messenger-$role"
$directory = Join-Path $projectRoot "secrets\openbao\$role"
New-Item -ItemType Directory -Path $directory -Force | Out-Null
$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)
[System.IO.File]::WriteAllText((Join-Path $directory 'secret-id'),$secretId,[System.Text.Encoding]::ASCII)
}
Write-Host 'AppRole SecretIDs rotated without printing their values.'
+1 -1
View File
@@ -24,7 +24,7 @@ foreach($role in 'api','worker') {
$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" }
if((Bao-WithToken $token policy write forbidden /openbao/policies/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.'
+3 -3
View File
@@ -6,17 +6,17 @@ from openapi_spec_validator import validate
from jsonschema import Draft202012Validator
root = Path(__file__).resolve().parents[1]
spec = json.loads((root/'contracts/openapi.json').read_text())
spec = json.loads((root/'contracts/openapi.json').read_text(encoding='utf-8'))
validate(spec)
from referencing import Registry, Resource
# The base URI resolves local #/components references inside examples.
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
for name, example in json.loads((root/'contracts/examples.json').read_text(encoding='utf-8')).items():
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
Draft202012Validator(schema, registry=registry).validate(example)
for path in (root/'contracts').glob('*.schema.json'):
schema = json.loads(path.read_text())
schema = json.loads(path.read_text(encoding='utf-8'))
Draft202012Validator.check_schema(schema)
for example in schema.get('examples',[]):
Draft202012Validator(schema).validate(example)
+48
View File
@@ -0,0 +1,48 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$Python = 'python',
[string]$BaseUrl = 'https://localhost:8443'
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
& "$PSScriptRoot\check-compose-hardening.ps1" -EnvFile $EnvFile
& "$PSScriptRoot\check-security-lifecycle.ps1"
& docker info --format '{{.ServerVersion}}' | Out-Null
if($LASTEXITCODE -ne 0){ throw 'Docker engine is unavailable' }
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
if($replicas.Count -lt 2){ throw 'At least two running API replicas are required' }
function Run-Test([string[]]$Arguments) {
& $Python @Arguments
if($LASTEXITCODE -ne 0){ throw "HTTPS test failed: $($Arguments[0])" }
}
function Wait-HttpsReady([int]$TimeoutSeconds = 120) {
$probe = @'
import ssl, sys, urllib.request
context = ssl.create_default_context(cafile=sys.argv[2])
with urllib.request.urlopen(sys.argv[1].rstrip('/') + '/health/ready', context=context, timeout=2) as response:
raise SystemExit(0 if response.status == 200 else 1)
'@
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
do {
& $Python -c $probe $BaseUrl $ca 2>$null
if($LASTEXITCODE -eq 0){ return }
Start-Sleep -Milliseconds 500
} while((Get-Date) -lt $deadline)
throw "HTTPS readiness did not recover within $TimeoutSeconds seconds"
}
# All clients receive an explicit CA file. This workflow has no insecure mode and never uses -k.
Wait-HttpsReady
Run-Test @('tests/smoke.py','--base-url',$BaseUrl,'--ca-file',$ca)
Run-Test @('tests/resilience.py','--mode','persistence','--action-script',(Resolve-Path 'scripts/restart.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
Run-Test @('tests/resilience.py','--mode','failover','--action-script',(Resolve-Path 'scripts/stop-one.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
& docker compose --env-file $EnvFile up -d --no-deps --scale api=2 api
if($LASTEXITCODE -ne 0){ throw 'Failed to restore the stopped API replica' }
Write-Host 'PASS: HTTPS smoke, persistence restart and one-replica failure completed with CA and hostname verification enabled.'