From 8c75c8fe6f7f5d8173f3c32da0738b3ca4660776 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:34:22 +0530 Subject: [PATCH 01/41] Verify database TLS and add least-privilege logins (R11 part 1) - DATABASE_SSL=verify checks the server certificate against DATABASE_CA_CERT or DATABASE_CA_CERT_FILE and refuses to run without one; "require" stays encrypted-but-unverified. ensure-database uses the same rules instead of always skipping verification - Production startup (web and worker) refuses a remote database without verify + CA, and the web app refuses a non-https APP_BASE_URL; local hosts stay exempt so docker-compose still runs - HSTS is sent when APP_BASE_URL is https - Web, worker, migrate and Keycloak images ship Amazon's RDS CA bundle - ensure-roles.ts (run by the migration task as the master user): a runtime login with row-level read/write and no DDL, and a Keycloak login that owns the Keycloak database, including tables an earlier deploy created as master (handed over object by object, since REASSIGN OWNED would also move databases). CONNECT is revoked from PUBLIC on both databases. Re-running rotates passwords - Real-Postgres test of what each login can and cannot do --- apps/web/Dockerfile | 4 + apps/web/next.config.mjs | 4 + apps/web/src/lib/env.ts | 27 ++++- infra/docker/keycloak.Dockerfile | 3 + infra/docker/migrate.Dockerfile | 4 + infra/docker/worker.Dockerfile | 5 + packages/db/src/client.ts | 43 +++++-- packages/db/src/ensure-database.ts | 6 +- packages/db/src/ensure-roles.ts | 148 +++++++++++++++++++++++ tests/integration/database-roles.test.ts | 100 +++++++++++++++ tests/unit/env.test.ts | 2 +- tests/unit/production-transport.test.ts | 73 +++++++++++ 12 files changed, 400 insertions(+), 19 deletions(-) create mode 100644 packages/db/src/ensure-roles.ts create mode 100644 tests/integration/database-roles.test.ts create mode 100644 tests/unit/production-transport.test.ts diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 4b1eae2..e5fffc4 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -56,6 +56,10 @@ COPY --from=builder --chown=node:node /repo/apps/web/.next/standalone ./ COPY --from=builder --chown=node:node /repo/apps/web/.next/static ./apps/web/.next/static COPY --from=builder --chown=node:node /repo/apps/web/public ./apps/web/public +# Amazon's RDS CA bundle, so DATABASE_SSL=verify can check the database +# certificate (DATABASE_CA_CERT_FILE points here in the task definitions). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem + # The release tag (commit SHA) the deploy built, reported by /api/health so # smoke tests and rollbacks can tell which version is serving. Declared late # so a new tag does not invalidate the cached layers above. diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs index e6f283f..e50b24c 100644 --- a/apps/web/next.config.mjs +++ b/apps/web/next.config.mjs @@ -42,6 +42,10 @@ const nextConfig = { { key: "X-Content-Type-Options", value: "nosniff" }, { key: "X-Frame-Options", value: "DENY" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, + // Browsers that have seen the HTTPS site never fall back to HTTP. + ...(process.env.APP_BASE_URL?.startsWith("https://") + ? [{ key: "Strict-Transport-Security", value: "max-age=31536000; includeSubDomains" }] + : []), ], }, ]; diff --git a/apps/web/src/lib/env.ts b/apps/web/src/lib/env.ts index 36902de..2a9f2b3 100644 --- a/apps/web/src/lib/env.ts +++ b/apps/web/src/lib/env.ts @@ -26,7 +26,7 @@ const POSITIVE_INTEGERS = [ ]; const ALLOWED: Record = { - DATABASE_SSL: ["disable", "require"], + DATABASE_SSL: ["disable", "require", "verify"], EMBEDDING_PROVIDER: ["gemini", "local"], EMAIL_DEV_FALLBACK: ["true", "false"], TRUSTED_PROXY_HOPS: ["0", "1", "2", "3"], @@ -63,6 +63,23 @@ export function checkEnv(role: EnvRole, env: Env = process.env): string[] { problems.push("DATABASE_URL must start with postgres:// or postgresql://."); } + // Production must not quietly fall back to unverified or plain transport. + // Local hosts are exempt so the docker-compose stack still runs as production. + if (value("NODE_ENV") === "production") { + if (databaseUrl && !isLocalHost(databaseUrl)) { + if (value("DATABASE_SSL") !== "verify") { + problems.push("DATABASE_SSL must be verify in production, so the database certificate is checked."); + } else if (!value("DATABASE_CA_CERT") && !value("DATABASE_CA_CERT_FILE")) { + problems.push("DATABASE_SSL=verify needs DATABASE_CA_CERT or DATABASE_CA_CERT_FILE (the RDS CA bundle)."); + } + } + const base = value("APP_BASE_URL"); + if (role === "web" && !base) problems.push("APP_BASE_URL is required in production."); + if (role === "web" && base && isHttpUrl(base) && !isLocalHost(base) && new URL(base).protocol !== "https:") { + problems.push(`APP_BASE_URL must use https in production, got "${base}".`); + } + } + if (role === "web") { const secret = value("SESSION_SECRET"); if (secret && secret.length < 32) { @@ -109,6 +126,14 @@ function isSenderAddress(raw: string): boolean { return /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(address.trim()); } +function isLocalHost(raw: string): boolean { + try { + return ["localhost", "127.0.0.1", "postgres"].includes(new URL(raw).hostname); + } catch { + return false; + } +} + function isHttpUrl(raw: string): boolean { try { const { protocol } = new URL(raw); diff --git a/infra/docker/keycloak.Dockerfile b/infra/docker/keycloak.Dockerfile index e3b197c..a4b68a9 100644 --- a/infra/docker/keycloak.Dockerfile +++ b/infra/docker/keycloak.Dockerfile @@ -23,6 +23,9 @@ FROM quay.io/keycloak/keycloak:26.0 COPY --from=builder /opt/keycloak/ /opt/keycloak/ +# Amazon's RDS CA bundle, referenced by KC_DB_URL (sslmode=verify-full). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /opt/keycloak/conf/rds-global-bundle.pem + # Imported on first boot. Placeholders inside are filled from the task's # environment (client secret, app URL, Google credentials). COPY keycloak/realm-export.json /opt/keycloak/data/import/realm-export.json diff --git a/infra/docker/migrate.Dockerfile b/infra/docker/migrate.Dockerfile index 5ff48e9..dc200b4 100644 --- a/infra/docker/migrate.Dockerfile +++ b/infra/docker/migrate.Dockerfile @@ -19,5 +19,9 @@ RUN --mount=type=cache,target=/root/.npm \ COPY packages/db packages/db COPY tools tools +# Amazon's RDS CA bundle, so DATABASE_SSL=verify can check the database +# certificate (DATABASE_CA_CERT_FILE points here in the task definitions). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem + # Seeding is opt-in: it must run on a fresh local stack, never against prod data. CMD ["sh", "-c", "npx tsx packages/db/src/migrate.ts && if [ \"$SEED_ON_MIGRATE\" = \"true\" ]; then npx tsx packages/db/src/seed.ts; fi"] diff --git a/infra/docker/worker.Dockerfile b/infra/docker/worker.Dockerfile index ca7b4e8..fb4e9eb 100644 --- a/infra/docker/worker.Dockerfile +++ b/infra/docker/worker.Dockerfile @@ -1,3 +1,4 @@ +# syntax=docker/dockerfile:1.7 # Runs the async profile embedding and matching queue processors. FROM node:22-alpine WORKDIR /repo @@ -15,6 +16,10 @@ COPY packages/db packages/db COPY packages/auth packages/auth COPY packages/email packages/email +# Amazon's RDS CA bundle, so DATABASE_SSL=verify can check the database +# certificate (DATABASE_CA_CERT_FILE points here in the task definitions). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem + ENV NODE_ENV=production # Release tag (commit SHA), logged when the worker starts. ARG APP_VERSION=dev diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 1a49db3..40c6aaa 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -1,4 +1,5 @@ import pg from "pg"; +import { readFileSync } from "node:fs"; import type { ConnectionOptions as TlsOptions } from "node:tls"; const { Pool } = pg; @@ -38,8 +39,6 @@ export function getPool(): pg.Pool { pool = new Pool({ connectionString, - // RDS terminates TLS with an Amazon-issued CA that is not in Node's default - // trust store. Verification is enabled only when a CA bundle is supplied. ssl: resolveSsl(connectionString), max: Number(process.env.DATABASE_POOL_MAX ?? 10), idleTimeoutMillis: 30_000, @@ -56,18 +55,36 @@ export function getPool(): pg.Pool { return pool; } -function resolveSsl(connectionString: string): TlsOptions | false { - if (process.env.DATABASE_SSL === "disable") return false; - - // Local docker-compose Postgres has no TLS at all. - const isLocal = - connectionString.includes("@localhost") || - connectionString.includes("@127.0.0.1") || - connectionString.includes("@postgres:"); - if (isLocal && process.env.DATABASE_SSL !== "require") return false; +/** + * TLS for a connection, from DATABASE_SSL: + * disable plain connection (local docker-compose Postgres has no TLS) + * require encrypted, certificate not checked + * verify encrypted and the server certificate is checked against + * DATABASE_CA_CERT (PEM text) or DATABASE_CA_CERT_FILE (a path); + * production images ship the RDS bundle for this + * Unset: off for local hosts, otherwise verify when a CA is configured and + * require when not. Production startup refuses `require` for remote hosts. + */ +export function resolveSsl(connectionString: string, env: NodeJS.ProcessEnv = process.env): TlsOptions | false { + const mode = env.DATABASE_SSL; + if (mode === "disable") return false; + if (!mode && isLocalDatabase(connectionString)) return false; + + const ca = env.DATABASE_CA_CERT || (env.DATABASE_CA_CERT_FILE ? readFileSync(env.DATABASE_CA_CERT_FILE, "utf8") : ""); + if (mode === "verify" && !ca) { + throw new Error("DATABASE_SSL=verify needs DATABASE_CA_CERT or DATABASE_CA_CERT_FILE"); + } + if (mode === "verify" || (!mode && ca)) return { ca, rejectUnauthorized: true }; + return { rejectUnauthorized: false }; +} - const ca = process.env.DATABASE_CA_CERT; - return ca ? { ca, rejectUnauthorized: true } : { rejectUnauthorized: false }; +/** Local docker-compose or developer databases, which have no TLS. */ +export function isLocalDatabase(connectionString: string): boolean { + try { + return ["localhost", "127.0.0.1", "postgres"].includes(new URL(connectionString).hostname); + } catch { + return false; + } } /** Run a parameterised query. Never interpolate user input into `text`. */ diff --git a/packages/db/src/ensure-database.ts b/packages/db/src/ensure-database.ts index 0ffeeea..a61ab19 100644 --- a/packages/db/src/ensure-database.ts +++ b/packages/db/src/ensure-database.ts @@ -10,6 +10,7 @@ import "dotenv/config"; import pg from "pg"; import { isMainModule } from "./is-main"; +import { resolveSsl } from "./client"; /** * Connect to the `postgres` maintenance database rather than the target, since @@ -32,10 +33,7 @@ export async function ensureDatabase(name: string): Promise { const client = new pg.Client({ connectionString: maintenanceUrl(databaseUrl), - ssl: - process.env.DATABASE_SSL === "disable" - ? false - : { rejectUnauthorized: false }, + ssl: resolveSsl(databaseUrl), }); await client.connect(); diff --git a/packages/db/src/ensure-roles.ts b/packages/db/src/ensure-roles.ts new file mode 100644 index 0000000..15388da --- /dev/null +++ b/packages/db/src/ensure-roles.ts @@ -0,0 +1,148 @@ +/** + * Create or update the least-privilege database logins. The migration task runs + * this as the master user, before migrations: + * + * runtime web and worker: read and write application rows; no DDL, and no + * access to other databases + * keycloak owns the Keycloak database and nothing in the application one + * + * The master login is then used only by migrations. Passwords come from the + * task's secrets, and re-running updates them, so rotation is a redeploy. + * + * Usage: tsx packages/db/src/ensure-roles.ts + * DATABASE_URL master connection to the application database + * DATABASE_RUNTIME_USER / _PASSWORD runtime login (skipped when unset) + * KEYCLOAK_DB_USER / _PASSWORD Keycloak login (skipped when unset) + * KEYCLOAK_DB_NAME Keycloak database (default "keycloak") + */ +import "dotenv/config"; +import pg from "pg"; +import { isMainModule } from "./is-main"; +import { resolveSsl } from "./client"; + +export interface RoleSpec { + runtime?: { user: string; password: string }; + keycloak?: { user: string; password: string; database: string }; +} + +const IDENTIFIER = /^[a-z_][a-z0-9_]{0,62}$/; + +export async function ensureRoles(databaseUrl: string, spec: RoleSpec): Promise { + for (const name of [spec.runtime?.user, spec.keycloak?.user, spec.keycloak?.database]) { + if (name !== undefined && !IDENTIFIER.test(name)) throw new Error(`Invalid role or database name: ${name}`); + } + + const app = await connect(databaseUrl); + try { + if (spec.runtime) await ensureRuntime(app, spec.runtime.user, spec.runtime.password, new URL(databaseUrl).pathname.slice(1)); + if (spec.keycloak) await ensureLogin(app, spec.keycloak.user, spec.keycloak.password); + } finally { + await app.end(); + } + + if (spec.keycloak) { + const url = new URL(databaseUrl); + url.pathname = `/${spec.keycloak.database}`; + const identity = await connect(url.toString()); + try { + await ensureKeycloakOwner(identity, spec.keycloak.user, spec.keycloak.database); + } finally { + await identity.end(); + } + } +} + +async function connect(connectionString: string): Promise { + const client = new pg.Client({ connectionString, ssl: resolveSsl(connectionString) }); + await client.connect(); + return client; +} + +async function ensureLogin(client: pg.Client, user: string, password: string): Promise { + const role = client.escapeIdentifier(user); + const { rowCount } = await client.query(`select 1 from pg_roles where rolname = $1`, [user]); + if (!rowCount) await client.query(`create role ${role} login`); + await client.query(`alter role ${role} with login nosuperuser nocreatedb nocreaterole password ${client.escapeLiteral(password)}`); + console.log(`[ensure-roles] login ${user} ready`); +} + +async function ensureRuntime(client: pg.Client, user: string, password: string, database: string): Promise { + await ensureLogin(client, user, password); + const role = client.escapeIdentifier(user); + const db = client.escapeIdentifier(database); + for (const statement of [ + // Only named logins may connect to the application database. + `revoke connect on database ${db} from public`, + `grant connect on database ${db} to ${role}`, + `grant usage on schema public to ${role}`, + `grant select, insert, update, delete on all tables in schema public to ${role}`, + `grant usage, select on all sequences in schema public to ${role}`, + // Tables and sequences that later migrations create (as this master login). + `alter default privileges in schema public grant select, insert, update, delete on tables to ${role}`, + `alter default privileges in schema public grant usage, select on sequences to ${role}`, + ]) await client.query(statement); + console.log(`[ensure-roles] ${user} can read and write ${database} rows, without DDL`); +} + +/** + * Makes the Keycloak login own its database and every object in it, including + * tables an earlier deploy created as the master user. Objects are handed over + * one by one: REASSIGN OWNED would also move databases the master owns. + */ +async function ensureKeycloakOwner(client: pg.Client, user: string, database: string): Promise { + const role = client.escapeIdentifier(user); + const db = client.escapeIdentifier(database); + // A non-superuser master (RDS) may only transfer ownership to roles it belongs to. + await client.query(`grant ${role} to current_user`).catch(() => {}); + await client.query(`alter database ${db} owner to ${role}`); + await client.query(`revoke connect on database ${db} from public`); + await client.query(`grant connect on database ${db} to ${role}`); + await client.query( + `do $$ + declare item record; + begin + for item in + select 'table' as kind, format('%I.%I', schemaname, tablename) as name from pg_tables + where schemaname = 'public' and tableowner = current_user + union all + select 'view', format('%I.%I', schemaname, viewname) from pg_views + where schemaname = 'public' and viewowner = current_user + union all + select 'sequence', format('%I.%I', schemaname, sequencename) from pg_sequences + where schemaname = 'public' and sequenceowner = current_user + loop + begin + execute format('alter %s %s owner to %s', item.kind, item.name, ${client.escapeLiteral(role)}); + exception when others then + -- Sequences owned by a column move with their table. + null; + end; + end loop; + end $$` + ); + console.log(`[ensure-roles] ${user} owns database ${database}`); +} + +function pair(user: string | undefined, password: string | undefined, label: string) { + if (!user && !password) return undefined; + if (!user || !password) throw new Error(`${label} user and password must be set together`); + return { user, password }; +} + +if (isMainModule(import.meta.url)) { + const databaseUrl = process.env.DATABASE_URL; + if (!databaseUrl) { + console.error("[ensure-roles] DATABASE_URL is not set"); + process.exit(1); + } + const runtime = pair(process.env.DATABASE_RUNTIME_USER, process.env.DATABASE_RUNTIME_PASSWORD, "DATABASE_RUNTIME"); + const keycloakLogin = pair(process.env.KEYCLOAK_DB_USER, process.env.KEYCLOAK_DB_PASSWORD, "KEYCLOAK_DB"); + const keycloak = keycloakLogin && { ...keycloakLogin, database: process.env.KEYCLOAK_DB_NAME || "keycloak" }; + if (!runtime && !keycloak) console.log("[ensure-roles] no logins configured; nothing to do"); + ensureRoles(databaseUrl, { runtime, keycloak }) + .then(() => process.exit(0)) + .catch((err) => { + console.error("[ensure-roles] failed:", err.message); + process.exit(1); + }); +} diff --git a/tests/integration/database-roles.test.ts b/tests/integration/database-roles.test.ts new file mode 100644 index 0000000..3afad1d --- /dev/null +++ b/tests/integration/database-roles.test.ts @@ -0,0 +1,100 @@ +/** + * The least-privilege logins against a real Postgres. Creates its own roles and + * Keycloak-style database, removes them afterwards, and restores the default + * CONNECT grant it revokes on the local application database. + * Skipped when DATABASE_URL is unset. + */ +import { randomBytes } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import pg from "pg"; +import { migrate } from "../../packages/db/src/migrate"; +import { ensureRoles } from "../../packages/db/src/ensure-roles"; + +const databaseUrl = process.env.DATABASE_URL; +const describeDb = databaseUrl ? describe : describe.skip; + +const suffix = randomBytes(3).toString("hex"); +const runtime = { user: `test_runtime_${suffix}`, password: randomBytes(12).toString("hex") }; +const keycloak = { user: `test_kc_${suffix}`, password: randomBytes(12).toString("hex"), database: `test_kc_db_${suffix}` }; + +function urlFor(user?: { user: string; password: string }, database?: string): string { + const url = new URL(databaseUrl!); + if (user) { + url.username = user.user; + url.password = user.password; + } + if (database) url.pathname = `/${database}`; + return url.toString(); +} + +async function as(connection: string, work: (client: pg.Client) => Promise): Promise { + const client = new pg.Client({ connectionString: connection }); + await client.connect(); + try { + return await work(client); + } finally { + await client.end(); + } +} + +describeDb("least-privilege database logins", () => { + const appDatabase = () => new URL(databaseUrl!).pathname.slice(1); + + beforeAll(async () => { + await migrate(); + // A Keycloak database that an earlier deploy filled as the master user. + await as(urlFor(undefined, "postgres"), (c) => c.query(`create database ${keycloak.database}`)); + await as(urlFor(undefined, keycloak.database), (c) => c.query(`create table realm (id serial primary key, name text)`)); + await ensureRoles(databaseUrl!, { runtime, keycloak }); + }); + + afterAll(async () => { + await as(urlFor(undefined, "postgres"), (c) => c.query(`drop database if exists ${keycloak.database}`)); + await as(databaseUrl!, async (c) => { + await c.query(`grant connect on database ${c.escapeIdentifier(appDatabase())} to public`); + await c.query(`drop owned by ${runtime.user}, ${keycloak.user}`); + await c.query(`drop role if exists ${runtime.user}`); + await c.query(`drop role if exists ${keycloak.user}`); + }); + }); + + it("lets the runtime login read and write application rows", async () => { + await as(urlFor(runtime), async (c) => { + const key = `test:roles:${suffix}`; + await c.query(`insert into rate_limit_buckets (bucket_key, window_started_at, count) values ($1, now(), 1)`, [key]); + expect((await c.query(`select count(*)::int as n from rate_limit_buckets where bucket_key = $1`, [key])).rows[0].n).toBe(1); + await c.query(`delete from rate_limit_buckets where bucket_key = $1`, [key]); + }); + }); + + it("refuses the runtime login any schema change", async () => { + await as(urlFor(runtime), async (c) => { + await expect(c.query(`create table test_forbidden (id int)`)).rejects.toThrow(/permission denied/); + await expect(c.query(`drop table rate_limit_buckets`)).rejects.toThrow(/must be owner|permission denied/); + }); + }); + + it("keeps the runtime login out of the Keycloak database", async () => { + await expect(as(urlFor(runtime, keycloak.database), (c) => c.query("select 1"))).rejects.toThrow(/permission denied/); + }); + + it("makes the Keycloak login own its database, including older tables", async () => { + await as(urlFor(keycloak, keycloak.database), async (c) => { + const owner = await c.query(`select tableowner from pg_tables where tablename = 'realm'`); + expect(owner.rows[0].tableowner).toBe(keycloak.user); + await c.query(`alter table realm add column if not exists display_name text`); + await c.query(`insert into realm (name) values ('match-maker')`); + }); + }); + + it("keeps the Keycloak login out of the application database", async () => { + await expect(as(urlFor(keycloak), (c) => c.query("select 1"))).rejects.toThrow(/permission denied/); + }); + + it("is safe to run again and updates passwords", async () => { + const rotated = { ...runtime, password: randomBytes(12).toString("hex") }; + await ensureRoles(databaseUrl!, { runtime: rotated }); + await expect(as(urlFor(rotated), (c) => c.query("select 1 from events limit 1"))).resolves.toBeDefined(); + await expect(as(urlFor(runtime), (c) => c.query("select 1"))).rejects.toThrow(/password/); + }); +}); diff --git a/tests/unit/env.test.ts b/tests/unit/env.test.ts index d5f2b85..29a12fb 100644 --- a/tests/unit/env.test.ts +++ b/tests/unit/env.test.ts @@ -47,7 +47,7 @@ describe("checkEnv", () => { expect(problems).toEqual([ 'APP_BASE_URL must be an http(s) URL, got "localhost:3000".', 'DATABASE_POOL_MAX must be a positive integer, got "ten".', - 'DATABASE_SSL must be one of disable, require, got "on".', + 'DATABASE_SSL must be one of disable, require, verify, got "on".', ]); }); diff --git a/tests/unit/production-transport.test.ts b/tests/unit/production-transport.test.ts new file mode 100644 index 0000000..2f25bd7 --- /dev/null +++ b/tests/unit/production-transport.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { checkEnv } from "@/src/lib/env"; +import { isLocalDatabase, resolveSsl } from "../../packages/db/src/client"; + +const REMOTE = "postgres://app:pw@db.abc.ap-south-1.rds.amazonaws.com:5432/match_maker"; +const LOCAL = "postgres://matchmaker:matchmaker@postgres:5432/matchmaker"; +const CA = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----"; + +describe("resolveSsl", () => { + it("leaves local databases unencrypted unless asked", () => { + expect(isLocalDatabase(LOCAL)).toBe(true); + expect(resolveSsl(LOCAL, {})).toBe(false); + expect(resolveSsl(LOCAL, { DATABASE_SSL: "require" })).toEqual({ rejectUnauthorized: false }); + }); + + it("verifies the certificate in verify mode, from inline PEM or a file", () => { + expect(resolveSsl(REMOTE, { DATABASE_SSL: "verify", DATABASE_CA_CERT: CA })).toEqual({ ca: CA, rejectUnauthorized: true }); + const file = join(mkdtempSync(join(tmpdir(), "ca-")), "bundle.pem"); + writeFileSync(file, CA); + expect(resolveSsl(REMOTE, { DATABASE_SSL: "verify", DATABASE_CA_CERT_FILE: file })).toEqual({ ca: CA, rejectUnauthorized: true }); + }); + + it("refuses verify mode without a CA instead of silently skipping the check", () => { + expect(() => resolveSsl(REMOTE, { DATABASE_SSL: "verify" })).toThrow(/DATABASE_CA_CERT/); + }); + + it("does not treat a hostname merely containing 'postgres' as local", () => { + expect(isLocalDatabase("postgres://u:p@postgres.example.com/db")).toBe(false); + }); +}); + +describe("production startup checks", () => { + const web = { + NODE_ENV: "production", + DATABASE_URL: REMOTE, + DATABASE_SSL: "verify", + DATABASE_CA_CERT_FILE: "/etc/ssl/certs/rds-global-bundle.pem", + SESSION_SECRET: "x".repeat(32), + KEYCLOAK_ISSUER: "https://bridge.example.com/realms/match-maker", + KEYCLOAK_CLIENT_ID: "match-maker-web", + KEYCLOAK_CLIENT_SECRET: "secret", + RESEND_API_KEY: "re_key", + EMAIL_FROM: "Bridge ", + APP_BASE_URL: "https://bridge.example.com", + }; + + it("accepts verified TLS and an https base URL", () => { + expect(checkEnv("web", web)).toEqual([]); + }); + + it.each([ + [{ DATABASE_SSL: "require" }, /DATABASE_SSL must be verify/], + [{ DATABASE_SSL: undefined }, /DATABASE_SSL must be verify/], + [{ DATABASE_CA_CERT_FILE: undefined }, /needs DATABASE_CA_CERT/], + [{ APP_BASE_URL: "http://bridge.example.com" }, /must use https/], + [{ APP_BASE_URL: undefined }, /APP_BASE_URL is required/], + ])("refuses %o", (change, message) => { + expect(checkEnv("web", { ...web, ...change }).join("\n")).toMatch(message); + }); + + it("applies the database rule to the worker too", () => { + expect(checkEnv("worker", { NODE_ENV: "production", DATABASE_URL: REMOTE, DATABASE_SSL: "require" }).join("\n")) + .toMatch(/DATABASE_SSL must be verify/); + }); + + it("still lets the local docker-compose stack run as production", () => { + const local = { ...web, DATABASE_URL: LOCAL, DATABASE_SSL: "disable", APP_BASE_URL: "http://localhost:3000" }; + expect(checkEnv("web", local)).toEqual([]); + }); +}); From b4d1327c750febe902e799c5ede16378d2fc804b Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:38:50 +0530 Subject: [PATCH 02/41] Require HTTPS, restrict Keycloak admin, separate DB logins (R11 part 2) - An environment = "prod" plan fails unless domain_name and acm_certificate_arn are set, so production never serves over HTTP - /admin on Keycloak is no longer routed publicly: a 404 rule blocks it at the load balancer, with an allow rule only for var.keycloak_admin_cidrs (empty by default). The app's admin API calls already go over Cloud Map inside the VPC - Web and worker connect as app_runtime (row access only), Keycloak as its own keycloak login over JDBC sslmode=verify-full, and only the migration task holds the master login; it runs ensure-roles.ts after migrations to create/rotate the other two - Secrets split into app (web/worker), identity (Keycloak) and migrate (master login and the passwords it sets) - Every task uses DATABASE_SSL=verify with the RDS bundle in the image - deploy.yml pins images onto the family's newest task definition revision instead of the one the service is running, so environment and secret changes applied by Terraform (these, and R09's TRUSTED_PROXY_HOPS) actually reach the services --- .env.example | 11 +++++ .github/workflows/deploy.yml | 17 ++++--- infra/terraform/alb.tf | 61 ++++++++++++++++++++++-- infra/terraform/database.tf | 34 ++++++++++++- infra/terraform/ecs.tf | 40 +++++++++------- infra/terraform/iam.tf | 8 +++- infra/terraform/outputs.tf | 7 +-- infra/terraform/secrets.tf | 56 +++++++++++++++++----- infra/terraform/terraform.tfvars.example | 9 +++- infra/terraform/variables.tf | 8 +++- 10 files changed, 205 insertions(+), 46 deletions(-) diff --git a/.env.example b/.env.example index 5e1a5d0..a64d1d3 100644 --- a/.env.example +++ b/.env.example @@ -22,7 +22,18 @@ POSTGRES_PORT=5432 # Used by scripts run on the HOST (migrate/seed/import). # Inside docker-compose the host is `postgres`, not `localhost`. DATABASE_URL=postgres://matchmaker:matchmaker@localhost:5432/matchmaker +# disable (local, no TLS) | require (encrypted, unverified) | verify (encrypted, +# certificate checked against DATABASE_CA_CERT or DATABASE_CA_CERT_FILE). +# Production refuses anything but verify for a remote database. DATABASE_SSL=disable +# DATABASE_CA_CERT_FILE=/etc/ssl/certs/rds-global-bundle.pem + +# Deployed only: the migration task creates these least-privilege logins +# (packages/db/src/ensure-roles.ts); web and worker then use the runtime one. +# DATABASE_RUNTIME_USER=app_runtime +# DATABASE_RUNTIME_PASSWORD= +# KEYCLOAK_DB_USER=keycloak +# KEYCLOAK_DB_PASSWORD= # ── Keycloak ────────────────────────────────────────────────── KEYCLOAK_PORT=8080 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 1a48e80..25ad537 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -252,8 +252,11 @@ jobs: set -euo pipefail REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" - aws ecs describe-task-definition \ - --task-definition "$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" --query 'services[0].taskDefinition' --output text)" \ + # Start from the family's newest revision, not the one the service is + # running, so settings and secrets changed by Terraform ship too. + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ --query 'taskDefinition' > taskdef.json # Production login must send real e-mail: never ship the dev fallback, @@ -296,8 +299,9 @@ jobs: set -euo pipefail REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" - aws ecs describe-task-definition \ - --task-definition "$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WORKER_SERVICE" --query 'services[0].taskDefinition' --output text)" \ + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WORKER_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ --query 'taskDefinition' > worker-taskdef.json jq --arg IMAGE "$REGISTRY/match-maker-prod/worker:$TAG" ' @@ -327,8 +331,9 @@ jobs: run: | set -euo pipefail REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" - aws ecs describe-task-definition \ - --task-definition "$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_KEYCLOAK_SERVICE" --query 'services[0].taskDefinition' --output text)" \ + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_KEYCLOAK_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ --query 'taskDefinition' > keycloak-taskdef.json jq --arg IMAGE "$REGISTRY/match-maker-prod/keycloak:$TAG" ' .containerDefinitions[0].image = $IMAGE diff --git a/infra/terraform/alb.tf b/infra/terraform/alb.tf index 1e41e9c..c363314 100644 --- a/infra/terraform/alb.tf +++ b/infra/terraform/alb.tf @@ -104,6 +104,14 @@ resource "aws_lb_listener" "http" { port = 80 protocol = "HTTP" + lifecycle { + # Production must never serve logins and session cookies over plain HTTP. + precondition { + condition = var.environment != "prod" || (local.https_enabled && var.domain_name != "") + error_message = "environment = \"prod\" requires domain_name and acm_certificate_arn so the app is served over HTTPS." + } + } + dynamic "default_action" { for_each = local.https_enabled ? [1] : [] content { @@ -166,9 +174,56 @@ resource "aws_lb_listener_rule" "keycloak_host" { } } +# The admin console is not public: only var.keycloak_admin_cidrs reach it, and +# everyone else gets a 404 before the request is routed to Keycloak. The app's +# own admin API calls go over Cloud Map inside the VPC, not through the ALB. +resource "aws_lb_listener_rule" "keycloak_admin_allow" { + count = length(var.keycloak_admin_cidrs) > 0 ? 1 : 0 + + listener_arn = local.active_listener_arn + priority = 5 + + action { + type = "forward" + target_group_arn = aws_lb_target_group.keycloak.arn + } + + condition { + path_pattern { + values = ["/admin", "/admin/*"] + } + } + + condition { + source_ip { + values = var.keycloak_admin_cidrs + } + } +} + +resource "aws_lb_listener_rule" "keycloak_admin_deny" { + listener_arn = local.active_listener_arn + priority = 6 + + action { + type = "fixed-response" + fixed_response { + content_type = "text/plain" + message_body = "Not found" + status_code = "404" + } + } + + condition { + path_pattern { + values = ["/admin", "/admin/*"] + } + } +} + # Fallback: share the app hostname and split on the paths Keycloak owns. -# /auth/callback belongs to the APP, and is not listed here — Keycloak's own -# paths are /realms/*, /resources/* and /admin/*. +# /auth/callback belongs to the APP, and is not listed here. /admin/* is +# handled by the two rules above. resource "aws_lb_listener_rule" "keycloak_path" { count = local.keycloak_has_own_domain ? 0 : 1 @@ -182,7 +237,7 @@ resource "aws_lb_listener_rule" "keycloak_path" { condition { path_pattern { - values = ["/realms/*", "/resources/*", "/admin/*", "/js/*"] + values = ["/realms/*", "/resources/*", "/js/*"] } } } diff --git a/infra/terraform/database.tf b/infra/terraform/database.tf index a25b411..1d9f46c 100644 --- a/infra/terraform/database.tf +++ b/infra/terraform/database.tf @@ -19,6 +19,18 @@ resource "random_password" "db" { override_special = "!#$%&*()-_=+[]{}<>:?" } +# Least-privilege logins, created by the migration task (ensure-roles.ts). The +# master login above is used only to run migrations. +resource "random_password" "db_runtime" { + length = 40 + special = false +} + +resource "random_password" "db_keycloak" { + length = 40 + special = false +} + resource "aws_db_parameter_group" "main" { name = "${local.name}-pg16" family = "postgres16" @@ -86,7 +98,11 @@ resource "aws_db_instance" "main" { locals { db_password_encoded = urlencode(random_password.db.result) - app_database_url = format( + db_runtime_user = "app_runtime" + db_keycloak_user = "keycloak" + + # Migrations only. + admin_database_url = format( "postgres://%s:%s@%s:%s/%s", aws_db_instance.main.username, local.db_password_encoded, @@ -95,9 +111,23 @@ locals { aws_db_instance.main.db_name, ) + # Web and worker: row access only. + app_database_url = format( + "postgres://%s:%s@%s:%s/%s", + local.db_runtime_user, + random_password.db_runtime.result, + aws_db_instance.main.address, + aws_db_instance.main.port, + aws_db_instance.main.db_name, + ) + + # verify-full checks the RDS certificate with the bundle baked into the image. keycloak_jdbc_url = format( - "jdbc:postgresql://%s:%s/keycloak", + "jdbc:postgresql://%s:%s/keycloak?sslmode=verify-full&sslrootcert=/opt/keycloak/conf/rds-global-bundle.pem", aws_db_instance.main.address, aws_db_instance.main.port, ) + + # Path of the RDS CA bundle inside the web, worker and migrate images. + database_ca_file = "/etc/ssl/certs/rds-global-bundle.pem" } diff --git a/infra/terraform/ecs.tf b/infra/terraform/ecs.tf index e93cd80..d3df2a1 100644 --- a/infra/terraform/ecs.tf +++ b/infra/terraform/ecs.tf @@ -221,10 +221,10 @@ resource "aws_ecs_task_definition" "web" { { name = "KEYCLOAK_CLIENT_ID", value = var.keycloak_client_id }, { name = "KEYCLOAK_GOOGLE_IDP_ALIAS", value = "google" }, { name = "EMAIL_FROM", value = var.email_from }, - # RDS enforces TLS (rds.force_ssl), and the AWS CA is not in Node's - # default trust store, so verification is relaxed for this hop inside - # the VPC. Set DATABASE_CA_CERT to the RDS bundle to tighten it. - { name = "DATABASE_SSL", value = "require" }, + # RDS enforces TLS (rds.force_ssl); the certificate is checked against + # the RDS CA bundle baked into the image. + { name = "DATABASE_SSL", value = "verify" }, + { name = "DATABASE_CA_CERT_FILE", value = local.database_ca_file }, ] secrets = [ @@ -323,7 +323,7 @@ resource "aws_ecs_task_definition" "keycloak" { environment = [ { name = "KC_DB", value = "postgres" }, { name = "KC_DB_URL", value = local.keycloak_jdbc_url }, - { name = "KC_DB_USERNAME", value = aws_db_instance.main.username }, + { name = "KC_DB_USERNAME", value = local.db_keycloak_user }, # Tokens must be issued with the hostname the browser uses, or `iss` # will not match what the app verifies. { name = "KC_HOSTNAME", value = local.keycloak_public_origin }, @@ -341,12 +341,12 @@ resource "aws_ecs_task_definition" "keycloak" { ] secrets = [ - { name = "KC_DB_PASSWORD", valueFrom = local.secret_ref.KEYCLOAK_DB_PASSWORD }, - { name = "KC_BOOTSTRAP_ADMIN_PASSWORD", valueFrom = local.secret_ref.KEYCLOAK_ADMIN_PASSWORD }, + { name = "KC_DB_PASSWORD", valueFrom = local.identity_secret_ref.KEYCLOAK_DB_PASSWORD }, + { name = "KC_BOOTSTRAP_ADMIN_PASSWORD", valueFrom = local.identity_secret_ref.KEYCLOAK_ADMIN_PASSWORD }, # Substituted into realm-export.json during import. - { name = "KEYCLOAK_CLIENT_SECRET", valueFrom = local.secret_ref.KEYCLOAK_CLIENT_SECRET }, - { name = "GOOGLE_CLIENT_ID", valueFrom = local.secret_ref.GOOGLE_CLIENT_ID }, - { name = "GOOGLE_CLIENT_SECRET", valueFrom = local.secret_ref.GOOGLE_CLIENT_SECRET }, + { name = "KEYCLOAK_CLIENT_SECRET", valueFrom = local.identity_secret_ref.KEYCLOAK_CLIENT_SECRET }, + { name = "GOOGLE_CLIENT_ID", valueFrom = local.identity_secret_ref.GOOGLE_CLIENT_ID }, + { name = "GOOGLE_CLIENT_SECRET", valueFrom = local.identity_secret_ref.GOOGLE_CLIENT_SECRET }, ] logConfiguration = { @@ -420,23 +420,30 @@ resource "aws_ecs_task_definition" "migrate" { image = "${aws_ecr_repository.migrate.repository_url}:latest" essential = true - # Creates Keycloak's database on first run, then applies app migrations. - # Both steps are idempotent, so re-running a deploy is safe. + # Creates Keycloak's database on first run, applies app migrations, then + # creates/updates the runtime and Keycloak logins (after migrations, so + # grants cover every table). All steps are idempotent. command = [ "sh", "-c", - "npx tsx packages/db/src/ensure-database.ts keycloak && npx tsx packages/db/src/migrate.ts" + "npx tsx packages/db/src/ensure-database.ts keycloak && npx tsx packages/db/src/migrate.ts && npx tsx packages/db/src/ensure-roles.ts" ] environment = [ { name = "NODE_ENV", value = "production" }, - { name = "DATABASE_SSL", value = "require" }, + { name = "DATABASE_SSL", value = "verify" }, + { name = "DATABASE_CA_CERT_FILE", value = local.database_ca_file }, + { name = "DATABASE_RUNTIME_USER", value = local.db_runtime_user }, + { name = "KEYCLOAK_DB_USER", value = local.db_keycloak_user }, + { name = "KEYCLOAK_DB_NAME", value = "keycloak" }, # Seeding is for local development only; production data comes from the # Excel importer. { name = "SEED_ON_MIGRATE", value = "false" }, ] secrets = [ - { name = "DATABASE_URL", valueFrom = local.secret_ref.DATABASE_URL }, + { name = "DATABASE_URL", valueFrom = local.migrate_secret_ref.DATABASE_ADMIN_URL }, + { name = "DATABASE_RUNTIME_PASSWORD", valueFrom = local.migrate_secret_ref.DATABASE_RUNTIME_PASSWORD }, + { name = "KEYCLOAK_DB_PASSWORD", valueFrom = local.migrate_secret_ref.KEYCLOAK_DB_PASSWORD }, ] logConfiguration = { @@ -468,7 +475,8 @@ resource "aws_ecs_task_definition" "worker" { essential = true environment = [ { name = "NODE_ENV", value = "production" }, - { name = "DATABASE_SSL", value = "require" }, + { name = "DATABASE_SSL", value = "verify" }, + { name = "DATABASE_CA_CERT_FILE", value = local.database_ca_file }, { name = "GEMINI_LLM_MODEL", value = "gemini-3.8-flash" }, { name = "EMBEDDING_PROVIDER", value = "gemini" }, ] diff --git a/infra/terraform/iam.tf b/infra/terraform/iam.tf index 18a0ef1..3061fd9 100644 --- a/infra/terraform/iam.tf +++ b/infra/terraform/iam.tf @@ -37,8 +37,12 @@ resource "aws_iam_role_policy_attachment" "ecs_execution_managed" { # read access — not the task role. data "aws_iam_policy_document" "secrets_read" { statement { - actions = ["secretsmanager:GetSecretValue"] - resources = [aws_secretsmanager_secret.app.arn] + actions = ["secretsmanager:GetSecretValue"] + resources = [ + aws_secretsmanager_secret.app.arn, + aws_secretsmanager_secret.identity.arn, + aws_secretsmanager_secret.migrate.arn, + ] } } diff --git a/infra/terraform/outputs.tf b/infra/terraform/outputs.tf index cb2f601..f3c3043 100644 --- a/infra/terraform/outputs.tf +++ b/infra/terraform/outputs.tf @@ -94,7 +94,7 @@ output "secrets_manager_secret_name" { } output "keycloak_admin_console_url" { - description = "Keycloak admin console. The bootstrap password is in Secrets Manager." + description = "Keycloak admin console, reachable only from var.keycloak_admin_cidrs. The bootstrap password is in the identity secret." value = "${local.keycloak_public_origin}/admin" } @@ -103,8 +103,9 @@ output "post_apply_checklist" { value = <<-EOT 1. Create a Google OAuth client and set its authorised redirect URI to: ${local.keycloak_public_origin}/realms/${var.keycloak_realm}/broker/google/endpoint - Then put the id/secret into the ${aws_secretsmanager_secret.app.name} secret - (GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET) and redeploy Keycloak. + Then put the id/secret into the ${aws_secretsmanager_secret.identity.name} secret + (GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET), and GOOGLE_CLIENT_ID into + ${aws_secretsmanager_secret.app.name} too, then redeploy web and Keycloak. 2. Verify your sending domain in Resend and set RESEND_API_KEY in the same secret. 3. Set GEMINI_API_KEY in the same secret. 4. Import the attendee roster: npm run db:import -- attendees.xlsx diff --git a/infra/terraform/secrets.tf b/infra/terraform/secrets.tf index ecb51fa..f3b1e51 100644 --- a/infra/terraform/secrets.tf +++ b/infra/terraform/secrets.tf @@ -22,25 +22,40 @@ resource "random_password" "keycloak_admin_password" { override_special = "!#$%&*()-_=+" } +# Three secrets, so each task reads only its own credentials: +# app web and worker (runtime database login, no master password) +# identity Keycloak (its own database login and admin bootstrap) +# migrate the migration task (master login plus the passwords it sets) locals { secret_values = { DATABASE_URL = local.app_database_url SESSION_SECRET = random_password.session_secret.result KEYCLOAK_CLIENT_SECRET = random_password.keycloak_client_secret.result - KEYCLOAK_ADMIN_PASSWORD = random_password.keycloak_admin_password.result - KEYCLOAK_DB_PASSWORD = random_password.db.result GEMINI_API_KEY = var.gemini_api_key UPSTASH_REDIS_REST_URL = var.upstash_redis_rest_url UPSTASH_REDIS_REST_TOKEN = var.upstash_redis_rest_token RESEND_API_KEY = var.resend_api_key GOOGLE_CLIENT_ID = var.google_client_id - GOOGLE_CLIENT_SECRET = var.google_client_secret + } + + identity_secret_values = { + KEYCLOAK_ADMIN_PASSWORD = random_password.keycloak_admin_password.result + KEYCLOAK_DB_PASSWORD = random_password.db_keycloak.result + KEYCLOAK_CLIENT_SECRET = random_password.keycloak_client_secret.result + GOOGLE_CLIENT_ID = var.google_client_id + GOOGLE_CLIENT_SECRET = var.google_client_secret + } + + migrate_secret_values = { + DATABASE_ADMIN_URL = local.admin_database_url + DATABASE_RUNTIME_PASSWORD = random_password.db_runtime.result + KEYCLOAK_DB_PASSWORD = random_password.db_keycloak.result } } resource "aws_secretsmanager_secret" "app" { name = "${local.name}/app" - description = "Runtime secrets for the Mr. Bridge web and Keycloak services." + description = "Runtime secrets for the Mr. Bridge web and worker services." # Zero means immediate deletion, which keeps `terraform destroy` from leaving # a name reserved for 30 days and blocking a re-apply. @@ -52,13 +67,32 @@ resource "aws_secretsmanager_secret_version" "app" { secret_string = jsonencode(local.secret_values) } -# Individual ARNs, referenced one-by-one from the task definitions so each +resource "aws_secretsmanager_secret" "identity" { + name = "${local.name}/identity" + description = "Keycloak's database login, admin bootstrap and identity-provider secrets." + recovery_window_in_days = 0 +} + +resource "aws_secretsmanager_secret_version" "identity" { + secret_id = aws_secretsmanager_secret.identity.id + secret_string = jsonencode(local.identity_secret_values) +} + +resource "aws_secretsmanager_secret" "migrate" { + name = "${local.name}/migrate" + description = "Database master login, used only by the migration task." + recovery_window_in_days = 0 +} + +resource "aws_secretsmanager_secret_version" "migrate" { + secret_id = aws_secretsmanager_secret.migrate.id + secret_string = jsonencode(local.migrate_secret_values) +} + +# Individual keys, referenced one by one from the task definitions so each # container receives only the values it actually needs. locals { - secret_arn = aws_secretsmanager_secret.app.arn - - secret_ref = { - for key in keys(local.secret_values) : - key => "${local.secret_arn}:${key}::" - } + secret_ref = { for key in keys(local.secret_values) : key => "${aws_secretsmanager_secret.app.arn}:${key}::" } + identity_secret_ref = { for key in keys(local.identity_secret_values) : key => "${aws_secretsmanager_secret.identity.arn}:${key}::" } + migrate_secret_ref = { for key in keys(local.migrate_secret_values) : key => "${aws_secretsmanager_secret.migrate.arn}:${key}::" } } diff --git a/infra/terraform/terraform.tfvars.example b/infra/terraform/terraform.tfvars.example index 5137123..c6385b3 100644 --- a/infra/terraform/terraform.tfvars.example +++ b/infra/terraform/terraform.tfvars.example @@ -6,13 +6,18 @@ environment = "prod" default_event_slug = "demo" # ── DNS / TLS ───────────────────────────────────────────────── -# Leave all three empty for a first apply; the stack comes up on the ALB's own -# DNS name over HTTP, and you can add the domain later. +# Required when environment = "prod": the plan refuses to serve production +# over plain HTTP. For an HTTP-only evaluation stack, set environment = "staging" +# and leave these empty. domain_name = "" keycloak_domain_name = "" acm_certificate_arn = "" route53_zone_id = "" +# CIDR blocks allowed to open the Keycloak admin console through the load +# balancer, e.g. ["203.0.113.10/32"]. Empty keeps it off the internet. +keycloak_admin_cidrs = [] + # ── CI/CD ───────────────────────────────────────────────────── # Enables the GitHub OIDC deploy role. Format: "owner/repo". github_repository = "LucknowAI/Bridge" diff --git a/infra/terraform/variables.tf b/infra/terraform/variables.tf index a58730a..028ca0f 100644 --- a/infra/terraform/variables.tf +++ b/infra/terraform/variables.tf @@ -54,7 +54,7 @@ variable "enable_nat_gateway" { # ── DNS / TLS ───────────────────────────────────────────────── variable "domain_name" { - description = "Public hostname for the app, e.g. bridge.example.com. Leave empty to serve on the ALB's own DNS name over HTTP only." + description = "Public hostname for the app, e.g. bridge.example.com. Required (with acm_certificate_arn) when environment is prod; leave empty only for a non-prod evaluation stack served over HTTP." type = string default = "" } @@ -71,6 +71,12 @@ variable "acm_certificate_arn" { default = "" } +variable "keycloak_admin_cidrs" { + description = "IPv4 CIDR blocks allowed to reach the Keycloak admin console (/admin) through the load balancer. Empty keeps it unreachable from the internet; use ECS Exec port forwarding instead." + type = list(string) + default = [] +} + variable "route53_zone_id" { description = "Route53 hosted zone to create records in. Leave empty to manage DNS elsewhere." type = string From aa5e020831712a9ba0f3f8eb9f8ca4f79254916e Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:42:58 +0530 Subject: [PATCH 03/41] Track invitations, claims and revoked access per event (R12 part 1) - Migration 0006: event_participants gains invited_at, invite_count, invite_error, claimed_at and revoked_at; existing profiles count as claimed - Revoked attendees lose event sign-in (isParticipant), page and action access (hasEventAccess, so existing sessions too), matching (participantIds) and every results path (ELIGIBLE_CANDIDATE). Re-importing the roster does not silently restore them - The first signed-in visit to the event records the claim time - sendInvitations e-mails everyone never invited, or one attendee as a resend (at most every 10 minutes, never after claiming or removal); each attempt is recorded, failures with their reason - setAttendeeAccess removes or restores access - Invitation e-mail template and NotificationPort.invitation - Analytics count invited, claimed and removed attendees separately --- .../src/application/ports/event-repository.ts | 10 ++- .../web/src/application/ports/notification.ts | 1 + .../use-cases/manage-invitations.ts | 56 ++++++++++++ apps/web/src/domain/participant/invitation.ts | 32 +++++++ .../notifications/realtime.notifier.ts | 6 +- .../src/infrastructure/postgres/event.repo.ts | 28 +++++- .../postgres/participant.repo.ts | 6 +- apps/web/src/lib/auth.ts | 1 + packages/db/migrations/0006_invitations.sql | 18 ++++ packages/db/src/repositories/events.ts | 76 +++++++++++++++- packages/email/src/index.ts | 1 + .../email/src/templates/invitation-email.ts | 34 +++++++ tests/integration/invitations.test.ts | 90 +++++++++++++++++++ tests/unit/invitations.test.ts | 84 +++++++++++++++++ 14 files changed, 434 insertions(+), 9 deletions(-) create mode 100644 apps/web/src/application/use-cases/manage-invitations.ts create mode 100644 apps/web/src/domain/participant/invitation.ts create mode 100644 packages/db/migrations/0006_invitations.sql create mode 100644 packages/email/src/templates/invitation-email.ts create mode 100644 tests/integration/invitations.test.ts create mode 100644 tests/unit/invitations.test.ts diff --git a/apps/web/src/application/ports/event-repository.ts b/apps/web/src/application/ports/event-repository.ts index c902136..e13dfb4 100644 --- a/apps/web/src/application/ports/event-repository.ts +++ b/apps/web/src/application/ports/event-repository.ts @@ -38,5 +38,13 @@ export interface EventRepository { attachRoster(eventId: string, attendeeIds: string[]): Promise; participantIds(eventId: string): Promise; importRoster(eventId: string, records: RosterAttendeeInput[]): Promise<{ upserted: number; attached: number }>; - analytics(eventId: string): Promise<{ roster: number; profiles: number; matches: number; pendingIntros: number; acceptedIntros: number }>; + analytics(eventId: string): Promise<{ + roster: number; invited: number; claimed: number; profiles: number; removed: number; + matches: number; pendingIntros: number; acceptedIntros: number; + }>; + invitationTargets(eventId: string, attendeeId: string | null, resendAfterMinutes: number): Promise>; + recordInvitation(eventId: string, attendeeId: string, error: string | null): Promise; + markClaimed(eventId: string, attendeeId: string): Promise; + setRevoked(eventId: string, attendeeId: string, revoked: boolean): Promise; + rosterState(eventId: string, attendeeId: string): Promise<"active" | "revoked" | null>; } diff --git a/apps/web/src/application/ports/notification.ts b/apps/web/src/application/ports/notification.ts index bd84477..7db58ee 100644 --- a/apps/web/src/application/ports/notification.ts +++ b/apps/web/src/application/ports/notification.ts @@ -1,4 +1,5 @@ export interface NotificationPort { + invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise; introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise; introResponded(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; accepted: boolean }): Promise; } diff --git a/apps/web/src/application/use-cases/manage-invitations.ts b/apps/web/src/application/use-cases/manage-invitations.ts new file mode 100644 index 0000000..56b67c9 --- /dev/null +++ b/apps/web/src/application/use-cases/manage-invitations.ts @@ -0,0 +1,56 @@ +import { RESEND_AFTER_MINUTES } from "../../domain/participant/invitation"; +import type { EventRepository } from "../ports/event-repository"; +import type { NotificationPort } from "../ports/notification"; + +export interface InvitationResult { + sent: number; + failed: number; +} + +/** + * E-mails invitations: to one attendee (a resend), or to everyone on the + * roster never invited. Each attempt is recorded, so a failed delivery shows + * up on the roster instead of disappearing. + */ +export async function sendInvitations( + input: { eventId: string; eventName: string; organizationName: string; eventUrl: string; attendeeId?: string }, + dependencies: { events: EventRepository; notifications: NotificationPort } +): Promise { + const targets = await dependencies.events.invitationTargets(input.eventId, input.attendeeId ?? null, RESEND_AFTER_MINUTES); + if (input.attendeeId && !targets.length) { + throw new Error(`This attendee cannot be invited right now: they may have signed in already, been removed, or been invited in the last ${RESEND_AFTER_MINUTES} minutes.`); + } + const result: InvitationResult = { sent: 0, failed: 0 }; + for (const target of targets) { + try { + await dependencies.notifications.invitation({ + email: target.email, + name: target.name, + eventName: input.eventName, + organizationName: input.organizationName, + eventUrl: input.eventUrl, + }); + await dependencies.events.recordInvitation(input.eventId, target.attendee_id, null); + result.sent += 1; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + await dependencies.events.recordInvitation(input.eventId, target.attendee_id, message.slice(0, 300)); + result.failed += 1; + } + } + return result; +} + +/** + * Removes or restores one attendee's access. Removal takes effect on their + * next request (existing sessions included) and drops them from matching and + * everyone's results; their history stays for the organizer. + */ +export async function setAttendeeAccess( + input: { eventId: string; attendeeId: string; revoked: boolean }, + dependencies: { events: EventRepository } +): Promise { + if (!(await dependencies.events.setRevoked(input.eventId, input.attendeeId, input.revoked))) { + throw new Error("This attendee is not on the event roster"); + } +} diff --git a/apps/web/src/domain/participant/invitation.ts b/apps/web/src/domain/participant/invitation.ts new file mode 100644 index 0000000..93509cc --- /dev/null +++ b/apps/web/src/domain/participant/invitation.ts @@ -0,0 +1,32 @@ +/** + * Where an invited attendee stands for one event, as the organizer sees it. + * Removed overrides everything; otherwise the furthest step reached wins. + */ +export type InvitationState = "removed" | "complete" | "claimed" | "invited" | "failed" | "not_invited"; + +/** A resend for the same attendee is refused until this much time has passed. */ +export const RESEND_AFTER_MINUTES = 10; + +export interface InvitationFacts { + revokedAt: Date | null; + profileUpdatedAt: Date | null; + claimedAt: Date | null; + invitedAt: Date | null; + inviteError: string | null; +} + +export function invitationState(facts: InvitationFacts): InvitationState { + if (facts.revokedAt) return "removed"; + if (facts.profileUpdatedAt) return "complete"; + if (facts.claimedAt) return "claimed"; + if (facts.inviteError) return "failed"; + if (facts.invitedAt) return "invited"; + return "not_invited"; +} + +/** Whether the organizer can send this attendee an invitation now. */ +export function canInvite(facts: InvitationFacts, now = Date.now()): boolean { + const state = invitationState(facts); + if (state === "removed" || state === "claimed" || state === "complete") return false; + return !facts.invitedAt || now - facts.invitedAt.getTime() >= RESEND_AFTER_MINUTES * 60_000; +} diff --git a/apps/web/src/infrastructure/notifications/realtime.notifier.ts b/apps/web/src/infrastructure/notifications/realtime.notifier.ts index ab37a8f..b5ca8fa 100644 --- a/apps/web/src/infrastructure/notifications/realtime.notifier.ts +++ b/apps/web/src/infrastructure/notifications/realtime.notifier.ts @@ -1,7 +1,11 @@ -import { sendNotificationEmail } from "@match-maker/email"; +import { renderInvitationEmail, sendNotificationEmail } from "@match-maker/email"; import type { NotificationPort } from "../../application/ports/notification"; export class RealtimeNotifier implements NotificationPort { + async invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise { + await sendNotificationEmail({ to: input.email, ...renderInvitationEmail(input) }); + } + async introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise { const subject = `${input.requesterName} would like to meet at ${input.eventName}`; const text = `Hi ${input.recipientName},\n\n${input.requesterName} requested an introduction at ${input.eventName}. Sign in to Mr. Bridge to respond.`; diff --git a/apps/web/src/infrastructure/postgres/event.repo.ts b/apps/web/src/infrastructure/postgres/event.repo.ts index 821ebbf..cc1f2a7 100644 --- a/apps/web/src/infrastructure/postgres/event.repo.ts +++ b/apps/web/src/infrastructure/postgres/event.repo.ts @@ -37,6 +37,21 @@ export class PostgresEventRepository implements EventRepository { participantIds(eventId: string) { return events.participantIds(eventId); } + invitationTargets(eventId: string, attendeeId: string | null, resendAfterMinutes: number) { + return events.invitationTargets(eventId, attendeeId, resendAfterMinutes); + } + recordInvitation(eventId: string, attendeeId: string, error: string | null) { + return events.recordInvitation(eventId, attendeeId, error); + } + markClaimed(eventId: string, attendeeId: string) { + return events.markClaimed(eventId, attendeeId); + } + setRevoked(eventId: string, attendeeId: string, revoked: boolean) { + return events.setRevoked(eventId, attendeeId, revoked); + } + rosterState(eventId: string, attendeeId: string) { + return events.rosterState(eventId, attendeeId); + } async importRoster(eventId: string, records: Parameters[1]) { let upserted = 0; @@ -51,14 +66,20 @@ export class PostgresEventRepository implements EventRepository { async analytics(eventId: string) { const { rows } = await query<{ roster: string; + invited: string; + claimed: string; + removed: string; profiles: string; matches: string; pending_intros: string; accepted_intros: string; }>( `select - (select count(*) from event_participants where event_id = $1) as roster, - (select count(*) from event_participants where event_id = $1 and profile_updated_at is not null) as profiles, + (select count(*) from event_participants where event_id = $1 and revoked_at is null) as roster, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and invited_at is not null) as invited, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and claimed_at is not null) as claimed, + (select count(*) from event_participants where event_id = $1 and revoked_at is not null) as removed, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and profile_updated_at is not null) as profiles, (select count(*) from event_matches where event_id = $1) as matches, (select count(*) from intro_requests where event_id = $1 and status = 'pending') as pending_intros, (select count(*) from intro_requests where event_id = $1 and status = 'accepted') as accepted_intros`, @@ -66,6 +87,9 @@ export class PostgresEventRepository implements EventRepository { ); return { roster: Number(rows[0]?.roster ?? 0), + invited: Number(rows[0]?.invited ?? 0), + claimed: Number(rows[0]?.claimed ?? 0), + removed: Number(rows[0]?.removed ?? 0), profiles: Number(rows[0]?.profiles ?? 0), matches: Number(rows[0]?.matches ?? 0), pendingIntros: Number(rows[0]?.pending_intros ?? 0), diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index c93ed7a..54ce014 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -39,7 +39,7 @@ const PROFILE_FROM = `from event_participants p * join), visible, named, and with a saved event profile. Every results path — * fresh retrieval, cached ids, saved matches — applies this same rule. */ -export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null`; +export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null and p.revoked_at is null`; export class PostgresParticipantRepository implements ParticipantRepository { async findProfile(eventId: string, attendeeId: string): Promise { @@ -118,7 +118,9 @@ export class PostgresParticipantRepository implements ParticipantRepository { async hasEventAccess(eventId: string, attendeeId: string): Promise { const { rows } = await query<{ allowed: boolean }>( - `select exists(select 1 from event_participants where event_id = $1 and attendee_id = $2) as allowed`, + `select exists( + select 1 from event_participants where event_id = $1 and attendee_id = $2 and revoked_at is null + ) as allowed`, [eventId, attendeeId] ); return rows[0]?.allowed ?? false; diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts index e95b9fd..0259401 100644 --- a/apps/web/src/lib/auth.ts +++ b/apps/web/src/lib/auth.ts @@ -13,6 +13,7 @@ export async function requireParticipantEvent(eventSlug: string, returnPath?: st if (!event) notFound(); const registered = await container.participants.hasEventAccess(event.id, session.attendeeId); if (!registered) notFound(); + await container.events.markClaimed(event.id, session.attendeeId); if (action && !eventAllows(event.status, action)) redirect(`/e/${eventSlug}`); return { session, event, container }; } diff --git a/packages/db/migrations/0006_invitations.sql b/packages/db/migrations/0006_invitations.sql new file mode 100644 index 0000000..b5daed9 --- /dev/null +++ b/packages/db/migrations/0006_invitations.sql @@ -0,0 +1,18 @@ +-- Invited account lifecycle per event. +-- +-- The roster row is the invitation. These columns record whether the +-- invitation e-mail went out (and why it failed), when the attendee first +-- signed in to the event (claimed), and whether the organizer removed their +-- access. A revoked row keeps its history but grants nothing: no sign-in to +-- the event, no matching, no appearance in anyone's results. + +alter table event_participants add column if not exists invited_at timestamptz; +alter table event_participants add column if not exists invite_count integer not null default 0; +alter table event_participants add column if not exists invite_error text; +alter table event_participants add column if not exists claimed_at timestamptz; +alter table event_participants add column if not exists revoked_at timestamptz; + +-- Anyone who already saved a profile has evidently claimed their invitation. +update event_participants + set claimed_at = profile_updated_at + where claimed_at is null and profile_updated_at is not null; diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index 55e88db..a2023e2 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -113,7 +113,9 @@ export async function isOrganizer(eventId: string, attendeeId: string): Promise< export async function isParticipant(eventId: string, attendeeId: string): Promise { const { rows } = await query<{ allowed: boolean }>( - `select exists(select 1 from event_participants where event_id = $1 and attendee_id = $2) as allowed`, + `select exists( + select 1 from event_participants where event_id = $1 and attendee_id = $2 and revoked_at is null + ) as allowed`, [eventId, attendeeId] ); return rows[0]?.allowed ?? false; @@ -131,7 +133,8 @@ export async function hasOrganizationAccess(organizationSlug: string, attendeeId export async function participantIds(eventId: string): Promise { const { rows } = await query<{ attendee_id: string }>( - `select attendee_id from event_participants where event_id = $1 and profile_updated_at is not null`, [eventId] + `select attendee_id from event_participants + where event_id = $1 and profile_updated_at is not null and revoked_at is null`, [eventId] ); return rows.map((row) => row.attendee_id); } @@ -155,9 +158,76 @@ export async function roster(eventId: string): Promise { + const { rows } = await query( + `select a.id as attendee_id, a.email, a.name + from event_participants p join registered_attendees a on a.id = p.attendee_id + where p.event_id = $1 and p.revoked_at is null and p.claimed_at is null and a.email is not null + and ($2::uuid is null and p.invited_at is null + or a.id = $2::uuid and (p.invited_at is null or p.invited_at < now() - make_interval(mins => $3))) + order by a.name nulls last`, + [eventId, attendeeId, resendAfterMinutes] + ); + return rows; +} + +/** Records one delivery attempt; a failure keeps the last successful send time. */ +export async function recordInvitation(eventId: string, attendeeId: string, error: string | null): Promise { + await query( + `update event_participants + set invited_at = case when $3::text is null then now() else invited_at end, + invite_count = invite_count + case when $3::text is null then 1 else 0 end, + invite_error = $3, updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId, error] + ); +} + +/** The first signed-in visit to the event claims the invitation. */ +export async function markClaimed(eventId: string, attendeeId: string): Promise { + await query( + `update event_participants set claimed_at = now() + where event_id = $1 and attendee_id = $2 and claimed_at is null and revoked_at is null`, + [eventId, attendeeId] + ); +} + +/** Removes or restores an attendee's access; returns false when they are not on the roster. */ +export async function setRevoked(eventId: string, attendeeId: string, revoked: boolean): Promise { + const { rowCount } = await query( + `update event_participants + set revoked_at = case when $3 then coalesce(revoked_at, now()) else null end, updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId, revoked] + ); + return (rowCount ?? 0) > 0; +} + +/** Whether an attendee is on the roster, and if so whether access was removed. */ +export async function rosterState(eventId: string, attendeeId: string): Promise<"active" | "revoked" | null> { + const { rows } = await query<{ revoked: boolean }>( + `select revoked_at is not null as revoked from event_participants where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId] + ); + if (!rows[0]) return null; + return rows[0].revoked ? "revoked" : "active"; +} diff --git a/packages/email/src/index.ts b/packages/email/src/index.ts index c48847d..461b011 100644 --- a/packages/email/src/index.ts +++ b/packages/email/src/index.ts @@ -1,4 +1,5 @@ export { sendLoginEmail, sendNotificationEmail, type SendResult } from "./client"; +export { renderInvitationEmail, type InvitationEmailInput } from "./templates/invitation-email"; export { renderLoginEmail, type LoginEmailInput, diff --git a/packages/email/src/templates/invitation-email.ts b/packages/email/src/templates/invitation-email.ts new file mode 100644 index 0000000..e9f6384 --- /dev/null +++ b/packages/email/src/templates/invitation-email.ts @@ -0,0 +1,34 @@ +/** The invitation an organizer sends to everyone on an event roster. */ +export interface InvitationEmailInput { + name: string | null; + eventName: string; + organizationName: string; + /** The event page, where the attendee signs in and claims the invitation. */ + eventUrl: string; +} + +export function renderInvitationEmail(input: InvitationEmailInput): { subject: string; html: string; text: string } { + const greeting = input.name ? `Hi ${input.name},` : "Hi,"; + const subject = `You're invited to ${input.eventName} on Mr. Bridge`; + const text = [ + greeting, + "", + `${input.organizationName} added you to ${input.eventName}. Sign in with this e-mail address to claim your invitation, complete your profile, and see who you should meet.`, + "", + input.eventUrl, + "", + "If you did not expect this, you can ignore this e-mail.", + ].join("\n"); + const html = `
+

Mr. Bridge

+

${escapeHtml(greeting)}

+

${escapeHtml(input.organizationName)} added you to ${escapeHtml(input.eventName)}. Sign in with this e-mail address to claim your invitation, complete your profile, and see who you should meet.

+

Claim your invitation

+

If you did not expect this, you can ignore this e-mail.

+
`; + return { subject, html, text }; +} + +function escapeHtml(value: string): string { + return value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!); +} diff --git a/tests/integration/invitations.test.ts b/tests/integration/invitations.test.ts new file mode 100644 index 0000000..b48d3f5 --- /dev/null +++ b/tests/integration/invitations.test.ts @@ -0,0 +1,90 @@ +/** + * Invitation lifecycle against a real Postgres: who gets invited, claims, + * and what removing access takes away. Uses its own organization, event and + * attendees. Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { query, closePool, attendees, events } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const ORG = "integration-invitations"; +const KEYS = ["new", "invited", "claimed", "removed", "viewer"] as const; +const emailOf = (key: string) => `invite-${key}@example.com`; + +describeDb("invitation lifecycle", () => { + const participants = new PostgresParticipantRepository(); + let eventId: string; + let ids: Record; + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(KEYS.map((key) => ({ name: `Invite ${key}`, email: emailOf(key) }))); + const found = await attendees.findIdsByEmails(KEYS.map(emailOf)); + ids = Object.fromEntries(KEYS.map((key) => [key, found.find((row) => row.email === emailOf(key))!.id])); + const { rows: [org] } = await query<{ id: string }>( + `insert into organizations (name, slug) values ('Invitations', $1) + on conflict (slug) do update set name = excluded.name returning id`, [ORG]); + const { rows: [event] } = await query<{ id: string }>( + `insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open') + on conflict (organization_id, slug) do update set status = 'open' returning id`, [org.id, ORG]); + eventId = event.id; + await query(`delete from event_participants where event_id = $1`, [eventId]); + await events.attachRoster(eventId, Object.values(ids)); + await query( + `update event_participants set profile_updated_at = now(), designation = 'Engineer', domain = 'AI', about_me = 'Builds things' + where event_id = $1 and attendee_id = any($2::uuid[])`, [eventId, [ids.removed, ids.viewer]]); + await query(`update event_participants set invited_at = now() - interval '2 minutes', invite_count = 1 where event_id = $1 and attendee_id = $2`, [eventId, ids.invited]); + await events.markClaimed(eventId, ids.claimed); + await events.setRevoked(eventId, ids.removed, true); + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email = any($1::text[])`, [KEYS.map(emailOf)]); + await closePool(); + }); + + it("invites only people never invited, never claimed and not removed", async () => { + const targets = await events.invitationTargets(eventId, null, 10); + expect(targets.map((target) => target.email).sort()).toEqual([emailOf("new"), emailOf("viewer")]); + }); + + it("throttles a resend to the same person", async () => { + expect(await events.invitationTargets(eventId, ids.invited, 10)).toEqual([]); + expect(await events.invitationTargets(eventId, ids.invited, 1)).toHaveLength(1); + expect(await events.invitationTargets(eventId, ids.claimed, 0)).toEqual([]); + }); + + it("records a failure without pretending the e-mail went out", async () => { + await events.recordInvitation(eventId, ids.new, "Resend rejected the address"); + await events.recordInvitation(eventId, ids.invited, null); + const rows = await events.roster(eventId); + const byId = new Map(rows.map((row) => [row.id, row])); + expect(byId.get(ids.new)).toMatchObject({ invited_at: null, invite_count: 0, invite_error: "Resend rejected the address" }); + expect(byId.get(ids.invited)).toMatchObject({ invite_count: 2, invite_error: null }); + }); + + it("keeps the first claim time", async () => { + const before = (await events.roster(eventId)).find((row) => row.id === ids.claimed)!.claimed_at; + await events.markClaimed(eventId, ids.claimed); + expect((await events.roster(eventId)).find((row) => row.id === ids.claimed)!.claimed_at).toEqual(before); + }); + + it("removes every kind of access from a revoked attendee", async () => { + expect(await events.isParticipant(eventId, ids.removed)).toBe(false); + expect(await participants.hasEventAccess(eventId, ids.removed)).toBe(false); + expect(await events.participantIds(eventId)).not.toContain(ids.removed); + expect(await events.rosterState(eventId, ids.removed)).toBe("revoked"); + const candidates = await participants.findCandidatesByIds(eventId, [ids.removed, ids.viewer]); + expect(candidates.map((candidate) => candidate.attendeeId)).toEqual([ids.viewer]); + }); + + it("restores access explicitly, and re-importing does not do it silently", async () => { + await events.attachRoster(eventId, [ids.removed]); + expect(await events.rosterState(eventId, ids.removed)).toBe("revoked"); + await events.setRevoked(eventId, ids.removed, false); + expect(await participants.hasEventAccess(eventId, ids.removed)).toBe(true); + }); +}); diff --git a/tests/unit/invitations.test.ts b/tests/unit/invitations.test.ts new file mode 100644 index 0000000..6eb09e5 --- /dev/null +++ b/tests/unit/invitations.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from "vitest"; +import { canInvite, invitationState, RESEND_AFTER_MINUTES, type InvitationFacts } from "@/src/domain/participant/invitation"; +import { sendInvitations, setAttendeeAccess } from "@/src/application/use-cases/manage-invitations"; +import { renderInvitationEmail } from "@match-maker/email"; + +const NOW = Date.parse("2026-10-19T12:00:00Z"); +const facts = (overrides: Partial): InvitationFacts => ({ + revokedAt: null, profileUpdatedAt: null, claimedAt: null, invitedAt: null, inviteError: null, ...overrides, +}); +const at = (minutesAgo: number) => new Date(NOW - minutesAgo * 60_000); + +describe("invitationState", () => { + it.each([ + [facts({}), "not_invited"], + [facts({ invitedAt: at(1) }), "invited"], + [facts({ inviteError: "bounced" }), "failed"], + [facts({ invitedAt: at(5), claimedAt: at(1) }), "claimed"], + [facts({ claimedAt: at(5), profileUpdatedAt: at(1) }), "complete"], + [facts({ profileUpdatedAt: at(5), revokedAt: at(1) }), "removed"], + ] as const)("%o is %s", (input, state) => { + expect(invitationState(input)).toBe(state); + }); + + it("allows a resend only after the waiting period, and never after claiming or removal", () => { + expect(canInvite(facts({}), NOW)).toBe(true); + expect(canInvite(facts({ invitedAt: at(RESEND_AFTER_MINUTES - 1) }), NOW)).toBe(false); + expect(canInvite(facts({ invitedAt: at(RESEND_AFTER_MINUTES) }), NOW)).toBe(true); + expect(canInvite(facts({ claimedAt: at(1) }), NOW)).toBe(false); + expect(canInvite(facts({ revokedAt: at(1) }), NOW)).toBe(false); + }); +}); + +function ports(targets: Array<{ attendee_id: string; email: string; name: string | null }>, fail: string[] = []) { + const events = { + invitationTargets: vi.fn().mockResolvedValue(targets), + recordInvitation: vi.fn().mockResolvedValue(undefined), + setRevoked: vi.fn().mockResolvedValue(true), + }; + const notifications = { + invitation: vi.fn(async ({ email }: { email: string }) => { + if (fail.includes(email)) throw new Error("Resend rejected the address"); + }), + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { events: events as any, notifications: notifications as any, raw: { events, notifications } }; +} + +const event = { eventId: "event", eventName: "Summit", organizationName: "Acme", eventUrl: "https://bridge.example.com/e/summit" }; + +describe("sendInvitations", () => { + it("sends to every target and records successes and failures separately", async () => { + const { events, notifications, raw } = ports([ + { attendee_id: "a", email: "a@example.com", name: "A" }, + { attendee_id: "b", email: "bad@example.com", name: null }, + ], ["bad@example.com"]); + await expect(sendInvitations(event, { events, notifications })).resolves.toEqual({ sent: 1, failed: 1 }); + expect(raw.events.invitationTargets).toHaveBeenCalledWith("event", null, RESEND_AFTER_MINUTES); + expect(raw.events.recordInvitation).toHaveBeenCalledWith("event", "a", null); + expect(raw.events.recordInvitation).toHaveBeenCalledWith("event", "b", "Resend rejected the address"); + }); + + it("explains why a single resend is refused", async () => { + const { events, notifications } = ports([]); + await expect(sendInvitations({ ...event, attendeeId: "a" }, { events, notifications })).rejects.toThrow(/cannot be invited right now/); + }); +}); + +describe("setAttendeeAccess", () => { + it("refuses someone not on the roster", async () => { + const { events, raw } = ports([]); + raw.events.setRevoked.mockResolvedValue(false); + await expect(setAttendeeAccess({ eventId: "event", attendeeId: "x", revoked: true }, { events })).rejects.toThrow(/not on the event roster/); + }); +}); + +describe("renderInvitationEmail", () => { + it("links to the event and escapes names in the HTML", () => { + const mail = renderInvitationEmail({ name: "