[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>
This commit is contained in:
pqhuy1987
2026-04-21 12:57:12 +07:00
parent fe7ad8e4a3
commit f3fb3fd565
19 changed files with 1382 additions and 91 deletions

123
docs/guides/cicd.md Normal file
View File

@ -0,0 +1,123 @@
# CI/CD — Gitea Actions
> Automation pipeline từ push → build → test → deploy. Chạy trên Windows self-hosted runner (cần cho WinRM + Word COM).
## 1. Pipeline overview
```
Push main
├─ build-backend (Windows runner)
│ └─ dotnet restore/build/publish → artifact "backend-api"
├─ build-fe-admin (Ubuntu runner)
│ └─ npm ci + npm run build → artifact "fe-admin-dist"
├─ build-fe-user (Ubuntu runner)
│ └─ npm ci + npm run build → artifact "fe-user-dist"
└─ deploy-iis (Windows runner) — chỉ khi ref = main
├─ download 3 artifact
├─ Compress-Archive → 3 zip
├─ Copy-Item via PSSession WinRM → target server
└─ Invoke-Command → scripts/deploy-iis.ps1
```
File spec: `.gitea/workflows/deploy.yml` (đã có).
## 2. Secrets setup
Trong Gitea repo → Settings → Actions → Secrets, thêm:
| Secret | Ví dụ | Mô tả |
|---|---|---|
| `IIS_HOST` | `10.0.0.100` | Hostname/IP target IIS server |
| `IIS_USER` | `solution-erp\deploy` | Windows user có admin + WinRM enabled |
| `IIS_PASSWORD` | `...` | Password tương ứng |
| `JWT_SECRET` | 64+ random chars | Pass vào user-secrets khi deploy |
| `DB_CONNECTION` | `Server=.;Database=SolutionErp;...` | ConnectionString production |
**KHÔNG** echo secret ra log (Gitea auto-mask nhưng vẫn cẩn thận).
## 3. Runner setup
### Windows self-hosted runner (cho build BE + deploy)
Trên Windows VM:
```powershell
# Download Gitea Act runner
# https://gitea.com/gitea/act_runner/releases
.\act_runner register --instance https://gitea.yourcorp.local --token <token>
.\act_runner daemon
```
Prereqs trên runner:
- .NET 10 SDK
- Git 2.40+
- PowerShell 7+
- Node 20 (cho test/build nếu cần BE test với FE proxy)
- WinRM client: `winrm quickconfig`
- Test connectivity: `Test-NetConnection $env:IIS_HOST -Port 5985`
### Ubuntu runner (cho build FE)
```bash
# Docker runner
docker run -d --name gitea-runner \
-v /var/run/docker.sock:/var/run/docker.sock \
-e GITEA_INSTANCE_URL=https://gitea.yourcorp.local \
-e GITEA_RUNNER_REGISTRATION_TOKEN=<token> \
gitea/act_runner:latest
```
Prereqs:
- Node 20 (qua `actions/setup-node` — KHÔNG dùng latest, xem [`gotchas.md #5`](../gotchas.md))
- npm cache
## 4. Branch strategy + trigger
| Branch | Trigger | Action |
|---|---|---|
| `main` | push | full build + deploy production |
| `staging` | push | full build + deploy staging (nếu có) |
| `feature/*` | push | chỉ build + test, không deploy |
| PR merge | merge_request | build + test, optional auto-merge nếu pass |
| Manual | `workflow_dispatch` | re-deploy current main |
## 5. Build optimizations
- Node cache qua `actions/setup-node@v4` với `cache: 'npm'` + `cache-dependency-path`
- NuGet cache qua `actions/cache@v4` path `~/.nuget/packages` (Windows: `%USERPROFILE%\.nuget\packages`)
- Parallel build 3 job FE/BE độc lập
## 6. Pre-commit checks (Phase 5.1 — khi có thời gian)
Thêm job `verify` chạy trước deploy:
- `dotnet format --verify-no-changes`
- `dotnet test` (khi có unit test)
- `npm run lint`
- `npm run build` (both FE)
## 7. Rollback qua CI/CD
1. Gitea repo → Actions → tìm run cũ đã deploy thành công
2. Re-run job đó (re-runner download artifact cũ + deploy lại)
Hoặc revert git:
```bash
git revert <bad-commit>
git push
```
## 8. Common CI/CD issues
| Problem | Fix |
|---|---|
| Node build fail trên CI nhưng OK local | Pin Node 20 qua `.nvmrc` (gotcha #5) |
| WinRM timeout | Check firewall port 5985/5986, increase `Test-NetConnection -TimeoutSec` |
| NuGet restore slow | Add cache action |
| Artifact size > 100MB | Exclude `bin/`, `obj/`, `node_modules/` trong `dotnet publish` |
| Deploy không thấy file mới | App pool chưa restart — xem log `scripts/deploy-iis.ps1` xem Stop+Start có chạy không |
## 9. Liên quan
- [`deployment-iis.md`](deployment-iis.md) — IIS setup chi tiết
- [`runbook.md`](runbook.md) — operations
- `.gitea/workflows/deploy.yml` — workflow YAML
- `scripts/deploy-iis.ps1` — deploy script

View File

@ -0,0 +1,216 @@
# Deployment — Windows Server + IIS
> Step-by-step setup lần đầu + deploy hàng ngày. Test với Windows Server 2019/2022 + IIS 10.
## 1. Prerequisites trên target server
### OS + IIS
- Windows Server 2019 / 2022 (hoặc Windows 10/11 Pro cho staging)
- IIS với features: **Static Content**, **HTTP Redirection**, **Application Initialization**, **WebSocket Protocol**, **Management Console**, **Windows Auth** (optional)
- **URL Rewrite Module 2.1+**: https://www.iis.net/downloads/microsoft/url-rewrite
- **Application Request Routing (ARR) 3.0+** (nếu dùng reverse proxy): https://www.iis.net/downloads/microsoft/application-request-routing
### .NET 10 Hosting Bundle
```
https://dotnet.microsoft.com/en-us/download/dotnet/10.0
→ .NET 10 Hosting Bundle (không phải SDK, runtime + ASP.NET Core Module)
```
Sau khi cài → restart IIS: `iisreset` trong cmd elevated.
### SQL Server
- SQL Server 2019+ Express / Standard / Enterprise
- Tạo DB `SolutionErp` + SQL user `solutionerp_app` với db_owner
- Bật **Named Pipes** hoặc **TCP/IP** protocol (SQL Server Configuration Manager)
### WinRM (cho CI/CD deploy từ xa)
```powershell
# Run as admin trên target server
Enable-PSRemoting -Force
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force
winrm quickconfig -Transport:HTTPS
```
## 2. Setup lần đầu
### 2.1 Tạo app pool
```powershell
Import-Module WebAdministration
New-WebAppPool -Name "SolutionErpApi"
Set-ItemProperty IIS:\AppPools\SolutionErpApi -Name managedRuntimeVersion -Value "" # .NET CORE (no CLR)
Set-ItemProperty IIS:\AppPools\SolutionErpApi -Name startMode -Value "AlwaysRunning"
Set-ItemProperty IIS:\AppPools\SolutionErpApi -Name processModel.identityType -Value "ApplicationPoolIdentity"
```
### 2.2 Tạo site (3 site hoặc 1 site với 3 path)
**Recommended:** 3 site riêng để quản lý binding dễ:
```powershell
# Api
New-WebSite -Name "SolutionErp-Api" -Port 443 -HostHeader "api.solutionerp.local" `
-PhysicalPath "C:\inetpub\solution-erp\api" -ApplicationPool "SolutionErpApi" -Ssl
# Admin FE
New-WebSite -Name "SolutionErp-Admin" -Port 443 -HostHeader "admin.solutionerp.local" `
-PhysicalPath "C:\inetpub\solution-erp\fe-admin" -Ssl
# User FE
New-WebSite -Name "SolutionErp-User" -Port 443 -HostHeader "app.solutionerp.local" `
-PhysicalPath "C:\inetpub\solution-erp\fe-user" -Ssl
```
### 2.3 HTTPS certificate
#### Option A — win-acme (Let's Encrypt free)
```powershell
# Download từ https://www.win-acme.com/
wacs.exe
# Menu: N (new cert) → chọn sites → auto-renew via scheduled task
```
#### Option B — Self-signed (dev/staging only)
```powershell
$cert = New-SelfSignedCertificate -DnsName "api.solutionerp.local", "admin.solutionerp.local", "app.solutionerp.local" `
-CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears(5)
$bytes = $cert.GetCertHash()
```
### 2.4 Secrets cho Api
**KHÔNG commit `appsettings.Production.json` với secret thật.** Dùng user-secrets:
```powershell
# Trên target server, với identity app pool
cd C:\inetpub\solution-erp\api
dotnet user-secrets set "Jwt:Secret" "__RANDOM_64_CHAR_STRING__"
dotnet user-secrets set "ConnectionStrings:Default" "Server=.;Database=SolutionErp;User Id=solutionerp_app;Password=..."
```
Hoặc dùng env vars (set qua IIS app pool advanced settings):
- `Jwt__Secret` = `...`
- `ConnectionStrings__Default` = `...`
### 2.5 FE build — adjust Vite base URL + API proxy
`fe-admin/vite.config.ts` production build không proxy, FE gọi trực tiếp `https://api.solutionerp.local`. Thêm env:
```
# fe-admin/.env.production
VITE_API_BASE_URL=https://api.solutionerp.local
```
Update `src/lib/api.ts` sử dụng `import.meta.env.VITE_API_BASE_URL ?? '/api'`.
### 2.6 Init DB
```powershell
# Run trên app server với .NET SDK installed (KHÔNG chỉ runtime)
cd C:\Deploy\staging
dotnet ef database update --project src\Backend\SolutionErp.Infrastructure --startup-project src\Backend\SolutionErp.Api
```
Hoặc tự động khi app khởi động lần đầu (đã có trong `DbInitializer`).
## 3. Deploy hàng ngày
### 3.1 Qua CI/CD (Gitea Actions)
Push code vào `main``.gitea/workflows/deploy.yml` auto:
1. Build BE + 2 FE
2. Upload artifact
3. WinRM tới IIS host
4. Run `scripts/deploy-iis.ps1`
### 3.2 Manual deploy
```powershell
# Trên dev machine
dotnet publish src/Backend/SolutionErp.Api --configuration Release -o .\publish\api
cd fe-admin && npm ci && npm run build # dist/
cd fe-user && npm ci && npm run build # dist/
Compress-Archive .\publish\api\* api.zip
Compress-Archive .\fe-admin\dist\* fe-admin.zip
Compress-Archive .\fe-user\dist\* fe-user.zip
# Copy lên target server
Copy-Item api.zip, fe-admin.zip, fe-user.zip -Destination \\server\C$\Deploy\ -Force
# Trên target server
.\scripts\deploy-iis.ps1 -Artifact C:\Deploy\api.zip -Site SolutionErpApi
Expand-Archive C:\Deploy\fe-admin.zip C:\inetpub\solution-erp\fe-admin -Force
Expand-Archive C:\Deploy\fe-user.zip C:\inetpub\solution-erp\fe-user -Force
```
### 3.3 Rollback
```powershell
# Deploy script tự backup vào C:\inetpub\solution-erp\backups\api-{timestamp}
Stop-WebAppPool SolutionErpApi
Copy-Item C:\inetpub\solution-erp\backups\api-20260421-0930\* `
C:\inetpub\solution-erp\api\ -Recurse -Force
Start-WebAppPool SolutionErpApi
# Nếu migration hỏng → revert DB:
dotnet ef database update <PreviousMigrationName> --project ...
```
## 4. Monitoring
### 4.1 Health check
- `/health/live` — liveness probe (IIS ping)
- `/health/ready` — readiness probe (DB reachable)
### 4.2 Logs
- Serilog → `C:\inetpub\solution-erp\api\logs\solution-erp-{yyyyMMdd}.log`
- Retention 30 ngày auto
- IIS request log: `C:\inetpub\logs\LogFiles\`
- Application event log: `eventvwr` → Windows Logs → Application → Source: IIS Express / .NET Runtime
### 4.3 SQL backup
Task Scheduler trigger `scripts\backup-sql.ps1` daily 2:00 AM. Retention 30 ngày `.bak` files.
## 5. Troubleshooting
| Triệu chứng | Check |
|---|---|
| HTTP 500.30 ANCM startup | event log `Application`, logs folder có được tạo không, permission app pool identity |
| HTTP 502.5 ANCM Process failure | .NET 10 Hosting Bundle đã cài chưa, app pool CLR = "" |
| 500 khi login | secrets config đúng chưa (Jwt__Secret + ConnectionStrings__Default) |
| CORS fail | `appsettings.Production.json``AllowedOrigins` match domain FE |
| Slow query | check index (xem `database/schema-diagram.md §4`) |
| App pool crash loop | disable rapid fail protection tạm thời khi debug: `Set-ItemProperty IIS:\AppPools\SolutionErpApi -Name failure.rapidFailProtection -Value false` |
| FE 404 routes (vd /contracts/123) | IIS URL Rewrite config SPA fallback — tạo `web.config` FE folder với rule rewrite `.*``index.html` |
### web.config cho SPA FE (sample)
```xml
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="SPA Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/api" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
```
## 6. Liên quan
- [`cicd.md`](cicd.md) — Gitea Actions workflow chi tiết
- [`security-checklist.md`](security-checklist.md) — OWASP top 10
- [`runbook.md`](runbook.md) — operations (restart, restore, common tasks)
- [`../database/database-guide.md`](../database/database-guide.md) — DB backup/restore chi tiết

195
docs/guides/runbook.md Normal file
View File

@ -0,0 +1,195 @@
# Runbook — Operations
> Tác vụ vận hành thường gặp. Copy-paste command khi cần.
## 1. Daily operations
### 1.1 Check health
```powershell
Invoke-WebRequest https://api.solutionerp.local/health/ready -SkipCertificateCheck
# → Status 200 "Healthy"
```
### 1.2 Check logs
```powershell
# Tail log hôm nay
Get-Content "C:\inetpub\solution-erp\api\logs\solution-erp-$(Get-Date -Format 'yyyyMMdd').log" -Tail 50 -Wait
# Grep error
Select-String -Path "C:\inetpub\solution-erp\api\logs\*.log" -Pattern "ERR|FTL" -Context 2
```
### 1.3 Check recent failed logins
```sql
-- Nếu có audit log (Phase 5.1). Hiện chỉ có ContractApprovals → check Serilog file.
```
## 2. Restart / rollback
### 2.1 Restart Api app pool
```powershell
Restart-WebAppPool -Name SolutionErpApi
```
### 2.2 Restart toàn bộ IIS (nặng, chỉ khi cần)
```powershell
iisreset /noforce
```
### 2.3 Rollback deploy
```powershell
# Deploy script auto-backup vào C:\inetpub\solution-erp\backups\api-{timestamp}
Stop-WebAppPool SolutionErpApi
$latest = Get-ChildItem "C:\inetpub\solution-erp\backups" | Sort-Object Name -Descending | Select-Object -First 1
Copy-Item "$($latest.FullName)\*" -Destination "C:\inetpub\solution-erp\api\" -Recurse -Force
Start-WebAppPool SolutionErpApi
Invoke-WebRequest https://api.solutionerp.local/health/ready -SkipCertificateCheck # verify
```
## 3. Database
### 3.1 Manual backup (ngoài daily job)
```powershell
.\scripts\backup-sql.ps1 -Server "." -Database "SolutionErp" -BackupDir "D:\Backups\SolutionErp-manual"
```
### 3.2 Restore từ backup
```sql
-- WARNING: Destructive. Stop app trước.
USE master;
ALTER DATABASE SolutionErp SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
RESTORE DATABASE SolutionErp
FROM DISK = N'D:\Backups\SolutionErp\SolutionErp_20260421-020000.bak'
WITH REPLACE, RECOVERY;
ALTER DATABASE SolutionErp SET MULTI_USER;
```
### 3.3 Rollback migration
```powershell
# List migrations đã apply
cd C:\Deploy\staging # nơi có .NET SDK
dotnet ef migrations list --project src\Backend\SolutionErp.Infrastructure --startup-project src\Backend\SolutionErp.Api
# Rollback về migration cụ thể
dotnet ef database update <PreviousMigrationName> --project ... --startup-project ...
```
### 3.4 Clear test data (dev)
```sql
-- Clear toàn bộ Contracts + related (giữ master data)
DELETE FROM ContractApprovals;
DELETE FROM ContractComments;
DELETE FROM ContractAttachments;
DELETE FROM Contracts;
DELETE FROM ContractCodeSequences;
```
## 4. User management
### 4.1 Tạo user mới
```sql
-- Phase 5.1 có FE, hiện manual qua SQL (không khuyến khích — password hash phải đúng format)
-- Recommend: tạo qua UserManager trong 1 script .NET, hoặc API `POST /api/users` (chưa implement)
```
### 4.2 Reset password admin (emergency)
```powershell
# Run script one-off trên server
cd C:\inetpub\solution-erp\api
dotnet SolutionErp.Api.dll --reset-password admin@solutionerp.local NewPassword@2026
# (Feature chưa có — Phase 5.1)
```
Temporary workaround: update `PasswordHash` qua Identity `UserManager` trong code, redeploy.
### 4.3 Unlock account bị lock
```sql
UPDATE Users SET LockoutEnd = NULL, AccessFailedCount = 0 WHERE Email = 'user@example.com';
```
### 4.4 Disable user
```sql
UPDATE Users SET IsActive = 0 WHERE Email = 'user@example.com';
-- Note: JWT hiện tại vẫn valid tới hết expiry (1h) — Phase 5.1 cần check IsActive trong middleware
```
## 5. Monitoring + incident
### 5.1 High CPU app pool
```powershell
# Identify worker process
Get-Process w3wp | Select-Object Id, CPU, WorkingSet64, StartTime
# Kill nếu stuck (IIS tự restart)
Stop-Process -Id <pid> -Force
```
### 5.2 Out of disk
```powershell
# Check logs folder
Get-ChildItem "C:\inetpub\solution-erp\api\logs" | Sort-Object LastWriteTime | Select -First 20
# Delete logs cũ hơn 30 ngày (đã config retention nhưng check)
Get-ChildItem "C:\inetpub\solution-erp\api\logs" -Filter "*.log" |
Where-Object LastWriteTime -lt (Get-Date).AddDays(-30) | Remove-Item
```
### 5.3 Suspected brute-force attack
```powershell
# Grep 401 qua IIS log
Get-Content C:\inetpub\logs\LogFiles\W3SVC1\*.log -Tail 5000 |
Select-String " 401 " | Group-Object { ($_ -split ' ')[8] } |
Sort-Object Count -Descending | Select -First 10
# Nếu thấy IP suspicious → block IIS IP Restriction hoặc firewall rule
```
### 5.4 DB connection pool exhausted
```sql
-- Check active connections
SELECT DB_NAME(dbid) AS DB, COUNT(*) AS Connections, loginame AS Login
FROM sys.sysprocesses
WHERE dbid > 0
GROUP BY dbid, loginame
ORDER BY 2 DESC;
-- Kill connection cụ thể nếu stuck
KILL <spid>;
```
## 6. Deployment checklist
Trước khi deploy:
- [ ] Backup DB (manual nếu chưa auto chạy)
- [ ] Note commit SHA đang live
- [ ] Check CI/CD passed all checks
- [ ] Notify team trong Slack/Teams (nếu có downtime)
Sau deploy:
- [ ] Health check `/health/ready` → 200
- [ ] Smoke test: login + list HĐ + export Excel
- [ ] Check log 5 phút đầu không có ERR
- [ ] Monitor CPU/RAM 15 phút
## 7. Common "gotcha" vận hành
| Symptom | Fix |
|---|---|
| App pool crash rapid fail sau deploy | Disable temp: `Set-ItemProperty IIS:\AppPools\SolutionErpApi -Name failure.rapidFailProtection -Value false` — debug log → enable lại |
| User bị logout mass sau deploy | Check Jwt:Secret có đổi không — rotate secret → buộc mọi user login lại (expected nếu intentional) |
| Migration fail "connection string" | Check user secrets / env var chưa set trong app pool advanced settings |
| FE trắng trang | F12 console check path — thường do `base` trong vite.config.ts khác env, hoặc missing web.config SPA rewrite |
| Export Excel 500 | Check `wwwroot/templates` có đủ 5 file .docx/.xlsx không — ClosedXML fail khi template missing |
## 8. Escalation contacts
| Role | Name | Contact |
|---|---|---|
| Dev lead | pqhuy@solutions.local | pqhuy1987@gmail.com |
| DBA | TBD | — |
| On-call 24/7 | TBD | — |
## 9. Liên quan
- [`deployment-iis.md`](deployment-iis.md) — setup chi tiết
- [`cicd.md`](cicd.md) — CI/CD pipeline
- [`security-checklist.md`](security-checklist.md) — incident response
- [`../gotchas.md`](../gotchas.md) — bẫy dev + ops
- [`../database/database-guide.md`](../database/database-guide.md) — backup/restore detail

View File

@ -0,0 +1,147 @@
# Security Checklist — SOLUTION_ERP
> OWASP Top 10 2021 + best practices production. Review trước Phase 5 go-live.
## Current status (sau Phase 5 prep)
| Item | Status | Nơi kiểm |
|---|---|---|
| HTTPS enforce (HSTS 365d) | ✅ | `Program.cs``app.UseHsts()` production |
| JWT expiry 1h + refresh 7d | ✅ | `appsettings.json` Jwt section |
| Password hash PBKDF2 | ✅ | ASP.NET Identity default |
| Rate limit `/auth/login` 5/min/IP | ✅ | `Program.cs` `[EnableRateLimiting("auth-login")]` |
| Rate limit global 300/min/IP | ✅ | `Program.cs` `GlobalLimiter` |
| CORS whitelist 2 origin prod | ✅ | `appsettings.Production.json` `AllowedOrigins` |
| JWT secret from user-secrets prod | 🔲 | Cần set khi deploy — xem [`deployment-iis.md §2.4`](deployment-iis.md) |
| DB connection user least privilege | 🔲 | `solutionerp_app` cần chỉ `db_owner` trên DB chính, không sysadmin |
| Audit log writes | 🟡 | Có `ContractApprovals` cho workflow, chưa có global audit |
| SQL injection via EF parameterized | ✅ | EF Core mặc định parameterize |
| Input validation | ✅ | FluentValidation mọi command |
| XSS protection | ⚠️ | React auto-escape OK, nhưng TextArea notes có thể render raw nếu dev viết `dangerouslySetInnerHTML` |
| CSRF protection | 🔲 | JWT localStorage + sameOrigin — không vulnerable CSRF theo classic (không dùng cookie) |
| Dependencies scan | 🔲 | Chưa có — thêm `dotnet list package --vulnerable` + `npm audit` vào CI |
## OWASP Top 10 2021 mapping
### A01:2021 — Broken Access Control
**Guard:** `[Authorize]` default trên mọi controller, policy `{Menu}.{Action}` cho granular check.
**FE guard:** `<PermissionGuard>` + `usePermission()` — nhưng BE là source of truth (403 từ BE nếu FE bypass).
**Check trước go-live:**
- [ ] Test user role Drafter → không access được endpoint `/api/permissions`, `/api/users`
- [ ] Test IDOR: user A không truy cập được HĐ user B qua `/api/contracts/{id}`**HIỆN CHƯA CHECK**. Phase 5 cần thêm check "user tham gia HĐ" (DrafterUserId hoặc có role giữ phase hiện tại).
### A02:2021 — Cryptographic Failures
✅ HTTPS + HSTS production.
✅ JWT HS256 với secret 64+ chars (random).
🔲 Password policy min 8 chars + mixed case + digit + symbol. Prod strong password tối thiểu 12.
### A03:2021 — Injection
✅ EF Core parameterized queries (no raw SQL).
✅ Input validation FluentValidation.
⚠️ File upload: chưa implement upload endpoint; khi làm phải validate MIME + magic bytes + path traversal.
### A04:2021 — Insecure Design
✅ Workflow state machine với explicit adjacency — không cho skip phase bypass rule.
✅ Audit trail qua `ContractApprovals`.
🔲 Business rule: ai được tạo HĐ? Hiện default Drafter role, Phase 5 nên limit theo dept.
### A05:2021 — Security Misconfiguration
`appsettings.Production.json` template có placeholder `__SET_VIA_USER_SECRETS_OR_ENV__` — không có secret thật commit.
`appsettings.Development.json` với dev-only secret.
🔲 IIS hardening: disable server banner header, disable X-Powered-By.
🔲 Swagger chỉ bật dev.
**Thêm vào web.config hoặc Program.cs:**
```csharp
app.Use(async (ctx, next) =>
{
ctx.Response.Headers.Remove("Server");
ctx.Response.Headers.Remove("X-Powered-By");
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
ctx.Response.Headers["X-Frame-Options"] = "DENY";
ctx.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
ctx.Response.Headers["Content-Security-Policy"] = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'";
await next();
});
```
### A06:2021 — Vulnerable Components
🔲 CI thêm `dotnet list package --vulnerable --include-transitive`
🔲 CI thêm `npm audit --audit-level=high`
🔲 Monthly update: patch minor versions, major khi LTS cần
### A07:2021 — Authentication Failures
✅ Rate limit login 5/min/IP.
✅ PBKDF2 hash.
🔲 Account lockout sau N lần sai password (config `UserLockout` trong Identity — chưa bật).
🔲 MFA — Phase 6+ nếu cần.
**Bật account lockout:**
```csharp
services.AddIdentityCore<User>(options =>
{
// ...
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
});
```
### A08:2021 — Software + Data Integrity Failures
✅ EF migrations versioned trong source.
✅ Git commits signed (optional — set `user.signingkey`).
🔲 CI artifact SHA256 verify trước deploy.
### A09:2021 — Logging + Monitoring Failures
✅ Serilog structured → file rolling daily retention 30d prod.
✅ Request log qua `UseSerilogRequestLogging`.
🔲 Alert khi có `/api/auth/login` fail >10/min/IP (SIEM hoặc manual grep log).
🔲 Alert khi `/api/contracts/{id}/transitions` fail role guard >5/min (suspicious activity).
### A10:2021 — SSRF
Không áp dụng — app không fetch URL do user cung cấp.
## Pre go-live checklist
- [ ] `JWT_SECRET` production ≥ 64 random chars
- [ ] Connection string dùng SQL user `solutionerp_app` với password mạnh
- [ ] `appsettings.Production.json` đã set `AllowedOrigins` chính xác
- [ ] HTTPS cert valid + auto-renew (win-acme scheduled task)
- [ ] HSTS preload list (optional)
- [ ] Security headers middleware added
- [ ] Account lockout enabled (5 fail → lock 15min)
- [ ] Password policy min 12 chars prod
- [ ] Backup SQL chạy (test restore)
- [ ] Log retention 30d verified
- [ ] Rate limit test: flood 10 req → 429 từ request thứ 6
- [ ] IDOR check: user Drafter A không xem được HĐ tôi của user B
- [ ] CSP header prevent inline script
- [ ] Run OWASP ZAP scan → no critical finding
- [ ] Dependencies: `dotnet list package --vulnerable` + `npm audit` → clean
- [ ] Admin account mặc định `admin@solutionerp.local` — đổi password production hoặc disable
## Incident response
**Suspected compromise:**
1. Rotate JWT secret → mọi user bị logout
2. Disable account lockout temporarily để admin login được
3. Check `ContractApprovals` last 24h cho activity bất thường
4. Restore SQL backup nếu có data corruption
5. Report CERT team
## Liên quan
- [`deployment-iis.md`](deployment-iis.md) — IIS hardening
- [`runbook.md`](runbook.md) — incident response detail
- [`../gotchas.md`](../gotchas.md) — pitfall đã gặp