Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

perf(auth): resolve the session once per request and stop signing unused session JWTs (#1312)

Goldflagd61502e022b4
diff --git a/server/src/lib/auth-utils.test.ts b/server/src/lib/auth-utils.test.ts
index 4fc3aecfb..144feec7b 100644
--- a/server/src/lib/auth-utils.test.ts
+++ b/server/src/lib/auth-utils.test.ts
@@ -1,5 +1,5 @@
import { eq } from "drizzle-orm";
-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
// Better-auth pulls in email, stripe, and env config at import time — stub the
// session API so getIsUserAdmin sees no session and auth never initializes.
@@ -48,6 +48,8 @@ import { member, memberSiteAccess, sites, team, teamMember, teamSiteAccess } fro
import { auth } from "./auth.js";
import {
checkApiKey,
+ getIsUserAdmin,
+ getSessionFromReq,
getSitesUserHasAccessTo,
getUserHasAccessToSite,
getUserHasAdminAccessToSite,
@@ -154,6 +156,10 @@ CREATE TABLE "sites" (
"detected_platform" text,
"claim_expires_at" timestamp
);
+CREATE TABLE "user" (
+ "id" text PRIMARY KEY,
+ "role" text
+);
`;
const ORG = "org_1";
@@ -848,15 +854,13 @@ describe("getOrganizationSitesForCaller", () => {
domain: "other.example.com",
organizationId: "org_other",
});
- await db
- .insert(member)
- .values({
- id: "m_owner_other",
- organizationId: "org_other",
- userId: "user_owner",
- role: "owner",
- createdAt: NOW,
- });
+ await db.insert(member).values({
+ id: "m_owner_other",
+ organizationId: "org_other",
+ userId: "user_owner",
+ role: "owner",
+ createdAt: NOW,
+ });
const peerSites = await getOrganizationSitesForCaller(reqFor("user_peer"), ORG);
expect(peerSites.map(site => site.siteId).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13]);
@@ -1031,3 +1035,72 @@ it("refreshes cached session access after another worker claims a site", async (
expect(await getUserHasAccessToSite(reqFor("user_owner"), 99)).toBe(true);
expect(await getUserHasAdminAccessToSite(reqFor("user_owner"), 99)).toBe(true);
});
+
+describe("getSessionFromReq — per-request memo", () => {
+ const getSession = vi.mocked(auth.api.getSession);
+ const cookieRequest = () => ({ headers: { cookie: "better-auth.session_token=t" } }) as any;
+ const sessionFor = (userId: string) => ({ user: { id: userId }, session: { id: `s_${userId}` } }) as any;
+
+ beforeEach(async () => {
+ getSession.mockReset();
+ await (sql as any).exec(`TRUNCATE "user"`);
+ });
+
+ afterEach(() => {
+ getSession.mockReset();
+ getSession.mockImplementation(async () => null);
+ });
+
+ it("looks the session up once per request, null included", async () => {
+ getSession.mockResolvedValue(null);
+ const req = cookieRequest();
+ expect(await getSessionFromReq(req)).toBeNull();
+ expect(await getSessionFromReq(req)).toBeNull();
+ expect(await getUserIdFromRequest(req)).toBeNull();
+ expect(getSession).toHaveBeenCalledTimes(1);
+ });
+
+ it("shares one in-flight lookup between concurrent callers", async () => {
+ let resolve!: (value: unknown) => void;
+ getSession.mockImplementation(() => new Promise(r => (resolve = r)) as any);
+ const req = cookieRequest();
+ const pending = Promise.all([getSessionFromReq(req), getSessionFromReq(req), getSessionFromReq(req)]);
+ resolve(sessionFor("u1"));
+ const results = await pending;
+ expect(getSession).toHaveBeenCalledTimes(1);
+ expect(results.map(result => result?.user.id)).toEqual(["u1", "u1", "u1"]);
+ });
+
+ it("resolves each request on its own", async () => {
+ getSession.mockResolvedValueOnce(sessionFor("u1")).mockResolvedValueOnce(sessionFor("u2"));
+ expect((await getSessionFromReq(cookieRequest()))?.user.id).toBe("u1");
+ expect((await getSessionFromReq(cookieRequest()))?.user.id).toBe("u2");
+ expect(getSession).toHaveBeenCalledTimes(2);
+ });
+
+ it("retries after a failed lookup instead of caching the error", async () => {
+ getSession.mockRejectedValueOnce(new Error("db down")).mockResolvedValueOnce(sessionFor("u1"));
+ const req = cookieRequest();
+ await expect(getSessionFromReq(req)).rejects.toThrow("db down");
+ expect((await getSessionFromReq(req))?.user.id).toBe("u1");
+ expect(getSession).toHaveBeenCalledTimes(2);
+ });
+
+ it("decides system admin once per request, from the current role", async () => {
+ await (sql as any).exec(`INSERT INTO "user" ("id", "role") VALUES ('u_admin', 'admin')`);
+ getSession.mockResolvedValue(sessionFor("u_admin"));
+ const req = cookieRequest();
+ expect(await getIsUserAdmin(req)).toBe(true);
+
+ // The same request keeps its decision; the next request sees the demotion.
+ await (sql as any).exec(`UPDATE "user" SET "role" = 'user' WHERE "id" = 'u_admin'`);
+ expect(await getIsUserAdmin(req)).toBe(true);
+ expect(await getIsUserAdmin(cookieRequest())).toBe(false);
+ expect(getSession).toHaveBeenCalledTimes(2);
+ });
+
+ it("is never admin without a session", async () => {
+ getSession.mockResolvedValue(null);
+ expect(await getIsUserAdmin(cookieRequest())).toBe(false);
+ });
+});
diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.ts
index 553b2d85d..c32b9446b 100644
--- a/server/src/lib/auth-utils.ts
+++ b/server/src/lib/auth-utils.ts
@@ -104,22 +104,59 @@ export function mapHeaders(headers: any) {
return map;
}
-export async function getSessionFromReq(req: FastifyRequest) {
+type RequestSession = Awaited<ReturnType<typeof auth.api.getSession>>;
+
+// A guard and its handler resolve the session several times per request (role
+// lookup, then attaching the user, then the system-admin check), and each
+// resolution reads the session and its user from Postgres. The cookie can't
+// change within a request, so the lookup is shared per request object,
+// including a null result and concurrent callers. A failed lookup is dropped
+// so a later caller retries instead of inheriting the error.
+const requestSessions = new WeakMap<FastifyRequest, Promise<RequestSession>>();
+
+export function getSessionFromReq(req: FastifyRequest): Promise<RequestSession> {
+ const memoized = requestSessions.get(req);
+ if (memoized) {
+ return memoized;
+ }
const headers = new Headers(req.headers as any);
- const session = await auth!.api.getSession({ headers });
- return session;
+ const promise = auth!.api.getSession({ headers });
+ requestSessions.set(req, promise);
+ promise.catch(() => {
+ if (requestSessions.get(req) === promise) {
+ requestSessions.delete(req);
+ }
+ });
+ return promise;
}
-export async function getIsUserAdmin(req: FastifyRequest) {
- const session = await getSessionFromReq(req);
- const userId = session?.user.id;
+// Shared per request like the session it derives from: one guard can ask
+// several times (site list, site role, org role).
+const requestIsAdmin = new WeakMap<FastifyRequest, Promise<boolean>>();
- if (!userId) {
- return false;
+export function getIsUserAdmin(req: FastifyRequest): Promise<boolean> {
+ const memoized = requestIsAdmin.get(req);
+ if (memoized) {
+ return memoized;
}
+ const promise = (async () => {
+ const session = await getSessionFromReq(req);
+ const userId = session?.user.id;
- const userRecord = await db.select({ role: user.role }).from(user).where(eq(user.id, userId)).limit(1);
- return userRecord.length > 0 && userRecord[0].role === "admin";
+ if (!userId) {
+ return false;
+ }
+
+ const userRecord = await db.select({ role: user.role }).from(user).where(eq(user.id, userId)).limit(1);
+ return userRecord.length > 0 && userRecord[0].role === "admin";
+ })();
+ requestIsAdmin.set(req, promise);
+ promise.catch(() => {
+ if (requestIsAdmin.get(req) === promise) {
+ requestIsAdmin.delete(req);
+ }
+ });
+ return promise;
}
const sitesAccessCache = new NodeCache({
diff --git a/server/src/lib/oauth.ts b/server/src/lib/oauth.ts
index 0bf00bd75..ee1f4772e 100644
--- a/server/src/lib/oauth.ts
+++ b/server/src/lib/oauth.ts
@@ -55,7 +55,11 @@ export function createOAuthPlugins(baseUrl: string) {
return [
// Non-TLS LAN self-hosting still supports password sessions and API keys.
// Better Auth 1.7 requires HTTPS (or loopback) for an OAuth resource.
- ...(supportsOAuth ? [jwt(), mcp(options)] : []),
+ // The JWT plugin is here for OAuth token signing and JWKS only. Without
+ // disableSettingJwtHeader it also signs a session JWT into a set-auth-jwt
+ // header on every getSession, including the server-side lookups behind
+ // each authenticated request, and nothing reads that header.
+ ...(supportsOAuth ? [jwt({ disableSettingJwtHeader: true }), mcp(options)] : []),
{
id: "rybbit-oauth",
hooks: {