184 lines
7.4 KiB
Markdown
184 lines
7.4 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. There are **two** ways in, and access is
|
|
**role-based** (`admin` = full access; `user` = read-only dashboard/trend):
|
|
|
|
1. **Microsoft Entra ID SSO** — allowed only if the user's email is in the
|
|
allowlist (see below). Unlisted emails cannot enter the app (fail closed).
|
|
2. **Local username/password** (break-glass admin) — a form on `/login`,
|
|
controlled by `LOCAL_ADMIN_USERNAME` / `LOCAL_ADMIN_PASSWORD`. This account is
|
|
always `admin` and bypasses the allowlist, so you can always get in to fix a
|
|
broken/empty `config/users.json`.
|
|
|
|
Middleware redirects any unauthenticated request to `/login` and enforces roles
|
|
**server-side**: normal 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 normal users.
|
|
|
|
### Role allowlist — `config/users.json`
|
|
|
|
Committed (NOT secret), hand-edited map of **email → role**:
|
|
|
|
```json
|
|
{
|
|
"Sunny_Ho@trendmicro.com": "admin",
|
|
"tom_chien@trendmicro.com": "user"
|
|
}
|
|
```
|
|
|
|
- Emails are matched **case-insensitively**.
|
|
- An email that is absent (or an unreadable/invalid file) ⇒ SSO sign-in denied.
|
|
- The role is baked into the session JWT at sign-in, so after editing this file
|
|
users must **re-login** (or restart the app) for changes to apply:
|
|
`pm2 restart it_cost_dashboard`.
|
|
|
|
### 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_MICROSOFT_ENTRA_ID_ID="<prod Application (client) ID>"
|
|
AUTH_MICROSOFT_ENTRA_ID_SECRET="<prod client secret VALUE>"
|
|
AUTH_MICROSOFT_ENTRA_ID_ISSUER="https://login.microsoftonline.com/<tenant ID>/v2.0"
|
|
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 break-glass admin. Non-empty password ENABLES the /login form; empty disables it.
|
|
LOCAL_ADMIN_USERNAME="admin"
|
|
LOCAL_ADMIN_PASSWORD="<set a strong password>"
|
|
```
|
|
|
|
After changing `config/users.json` or the auth env vars, rebuild and restart:
|
|
|
|
```bash
|
|
rm -rf .next && npm run build:prod && pm2 restart it_cost_dashboard --update-env
|
|
```
|
|
|
|
In the Entra app registration, add the prod **redirect URI**:
|
|
|
|
```
|
|
https://<your-prod-domain>/api/auth/callback/microsoft-entra-id
|
|
```
|
|
|
|
(Dev uses `http://localhost:3000/api/auth/callback/microsoft-entra-id`, configured
|
|
in the gitignored `.env.local`.) 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`.
|