$ErrorActionPreference = 'Stop' $root = Split-Path -Parent $PSScriptRoot $utf8 = [Text.UTF8Encoding]::new($false) $secretDir = Join-Path $root 'secrets' [void][IO.Directory]::CreateDirectory($secretDir) # Compose bind-mounts these files via Docker Desktop. Keep the host ACL private. $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User if (Test-Path -LiteralPath $secretDir -PathType Container) { $security = [Security.AccessControl.DirectorySecurity]::new() $security.SetOwner($sid) $security.SetAccessRuleProtection($true, $false) $inheritance = [Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit' foreach ($principal in @($sid, [Security.Principal.SecurityIdentifier]::new('S-1-5-18'))) { $rule = [Security.AccessControl.FileSystemAccessRule]::new( $principal, 'FullControl', $inheritance, 'None', 'Allow' ) $security.AddAccessRule($rule) } Set-Acl -LiteralPath $secretDir -AclObject $security } function New-HexSecret([string]$name, [int]$length) { $file = Join-Path $secretDir $name if (-not (Test-Path -LiteralPath $file)) { $bytes = New-Object byte[] $length $rng = [Security.Cryptography.RandomNumberGenerator]::Create() try { $rng.GetBytes($bytes) } finally { $rng.Dispose() } $value = [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant() [IO.File]::WriteAllText($file, $value, $utf8) } } New-HexSecret 'broker_password' 32 $brokerPassword = [IO.File]::ReadAllText((Join-Path $secretDir 'broker_password')).Trim() if ($brokerPassword -cnotmatch '^[a-f0-9]{64}$') { throw 'Invalid local RabbitMQ secret format.' } $brokerUrl = Join-Path $secretDir 'broker_url' $brokerExpected = "amqp://messenger:$brokerPassword@broker:5672/%2F" if (-not (Test-Path -LiteralPath $brokerUrl)) { [IO.File]::WriteAllText($brokerUrl, $brokerExpected, $utf8) } if ([IO.File]::ReadAllText($brokerUrl).Trim() -cne $brokerExpected) { throw 'Existing broker_url and broker_password disagree.' } New-HexSecret 'postgres_password' 32 New-HexSecret 's3_access_key_id' 10 New-HexSecret 's3_secret_access_key' 24 $password = [IO.File]::ReadAllText((Join-Path $secretDir 'postgres_password')).Trim() if ($password -cnotmatch '^[a-f0-9]{64}$') { throw 'Invalid local PostgreSQL secret format.' } $url = Join-Path $secretDir 'database_url' $expected = "postgresql://messenger:${password}@postgres:5432/messenger" if (-not (Test-Path -LiteralPath $url)) { [IO.File]::WriteAllText($url, $expected, $utf8) } if ([IO.File]::ReadAllText($url).Trim() -cne $expected) { throw 'Existing database_url and postgres_password disagree.' } $envFile = Join-Path $root '.env' if (-not (Test-Path -LiteralPath $envFile)) { Copy-Item -LiteralPath (Join-Path $root '.env.example') -Destination $envFile } Write-Output 'Lab 5 local configuration ready.'