fix(preview): point preview lambdas at the branch RDS, not DBInstances[0] - #316
Merged
Conversation
…s[0] Preview environments 401'd on every authenticated request while prod was fine. preview-env.yml resolved the preview lambdas' DB_HOST with `aws rds describe-db-instances --query "DBInstances[0].Endpoint.Address"`. This account hosts several unrelated C4C databases, and the branch instance is not first, so every preview lambda was pointed at `bhchp-postgres` — another project's DB, whose security group blackholes our traffic. Each query hit the 5s `connectionTimeoutMillis` in db.ts and threw. The prod lambda config the workflow already reads carries the correct DB_HOST, so stop re-deriving it and inherit it like every other DB credential. Added a guard that fails the job if any required key is missing, rather than shipping a preview that 401s on every call. Second half of the bug: authenticateRequest wrapped both the JWT check and the branch.users lookup in one try/catch that returned `isAuthenticated: false`, so an unreachable database surfaced as 401 "Authentication required". That hid the real fault and, because the frontend treats 401 as an expired session, cleared the user's tokens and logged them out on a DB blip. Only token verification is caught now; DB errors and a missing COGNITO_USER_POOL_ID propagate to the handlers' existing 500 mapping. Existing preview stacks were repaired out of band — the workflow only resolves lambda env on label-add, so already-created stacks kept the bad DB_HOST. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
nourshoreibah
force-pushed
the
worktree-fix-preview-db-host
branch
from
August 12, 2026 02:17
c034de6 to
a7c9513
Compare
Contributor
|
🌿 ⏳ Creating preview environment… (logs) |
Contributor
🌿 Preview environment — ready ✅Open: https://d3nmtjoh6ir9ym.cloudfront.net/pr-316/ Shared RDS + Cognito (prod data); DB migrations are not applied here — if this PR adds a migration, endpoints using the new columns will fail until it merges. New commits update this environment in place — a note is posted here on each update. Remove the |
Contributor
|
🌿 Preview environment torn down 🧹 — the stack for this PR has been destroyed. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The bug
Auth failed in every preview environment while prod was fine. Multiple devs hit it. Symptom from the UI: login appears to work, then hangs ~11s and errors out.
.github/workflows/preview-env.ymlresolved the preview lambdas'DB_HOSTlike this:DB_HOST=$(aws rds describe-db-instances --query "DBInstances[0].Endpoint.Address" --output text)This account hosts several unrelated C4C databases and the branch instance is not first:
bhchp-postgres← what previews gotc4c-hatsfcc-postgresterraform-2025…001← the actual branch DB (prod uses this)So all 12 preview lambdas across PRs #302 and #310 pointed at another project's database, whose security group blackholes our traffic. Every query hit the 5s
connectionTimeoutMillisindb.tsand threw.Why it looked like an auth bug
authenticateRequestwrapped both the JWT verification and thebranch.userslookup in onetry/catchthat returnedisAuthenticated: false. A dead database therefore surfaced as401 Authentication required.That is also actively harmful beyond the bad diagnostics: the frontend treats 401 as an expired session, so
authedFetchrefreshes, retries, then callsendSession()— a database blip logs the user out.Login and refresh kept working throughout because they only talk to Cognito and never touch the DB, which is exactly why this looked like "auth is broken" rather than "the DB is unreachable."
Evidence
Against the PR-310 preview API, with a valid token:
/auth/me, real token/auth/me, forged signature (realkid)nctobhchp-postgres:5432ncto branch RDS:5432The forged-token probe is what isolated it: JWKS fetch and JWT verification were healthy and failed fast, so the 5s had to come from the line after
verify().aws-jwt-verify's own timeouts (1500ms socket / 3000ms response) never matched 5.06s;connectionTimeoutMillis: 5000did, exactly.The fix
preview-env.yml— stop re-derivingDB_HOST. The prod lambda config the workflow already reads carries the right value, so inherit it like every other DB credential. Added a guard that fails the job ifDB_HOST/ DB creds / Cognito ids are missing, instead of silently shipping a preview that 401s on every call.shared/lambda-auth/src/authenticate.ts— only catch token verification. DB errors and a missingCOGNITO_USER_POOL_IDnow propagate into the handlers' existing 500 mapping. No handler changes needed; they all already have an outercatch→json(500, …).Already applied out of band
The workflow only resolves lambda env on label-add, so the 12 already-created preview lambdas kept the bad
DB_HOSTregardless of this change. I repatched all of them to the branch RDS, which is whatinfrastructure/preview/variables.tfalready documents as intended ("Preview envs deliberately reuse the shared RDS + Cognito pool"). PR-310's preview is working now — verified with the 200 above.Verification
shared/lambda-auth:npx jest→ 42/42 pass;npx tsc --noEmitclean.apps/backend/lambdas/auth: 67 unit tests pass. 3auth.e2e.test.tsfailures are pre-existing — they need a lambda onlocalhost:3000and fail identically on cleanmain./auth/meon the PR-310 preview returns 200 with the correct user record.Follow-ups not in scope here
apps/backend/lambdas/*/db.tsduplicates the same Pool config six times, so the 5s timeout and TLS rules have to be kept in sync by hand.🤖 Generated with Claude Code