⚡ 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(auth): prevent role changes from removing the last admin (#1733)
Tin Sever2f24f2d4634f
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 4bcb1a91e..ed5f82977 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -15,7 +15,6 @@ import {} from "@kaneo/permissions";import bcrypt from "bcryptjs";import { betterAuth } from "better-auth";-import { drizzleAdapter } from "better-auth/adapters/drizzle";import {APIError,createAuthMiddleware,@@ -43,6 +42,7 @@ import {} from "./billing/controllers/find-billable-workspaces";import { syncWorkspaceSeats } from "./billing/controllers/sync-seats";import db, { schema } from "./database";+import { authDatabaseAdapter } from "./database/auth-adapter";import { publishEvent } from "./events";import deleteAccountData from "./user/controllers/delete-account-data";import { resolveAuthSecret } from "./utils/auth-secret";@@ -187,7 +187,7 @@ export const auth = betterAuth({trustedOrigins,secret: authSecret,basePath: "/api/auth",- database: drizzleAdapter(db, {+ database: authDatabaseAdapter({provider: "pg",schema: {...schema,@@ -573,6 +573,21 @@ export const auth = betterAuth({},databaseHooks: {user: {+ update: {+ before: async (user, ctx) => {+ if (+ (ctx?.path === "/admin/set-role" ||+ ctx?.path === "/admin/update-user") &&+ Object.hasOwn(user, "role") &&+ ctx.body?.userId === ctx.context.session?.user.id+ ) {+ throw new APIError("BAD_REQUEST", {+ code: "YOU_CANNOT_CHANGE_YOUR_OWN_ROLE",+ message: "You cannot change your own role.",+ });+ }+ },+ },create: {before: async (user, ctx) => {await assertUserRegistrationAllowed(diff --git a/apps/api/src/database/auth-adapter.ts b/apps/api/src/database/auth-adapter.tsnew file mode 100644index 000000000..5bece4faa--- /dev/null+++ b/apps/api/src/database/auth-adapter.ts@@ -0,0 +1,59 @@+import type { BetterAuthOptions } from "better-auth";+import type { DBAdapter } from "better-auth/adapters";+import {+ type DrizzleAdapterConfig,+ drizzleAdapter,+} from "better-auth/adapters/drizzle";+import { APIError } from "better-auth/api";+import { count, sql } from "drizzle-orm";+import db, { schema } from ".";++function isAdmin(role: unknown) {+ return typeof role === "string" && role.split(",").includes("admin");+}++export function authDatabaseAdapter(config: DrizzleAdapterConfig) {+ return (options: BetterAuthOptions): DBAdapter => {+ const adapter = drizzleAdapter(db, config)(options);+ return {+ ...adapter,+ async update<T>(data: Parameters<DBAdapter["update"]>[0]) {+ if (+ data.model !== "user" ||+ !Object.hasOwn(data.update, "role") ||+ isAdmin(data.update.role)+ ) {+ return adapter.update<T>(data);+ }++ return db.transaction(async (tx) => {+ // Serialize role removals across API instances, keeping the count+ // and write in the same transaction so cross-demotions cannot race.+ await tx.execute(sql`SELECT pg_advisory_xact_lock(2026, 1732)`);+ const transactionAdapter = drizzleAdapter(tx, config)(options);+ const user = await transactionAdapter.findOne<{ role?: string }>({+ model: data.model,+ where: data.where,+ });++ if (isAdmin(user?.role)) {+ const [admins] = await tx+ .select({ value: count() })+ .from(schema.userTable)+ .where(+ sql`'admin' = ANY(string_to_array(${schema.userTable.role}, ','))`,+ );+ if ((admins?.value ?? 0) <= 1) {+ throw new APIError("BAD_REQUEST", {+ code: "CANNOT_REMOVE_LAST_ADMIN",+ message: "The instance must have at least one administrator.",+ });+ }+ }++ return transactionAdapter.update<T>(data);+ });+ },+ };+ };+}diff --git a/tests/api-integration/admin-role.test.ts b/tests/api-integration/admin-role.test.tsnew file mode 100644index 000000000..24afc567f--- /dev/null+++ b/tests/api-integration/admin-role.test.ts@@ -0,0 +1,203 @@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { auth } from "../../apps/api/src/auth";+import db, { schema } from "../../apps/api/src/database";+import { resetTestDatabase } from "./helpers/database";++async function createUser(role: "admin" | "user") {+ const email = `${randomUUID()}@example.com`;+ const password = "admin-role-test-password";+ const signUp = await request("/sign-up/email", {+ name: "Role test user",+ email,+ password,+ });+ expect(signUp.status).toBe(200);+ const { user } = (await signUp.json()) as { user: { id: string } };+ await db+ .update(schema.userTable)+ .set({ role })+ .where(eq(schema.userTable.id, user.id));+ const response = await request("/sign-in/email", { email, password });+ expect(response.status).toBe(200);+ const { token } = (await response.json()) as { token: string };+ const cookie = response.headers+ .getSetCookie()+ .map((value) => value.split(";")[0])+ .join("; ");+ expect(cookie).toContain("better-auth.session");+ return { id: user.id, cookie, token };+}++function request(path: string, body: unknown, headers: HeadersInit = {}) {+ return auth.handler(+ new Request(`http://localhost:1337/api/auth${path}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Origin: "http://localhost:5173",+ ...headers,+ },+ body: JSON.stringify(body),+ }),+ );+}++async function getRole(id: string) {+ const [user] = await db+ .select({ role: schema.userTable.role })+ .from(schema.userTable)+ .where(eq(schema.userTable.id, id));+ return user.role;+}++describe.each(["/admin/set-role", "/admin/update-user"])(+ "API integration: %s",+ (path) => {+ function body(userId: string, role: string | string[]) {+ return path === "/admin/set-role"+ ? { userId, role }+ : { userId, data: { role } };+ }++ beforeEach(resetTestDatabase);++ it.each([+ { role: "user" },+ { role: ["user"] },+ { role: [] },+ { role: "admin" },+ ])("rejects setting your own role to $role", async ({ role }) => {+ const admin = await createUser("admin");+ const response = await request(path, body(admin.id, role), {+ Cookie: admin.cookie,+ });++ expect(response.status).toBe(400);+ expect(await response.json()).toMatchObject({+ code: "YOU_CANNOT_CHANGE_YOUR_OWN_ROLE",+ });+ expect(await getRole(admin.id)).toBe("admin");+ });++ it("rejects changing your own role using a bearer token", async () => {+ const admin = await createUser("admin");+ const response = await request(path, body(admin.id, "user"), {+ Authorization: `Bearer ${admin.token}`,+ });++ expect(response.status).toBe(400);+ expect(await response.json()).toMatchObject({+ code: "YOU_CANNOT_CHANGE_YOUR_OWN_ROLE",+ });+ expect(await getRole(admin.id)).toBe("admin");+ });++ it("allows managing another user but preserves the remaining admin", async () => {+ const admin = await createUser("admin");+ const other = await createUser("user");+ const headers = { Cookie: admin.cookie };++ expect(+ (await request(path, body(other.id, "admin"), headers)).status,+ ).toBe(200);+ expect(await getRole(other.id)).toBe("admin");+ expect(+ (await request(path, body(admin.id, "user"), headers)).status,+ ).toBe(400);+ expect(+ (await request(path, body(other.id, "user"), headers)).status,+ ).toBe(200);+ expect(+ (await request(path, body(admin.id, "user"), headers)).status,+ ).toBe(400);+ expect(await getRole(admin.id)).toBe("admin");+ expect(await getRole(other.id)).toBe("user");+ });++ it("denies a demoted admin even with their old session cookie", async () => {+ const admin = await createUser("admin");+ const other = await createUser("admin");+ expect(+ (+ await request(path, body(other.id, "user"), {+ Cookie: admin.cookie,+ })+ ).status,+ ).toBe(200);++ const response = await request(path, body(admin.id, "user"), {+ Cookie: other.cookie,+ });+ expect(response.status).toBe(403);+ expect(await getRole(admin.id)).toBe("admin");+ });++ it("requires authentication", async () => {+ const admin = await createUser("admin");+ const response = await request(path, body(admin.id, "user"));+ expect(response.status).toBe(401);+ expect(await getRole(admin.id)).toBe("admin");+ });++ it("preserves an administrator when admins concurrently demote each other", async () => {+ const admin = await createUser("admin");+ const other = await createUser("admin");+ // Multiple roles must still count as an administrator.+ await db+ .update(schema.userTable)+ .set({ role: "user,admin" })+ .where(eq(schema.userTable.id, other.id));++ const context = await auth.$context;+ const updateUser = context.internalAdapter.updateUser.bind(+ context.internalAdapter,+ );+ let release = () => {};+ const bothAuthorized = new Promise<void>((resolve) => {+ release = resolve;+ });+ let arrivals = 0;+ // Hold both writes until both requests have passed authorization.+ vi.spyOn(context.internalAdapter, "updateUser").mockImplementation(+ async (...args) => {+ if (++arrivals === 2) release();+ await bothAuthorized;+ return updateUser(...args);+ },+ );++ const responses = await Promise.all([+ request(path, body(other.id, "user"), { Cookie: admin.cookie }),+ request(path, body(admin.id, "user"), { Cookie: other.cookie }),+ ]);++ expect(responses.map((response) => response.status).sort()).toEqual([+ 200, 400,+ ]);+ const rejected = responses.find((response) => response.status === 400);+ expect(await rejected?.json()).toMatchObject({+ code: "CANNOT_REMOVE_LAST_ADMIN",+ });+ const roles = await Promise.all([getRole(admin.id), getRole(other.id)]);+ expect(+ roles.filter((role) => role?.split(",").includes("admin")),+ ).toHaveLength(1);+ });+ },+);++it("allows an admin to update their own profile without changing their role", async () => {+ await resetTestDatabase();+ const admin = await createUser("admin");+ const response = await request(+ "/admin/update-user",+ { userId: admin.id, data: { name: "Updated name" } },+ { Cookie: admin.cookie },+ );++ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({ name: "Updated name" });+ expect(await getRole(admin.id)).toBe("admin");+});