Files
Tom Chien (IQ-AS)andClaude Opus 4.6 b3d48198c4 Migrate to Gitea + local Docker Desktop k8s/Harbor; remove SSO
- Remove Microsoft Entra ID SSO entirely; local admin credentials login
  is the only sign-in path (fail-closed on empty LOCAL_ADMIN_PASSWORD).
  Delete config/users.json allowlist and lookupRole.
- Move CI from .github to .gitea/workflows (Gitea Actions, runner label
  gitea-runner); drop the k8s-API network debug step.
- Replace JFrog with local Harbor: push/pull via
  host.docker.internal:8080/library, login with HARBOR_* Gitea secrets,
  pull secret renamed to harbor-pull-secret (created by CI per namespace).
- Adapt Helm values to Docker Desktop k8s: storageClassName hostpath,
  Harbor image repositories, *.local ingress hosts, AUTH_URL scheme http
  (configurable via ingress.scheme).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-17 14:00:45 +08:00

154 lines
6.1 KiB
Markdown

# Production Deployment (EC2 + RDS)
Dev runs on **SQLite**; production runs on **MySQL (AWS RDS)**. Because Prisma
cannot switch the datasource `provider` via `env()`, dev and prod use separate
schema files and migration histories:
| Environment | Schema | Migrations | DB |
| ----------- | -------------------------- | ------------------------- | --------------------------- |
| dev | `prisma/schema.prisma` | `prisma/migrations` | SQLite (`prisma/dev.db`) |
| prod | `prisma/prod/schema.prisma`| `prisma/prod/migrations` | MySQL / RDS |
## Infrastructure
- **App EC2**: `10.106.103.40`
- **RDS (private subnet)**: `it-cost-prod-db.c8hgbsblyypx.us-west-2.rds.amazonaws.com:3306`
- Database: `it_cost_dashboard`
- The EC2 host is verified able to reach the RDS instance.
## One-time setup on the EC2 host
1. Install dependencies:
```bash
npm ci
```
2. Create the production env file from the template and fill in the real
RDS credentials (this file is gitignored and must never be committed):
```bash
cp .env.production.example .env.production
# edit .env.production -> set the real DATABASE_URL
```
## Deploy / release steps
Run from the project root on the EC2 host (`/var/www/it_cost_dashboard`):
```bash
cd /var/www/it_cost_dashboard
# 1. Make the prod DATABASE_URL available to the Prisma CLI (it only reads .env
# by default, so we export .env.production explicitly).
set -a && source .env.production && set +a
# 2. Apply migrations to RDS (idempotent; safe to re-run).
npm run prod:migrate
# 3. (First release only) seed baseline data.
npm run seed
# 4. Generate the MySQL Prisma client. ALWAYS re-run this if you just ran
# `npm ci` / `npm install` — installing can reset the generated client in
# node_modules/.prisma/client back to the default (dev/SQLite) schema.
npm run prod:generate
# 5. Wipe stale build output BEFORE building. This is a hard rule: a leftover
# `.next/cache` from an earlier `npm run build` (dev/SQLite) can bake the
# wrong Prisma client into the compiled routes ("URL must start with `file:`").
rm -rf .next
# 6. Generate the MySQL client again + build Next.js.
npm run build:prod
# 7. (Re)start under pm2, picking up fresh env from .env.production.
pm2 restart it_cost_dashboard --update-env # first time: pm2 start npm --name it_cost_dashboard -- run start
```
### Verify the release
Always confirm the app came up on the MySQL client (not a stale SQLite build):
```bash
# No Prisma init errors in the logs.
pm2 logs it_cost_dashboard --lines 40 --nostream
# The failing endpoint returns 200 + JSON (adjust port if PORT differs).
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/api/years # expect 200
curl -s http://localhost:3000/api/years | head -c 300 # expect JSON, not a 500
```
Success = `/api/years` returns 200 + JSON and pm2 logs show no
`PrismaClientInitializationError` / `the URL must start with the protocol \`file:\``.
### Alternative: systemd unit
For a systemd-managed process instead of pm2:
```ini
# /etc/systemd/system/it-cost-dashboard.service
[Service]
WorkingDirectory=/var/www/it_cost_dashboard
EnvironmentFile=/var/www/it_cost_dashboard/.env.production
ExecStart=/usr/bin/npm run start
Restart=always
```
## Authentication & authorization
Sign-in uses Auth.js / NextAuth v5 with a single sign-in path:
- **Local username/password** — a form on `/login`, controlled by
`LOCAL_ADMIN_USERNAME` / `LOCAL_ADMIN_PASSWORD`. This account always has the
`admin` role. An empty `LOCAL_ADMIN_PASSWORD` disables login entirely (fail
closed).
Middleware redirects any unauthenticated request to `/login` and enforces roles
**server-side**: non-admin users are redirected away from admin pages
(`/cost-registration`, `/cost-item-creation`, `/year-creation`) and any write API
call (non-`GET` `/api/*`) returns **403**. Read APIs (`GET /api/*`) stay open to
any signed-in user. The sidebar "Admin" group is also hidden for non-admins.
### Required env vars (`.env.production`)
Next.js does **not** load `.env.local` in production, so these must live in
`.env.production` on the EC2 host:
```env
AUTH_SECRET="<32-byte random string, e.g. `npx auth secret`>"
AUTH_URL="https://<your-prod-domain>" # or set AUTH_TRUST_HOST=true behind a TLS proxy/ALB
# Local admin login. Non-empty password ENABLES the /login form; empty disables it.
LOCAL_ADMIN_USERNAME="admin"
LOCAL_ADMIN_PASSWORD="<set a strong password>"
```
After changing the auth env vars, rebuild and restart:
```bash
rm -rf .next && npm run build:prod && pm2 restart it_cost_dashboard --update-env
```
The `AUTH_*` vars are read at both build and runtime, so they must be present
before `npm run build:prod` and at `pm2` start.
## Notes
- Do **not** run `npm run build` (dev/SQLite) on prod — use `npm run build:prod`.
- Both `prisma/schema.prisma` (sqlite) and `prisma/prod/schema.prisma` (mysql)
generate to the same default path `node_modules/.prisma/client` (last-writer-wins),
and the app imports the bare `@prisma/client`. So the deployed client is whichever
schema was generated **last before `next build`**. Two ways prod can end up with the
wrong (SQLite) client baked into `.next`:
1. **Stale `.next` cache** — an earlier dev `npm run build` left compiled route
chunks that `build:prod` reused. Fix: always `rm -rf .next` before building (step 5).
2. **Clobbered client** — `npm ci` / `npm install` reset the generated client to the
default schema. Fix: re-run `npm run prod:generate` after any install (step 4).
- Symptom: every API call 500s with
`error: Error validating datasource \`db\`: the URL must start with the protocol \`file:\``
even though the runtime `DATABASE_URL` is MySQL.
- `DATABASE_URL` set as a real OS/systemd env var always takes precedence over
any value in `.env` / `.env.production`, so the committed dev `.env` (SQLite)
never leaks into production.
- If you change the schema, generate a new MySQL migration against a MySQL dev
instance with `prisma migrate dev --schema=prisma/prod/schema.prisma`, then
redeploy with `npm run prod:migrate`.