⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(admin): audit administrators who sign in with a bearer token
Tina435fd3feda6
diff --git a/apps/api/src/admin/audit/capture-auth-admin-audit.ts b/apps/api/src/admin/audit/capture-auth-admin-audit.tsindex d65da94d3..dabc8312d 100644--- a/apps/api/src/admin/audit/capture-auth-admin-audit.ts+++ b/apps/api/src/admin/audit/capture-auth-admin-audit.ts@@ -1,4 +1,4 @@-import { getSessionFromCtx } from "better-auth/api";+import type { getSessionFromCtx } from "better-auth/api";import { eq } from "drizzle-orm";import db, { schema } from "../../database";import { readClientIp } from "../../utils/client-ip";@@ -7,6 +7,11 @@ import type { AuditUserSnapshot } from "./audit-user-snapshot";type AuthContext = Parameters<typeof getSessionFromCtx>[0];+/** Resolves the caller's session from request headers, bearer tokens included. */+export type ResolveAuditSession = (+ headers: Headers,+) => Promise<{ user: { id: string } } | null>;+/** better-auth admin endpoints that change something worth auditing. */export const AUDITED_AUTH_ADMIN_PATHS = new Set(["/admin/create-user",@@ -69,12 +74,14 @@ async function findSessionOwner(token: unknown) {* target looked like: deletions and updates change it before the after hook.* Calls without a session (server-side `auth.api.*` use) are not recorded here.*/-export async function captureAuthAdminAudit(ctx: AuthContext) {+export async function captureAuthAdminAudit(+ ctx: AuthContext,+ resolveSession: ResolveAuditSession,+) {if (!AUDITED_AUTH_ADMIN_PATHS.has(ctx.path)) return;- const session = await getSessionFromCtx(ctx, {- disableCookieCache: true,- disableRefresh: true,- });+ // Hooks here run before the bearer plugin turns a token into a cookie, so+ // the session is resolved through the full auth API to see bearer callers.+ const session = await resolveSession(new Headers(ctx.headers));if (!session) return;const body = ctx.body as Record<string, unknown> | undefined;diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 7bb72ebf8..5d74b4154 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -888,7 +888,9 @@ export const auth = betterAuth({await assertNativeOrganizationReadAllowed(ctx, organizationViewer);}// Before removal prep deletes account data the entry needs to name.- await captureAuthAdminAudit(ctx);+ await captureAuthAdminAudit(ctx, (headers) =>+ auth.api.getSession({ headers, query: { disableRefresh: true } }),+ );if (ctx.path === "/admin/remove-user") {await prepareAdminUserRemoval(ctx);}diff --git a/tests/api-integration/admin-audit-log-auth-actions.test.ts b/tests/api-integration/admin-audit-log-auth-actions.test.tsindex 2c9c32a05..04e4d3f6a 100644--- a/tests/api-integration/admin-audit-log-auth-actions.test.ts+++ b/tests/api-integration/admin-audit-log-auth-actions.test.ts@@ -138,6 +138,29 @@ describe("audit of better-auth admin endpoints", () => {expect(Date.parse(expiresAt)).toBeGreaterThan(Date.now() + 3_000_000);});+ it("records administrators who authenticate with a bearer token", async () => {+ const token = decodeURIComponent(+ admin.cookies.match(/session_token=([^;]+)/)?.[1] ?? "",+ );+ expect(token).not.toBe("");++ await expectOk(+ await call(+ "set-role",+ { userId: target.userId, role: "admin" },+ // The bearer token decides the session even next to another cookie.+ { authorization: `Bearer ${token}`, cookie: target.cookies },+ ),+ );++ const [row] = await readAuditLog();+ expect(row).toMatchObject({+ action: "user.role_changed",+ actorUserId: admin.userId,+ targetId: target.userId,+ });+ });+it("keeps the label of a deleted user", async () => {await expectOk(await asAdmin("remove-user", { userId: target.userId }));