Files
solution-erp/scripts/deploy-iis.ps1
pqhuy1987 f3fb3fd565 [CLAUDE] Phase5 prep: production infra + deploy scripts + 4 guides + FE refresh token
Backend production infra:
- Packages: Serilog.Sinks.File, HealthChecks.EntityFrameworkCore (RateLimiting built-in .NET 10)
- appsettings.Production.json MOI: placeholder __SET_VIA_SECRETS__, AllowedOrigins, Serilog File sink rolling daily retention 30d, RateLimit config
- appsettings.json + Development.json: them Serilog WriteTo Console
- Program.cs REWRITE:
  - Serilog ReadFrom.Configuration (prod file / dev console)
  - Rate limiter: policy auth-login 5/min/IP (AuthController.Login) + GlobalLimiter 300/min/IP
  - Health checks: /health/live liveness (empty predicate) + /health/ready DB probe (AddDbContextCheck)
  - HSTS production 1 year
  - CORS origins from config AllowedOrigins (default dev 2 localhost)
- AuthController.Login gắn [EnableRateLimiting("auth-login")]

Deploy scripts:
- scripts/deploy-iis.ps1: stop pool → backup current → clean+extract artifact → start pool → health check loop 30s timeout → rollback instruction if fail
- scripts/backup-sql.ps1: BACKUP DATABASE voi INIT+COMPRESSION+CHECKSUM + retention 30d auto cleanup
- .gitea/workflows/deploy.yml MOI: 4 job build BE (Windows) + build 2 FE (Ubuntu, pin .nvmrc 20) + deploy-iis qua WinRM PSSession (secrets IIS_HOST/USER/PASSWORD/JWT_SECRET/DB_CONNECTION)

Docs guides MOI (4 file):
- deployment-iis.md: prereqs (IIS features, Hosting Bundle, SQL, WinRM) + setup lan dau (app pool, 3 site, HTTPS win-acme, user-secrets) + deploy hang ngay (CI/CD + manual) + rollback + monitoring + troubleshooting + SPA web.config sample
- cicd.md: pipeline overview 4 job, secrets setup, runner Windows+Ubuntu, branch strategy, build optimizations, common CI/CD issues
- security-checklist.md: OWASP top 10 2021 mapping voi status + pre go-live checklist + incident response
- runbook.md: daily ops (health/logs), restart/rollback, DB backup/restore/migration revert, user management (reset password, unlock, disable), monitoring (CPU/disk/connection pool), deployment checklist, common gotcha

Frontend refresh token (ca 2 app fe-admin + fe-user):
- lib/api.ts REWRITE: them REFRESH_KEY, axios response interceptor 401 → POST /auth/refresh → retry request goc. Queue pattern cho nhieu request song song chi 1 refresh call chay. Skip retry /auth/login + /auth/refresh tranh infinite loop. _retry flag tren original config.
- contexts/AuthContext.tsx: luu+xoa REFRESH_KEY trong login/logout

E2E verified:
- GET /health/live → 200 Healthy
- GET /health/ready → 200 Healthy (DB probe)
- Rate limit flood 7 POST /auth/login → #1-5 HTTP 400 (cred sai) + #6-7 HTTP 429 Too Many Requests 
- TS check fe-admin + fe-user → pass
- dotnet build → 0 errors

Docs updates:
- docs/STATUS.md: Phase 5 prep done, next Phase 5 deploy production + Phase 5.1 security hardening, cumulative stats 8 commits
- docs/HANDOFF.md: phase table them Phase 5 prep row, file tree update voi guides + scripts + workflows, git state commit 8
- docs/changelog/migration-todos.md: tick Phase 5 prep items (12 items done) + Phase 5 deploy items remaining + Phase 5.1 security hardening list
- docs/changelog/sessions/2026-04-21-1530-phase5-prep.md: session log chi tiet

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 12:57:12 +07:00

100 lines
3.6 KiB
PowerShell

# Deploy SOLUTION_ERP lên IIS Windows Server.
# Chạy trên target server với admin privilege.
#
# Usage:
# .\scripts\deploy-iis.ps1 -Artifact "C:\Deploy\solution-erp-20260421.zip" -Site "SolutionErpApi"
#
# Workflow:
# 1. Stop app pool
# 2. Backup current wwwroot
# 3. Extract artifact → publish path
# 4. Run EF migration (dotnet SolutionErp.Api.dll -- --migrate-only)
# 5. Start app pool
# 6. Health check /health/ready — rollback nếu fail
param(
[Parameter(Mandatory=$true)] [string]$Artifact,
[Parameter(Mandatory=$true)] [string]$Site,
[string]$PublishPath = "C:\inetpub\solution-erp\api",
[string]$AppPoolName = "SolutionErpApi",
[string]$HealthUrl = "https://localhost/health/ready",
[int]$HealthTimeoutSec = 30
)
$ErrorActionPreference = 'Stop'
Import-Module WebAdministration
function Write-Step($msg) { Write-Host "==> $msg" -ForegroundColor Cyan }
Write-Step "Deploy $Artifact -> $PublishPath"
# 1. Check prereqs
if (-not (Test-Path $Artifact)) { throw "Artifact khong ton tai: $Artifact" }
if (-not (Test-Path $PublishPath)) { New-Item -ItemType Directory -Force -Path $PublishPath | Out-Null }
# 2. Stop app pool
Write-Step "Stop app pool $AppPoolName"
if (Test-Path "IIS:\AppPools\$AppPoolName") {
Stop-WebAppPool -Name $AppPoolName -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3
} else {
Write-Warning "App pool $AppPoolName chua ton tai. Tao bang cach:"
Write-Host " New-WebAppPool -Name '$AppPoolName'" -ForegroundColor Yellow
Write-Host " Set-ItemProperty IIS:\AppPools\$AppPoolName -Name managedRuntimeVersion -Value ''" -ForegroundColor Yellow
throw "App pool missing"
}
# 3. Backup current
$BackupDir = "C:\inetpub\solution-erp\backups\api-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
if (Test-Path "$PublishPath\SolutionErp.Api.dll") {
Write-Step "Backup current -> $BackupDir"
New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
Copy-Item -Path "$PublishPath\*" -Destination $BackupDir -Recurse -Force
} else {
Write-Host " (Khong co build cu, skip backup)"
}
# 4. Clean + extract new artifact
Write-Step "Clean + extract $Artifact"
Get-ChildItem -Path $PublishPath -Recurse -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Expand-Archive -Path $Artifact -DestinationPath $PublishPath -Force
# 5. Apply EF migrations (call dotnet SolutionErp.Api.dll với arg --migrate-only — Phase 5 impl)
Write-Step "Apply EF migrations"
Push-Location $PublishPath
try {
# Note: Program.cs check `args.Contains("--no-db-init")`. Default khi start IIS KHONG co arg
# → migrations tu chay khi app boot len. Neu muon run migration truoc khi app start:
# dotnet SolutionErp.Api.dll --migrate-only (TODO: thêm --migrate-only flag trong Program.cs)
Write-Host " (skip — migrations chay tu dong khi app start lan dau)"
} finally {
Pop-Location
}
# 6. Start app pool
Write-Step "Start app pool"
Start-WebAppPool -Name $AppPoolName
# 7. Health check loop
Write-Step "Health check $HealthUrl (timeout ${HealthTimeoutSec}s)"
$deadline = (Get-Date).AddSeconds($HealthTimeoutSec)
$ok = $false
while ((Get-Date) -lt $deadline) {
try {
$resp = Invoke-WebRequest -Uri $HealthUrl -UseBasicParsing -SkipCertificateCheck -TimeoutSec 5
if ($resp.StatusCode -eq 200) { $ok = $true; break }
} catch {
Start-Sleep -Seconds 2
}
}
if ($ok) {
Write-Host "`nDeploy SUCCESS" -ForegroundColor Green
} else {
Write-Warning "`nHealth check FAIL. Rollback thu cong:"
Write-Host " Stop-WebAppPool $AppPoolName"
Write-Host " Copy-Item $BackupDir\* $PublishPath\* -Recurse -Force"
Write-Host " Start-WebAppPool $AppPoolName"
exit 1
}