diff --git a/packages/auth/src/lib/cached-jwks.ts b/packages/auth/src/lib/cached-jwks.ts new file mode 100644 index 00000000000..9a0ec5e07dd --- /dev/null +++ b/packages/auth/src/lib/cached-jwks.ts @@ -0,0 +1,50 @@ +import type { GenericEndpointContext } from "better-auth"; +import type { Jwk } from "better-auth/plugins/jwt"; + +/** + * The jwt plugin reads the whole `jwks` table every time it mints a token, and + * it mints one on every `/get-session` to set the `set-auth-jwt` header. That + * is a database round trip on every authenticated request in the product for a + * key set that only changes when a key is created. + * + * Disabling the header instead would be cheaper still, but the desktop and + * mobile clients read it opportunistically to refresh their token + * (apps/desktop/src/renderer/lib/auth-client.ts, apps/mobile/lib/auth/client.ts), + * so the header stays and the read gets cached. + * + * The TTL is short because the cost of being stale is real but bounded: a key + * created by another instance is absent from `/jwks` until the cache expires, + * so tokens signed with it fail verification until then. Creations go through + * `createJwk` below, which clears this instance's copy immediately. + */ +const JWKS_CACHE_TTL_MS = 60 * 1000; + +let cache: { keys: Jwk[]; fetchedAt: number } | null = null; + +export function jwksAdapter() { + return { + getJwks: async (ctx: GenericEndpointContext): Promise => { + if (cache && Date.now() - cache.fetchedAt < JWKS_CACHE_TTL_MS) { + return cache.keys; + } + + const keys = await ctx.context.adapter.findMany({ + model: "jwks", + }); + cache = { keys, fetchedAt: Date.now() }; + return keys; + }, + + createJwk: async ( + data: Omit, + ctx: GenericEndpointContext, + ): Promise => { + const created = await ctx.context.adapter.create, Jwk>({ + model: "jwks", + data: { ...data, createdAt: new Date() }, + }); + cache = null; + return created; + }, + }; +} diff --git a/packages/auth/src/lib/load-custom-session-data.ts b/packages/auth/src/lib/load-custom-session-data.ts new file mode 100644 index 00000000000..8e97e7c58ff --- /dev/null +++ b/packages/auth/src/lib/load-custom-session-data.ts @@ -0,0 +1,132 @@ +import { db } from "@superset/db/client"; +import type { SelectMember } from "@superset/db/schema/auth"; +import { ACTIVE_SUBSCRIPTION_STATUSES } from "@superset/shared/billing"; +import { sql } from "drizzle-orm"; + +/** + * Everything `customSession` needs, in one round trip. + * + * These were three sequential drizzle calls — memberships, then the active + * organization's subscription, then the user's own row. Neon speaks HTTP, so + * each call is its own request, and with the database in a different region to + * the functions that was ~220ms on every authenticated request in the product. + * Only the active-organization fallback made the order matter, and that is + * expressible in SQL, so the three collapse into one statement. + * + * Raw SQL rather than drizzle's query builder because the point is the single + * statement; expressing the fallback across three builder calls is what we are + * replacing. + */ +export interface CustomSessionData { + memberships: SelectMember[]; + /** + * The organization the plan below belongs to. A concurrent request can move + * the session's active organization between this query and the caller + * settling on one, so the caller compares before trusting `plan`. + */ + planOrganizationId: string | null; + plan: string | null; + onboardedAt: Date | null; + deletionRequestedAt: Date | null; +} + +interface CustomSessionRow extends Record { + memberships: Array<{ + id: string; + organizationId: string; + userId: string; + role: string; + createdAt: string; + }> | null; + active_organization_id: string | null; + plan: string | null; + onboarded_at: string | Date | null; + deletion_requested_at: string | Date | null; +} + +/** + * These are `timestamp` columns, so Postgres hands back a naive string with no + * zone. `new Date()` reads that as local time, which silently shifts every + * value by the server's offset; drizzle's own mapping treats it as UTC, so + * match that or the onboarding gate moves by hours depending on where the + * function ran. + */ +function toDate(value: string | Date | null): Date | null { + if (value === null) return null; + if (value instanceof Date) return value; + const normalized = value.replace(" ", "T"); + const hasZone = /(?:Z|[+-]\d{2}(?::?\d{2})?)$/.test(normalized); + return new Date(hasZone ? normalized : `${normalized}Z`); +} + +export async function loadCustomSessionData({ + userId, + activeOrganizationId, +}: { + userId: string; + activeOrganizationId: string | null; +}): Promise { + const statuses = sql.join( + ACTIVE_SUBSCRIPTION_STATUSES.map((status) => sql`${status}`), + sql`, `, + ); + + const result = await db.execute(sql` + WITH memberships AS ( + SELECT id, organization_id, user_id, role, created_at + FROM auth.members + WHERE user_id = ${userId}::uuid + ), + active AS ( + SELECT COALESCE( + (SELECT organization_id FROM memberships + WHERE organization_id = ${activeOrganizationId}::uuid LIMIT 1), + (SELECT organization_id FROM memberships + ORDER BY created_at DESC LIMIT 1) + ) AS organization_id + ) + SELECT + (SELECT COALESCE(json_agg(json_build_object( + 'id', id, + 'organizationId', organization_id, + 'userId', user_id, + 'role', role, + 'createdAt', created_at + ) ORDER BY created_at DESC), '[]'::json) + FROM memberships) AS memberships, + (SELECT organization_id FROM active) AS active_organization_id, + (SELECT s.plan FROM subscriptions s, active a + WHERE s.reference_id = a.organization_id + AND s.status IN (${statuses}) + LIMIT 1) AS plan, + u.onboarded_at, + u.deletion_requested_at + FROM auth.users u + WHERE u.id = ${userId}::uuid + `); + + const row = result.rows[0]; + if (!row) { + return { + memberships: [], + planOrganizationId: null, + plan: null, + onboardedAt: null, + deletionRequestedAt: null, + }; + } + + return { + memberships: (row.memberships ?? []).map((member) => ({ + id: member.id, + organizationId: member.organizationId, + userId: member.userId, + role: member.role, + createdAt: toDate(member.createdAt) ?? new Date(0), + })), + planOrganizationId: row.active_organization_id, + plan: row.plan, + onboardedAt: toDate(row.onboarded_at), + deletionRequestedAt: toDate(row.deletion_requested_at), + }; +} diff --git a/packages/auth/src/lib/resolve-session-organization-state.ts b/packages/auth/src/lib/resolve-session-organization-state.ts index 67baa797439..40b54190761 100644 --- a/packages/auth/src/lib/resolve-session-organization-state.ts +++ b/packages/auth/src/lib/resolve-session-organization-state.ts @@ -64,8 +64,9 @@ export async function resolveSessionOrganizationState( userId?: string | null; session?: SessionOrganizationContext | null; }, - deps: ResolveSessionOrganizationDeps = defaultResolveSessionOrganizationDeps, + overrides: Partial = {}, ) { + const deps = { ...defaultResolveSessionOrganizationDeps, ...overrides }; const previousActiveOrganizationId = session?.activeOrganizationId ?? null; let activeOrganizationId = previousActiveOrganizationId; if (!userId) { diff --git a/packages/auth/src/server.ts b/packages/auth/src/server.ts index 414938a6486..19b48dd69fb 100644 --- a/packages/auth/src/server.ts +++ b/packages/auth/src/server.ts @@ -33,7 +33,9 @@ import { and, asc, count, desc, eq, inArray, ne, sql } from "drizzle-orm"; import type Stripe from "stripe"; import { env } from "./env"; import { acceptInvitationEndpoint } from "./lib/accept-invitation-endpoint"; +import { jwksAdapter } from "./lib/cached-jwks"; import { generateMagicTokenForInvite } from "./lib/generate-magic-token"; +import { loadCustomSessionData } from "./lib/load-custom-session-data"; import { invitationRateLimit } from "./lib/rate-limit"; import { resend } from "./lib/resend"; import { @@ -305,6 +307,7 @@ export const auth = betterAuth({ jwks: { keyPairConfig: { alg: "RS256" }, }, + adapter: jwksAdapter(), jwt: { issuer: env.NEXT_PUBLIC_API_URL, audience: env.NEXT_PUBLIC_API_URL, @@ -872,22 +875,39 @@ export const auth = betterAuth({ customSession( async ({ user, session: baseSession }) => { const session = baseSession as typeof sessions.$inferSelect; + const userId = session.userId ?? user.id; + + // Memberships, the active organization's plan and the user's own + // flags in one statement. This runs on every authenticated request + // in the product, so each extra round trip here is a region-crossing + // hop the whole fleet pays for. + const data = await loadCustomSessionData({ + userId, + activeOrganizationId: session.activeOrganizationId ?? null, + }); + const { activeOrganizationId, allMemberships, membership } = - await resolveSessionOrganizationState({ - userId: session.userId ?? user.id, - session, - }); + await resolveSessionOrganizationState( + { userId, session }, + { listMemberships: async () => data.memberships }, + ); const organizationIds = [ ...new Set(allMemberships.map((m) => m.organizationId)), ]; + // Same statuses the rest of the app gates on — this is the value + // the paywall falls back to when the activePlan query can't be + // reached, so an "active"-only read here would strand trialing + // and past_due organizations on a cold start. let plan: string | null = null; - if (activeOrganizationId) { - // Same statuses the rest of the app gates on — this is the value - // the paywall falls back to when the activePlan query can't be - // reached, so an "active"-only read here would strand trialing - // and past_due orgs on a cold start. + if (activeOrganizationId === data.planOrganizationId) { + plan = data.plan; + } else if (activeOrganizationId) { + // A concurrent request moved the session's active organization + // after the query above ran, so the plan it found belongs to the + // wrong one. Rare enough to be worth a second read rather than + // serialising the common path behind it. const subscription = await db.query.subscriptions.findFirst({ where: and( eq(subscriptions.referenceId, activeOrganizationId), @@ -897,19 +917,11 @@ export const auth = betterAuth({ plan = subscription?.plan ?? null; } - // additionalFields declares onboardedAt for client typing, but the - // drizzle adapter doesn't surface it on the passed-in user — read it - // explicitly so the onboarding gate is deterministic. - const userRow = await db.query.users.findFirst({ - where: eq(authSchema.users.id, user.id), - columns: { onboardedAt: true, deletionRequestedAt: true }, - }); - return { user: { ...user, - onboardedAt: userRow?.onboardedAt ?? null, - deletionRequestedAt: userRow?.deletionRequestedAt ?? null, + onboardedAt: data.onboardedAt, + deletionRequestedAt: data.deletionRequestedAt, }, session: { ...session,