11 Commits
Author SHA1 Message Date
Tom Chien (IQ-AS) 396a0d0e6a Merge branch 'dev'
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Successful in 4m52s
2026-11-17 19:05:53 +08:00
Tom Chien (IQ-AS) 93324bf50a modify URL
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Successful in 4m11s
2026-11-17 17:42:30 +08:00
Tom Chien (IQ-AS) fcf7fb851b modify URL
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Successful in 3m28s
2026-11-17 15:58:05 +08:00
Tom Chien (IQ-AS) b3c14b5c86 ci: drop dynamic matrix (unsupported by act_runner), compute env config in bash
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Successful in 5m0s
2026-11-17 15:05:28 +08:00
Tom Chien (IQ-AS)andClaude Opus 4.6 3e5eee0c68 Install kubectl and helm at job start
CI/CD (dev on branch, prod on tag) / setup (push) Successful in 11s
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Failing after 1m10s
The runner's job image only ships docker; download static binaries so
the diagnostics and deploy steps work.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-17 14:59:42 +08:00
Tom Chien (IQ-AS)andClaude Opus 4.6 fb8b3fdcfb Serve the UI over plain HTTP only (POC)
CI/CD (dev on branch, prod on tag) / setup (push) Successful in 9s
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Failing after 28s
Drop the ingress TLS block and cert-manager annotation, disable the
nginx ssl-redirect, and hardcode AUTH_URL to http://<ingress.host>.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-17 14:57:56 +08:00
Tom Chien (IQ-AS)andClaude Opus 4.6 64275f8544 Use runner's actual label ubuntu-latest in runs-on
CI/CD (dev on branch, prod on tag) / setup (push) Successful in 4m3s
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Failing after 1m24s
The act_runner registered with default labels (name gitea-runner is not a
label), so jobs with runs-on: gitea-runner never matched an online runner.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-17 14:40:48 +08:00
Tom Chien (IQ-AS) 36025062db test
CI/CD (dev on branch, prod on tag) / setup (push) Canceled after 0s
CI/CD (dev on branch, prod on tag) / build-and-deploy (push) Canceled after 0s
2026-11-17 14:32:28 +08:00
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
s871077 d09a9fa47b Merge branch 'dev' 2026-09-22 10:50:33 +08:00
s871077 d976c0ff4f Remove .env.production.example from master 2026-09-16 17:37:44 +08:00
19 changed files with 336 additions and 551 deletions
+8 -1
View File
@@ -34,7 +34,14 @@
"Read(//tmp/**)",
"Bash(tail:*)",
"Bash(mkdir:*)",
"Bash(python3:*)"
"Bash(python3:*)",
"Bash(npx tsc:*)",
"Bash(ls node_modules/.bin/tsc* 2>/dev/null || echo \"no local tsc\"; ls node_modules 2>/dev/null | head -3)",
"Bash(npm ci:*)",
"Bash(./node_modules/.bin/prisma generate:*)",
"Bash(npm run:*)",
"Bash(cd \"/c/Users/tom_chien/Desktop/it_cost_dashboad.git_V02\" && sed -i 's/\\\\${JFROG_REGISTRY}/\\\\${REGISTRY}/g' .gitea/workflows/cicd.yaml && grep -n \"JFROG\\\\|REGISTRY\" .gitea/workflows/cicd.yaml)",
"Bash(cd \"/c/Users/tom_chien/Desktop/it_cost_dashboad.git_V02\" && grep -n \"REGISTRY\\\\|harbor\\\\|Harbor\" .gitea/workflows/cicd.yaml && helm lint ./helm -f helm/values-dev.yaml --set server.image.repository=x --set server.image.tag=t --set db.image.repository=y --set db.image.tag=t --set secrets.authSecret=a --set secrets.dbRootPassword=b --set secrets.localAdminPassword=c 2>&1 | tail -5)"
]
}
}
+4 -4
View File
@@ -1,7 +1,7 @@
# Version control
.git
.gitignore
.github
.gitea
# Dependencies / build output (rebuilt inside the image)
node_modules
@@ -19,9 +19,9 @@ prisma/dev.db
prisma/dev.db-journal
prisma/*.db
# Secrets: .env holds file:./dev.db, and .env.local / .env.production hold REAL
# Entra secrets and the RDS password. Baking these into a layer would push them
# to JFrog. All runtime env comes from the k8s Secret instead.
# Secrets: .env holds file:./dev.db, and .env.local / .env.production hold the
# real admin password and the RDS password. Baking these into a layer would push
# them to Harbor. All runtime env comes from the k8s Secret instead.
.env
.env.*
!.env.production.example
+6 -7
View File
@@ -3,13 +3,12 @@
DATABASE_URL="file:./dev.db"
DATABASE_PROVIDER="sqlite"
# SSO secrets are NOT stored here (this file is committed). Dev auth vars live in
# .env.local (gitignored); prod auth vars in .env.production — see .env.production.example.
# Auth secrets are NOT stored here (this file is committed). Dev auth vars live
# in .env.local (gitignored); prod auth vars in .env.production.
# Local break-glass admin login (username/password, in addition to SSO). The
# password is intentionally EMPTY here so local login is DISABLED by default;
# set a real value in the gitignored .env.local (dev) / .env.production (prod).
# Role model: config/users.json maps SSO emails -> "admin" | "user"; unlisted
# SSO emails cannot sign in. The local admin always has the admin role.
# Local admin login (username/password) — the only sign-in path. The password is
# intentionally EMPTY here so login is DISABLED by default; set a real value in
# the gitignored .env.local (dev) / .env.production (prod). The local admin
# always has the admin role.
LOCAL_ADMIN_USERNAME="admin"
LOCAL_ADMIN_PASSWORD=""
+252
View File
@@ -0,0 +1,252 @@
name: CI/CD (dev on branch, prod on tag)
on:
push:
branches:
- dev # build & deploy for dev only
tags:
- "*" # build & deploy for prod only when a tag is pushed
jobs:
build-and-deploy:
# Gitea Actions: runners are selected by label only (no runner groups).
runs-on: ubuntu-latest
# Per-environment group: a dev push must never cancel an in-flight prod
# deploy. NOTE: act_runner does not support dynamic matrix (fromJSON of a
# job output expands every matrix.* to ""), so per-env config is computed
# in the "Resolve environment config" bash step below instead.
concurrency:
group: deploy-${{ github.ref_type == 'tag' && 'prod' || 'dev' }}
cancel-in-progress: true
env:
# Harbor on the Mac mini host. The runner pod mounts the Docker Desktop
# daemon socket, so from the daemon's point of view the registry is
# reachable as host.docker.internal:8080 (plain HTTP — the daemon must
# list it under "insecure-registries"). Images live in Harbor's
# "library" project.
REGISTRY: host.docker.internal:8080/library
DOCKER_BUILDKIT: "1"
COMPOSE_DOCKER_CLI_BUILD: "1"
steps:
- name: Checkout (with tags)
uses: actions/checkout@v4
with:
fetch-depth: 0 # IMPORTANT to access tags
# Replaces the former setup job + dynamic matrix (unsupported on
# act_runner). Everything derived from the ref type lands in GITHUB_ENV
# so later steps can use plain $VARS.
- name: Resolve environment config
shell: bash
run: |
if [[ "${{ github.ref_type }}" == "tag" ]]; then
DEPLOY_ENV=prod
RELEASE_TAG="${GITHUB_REF#refs/tags/}"
else
DEPLOY_ENV=dev
RELEASE_TAG=""
fi
{
echo "DEPLOY_ENV=${DEPLOY_ENV}"
echo "RELEASE_TAG=${RELEASE_TAG}"
echo "IMAGE_SERVER=${REGISTRY}/it-cost-dashboard-server-${DEPLOY_ENV}"
echo "IMAGE_DB=${REGISTRY}/it-cost-dashboard-db-${DEPLOY_ENV}"
echo "LATEST_TAG=latest-${DEPLOY_ENV}"
echo "RELEASE=it-cost-dashboard-${DEPLOY_ENV}"
echo "NAMESPACE=it-cost-dashboard-${DEPLOY_ENV}"
echo "CHART=./helm"
echo "VALUES_FILE=./helm/values-${DEPLOY_ENV}.yaml"
} >> "$GITHUB_ENV"
echo "Resolved environment: ${DEPLOY_ENV} (release tag: '${RELEASE_TAG}')"
- name: Verify tag is on prod branch (main)
if: github.ref_type == 'tag'
shell: bash
run: |
git fetch origin main --quiet
if git merge-base --is-ancestor "${{ github.sha }}" origin/main; then
echo "Tag commit is on main. Proceeding with prod deploy."
else
echo "::error::Tag ${GITHUB_REF#refs/tags/} points at a commit not on main. Refusing prod deploy."
exit 1
fi
# The runner's job image ships docker but not kubectl/helm, so install
# them at job start (static binaries, linux/amd64).
- name: Install kubectl & helm
run: |
if ! command -v kubectl >/dev/null 2>&1; then
KVER=$(curl -sfL https://dl.k8s.io/release/stable.txt)
curl -sfL -o /usr/local/bin/kubectl "https://dl.k8s.io/release/${KVER}/bin/linux/amd64/kubectl"
chmod +x /usr/local/bin/kubectl
fi
if ! command -v helm >/dev/null 2>&1; then
curl -sfL https://get.helm.sh/helm-v3.16.4-linux-amd64.tar.gz | tar xz -C /tmp
mv /tmp/linux-amd64/helm /usr/local/bin/helm
fi
kubectl version --client
helm version
- name: Set up kubeconfig
run: |
echo "KUBECONFIG=${RUNNER_TEMP}/kubeconfig" >> "$GITHUB_ENV"
echo "${{ secrets.KUBE_CONFIG_DATA }}" | base64 -d > "${RUNNER_TEMP}/kubeconfig"
chmod 600 "${RUNNER_TEMP}/kubeconfig"
- name: Login to Harbor
run: |
# REGISTRY is host/project but `docker login` takes only the host.
REGISTRY_HOST=$(echo "${REGISTRY}" | cut -d'/' -f1)
echo "Logging in to ${REGISTRY_HOST}"
echo "${{ secrets.HARBOR_PASSWORD }}" | docker login "${REGISTRY_HOST}" \
-u "${{ secrets.HARBOR_USERNAME }}" \
--password-stdin
- name: Pre-build diagnostics
run: |
echo "Ref: ${GITHUB_REF}"
echo "Environment: ${DEPLOY_ENV}"
echo "Release tag: ${RELEASE_TAG}"
echo "Server image: ${IMAGE_SERVER}"
echo "DB image: ${IMAGE_DB}"
docker version
helm version
kubectl version --client
- name: Build & Push server image
run: |
BUILD_TAG_ARGS=(
-t "${IMAGE_SERVER}:${LATEST_TAG}"
-t "${IMAGE_SERVER}:${{ github.sha }}"
)
if [[ -n "${RELEASE_TAG}" ]]; then
BUILD_TAG_ARGS+=( -t "${IMAGE_SERVER}:${RELEASE_TAG}" )
fi
# AUTH_SECRET is build-time only (Auth.js v5 initializes NextAuth() at
# module load during `next build`). The real secret comes from k8s.
docker build \
-f Dockerfile \
--build-arg AUTH_SECRET=build-placeholder-not-used-at-runtime \
"${BUILD_TAG_ARGS[@]}" \
.
docker push "${IMAGE_SERVER}:${LATEST_TAG}"
docker push "${IMAGE_SERVER}:${{ github.sha }}"
if [[ -n "${RELEASE_TAG}" ]]; then
docker push "${IMAGE_SERVER}:${RELEASE_TAG}"
fi
- name: Build & Push db image
run: |
BUILD_TAG_ARGS=(
-t "${IMAGE_DB}:${LATEST_TAG}"
-t "${IMAGE_DB}:${{ github.sha }}"
)
if [[ -n "${RELEASE_TAG}" ]]; then
BUILD_TAG_ARGS+=( -t "${IMAGE_DB}:${RELEASE_TAG}" )
fi
docker build \
-f Dockerfile.db \
"${BUILD_TAG_ARGS[@]}" \
.
docker push "${IMAGE_DB}:${LATEST_TAG}"
docker push "${IMAGE_DB}:${{ github.sha }}"
if [[ -n "${RELEASE_TAG}" ]]; then
docker push "${IMAGE_DB}:${RELEASE_TAG}"
fi
- name: Ensure namespace exists
run: |
# `helm --atomic` against a missing namespace fails outright.
kubectl create namespace "${NAMESPACE}" \
--dry-run=client -o yaml | kubectl apply -f -
# The kubelet pulls through the same Docker Desktop daemon that built the
# image, so the pull server must match the push host exactly
# (host.docker.internal:8080).
- name: Ensure Harbor pull secret exists
run: |
kubectl create secret docker-registry harbor-pull-secret \
--docker-server="$(echo "${REGISTRY}" | cut -d'/' -f1)" \
--docker-username="${{ secrets.HARBOR_USERNAME }}" \
--docker-password="${{ secrets.HARBOR_PASSWORD }}" \
--namespace "${NAMESPACE}" \
--dry-run=client -o yaml | kubectl apply -f -
# ---- DEV DEPLOY (branch dev only) ----
# Deployed by commit SHA, not latest-dev: an immutable tag sidesteps the
# moving-tag + IfNotPresent stale-cache trap and makes `kubectl describe
# pod` show exactly which commit is live.
- name: Deploy DEV with Helm
if: github.ref_type == 'branch' && github.ref == 'refs/heads/dev'
run: |
kubectl get nodes
kubectl get ns
helm upgrade --install "${RELEASE}" "${CHART}" \
-f "${VALUES_FILE}" \
--namespace "${NAMESPACE}" \
--set server.image.repository="${IMAGE_SERVER}" \
--set server.image.tag="${{ github.sha }}" \
--set db.image.repository="${IMAGE_DB}" \
--set db.image.tag="${{ github.sha }}" \
--set-string secrets.authSecret="${{ secrets.AUTH_SECRET_DEV }}" \
--set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_DEV }}" \
--set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_DEV }}" \
--wait --timeout 10m --atomic --debug
# ---- PROD DEPLOY (tag push only) ----
- name: Deploy PROD with Helm
if: github.ref_type == 'tag'
run: |
kubectl get nodes
kubectl get ns
if [[ -z "${RELEASE_TAG}" ]]; then
echo "No tag detected; aborting prod deploy."
exit 1
fi
helm upgrade --install "${RELEASE}" "${CHART}" \
-f "${VALUES_FILE}" \
--namespace "${NAMESPACE}" \
--set server.image.repository="${IMAGE_SERVER}" \
--set server.image.tag="${RELEASE_TAG}" \
--set db.image.repository="${IMAGE_DB}" \
--set db.image.tag="${RELEASE_TAG}" \
--set-string secrets.authSecret="${{ secrets.AUTH_SECRET_PROD }}" \
--set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_PROD }}" \
--set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_PROD }}" \
--wait --timeout 10m --atomic --debug
# Strictly redundant with immutable image tags: Helm already rolled the
# pods and --atomic already verified health. Retained as belt-and-braces.
# Scoped to component=server so it does not bounce MySQL every push.
- name: Rollout restart (server only)
if: success()
run: |
kubectl rollout restart deployment \
-l "app.kubernetes.io/instance=${RELEASE},app.kubernetes.io/component=server" \
-n "${NAMESPACE}"
- name: Post-deploy diagnostics (if failure)
if: failure()
run: |
echo "----- Diagnostics -----"
kubectl get deploy,sts,po,svc,ing -n "${NAMESPACE}" -o wide || true
echo "----- PVCs (a Pending PVC = missing/wrong StorageClass; invisible in pod logs) -----"
kubectl get pvc -n "${NAMESPACE}" -o wide || true
echo "----- Events -----"
kubectl get events -n "${NAMESPACE}" --sort-by=.lastTimestamp || true
for p in $(kubectl get po -n "${NAMESPACE}" -o name); do
echo "### $p"
kubectl describe "$p" -n "${NAMESPACE}" || true
kubectl logs "$p" -n "${NAMESPACE}" --all-containers --tail=200 || true
done
-324
View File
@@ -1,324 +0,0 @@
name: CI/CD (dev on branch, prod on tag)
on:
push:
branches:
- dev # build & deploy for dev only
tags:
- "*" # build & deploy for prod only when a tag is pushed
jobs:
setup:
runs-on:
group: trend-emu-intranet
labels:
- "ubuntu-latest-intranet"
outputs:
matrix: ${{ steps.pick.outputs.matrix }}
steps:
- name: Pick matrix config from ref type
id: pick
shell: bash
run: |
if [[ "${{ github.ref_type }}" == "tag" ]]; then
echo 'matrix={"include":[{"env":"prod","image_name_server":"it-cost-dashboard-server-prod","image_name_db":"it-cost-dashboard-db-prod","latest_tag":"latest-prod","release":"it-cost-dashboard-prod","namespace":"it-cost-dashboard-prod","chart":"./helm","values_file":"./helm/values-prod.yaml"}]}' >> "$GITHUB_OUTPUT"
else
echo 'matrix={"include":[{"env":"dev","image_name_server":"it-cost-dashboard-server-dev","image_name_db":"it-cost-dashboard-db-dev","latest_tag":"latest-dev","release":"it-cost-dashboard-dev","namespace":"it-cost-dashboard-dev","chart":"./helm","values_file":"./helm/values-dev.yaml"}]}' >> "$GITHUB_OUTPUT"
fi
build-and-deploy:
needs: setup
runs-on:
group: trend-emu-intranet
labels:
- "ubuntu-latest-intranet"
strategy:
matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}
# Per-environment group: a dev push must never cancel an in-flight prod
# deploy (the original used a hardcoded "prod" group for both refs).
concurrency:
group: deploy-${{ matrix.env }}
cancel-in-progress: true
env:
# host/repo, e.g. jfrog.trendmicro.com/ameait-it-cost-dashboard
JFROG_REGISTRY: ${{ secrets.JFROG_REGISTRY }}
DOCKER_BUILDKIT: "1"
COMPOSE_DOCKER_CLI_BUILD: "1"
steps:
- name: Checkout (with tags)
uses: actions/checkout@v4
with:
fetch-depth: 0 # IMPORTANT to access tags
- name: Verify tag is on prod branch (main)
id: guard
if: github.ref_type == 'tag'
shell: bash
run: |
git fetch origin main --quiet
if git merge-base --is-ancestor "${{ github.sha }}" origin/main; then
echo "Tag commit is on main. Proceeding with prod deploy."
else
echo "::error::Tag ${GITHUB_REF#refs/tags/} points at a commit not on main. Refusing prod deploy."
exit 1
fi
- name: Set up kubeconfig
run: |
echo "KUBECONFIG=${RUNNER_TEMP}/kubeconfig" >> "$GITHUB_ENV"
echo "${{ secrets.KUBE_CONFIG_DATA }}" | base64 -d > "${RUNNER_TEMP}/kubeconfig"
chmod 600 "${RUNNER_TEMP}/kubeconfig"
# Temporary debug step: we cannot shell into this self-hosted runner
# directly, so this proves (or disproves) network reachability to the
# k8s API from inside the runner itself, ahead of the image build/push
# so we fail fast instead of waiting ~10 min for the helm timeout.
# Remove once the ACL/connectivity issue is confirmed fixed.
- name: "[DEBUG] Network path to k8s API (6443)"
run: |
set +e
echo "===== Runner identity / network info ====="
hostname -f 2>/dev/null || hostname
echo "--- Interfaces ---"
ip -brief addr show 2>/dev/null || ifconfig
echo "--- Default route ---"
ip route show 2>/dev/null || route -n
echo
echo "===== K8s API endpoint (parsed from kubeconfig) ====="
KUBE_HOST=$(grep -m1 'server:' "${KUBECONFIG}" | sed -E 's#.*https?://([^:/]+).*#\1#')
KUBE_PORT=$(grep -m1 'server:' "${KUBECONFIG}" | sed -E 's#.*:([0-9]+)/?.*#\1#')
KUBE_PORT="${KUBE_PORT:-6443}"
echo "Host: ${KUBE_HOST}"
echo "Port: ${KUBE_PORT}"
echo
echo "===== DNS resolution ====="
getent hosts "${KUBE_HOST}" || nslookup "${KUBE_HOST}" || dig +short "${KUBE_HOST}"
RESOLVED_IPS=$(getent hosts "${KUBE_HOST}" | awk '{print $1}')
echo
echo "===== Route to each resolved IP ====="
for ip in ${RESOLVED_IPS}; do
echo "-- ip route get ${ip} --"
ip route get "${ip}" 2>/dev/null || echo "(ip route not available)"
done
echo
echo "===== TCP connect test per resolved IP (port ${KUBE_PORT}) ====="
for ip in ${RESOLVED_IPS}; do
if timeout 5 bash -c "cat < /dev/null > /dev/tcp/${ip}/${KUBE_PORT}" 2>/dev/null; then
echo "OK ${ip}:${KUBE_PORT} - TCP connect succeeded"
else
echo "FAIL ${ip}:${KUBE_PORT} - TCP connect timed out or refused"
fi
done
echo
echo "===== TCP connect test via hostname (through NLB, port ${KUBE_PORT}) ====="
if timeout 5 bash -c "cat < /dev/null > /dev/tcp/${KUBE_HOST}/${KUBE_PORT}" 2>/dev/null; then
echo "OK ${KUBE_HOST}:${KUBE_PORT} - TCP connect succeeded"
else
echo "FAIL ${KUBE_HOST}:${KUBE_PORT} - TCP connect timed out or refused"
fi
echo
echo "===== curl -v (expect HTTP 401/403 = reachable; a hang/timeout = blocked) ====="
curl -v -k --max-time 8 "https://${KUBE_HOST}:${KUBE_PORT}/version"
echo
echo "===== traceroute (best effort, may be blocked itself) ====="
if command -v traceroute >/dev/null 2>&1; then
traceroute -T -p "${KUBE_PORT}" -w 2 -m 15 "${KUBE_HOST}" || true
else
echo "traceroute not installed on runner, skipping"
fi
set -e
- name: Login to JFrog
run: |
# JFROG_REGISTRY is host/repo but `docker login` takes only the host.
JFROG_HOST=$(echo "${JFROG_REGISTRY}" | cut -d'/' -f1)
echo "Logging in to ${JFROG_HOST}"
echo "${{ secrets.JFROG_IDENTITY_TOKEN }}" | docker login "${JFROG_HOST}" \
-u "${{ secrets.JFROG_USERNAME }}" \
--password-stdin
- name: Determine ref type and release tag
id: refinfo
shell: bash
run: |
echo "GITHUB_REF=${GITHUB_REF}"
echo "GITHUB_REF_TYPE=${GITHUB_REF_TYPE:-${{ github.ref_type }}}"
if [[ "${{ github.ref_type }}" == "tag" ]]; then
echo "ref_type=tag" >> $GITHUB_OUTPUT
echo "release_tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
elif [[ "${{ github.ref_type }}" == "branch" ]]; then
echo "ref_type=branch" >> $GITHUB_OUTPUT
echo "release_tag=" >> $GITHUB_OUTPUT
else
echo "ref_type=unknown" >> $GITHUB_OUTPUT
echo "release_tag=" >> $GITHUB_OUTPUT
fi
- name: Pre-build diagnostics
run: |
echo "Ref: ${GITHUB_REF}"
echo "Ref type: ${{ steps.refinfo.outputs.ref_type }}"
echo "Release tag: ${{ steps.refinfo.outputs.release_tag }}"
echo "Environment: ${{ matrix.env }}"
echo "Server image: ${JFROG_REGISTRY}/${{ matrix.image_name_server }}"
echo "DB image: ${JFROG_REGISTRY}/${{ matrix.image_name_db }}"
docker version
helm version
kubectl version --client
- name: Build & Push server image
run: |
REF_TYPE="${{ steps.refinfo.outputs.ref_type }}"
RELEASE_TAG="${{ steps.refinfo.outputs.release_tag }}"
IMAGE="${JFROG_REGISTRY}/${{ matrix.image_name_server }}"
BUILD_TAG_ARGS=(
-t "${IMAGE}:${{ matrix.latest_tag }}"
-t "${IMAGE}:${{ github.sha }}"
)
if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then
BUILD_TAG_ARGS+=( -t "${IMAGE}:${RELEASE_TAG}" )
fi
# AUTH_SECRET is build-time only (Auth.js v5 initializes NextAuth() at
# module load during `next build`). The real secret comes from k8s.
docker build \
-f Dockerfile \
--build-arg AUTH_SECRET=build-placeholder-not-used-at-runtime \
"${BUILD_TAG_ARGS[@]}" \
.
docker push "${IMAGE}:${{ matrix.latest_tag }}"
docker push "${IMAGE}:${{ github.sha }}"
if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then
docker push "${IMAGE}:${RELEASE_TAG}"
fi
- name: Build & Push db image
run: |
REF_TYPE="${{ steps.refinfo.outputs.ref_type }}"
RELEASE_TAG="${{ steps.refinfo.outputs.release_tag }}"
IMAGE="${JFROG_REGISTRY}/${{ matrix.image_name_db }}"
BUILD_TAG_ARGS=(
-t "${IMAGE}:${{ matrix.latest_tag }}"
-t "${IMAGE}:${{ github.sha }}"
)
if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then
BUILD_TAG_ARGS+=( -t "${IMAGE}:${RELEASE_TAG}" )
fi
docker build \
-f Dockerfile.db \
"${BUILD_TAG_ARGS[@]}" \
.
docker push "${IMAGE}:${{ matrix.latest_tag }}"
docker push "${IMAGE}:${{ github.sha }}"
if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then
docker push "${IMAGE}:${RELEASE_TAG}"
fi
- name: Ensure namespace exists
run: |
# `helm --atomic` against a missing namespace fails outright.
kubectl create namespace "${{ matrix.namespace }}" \
--dry-run=client -o yaml | kubectl apply -f -
- name: Ensure JFrog pull secret exists
run: |
kubectl create secret docker-registry jfrog-registry-creds \
--docker-server="$(echo "${JFROG_REGISTRY}" | cut -d'/' -f1)" \
--docker-username="${{ secrets.JFROG_USERNAME }}" \
--docker-password="${{ secrets.JFROG_IDENTITY_TOKEN }}" \
--namespace "${{ matrix.namespace }}" \
--dry-run=client -o yaml | kubectl apply -f -
# ---- DEV DEPLOY (branch dev only) ----
# Deployed by commit SHA, not latest-dev: an immutable tag sidesteps the
# moving-tag + IfNotPresent stale-cache trap and makes `kubectl describe
# pod` show exactly which commit is live.
- name: Deploy DEV with Helm
if: github.ref_type == 'branch' && github.ref == 'refs/heads/dev'
run: |
kubectl get nodes
kubectl get ns
helm upgrade --install "${{ matrix.release }}" "${{ matrix.chart }}" \
-f "${{ matrix.values_file }}" \
--namespace "${{ matrix.namespace }}" \
--set server.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_server }}" \
--set server.image.tag="${{ github.sha }}" \
--set db.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_db }}" \
--set db.image.tag="${{ github.sha }}" \
--set-string secrets.authSecret="${{ secrets.AUTH_SECRET_DEV }}" \
--set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_DEV }}" \
--set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_DEV }}" \
--set-string secrets.entraClientId="${{ secrets.ENTRA_CLIENT_ID_DEV }}" \
--set-string secrets.entraClientSecret="${{ secrets.ENTRA_CLIENT_SECRET_DEV }}" \
--set-string secrets.entraIssuer="${{ secrets.ENTRA_ISSUER_DEV }}" \
--wait --timeout 10m --atomic --debug
# ---- PROD DEPLOY (tag push only) ----
- name: Deploy PROD with Helm
if: github.ref_type == 'tag'
run: |
kubectl get nodes
kubectl get ns
TAG="${GITHUB_REF#refs/tags/}"
if [[ -z "${TAG}" ]]; then
echo "No tag detected; aborting prod deploy."
exit 1
fi
helm upgrade --install "${{ matrix.release }}" "${{ matrix.chart }}" \
-f "${{ matrix.values_file }}" \
--namespace "${{ matrix.namespace }}" \
--set server.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_server }}" \
--set server.image.tag="${TAG}" \
--set db.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_db }}" \
--set db.image.tag="${TAG}" \
--set-string secrets.authSecret="${{ secrets.AUTH_SECRET_PROD }}" \
--set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_PROD }}" \
--set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_PROD }}" \
--set-string secrets.entraClientId="${{ secrets.ENTRA_CLIENT_ID_PROD }}" \
--set-string secrets.entraClientSecret="${{ secrets.ENTRA_CLIENT_SECRET_PROD }}" \
--set-string secrets.entraIssuer="${{ secrets.ENTRA_ISSUER_PROD }}" \
--wait --timeout 10m --atomic --debug
# Strictly redundant with immutable image tags: Helm already rolled the
# pods and --atomic already verified health. Retained as belt-and-braces.
# Scoped to component=server so it does not bounce MySQL every push.
- name: Rollout restart (server only)
if: success() && (github.ref_type == 'branch' || github.ref_type == 'tag')
run: |
kubectl rollout restart deployment \
-l "app.kubernetes.io/instance=${{ matrix.release }},app.kubernetes.io/component=server" \
-n "${{ matrix.namespace }}"
- name: Post-deploy diagnostics (if failure)
if: failure()
run: |
echo "----- Diagnostics -----"
kubectl get deploy,sts,po,svc,ing -n "${{ matrix.namespace }}" -o wide || true
echo "----- PVCs (a Pending PVC = missing gp3 StorageClass; invisible in pod logs) -----"
kubectl get pvc -n "${{ matrix.namespace }}" -o wide || true
echo "----- Events -----"
kubectl get events -n "${{ matrix.namespace }}" --sort-by=.lastTimestamp || true
for p in $(kubectl get po -n "${{ matrix.namespace }}" -o name); do
echo "### $p"
kubectl describe "$p" -n "${{ matrix.namespace }}" || true
kubectl logs "$p" -n "${{ matrix.namespace }}" --all-containers --tail=200 || true
done
+11 -41
View File
@@ -94,38 +94,18 @@ 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):
Sign-in uses Auth.js / NextAuth v5 with a single sign-in path:
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`.
- **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**: normal users are redirected away from admin pages
**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 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`.
any signed-in user. The sidebar "Admin" group is also hidden for non-admins.
### Required env vars (`.env.production`)
@@ -133,32 +113,22 @@ 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 login. 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:
After changing 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.
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
+1 -3
View File
@@ -66,12 +66,10 @@ RUN groupadd --system --gid 1001 nodejs \
# .next/standalone ships its own traced node_modules — do NOT copy the
# builder's. .next/static is NOT part of standalone and must come separately or
# every CSS/JS chunk 404s. config/ is read at runtime by lookupRole()
# (src/lib/authz.ts) via process.cwd() once SSO is re-enabled.
# every CSS/JS chunk 404s.
# NOTE: this repo has no public/ directory; adding a COPY for it would fail.
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/config ./config
USER nextjs
-4
View File
@@ -1,4 +0,0 @@
{
"Sunny_Ho@trendmicro.com": "admin",
"tom_chien@trendmicro.com": "user"
}
+2 -5
View File
@@ -10,13 +10,10 @@ metadata:
# Headroom for large request headers (chunked Auth.js session cookies).
nginx.ingress.kubernetes.io/proxy-buffer-size: "16k"
nginx.ingress.kubernetes.io/proxy-buffers-number: "4"
cert-manager.io/cluster-issuer: sectigo-acme
# POC runs plain HTTP — no TLS, no redirect to https.
nginx.ingress.kubernetes.io/ssl-redirect: "false"
spec:
ingressClassName: {{ .Values.ingress.className }}
tls:
- hosts:
- {{ .Values.ingress.host | quote }}
secretName: {{ include "it-cost-dashboard.fullname" . }}-server-tls
rules:
- host: {{ required "ingress.host is required" .Values.ingress.host | quote }}
http:
+7 -13
View File
@@ -11,20 +11,14 @@ stringData:
# URL-reserved characters (@ : / # ? % + & and space) — keep it [A-Za-z0-9-].
DATABASE_URL: "mysql://root:{{ required "secrets.dbRootPassword is required" .Values.secrets.dbRootPassword }}@{{ include "it-cost-dashboard.dbServiceName" . }}:{{ .Values.db.port }}/{{ .Values.db.database }}"
# Auth.js JWT signing key. Required at runtime even with SSO commented out.
# Auth.js JWT signing key.
AUTH_SECRET: {{ required "secrets.authSecret is required" .Values.secrets.authSecret | quote }}
AUTH_TRUST_HOST: "true"
# Break-glass local login. Empty disables it entirely (src/auth.ts fails closed).
LOCAL_ADMIN_PASSWORD: {{ .Values.secrets.localAdminPassword | default "" | quote }}
# Local admin login. Empty disables login entirely (src/auth.ts fails
# closed); required loudly here since it is now the only sign-in path.
LOCAL_ADMIN_PASSWORD: {{ required "secrets.localAdminPassword is required" .Values.secrets.localAdminPassword | quote }}
# Microsoft Entra ID SSO. Required: a deploy fails loudly rather than shipping
# a build whose sign-in button 500s.
AUTH_MICROSOFT_ENTRA_ID_ID: {{ required "secrets.entraClientId is required" .Values.secrets.entraClientId | quote }}
AUTH_MICROSOFT_ENTRA_ID_SECRET: {{ required "secrets.entraClientSecret is required" .Values.secrets.entraClientSecret | quote }}
AUTH_MICROSOFT_ENTRA_ID_ISSUER: {{ required "secrets.entraIssuer is required" .Values.secrets.entraIssuer | quote }}
# Derived from the ingress host so the OAuth callback URL always matches what
# is registered in Entra. AUTH_TRUST_HOST alone would leave Auth.js depending
# on X-Forwarded-Proto; if that is ever wrong it builds an http:// callback and
# Entra rejects it with AADSTS50011 (http is invalid for non-localhost).
AUTH_URL: {{ printf "https://%s" (required "ingress.host is required" .Values.ingress.host) | quote }}
# Derived from the ingress host so Auth.js builds correct absolute redirect
# URLs. POC UI is plain HTTP only (no TLS anywhere).
AUTH_URL: {{ printf "http://%s" (required "ingress.host is required" .Values.ingress.host) | quote }}
+6 -5
View File
@@ -4,7 +4,7 @@ replicaCount: 1
server:
image:
repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-server-dev
repository: host.docker.internal:8080/library/it-cost-dashboard-server-dev
resources:
requests:
cpu: 100m
@@ -15,10 +15,10 @@ server:
db:
image:
repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-db-dev
repository: host.docker.internal:8080/library/it-cost-dashboard-db-dev
storage:
size: 5Gi
storageClassName: gp3
storageClassName: hostpath
resources:
requests:
cpu: 100m
@@ -30,5 +30,6 @@ db:
ingress:
enabled: true
className: nginx
# TODO: point this at a hostname resolving to the ingress-nginx external IP.
host: it-cost-dashboard-dev.trendmicro.com
# Local ingress hostname — map it to the Mac mini's IP (192.168.0.31) in
# /etc/hosts or local DNS.
host: it-cost-dev.tomchien.com
+9 -5
View File
@@ -4,7 +4,7 @@ replicaCount: 2
server:
image:
repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-server-prod
repository: host.docker.internal:8080/library/it-cost-dashboard-server-prod
resources:
requests:
cpu: 250m
@@ -15,10 +15,10 @@ server:
db:
image:
repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-db-prod
repository: host.docker.internal:8080/library/it-cost-dashboard-db-prod
storage:
size: 20Gi
storageClassName: gp3
storageClassName: hostpath
resources:
requests:
cpu: 250m
@@ -30,5 +30,9 @@ db:
ingress:
enabled: true
className: nginx
# TODO: point this at a hostname resolving to the ingress-nginx external IP.
host: it-cost-dashboard-prod.trendmicro.com
# Local ingress hostname — map it to the Mac mini's IP (192.168.0.31) in
# /etc/hosts or local DNS.
host: tomchien.com
path: /it-cost-prod
pathType: Prefix
+10 -13
View File
@@ -29,7 +29,8 @@ db:
database: it_cost_dashboard
storage:
size: 5Gi
storageClassName: gp3
# Docker Desktop's built-in StorageClass.
storageClassName: hostpath
resources:
requests:
cpu: 100m
@@ -44,23 +45,19 @@ ingress:
host: "" # required per-env
secrets:
authSecret: "" # from GitHub secret AUTH_SECRET_<ENV>
authSecret: "" # from Gitea secret AUTH_SECRET_<ENV>
# MySQL root password. MUST be [A-Za-z0-9-] only — it is interpolated into
# DATABASE_URL and Helm has no URL-encode function.
dbRootPassword: "" # from GitHub secret DB_ROOT_PASSWORD_<ENV>
# Optional; empty disables local login entirely (src/auth.ts fails closed).
dbRootPassword: "" # from Gitea secret DB_ROOT_PASSWORD_<ENV>
# Local admin login password. Empty disables login entirely (src/auth.ts
# fails closed), so this is effectively required now that it is the only
# sign-in path.
localAdminPassword: ""
# Microsoft Entra ID SSO. Supplied per-env by the CI workflow from GitHub
# secrets; server-secret.yaml marks them required, so a deploy fails loudly
# rather than shipping a build whose sign-in button 500s.
entraClientId: ""
entraClientSecret: ""
entraIssuer: ""
# Pre-created manually, once per namespace (see the deploy notes). Not templated:
# the kubelet needs it independently of Helm.
# Created/refreshed by the CI workflow in each namespace ("Ensure Harbor pull
# secret exists" step). Not templated: the kubelet needs it independently of Helm.
imagePullSecrets:
- name: jfrog-registry-creds
- name: harbor-pull-secret
nodeSelector: {}
tolerations: []
-23
View File
@@ -7,19 +7,11 @@ function errorMessage(code: string | undefined): string | null {
switch (code) {
case "CredentialsSignin":
return "Invalid username or password";
case "AccessDenied":
return "Your account is not authorized — contact the administrator";
default:
return code ? "Sign-in failed — please try again" : null;
}
}
// Server action: kick off the Microsoft SSO flow.
async function microsoftLogin() {
"use server";
await signIn("microsoft-entra-id", { redirectTo: "/" });
}
// Server action: local username/password login.
async function credentialsLogin(formData: FormData) {
"use server";
@@ -63,21 +55,6 @@ export default async function LoginPage({
</div>
)}
<form action={microsoftLogin} className="mt-6">
<button
type="submit"
className="w-full rounded-md bg-[#2F2F2F] px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-black"
>
Sign in with Microsoft
</button>
</form>
<div className="my-6 flex items-center gap-3 text-xs text-[#9CA3AF]">
<span className="h-px flex-1 bg-[#E5E7EB]" />
OR
<span className="h-px flex-1 bg-[#E5E7EB]" />
</div>
<form action={credentialsLogin} className="mt-6 flex flex-col gap-3">
<label className="flex flex-col gap-1 text-sm text-[#374151]">
Username
+4 -5
View File
@@ -10,14 +10,13 @@ const ADMIN_PAGE_PREFIXES = [
];
// Edge-safe Auth.js config. This is imported by the middleware, which runs in
// the edge runtime, so it MUST NOT import Node APIs (node:fs) or the providers
// (Credentials/MicrosoftEntraID pull in Node crypto). The JSON allowlist is read
// only at sign-in in src/auth.ts (Node) and the resulting role is baked into the
// JWT; here we only read the role off the token.
// the edge runtime, so it MUST NOT import Node APIs or the Credentials provider
// (it pulls in Node crypto). The role is baked into the JWT at sign-in in
// src/auth.ts (Node); here we only read the role off the token.
export const authConfig = {
// Stateless JWT sessions — no DB adapter, keeps the middleware edge-compatible.
session: { strategy: "jwt" },
// Custom sign-in page offering both SSO and local username/password.
// Custom sign-in page with local username/password.
pages: { signIn: "/login" },
// Providers are added in the Node config (src/auth.ts). Empty here on purpose.
providers: [],
+7 -42
View File
@@ -1,38 +1,17 @@
import NextAuth from "next-auth";
import MicrosoftEntraID from "next-auth/providers/microsoft-entra-id";
import Credentials from "next-auth/providers/credentials";
import { authConfig } from "@/auth.config";
import { lookupRole, safeEqual } from "@/lib/authz";
import { safeEqual } from "@/lib/authz";
// Auth.js v5 (NextAuth). Node-runtime config: spreads the edge-safe authConfig
// and adds the providers + Node-only callbacks (signIn/jwt) that need node:fs
// via lookupRole. Imported by the API route handler and server components —
// NEVER by the edge middleware (which uses src/auth.config.ts instead).
// and adds the Credentials provider + the jwt callback. Imported by the API
// route handler and server components — NEVER by the edge middleware (which
// uses src/auth.config.ts instead).
//
// Two sign-in paths:
// 1. Microsoft Entra ID SSO — allowed only if the email is in config/users.json.
// 2. Local username/password — break-glass admin, bypasses the JSON allowlist.
// Single sign-in path: local username/password (admin account).
export const { handlers, auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
MicrosoftEntraID({
clientId: process.env.AUTH_MICROSOFT_ENTRA_ID_ID,
clientSecret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET,
// Tenant-specific issuer restricts sign-in to our organization only.
issuer: process.env.AUTH_MICROSOFT_ENTRA_ID_ISSUER,
// The provider's default profile() pulls the Graph photo and inlines it as a
// base64 data-URI into user.image -> the `picture` JWT claim. Since sessions
// are JWTs, that becomes a multi-KB chunked session cookie whose combined
// Cookie header overflows nginx's proxy buffer -> 502 before the request ever
// reaches this app. We never render an avatar, so keep the token lean.
authorization: { params: { scope: "openid profile email" } },
profile: (profile) => ({
id: profile.sub,
name: profile.name,
email: profile.email,
image: null,
}),
}),
Credentials({
name: "Local account",
credentials: {
@@ -58,24 +37,10 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
],
callbacks: {
...authConfig.callbacks,
// Gate SSO sign-ins against the JSON allowlist. The local Credentials
// account is always allowed (its role is set in authorize()).
signIn({ user, account, profile }) {
if (account?.provider === "credentials") return true;
const email =
user.email ??
(profile?.email as string | undefined) ??
(profile?.preferred_username as string | undefined);
// Returning false surfaces to the login page as ?error=AccessDenied.
return lookupRole(email) !== null;
},
// On first sign-in, bake the role into the JWT so the edge middleware can
// read it without touching node:fs.
// On sign-in, bake the role into the JWT so the edge middleware can read it.
jwt({ token, user }) {
if (user) {
token.role = user.role ?? lookupRole(user.email) ?? "user";
token.role = user.role ?? "user";
}
return token;
},
+5 -11
View File
@@ -1,4 +1,5 @@
import { auth, signIn, signOut } from "@/auth";
import Link from "next/link";
import { auth, signOut } from "@/auth";
export default async function TopNav() {
const session = await auth();
@@ -25,19 +26,12 @@ export default async function TopNav() {
</form>
</div>
) : (
<form
action={async () => {
"use server";
await signIn("microsoft-entra-id");
}}
>
<button
type="submit"
<Link
href="/login"
className="rounded-md bg-white/10 px-4 py-1.5 text-sm font-medium hover:bg-white/20"
>
Login
</button>
</form>
</Link>
)}
</header>
);
-42
View File
@@ -1,48 +1,6 @@
import fs from "node:fs";
import path from "node:path";
// Role model for the app. Access is either full "admin" or read-only "user".
// NOTE: this module uses node:fs and MUST only be imported from Node runtime
// code (src/auth.ts / server components / API routes) — never from the edge
// middleware, or the edge bundle will fail to compile.
export type Role = "admin" | "user";
// Resolve a user's role from the hand-edited allowlist at config/users.json.
// Emails are matched case-insensitively. This is FAIL CLOSED: a missing file,
// invalid JSON, or an email that is not listed all return null (access denied).
export function lookupRole(email: string | null | undefined): Role | null {
if (!email) return null;
let raw: string;
try {
raw = fs.readFileSync(
path.join(process.cwd(), "config", "users.json"),
"utf8"
);
} catch {
// File missing/unreadable -> deny everyone (local admin is the break-glass).
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (!parsed || typeof parsed !== "object") return null;
// Lowercase every key so the lookup is case-insensitive.
const table: Record<string, Role> = {};
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
if (value === "admin" || value === "user") {
table[key.toLowerCase()] = value;
}
}
return table[email.toLowerCase()] ?? null;
}
// Constant-time string comparison to avoid leaking secrets via timing.
// Pure JS (no node:crypto) so this stays cheap and dependency-free.
export function safeEqual(a: string, b: string): boolean {
+2 -1
View File
@@ -2,7 +2,8 @@ import NextAuth from "next-auth";
import { authConfig } from "@/auth.config";
// Edge-runtime gate for the whole app. Uses the edge-safe config only —
// src/auth.ts pulls in node:fs via lookupRole and must never be imported here.
// src/auth.ts pulls in the Node-only Credentials provider and must never be
// imported here.
export const { auth: middleware } = NextAuth(authConfig);
export const config = {