fix(auth) : keep Guide sessions beyond Sudloh token expiry
CI / Verify (push) Successful in 1m31s
CI / Build immutable images and deploy (push) Successful in 2m16s

This commit is contained in:
2026-10-06 18:00:42 +07:00 Unverified
parent 41014ef654
commit 4b16941e11
14 changed files with 74 additions and 236 deletions
+6 -17
View File
@@ -1,22 +1,16 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import { betterAuth } from "better-auth";
import { memoryAdapter } from "better-auth/adapters/memory";
import { genericOAuth } from "better-auth/plugins";
import { isSudlohCallback } from "./sudloh-callback";
const origin = "https://guide.test";
function createReplica(database: Record<string, Record<string, unknown>[]>, onSession: (sessionId: string) => void) {
function createReplica(database: Record<string, Record<string, unknown>[]>) {
return betterAuth({
baseURL: origin,
secret: "a-shared-test-secret-with-enough-entropy-123",
database: memoryAdapter(database),
rateLimit: { enabled: false },
databaseHooks: { session: { create: { after: async (
session: { id: string }, context: { path: string; params?: { id?: string } } | null,
) => {
if (isSudlohCallback(context)) onSession(session.id);
} } } },
plugins: [genericOAuth({ config: [{
providerId: "sudloh",
clientId: "test-client",
@@ -31,11 +25,10 @@ function createReplica(database: Record<string, Record<string, unknown>[]>, onSe
}
describe("Sudloh OAuth callback", () => {
it("completes across replicas, binds the Guide session, and consumes state once", async () => {
it("completes across replicas, creates the Guide session, and consumes state once", async () => {
const database = { user: [], session: [], account: [], verification: [] };
const bind = vi.fn();
const first = createReplica(database, bind);
const second = createReplica(database, bind);
const first = createReplica(database);
const second = createReplica(database);
const start = await first.handler(new Request(`${origin}/api/auth/sign-in/social`, {
method: "POST", headers: { Origin: origin, "Content-Type": "application/json" },
body: JSON.stringify({ provider: "sudloh", callbackURL: "/profile" }),
@@ -54,7 +47,6 @@ describe("Sudloh OAuth callback", () => {
}));
expect(callback.status).toBe(302);
expect(callback.headers.get("location")).toBe("/profile");
expect(bind).toHaveBeenCalledOnce();
const sessionCookie = callback.headers.getSetCookie()
.find((cookie) => cookie.includes("session_token="))?.split(";", 1)[0];
const session = await second.api.getSession({ headers: new Headers({ Cookie: sessionCookie! }) });
@@ -63,15 +55,12 @@ describe("Sudloh OAuth callback", () => {
headers: { Cookie: stateCookie! },
}));
expect(replay.headers.get("location")).toContain("state_mismatch");
expect(bind).toHaveBeenCalledOnce();
});
it("rejects a callback without state before exchanging a code", async () => {
const bind = vi.fn();
const auth = createReplica({ user: [], session: [], account: [], verification: [] }, bind);
const auth = createReplica({ user: [], session: [], account: [], verification: [] });
const response = await auth.handler(new Request(`${origin}/api/auth/callback/sudloh?code=test-code`));
expect(response.status).toBe(302);
expect(response.headers.get("location")).toContain("state_not_found");
expect(bind).not.toHaveBeenCalled();
});
});
+4 -15
View File
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = { session: vi.fn(), auth: vi.fn() };
const sudloh = { bind: vi.fn(), validate: vi.fn() };
vi.mock("server-only", () => ({}));
vi.mock("@/db", () => ({ getDb: () => ({}) }));
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
@@ -11,7 +10,6 @@ vi.mock("better-auth/next-js", () => ({ nextCookies: () => ({}) }));
vi.mock("better-auth/plugins", () => ({ admin: (options: unknown) => options, captcha: () => ({}),
genericOAuth: (options: unknown) => ({ id: "generic-oauth", options }),
emailOTP: (options: unknown) => ({ id: "email-otp", options }) }));
vi.mock("./sudloh", () => ({ bindSudlohSession: sudloh.bind, validateSudlohSession: sudloh.validate }));
const envNames = ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_URL", "BETTER_AUTH_SECRET", "BUZZ_DEMO_MODE", "RESEND_API_KEY", "SUDLOH_OIDC_CLIENT_ID", "SUDLOH_OIDC_CLIENT_SECRET", "SUDLOH_OIDC_REDIRECT_URI", "SUDLOH_OIDC_ISSUER", "SUDLOH_OIDC_ONLY", "TRUSTED_CLIENT_IP_HEADER"] as const;
const testEnv = process.env as Record<string, string | undefined>;
@@ -25,8 +23,6 @@ beforeEach(() => {
testEnv.BETTER_AUTH_SECRET = "a-test-secret-with-more-than-32-characters";
mocks.auth.mockReturnValue({ api: { getSession: mocks.session } });
mocks.session.mockResolvedValue(null);
sudloh.bind.mockReset();
sudloh.validate.mockReset().mockResolvedValue(true);
delete testEnv.SUDLOH_OIDC_CLIENT_ID;
delete testEnv.SUDLOH_OIDC_CLIENT_SECRET;
delete testEnv.SUDLOH_OIDC_REDIRECT_URI;
@@ -98,25 +94,18 @@ describe("actual administrator session boundary", () => {
expect(options.advanced.ipAddress.ipAddressHeaders).toEqual(["x-forwarded-for"]);
expect(options.emailAndPassword).toMatchObject({ enabled: false, disableSignUp: true });
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(false);
await options.databaseHooks.session.create.after({ id: "guide-session", userId: "user-1" },
{ path: "/callback/:id", params: { id: "sudloh" } });
expect(sudloh.bind).toHaveBeenCalledWith("user-1", "guide-session");
sudloh.bind.mockClear();
await options.databaseHooks.session.create.after({ id: "other-session", userId: "user-1" },
{ path: "/callback/:id", params: { id: "other" } });
expect(sudloh.bind).not.toHaveBeenCalled();
expect(options.databaseHooks).toBeUndefined();
});
it("denies a revoked Sudloh session", async () => {
it("keeps the local Guide session after the Sudloh access token expires", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
testEnv.SUDLOH_OIDC_ONLY = "true";
mocks.session.mockResolvedValue({ user: { id: "user-1", email: "[email protected]",
emailVerified: true, role: "admin" }, session: { id: "guide-session" } });
sudloh.validate.mockResolvedValue(false);
const { getAdminSession, getCustomerSession } = await import("./server");
expect(await getCustomerSession()).toBeNull();
expect(await getAdminSession()).toBeNull();
expect(await getCustomerSession()).toMatchObject({ user: { id: "user-1" } });
expect(await getAdminSession()).toMatchObject({ user: { id: "user-1" } });
});
it("rejects incomplete or mismatched Sudloh client configuration", async () => {
const { getAuth, isSudlohOidcEnabled } = await import("./server");
-11
View File
@@ -19,8 +19,6 @@ import { isAuthorizedAdmin, type SessionUserLike } from "./authorization";
import { HttpError } from "@/lib/security/http";
import { consumeRateLimit } from "@/lib/security/rate-limit";
import { sendAuthEmail } from "./email";
import { bindSudlohSession, validateSudlohSession } from "./sudloh";
import { isSudlohCallback } from "./sudloh-callback";
function required(name: string): string {
const value = process.env[name];
@@ -65,13 +63,6 @@ function createAuth() {
},
transaction: true,
}),
...(oidcOnly ? { databaseHooks: { session: { create: { after: async (
session: { id: string; userId: string },
context: { path: string; params?: { id?: string } } | null,
) => {
if (isSudlohCallback(context))
await bindSudlohSession(session.userId, session.id);
} } } } } : {}),
baseURL: required("BETTER_AUTH_URL"),
trustedOrigins: process.env.BETTER_AUTH_TRUSTED_ORIGINS
?.split(",")
@@ -173,8 +164,6 @@ export const getVerifiedSession = cache(async () => {
if (!hasAuthConfiguration()) return null;
const session = await getAuth().api.getSession({ headers: await headers() });
if (!session?.session) return null;
if (isSudlohOidcEnabled() && process.env.SUDLOH_OIDC_ONLY === "true" &&
!await validateSudlohSession(session.user.id, session.session.id)) return null;
return session;
});
-3
View File
@@ -1,3 +0,0 @@
export function isSudlohCallback(context: { path: string; params?: { id?: string } } | null): boolean {
return context?.path === "/callback/:id" && context.params?.id === "sudloh";
}
+16 -46
View File
@@ -1,29 +1,20 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const rows: unknown[][] = [];
const values = new Map<string, string>();
const set = vi.fn(async (key: string, value: string) => { values.set(key, value); });
const removeSession = vi.fn(async () => undefined);
const updateUser = vi.fn(async () => undefined);
const redis = { get: vi.fn(async (key: string) => values.get(key) ?? null), set };
vi.mock("server-only", () => ({}));
vi.mock("@/db", () => ({ getDb: () => ({
select: () => ({ from: () => ({ where: () => ({ limit: async () => rows.shift() ?? [] }) }) }),
update: () => ({ set: () => ({ where: updateUser }) }),
delete: () => ({ where: removeSession }),
}) }));
vi.mock("@/lib/redis/client", () => ({
getRedisClient: async () => redis, redisCachePrefix: () => "test",
}));
const { bindSudlohSession, refreshLinkedSudlohProfile, validateSudlohSession } = await import("./sudloh");
const expiresAt = new Date(Date.now() + 60 * 60_000);
const account = { id: "account-1", accountId: "sub-1", accessToken: "access-1", accessTokenExpiresAt: expiresAt };
const { refreshLinkedSudlohProfile } = await import("./sudloh");
const account = { accountId: "sub-1", accessToken: "access-1",
accessTokenExpiresAt: new Date(Date.now() + 60 * 60_000) };
beforeEach(() => {
rows.length = 0;
values.clear();
vi.clearAllMocks();
process.env.SUDLOH_OIDC_ISSUER = "https://account.test/api/auth";
process.env.SUDLOH_OIDC_CLIENT_ID = "client";
@@ -31,7 +22,7 @@ beforeEach(() => {
});
function provider(active: boolean, profileSub = "sub-1") {
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
return vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
const url = String(input);
if (url.endsWith("openid-configuration")) return Response.json({
issuer: "https://account.test/api/auth",
@@ -44,63 +35,42 @@ function provider(active: boolean, profileSub = "sub-1") {
email: "[email protected]", email_verified: true, picture: "https://account.test/avatar.png" });
throw new Error(`unexpected URL: ${url}`);
});
return fetchMock;
}
describe("Sudloh session validation", () => {
it("rejects a new Guide session when the callback did not bind it", async () => {
rows.push([account]);
expect(await validateSudlohSession("user-1", "session-1")).toBe(false);
expect(removeSession).toHaveBeenCalledOnce();
describe("Sudloh profile refresh", () => {
it("requires a new Sudloh sign-in after the access token expires", async () => {
rows.push([{ ...account, accessTokenExpiresAt: new Date(Date.now() - 1000) }]);
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 401, message: "sudloh-sign-in-required" });
});
it("binds the callback token to its Guide session and caches a verified check", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
expect(await validateSudlohSession("user-1", "session-1")).toBe(true);
expect(updateUser).toHaveBeenCalledOnce();
const fetchCount = fetchMock.mock.calls.length;
rows.push([account]);
expect(await validateSudlohSession("user-1", "session-1")).toBe(true);
expect(fetchMock).toHaveBeenCalledTimes(fetchCount);
fetchMock.mockRestore();
});
it("ends the Guide session when Sudloh reports the bound token inactive", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
it("requires a new Sudloh sign-in when the token is revoked", async () => {
const fetchMock = provider(false);
rows.push([account]);
expect(await validateSudlohSession("user-1", "session-1")).toBe(false);
expect(removeSession).toHaveBeenCalledOnce();
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 401, message: "sudloh-sign-in-required" });
fetchMock.mockRestore();
});
it("fails closed when UserInfo returns another subject", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
it("rejects UserInfo for another subject", async () => {
const fetchMock = provider(true, "someone-else");
rows.push([account]);
await expect(validateSudlohSession("user-1", "session-1"))
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 503 });
expect(updateUser).not.toHaveBeenCalled();
fetchMock.mockRestore();
});
it("reports a verified Sudloh email that conflicts with another Guide account", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
updateUser.mockRejectedValueOnce({ cause: { code: "23505" } });
await expect(validateSudlohSession("user-1", "session-1"))
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 409, message: "sudloh-email-conflict" });
fetchMock.mockRestore();
});
it("refreshes a linked profile during the legacy sign-in transition", async () => {
it("updates a linked profile while its token is active", async () => {
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
await refreshLinkedSudlohProfile("user-1");
+3 -57
View File
@@ -1,19 +1,16 @@
import "server-only";
import { createHash } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { getDb } from "@/db";
import { accounts, sessions, users } from "@/db/schema";
import { getRedisClient, redisCachePrefix } from "@/lib/redis/client";
import { accounts, users } from "@/db/schema";
import { HttpError } from "@/lib/security/http";
const CHECK_SECONDS = 300;
const ACCOUNT_SETTINGS_URL = "https://account.sudloh.com/account";
export { ACCOUNT_SETTINGS_URL };
type Endpoints = { issuer: string; userinfo_endpoint: string; introspection_endpoint: string };
type BoundToken = { token: string; accountId: string; expiresAt: string };
type BoundToken = { token: string; accountId: string };
let discovery: { endpoints: Endpoints; until: number } | undefined;
@@ -80,10 +77,6 @@ async function introspect(account: BoundToken): Promise<boolean> {
return true;
}
function bindingKey(sessionId: string) {
return `${redisCachePrefix()}:sudloh:session:${sessionId}`;
}
async function updateProfile(userId: string, token: BoundToken): Promise<boolean> {
const profile = await userInfo(token);
const [current] = await getDb().select({ name: users.name, email: users.email,
@@ -111,54 +104,7 @@ export async function refreshLinkedSudlohProfile(userId: string): Promise<void>
)).limit(1);
if (!account?.accessToken || !account.accessTokenExpiresAt ||
account.accessTokenExpiresAt.getTime() <= Date.now()) throw new HttpError(401, "sudloh-sign-in-required");
const token: BoundToken = { token: account.accessToken, accountId: account.accountId,
expiresAt: account.accessTokenExpiresAt.toISOString() };
const token: BoundToken = { token: account.accessToken, accountId: account.accountId };
if (!await introspect(token)) throw new HttpError(401, "sudloh-sign-in-required");
if (!await updateProfile(userId, token)) throw new HttpError(401, "unauthorized");
}
export async function bindSudlohSession(userId: string, sessionId: string): Promise<void> {
const [account] = await getDb().select().from(accounts).where(and(
eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"),
)).limit(1);
if (!account?.accessToken || !account.accessTokenExpiresAt) throw new HttpError(503, "sudloh-token-missing");
const seconds = Math.floor((account.accessTokenExpiresAt.getTime() - Date.now()) / 1000);
if (seconds <= 0) throw new HttpError(503, "sudloh-token-expired");
const bound: BoundToken = { token: account.accessToken, accountId: account.accountId,
expiresAt: account.accessTokenExpiresAt.toISOString() };
await (await getRedisClient()).set(bindingKey(sessionId), JSON.stringify(bound), "EX", seconds);
}
export async function validateSudlohSession(userId: string, sessionId: string, force = false): Promise<boolean> {
const [account] = await getDb().select({ id: accounts.id, accountId: accounts.accountId })
.from(accounts).where(and(eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"))).limit(1);
const invalidate = async () => {
await getDb().delete(sessions).where(eq(sessions.id, sessionId));
return false;
};
if (!account) return invalidate();
const redis = await getRedisClient().catch(() => null);
if (!redis) throw new HttpError(503, "sudloh-check-unavailable");
const raw = await redis.get(bindingKey(sessionId)).catch(() => { throw new HttpError(503, "sudloh-check-unavailable"); });
if (!raw) return invalidate();
let bound: BoundToken;
try { bound = JSON.parse(raw) as BoundToken; }
catch { throw new HttpError(503, "sudloh-check-unavailable"); }
if (bound.accountId !== account.accountId || !bound.token ||
!Number.isFinite(Date.parse(bound.expiresAt)) || Date.parse(bound.expiresAt) <= Date.now()) return invalidate();
const digest = createHash("sha256").update(bound.token).digest("hex");
const key = `${redisCachePrefix()}:sudloh:active:${sessionId}:${digest}`;
if (!force && await redis.get(key).catch(() => null) === "1") return true;
try {
if (!await introspect(bound)) return invalidate();
if (!await updateProfile(userId, bound)) return invalidate();
const remaining = Math.floor((Date.parse(bound.expiresAt) - Date.now()) / 1000);
if (remaining > 0) await redis.set(key, "1", "EX", Math.min(CHECK_SECONDS, remaining)).catch(() => undefined);
return true;
} catch (cause) {
if (cause instanceof HttpError) throw cause;
throw new HttpError(503, "sudloh-unavailable");
}
}