Files
solution-erp/docs/changelog/sessions/2026-04-21-1530-phase5-prep.md
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

122 lines
5.4 KiB
Markdown

# Session 2026-04-21 15:30 — Phase 5 Prep (Production infra + docs + refresh token)
**Dev:** Claude (Opus 4.7)
**Duration:** ~1h
**Base commit:** `fe7ad8e`
## Làm được
### Chunk O — BE production infra
- Packages: `Serilog.Sinks.File`, `Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore` (RateLimiting built-in .NET 10)
- `appsettings.Production.json` template với placeholders `__SET_VIA_SECRETS__`, `AllowedOrigins`, Serilog File sink rolling daily retention 30d, RateLimit config
- `appsettings.Development.json` + `appsettings.json` thêm Serilog `WriteTo.Console`
- `Program.cs` rewrite:
- Serilog `.ReadFrom.Configuration` (thay hardcode Console) → prod file rolling, dev console
- Rate limiter: policy `auth-login` (5/min/IP) + global (300/min/IP)
- Health checks: `/health/live` liveness + `/health/ready` DB probe
- HSTS production (1 year)
- CORS origins từ config (`AllowedOrigins`)
- `AuthController.Login` gắn `[EnableRateLimiting("auth-login")]`
### Chunk P — Deploy scripts + CI/CD template
- `scripts/deploy-iis.ps1` — stop pool → backup → clean+extract artifact → start pool → health check loop với rollback instruction nếu fail
- `scripts/backup-sql.ps1` — daily BACKUP DATABASE với COMPRESSION+CHECKSUM + retention 30 ngày .bak
- `.gitea/workflows/deploy.yml` — 4 job: build BE (Windows) + build 2 FE (Ubuntu) + deploy IIS qua WinRM PSSession. Pin Node `.nvmrc` (gotcha #5). Secrets IIS_HOST/USER/PASSWORD/JWT_SECRET/DB_CONNECTION
### Chunk Q — Runbook docs (4 file mới trong `docs/guides/`)
- `deployment-iis.md` — prerequisites + setup lần đầu (app pool, site, HTTPS, secrets) + deploy hàng ngày + troubleshooting + SPA web.config sample
- `cicd.md` — pipeline overview, secrets, runner setup Windows+Ubuntu, branch strategy, build optimizations, common issues
- `security-checklist.md` — OWASP top 10 2021 mapping với status hiện tại + pre go-live checklist + incident response
- `runbook.md` — daily ops (health/logs), restart/rollback, DB backup/restore/migration revert, user management, monitoring, deployment checklist
### Chunk R — FE refresh token auto
- `fe-admin/src/lib/api.ts` + `fe-user/src/lib/api.ts` rewrite:
- Thêm `REFRESH_KEY` localStorage key
- Axios response interceptor: 401 → thử POST `/auth/refresh` → retry request gốc với token mới
- **Queue pattern** để nhiều request song song chỉ 1 refresh call chạy, các request khác chờ token mới
- Skip retry cho `/auth/login``/auth/refresh` (tránh infinite loop)
- `_retry` flag trên original config để không retry 2 lần
- `contexts/AuthContext.tsx` (cả 2 app): lưu+xóa `REFRESH_KEY` trong login/logout
## E2E verified
```bash
# Health check
GET /health/live → 200 Healthy
GET /health/ready → 200 Healthy (DB probe pass)
# Rate limit
POST /api/auth/login x 7 lần /phút/IP
#1-5: HTTP 400 (invalid cred) — còn trong limit
#6-7: HTTP 429 Too Many Requests ✅
# TS check fe-admin + fe-user → pass
# Build BE → pass
```
## Docs consolidation
- Docs: 4 file guides MỚI (`deployment-iis`, `cicd`, `security-checklist`, `runbook`)
- `Program.cs`: rewrite với prod infra
- `appsettings.Production.json` MỚI
- `appsettings.json` + `Development.json` update Serilog Console sink
- `scripts/deploy-iis.ps1` + `backup-sql.ps1` MỚI
- `.gitea/workflows/deploy.yml` MỚI
- fe-admin + fe-user: `lib/api.ts` refresh token queue pattern, `contexts/AuthContext.tsx` update
## Bug gặp + fix
| Bug | Fix |
|---|---|
| Write Program.cs không persist lần đầu (Dropbox?) | Verify qua grep → re-Write full file |
| `Microsoft.AspNetCore.RateLimiting` không có stable package | Dùng built-in `.AddRateLimiter()` ASP.NET Core 7+ không cần package |
## Handoff cho session tiếp theo
### Phase 5 còn cần (với Gitea URL)
- [ ] Setup Gitea remote + push code
- [ ] Enable Gitea Actions runner (Windows + Ubuntu)
- [ ] Set 5 secrets trong Gitea
- [ ] Test CI/CD workflow lần đầu trên staging
- [ ] Windows Server setup IIS theo `deployment-iis.md`
- [ ] HTTPS cert (win-acme)
- [ ] SQL Server prod + backup task schedule
- [ ] Smoke test end-to-end prod
- [ ] UAT 1 tuần với 2-3 user thật
### Security hardening (Phase 5.1)
- [ ] Security headers middleware (X-Content-Type-Options, X-Frame-Options, CSP)
- [ ] Account lockout (Identity options — đã có spec ở security-checklist.md)
- [ ] Password policy production min 12 chars
- [ ] IDOR check trong ContractsController (user không xem được HĐ không liên quan)
- [ ] Dependencies scan vào CI (`dotnet list package --vulnerable`, `npm audit`)
### Quick wins
- [ ] FE Users management + Roles CRUD (để test permission với non-admin user)
- [ ] Filter Inbox theo phase FE
- [ ] Dashboard user-specific
### Blocker
-**Gitea URL** — user sẽ cấp
## Thông số cumulative
| | Phase 3 | Phase 4 | **Phase 5 prep** |
|---|---:|---:|---:|
| BE LOC | ~2700 | ~3100 | **~3300** (thêm rate limit + health check wiring) |
| DB tables | 19 | 19 | 19 |
| API endpoints | ~31 | ~33 | **~35** (+ /health/live + /health/ready) |
| FE pages | 14 | 16 | 16 |
| Scripts PS | 2 (parse_forms, parse_workflow) | +1 (convert-doc) | **+3** (deploy-iis, backup-sql, existing) = 6 |
| CI/CD workflow | 0 | 0 | **1** (.gitea/workflows/deploy.yml) |
| Docs files | 26 | 30 | **35** (+4 guides + session log) |
| Commits | 6 | 7 | **8** (sắp) |