Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(admin): record administrative actions in an audit log

Tin429525b3e01b
diff --git a/apps/api/src/admin/audit/admin-audit-request.ts b/apps/api/src/admin/audit/admin-audit-request.ts
new file mode 100644
index 000000000..04b37f5e7
--- /dev/null
+++ b/apps/api/src/admin/audit/admin-audit-request.ts
@@ -0,0 +1,17 @@
+import type { Context } from "hono";
+import { readClientIp } from "../../utils/client-ip";
+
+/** Who performed an admin action, and from where. */
+export type AdminAuditRequest = {
+ actorUserId: string | null;
+ ipAddress: string | null;
+ userAgent: string | null;
+};
+
+export function adminAuditRequest(c: Context): AdminAuditRequest {
+ return {
+ actorUserId: c.get("user")?.id ?? null,
+ ipAddress: readClientIp(c.req.raw.headers),
+ userAgent: c.req.header("user-agent") ?? null,
+ };
+}
diff --git a/apps/api/src/admin/audit/audit-user-snapshot.ts b/apps/api/src/admin/audit/audit-user-snapshot.ts
new file mode 100644
index 000000000..3015a2c42
--- /dev/null
+++ b/apps/api/src/admin/audit/audit-user-snapshot.ts
@@ -0,0 +1,10 @@
+/** The fields of a user account that admin audit entries compare or name. */
+export type AuditUserSnapshot = {
+ id: string;
+ name: string;
+ email: string;
+ role: string | null;
+ banned: boolean | null;
+ emailVerified: boolean;
+ image: string | null;
+};
diff --git a/apps/api/src/admin/audit/capture-auth-admin-audit.ts b/apps/api/src/admin/audit/capture-auth-admin-audit.ts
new file mode 100644
index 000000000..2bbcd3494
--- /dev/null
+++ b/apps/api/src/admin/audit/capture-auth-admin-audit.ts
@@ -0,0 +1,101 @@
+import { getSessionFromCtx } from "better-auth/api";
+import { eq } from "drizzle-orm";
+import db, { schema } from "../../database";
+import { readClientIp } from "../../utils/client-ip";
+import type { AdminAuditRequest } from "./admin-audit-request";
+import type { AuditUserSnapshot } from "./audit-user-snapshot";
+
+type AuthContext = Parameters<typeof getSessionFromCtx>[0];
+
+/** better-auth admin endpoints that change something worth auditing. */
+export const AUDITED_AUTH_ADMIN_PATHS = new Set([
+ "/admin/create-user",
+ "/admin/update-user",
+ "/admin/set-role",
+ "/admin/ban-user",
+ "/admin/unban-user",
+ "/admin/remove-user",
+ "/admin/set-user-password",
+ "/admin/impersonate-user",
+ "/admin/revoke-user-session",
+ "/admin/revoke-user-sessions",
+]);
+
+export type AuthAdminAuditCapture = {
+ request: AdminAuditRequest;
+ target?: AuditUserSnapshot;
+ sessionId?: string;
+};
+
+// better-auth shares `ctx.context` between the before and after hooks.
+type CaptureContext = AuthContext["context"] & {
+ kaneoAdminAudit?: AuthAdminAuditCapture;
+};
+
+const userColumns = {
+ id: schema.userTable.id,
+ name: schema.userTable.name,
+ email: schema.userTable.email,
+ role: schema.userTable.role,
+ banned: schema.userTable.banned,
+ emailVerified: schema.userTable.emailVerified,
+ image: schema.userTable.image,
+};
+
+async function findUser(userId: unknown) {
+ if (typeof userId !== "string" || userId === "") return undefined;
+ const [user] = await db
+ .select(userColumns)
+ .from(schema.userTable)
+ .where(eq(schema.userTable.id, userId))
+ .limit(1);
+ return user;
+}
+
+async function findSessionOwner(token: unknown) {
+ if (typeof token !== "string" || token === "") return undefined;
+ const [session] = await db
+ .select({ id: schema.sessionTable.id, userId: schema.sessionTable.userId })
+ .from(schema.sessionTable)
+ .where(eq(schema.sessionTable.token, token))
+ .limit(1);
+ return session;
+}
+
+/**
+ * Before an audited admin endpoint runs, remember who is calling and what the
+ * 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) {
+ if (!AUDITED_AUTH_ADMIN_PATHS.has(ctx.path)) return;
+ const session = await getSessionFromCtx(ctx, {
+ disableCookieCache: true,
+ disableRefresh: true,
+ });
+ if (!session) return;
+
+ const body = ctx.body as Record<string, unknown> | undefined;
+ const revoked =
+ ctx.path === "/admin/revoke-user-session"
+ ? await findSessionOwner(body?.sessionToken)
+ : undefined;
+ const target = await findUser(revoked ? revoked.userId : body?.userId);
+
+ (ctx.context as CaptureContext).kaneoAdminAudit = {
+ request: {
+ actorUserId: session.user.id,
+ ipAddress: readClientIp(ctx.headers),
+ userAgent: ctx.headers?.get("user-agent") ?? null,
+ },
+ target,
+ sessionId: revoked?.id,
+ };
+}
+
+export function takeAuthAdminAuditCapture(ctx: AuthContext) {
+ const context = ctx.context as CaptureContext;
+ const capture = context.kaneoAdminAudit;
+ context.kaneoAdminAudit = undefined;
+ return capture;
+}
diff --git a/apps/api/src/admin/audit/describe-auth-admin-action.test.ts b/apps/api/src/admin/audit/describe-auth-admin-action.test.ts
new file mode 100644
index 000000000..d53894a0f
--- /dev/null
+++ b/apps/api/src/admin/audit/describe-auth-admin-action.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { AuditUserSnapshot } from "./audit-user-snapshot";
+import { describeAuthAdminAction } from "./describe-auth-admin-action";
+
+const target: AuditUserSnapshot = {
+ id: "u1",
+ name: "Tom",
+ email: "[email protected]",
+ role: "user",
+ banned: false,
+ emailVerified: true,
+ image: null,
+};
+
+const update = (data: Record<string, unknown>, returned: object) =>
+ describeAuthAdminAction({
+ path: "/admin/update-user",
+ body: { userId: "u1", data },
+ target,
+ returned: { ...target, ...returned },
+ });
+
+describe("describeAuthAdminAction", () => {
+ it("splits a role change from the other changed fields", () => {
+ expect(
+ update(
+ { name: "Tim", role: "admin", emailVerified: true },
+ { name: "Tim", role: "admin" },
+ ),
+ ).toEqual([
+ {
+ action: "user.role_changed",
+ targetType: "user",
+ targetId: "u1",
+ targetLabel: "[email protected]",
+ metadata: { from: "user", to: "admin" },
+ },
+ {
+ action: "user.updated",
+ targetType: "user",
+ targetId: "u1",
+ targetLabel: "[email protected]",
+ metadata: {
+ fields: ["name"],
+ changes: { name: { from: "Tom", to: "Tim" } },
+ },
+ },
+ ]);
+ });
+
+ it("names changed fields without copying their values", () => {
+ expect(update({ image: "data:..." }, { image: "data:..." })).toEqual([
+ expect.objectContaining({
+ action: "user.updated",
+ metadata: { fields: ["image"], changes: {} },
+ }),
+ ]);
+ });
+
+ it("treats a ban through update-user as a deactivation", () => {
+ expect(
+ update(
+ { banned: true, banReason: "Spam" },
+ { banned: true, banReason: "Spam" },
+ ).map((entry) => [entry.action, entry.metadata]),
+ ).toEqual([["user.deactivated", { reason: "Spam", expiresAt: null }]]);
+ });
+
+ it("records nothing for unchanged updates or unchanged roles", () => {
+ expect(update({ name: "Tom" }, {})).toEqual([]);
+ expect(
+ describeAuthAdminAction({
+ path: "/admin/set-role",
+ body: { userId: "u1", role: "user" },
+ target,
+ returned: { user: target },
+ }),
+ ).toEqual([]);
+ });
+
+ it("needs a known target, except when creating a user", () => {
+ expect(
+ describeAuthAdminAction({
+ path: "/admin/ban-user",
+ body: { userId: "u1" },
+ target: undefined,
+ returned: { user: target },
+ }),
+ ).toEqual([]);
+ expect(
+ describeAuthAdminAction({
+ path: "/admin/create-user",
+ body: { email: "[email protected]", password: "secret" },
+ target: undefined,
+ returned: { user: { id: "u2", email: "[email protected]", name: "N" } },
+ }),
+ ).toEqual([
+ {
+ action: "user.created",
+ targetType: "user",
+ targetId: "u2",
+ targetLabel: "[email protected]",
+ metadata: { name: "N", role: null },
+ },
+ ]);
+ });
+
+ it("only records a single-session revocation when the session was found", () => {
+ const revoke = (sessionId?: string) =>
+ describeAuthAdminAction({
+ path: "/admin/revoke-user-session",
+ body: { sessionToken: "secret-token" },
+ target,
+ sessionId,
+ returned: { success: true },
+ });
+ expect(revoke()).toEqual([]);
+ expect(revoke("s1")).toEqual([
+ expect.objectContaining({
+ action: "session.revoked",
+ metadata: { sessionId: "s1" },
+ }),
+ ]);
+ });
+});
diff --git a/apps/api/src/admin/audit/describe-auth-admin-action.ts b/apps/api/src/admin/audit/describe-auth-admin-action.ts
new file mode 100644
index 000000000..43d41b5ab
--- /dev/null
+++ b/apps/api/src/admin/audit/describe-auth-admin-action.ts
@@ -0,0 +1,163 @@
+import type { AuditUserSnapshot } from "./audit-user-snapshot";
+
+export type AuthAdminAuditEntry = {
+ action: string;
+ targetType: "user";
+ targetId: string;
+ targetLabel: string;
+ metadata?: Record<string, unknown>;
+};
+
+type ReturnedUser = Partial<AuditUserSnapshot> & {
+ banReason?: string | null;
+ banExpires?: Date | string | null;
+};
+
+const BAN_FIELDS = new Set(["banned", "banReason", "banExpires"]);
+// Values shown in the log; any other changed field is listed by name only.
+const SHOWN_FIELDS = new Set(["name", "email", "emailVerified"]);
+
+function same(a: unknown, b: unknown) {
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+}
+
+function unwrapUser(returned: unknown): ReturnedUser | undefined {
+ if (!returned || typeof returned !== "object") return undefined;
+ const value = returned as { user?: unknown };
+ return (
+ value.user && typeof value.user === "object" ? value.user : returned
+ ) as ReturnedUser;
+}
+
+function deactivation(user: ReturnedUser | undefined) {
+ return {
+ reason: user?.banReason ?? null,
+ expiresAt: user?.banExpires ?? null,
+ };
+}
+
+function describeUpdate(
+ target: AuditUserSnapshot,
+ data: Record<string, unknown>,
+ updated: ReturnedUser,
+) {
+ const read = (source: object, key: string) =>
+ (source as Record<string, unknown>)[key];
+ const changed = Object.keys(data).filter(
+ (key) =>
+ key !== "updatedAt" && !same(read(target, key), read(updated, key)),
+ );
+ const entries: Omit<AuthAdminAuditEntry, "targetType" | "targetId">[] = [];
+ const label = updated.email ?? target.email;
+
+ if (changed.includes("role")) {
+ entries.push({
+ action: "user.role_changed",
+ targetLabel: label,
+ metadata: { from: target.role, to: updated.role ?? null },
+ });
+ }
+ if (changed.includes("banned")) {
+ entries.push({
+ action: updated.banned ? "user.deactivated" : "user.reactivated",
+ targetLabel: label,
+ metadata: updated.banned ? deactivation(updated) : undefined,
+ });
+ }
+ const fields = changed.filter(
+ (key) =>
+ key !== "role" && !(changed.includes("banned") && BAN_FIELDS.has(key)),
+ );
+ if (fields.length > 0) {
+ const changes = Object.fromEntries(
+ fields
+ .filter((key) => SHOWN_FIELDS.has(key))
+ .map((key) => [
+ key,
+ { from: read(target, key) ?? null, to: read(updated, key) ?? null },
+ ]),
+ );
+ entries.push({
+ action: "user.updated",
+ targetLabel: label,
+ metadata: { fields, changes },
+ });
+ }
+ return entries;
+}
+
+export type AuthAdminCall = {
+ path: string;
+ body: Record<string, unknown> | undefined;
+ /** The affected user as it was before the call. */
+ target: AuditUserSnapshot | undefined;
+ /** For single-session revocation: the session's id, never its token. */
+ sessionId?: string;
+ returned: unknown;
+};
+
+/** Turn a successful better-auth admin endpoint call into audit entries. */
+export function describeAuthAdminAction({
+ path,
+ body,
+ target,
+ sessionId,
+ returned,
+}: AuthAdminCall): AuthAdminAuditEntry[] {
+ const user = unwrapUser(returned);
+
+ if (path === "/admin/create-user") {
+ if (!user?.id || !user.email) return [];
+ return [
+ {
+ action: "user.created",
+ targetType: "user",
+ targetId: user.id,
+ targetLabel: user.email,
+ metadata: { name: user.name ?? null, role: user.role ?? null },
+ },
+ ];
+ }
+
+ if (!target) return [];
+ const about = (
+ action: string,
+ metadata?: Record<string, unknown>,
+ ): AuthAdminAuditEntry => ({
+ action,
+ targetType: "user",
+ targetId: target.id,
+ targetLabel: target.email,
+ metadata,
+ });
+
+ switch (path) {
+ case "/admin/update-user": {
+ const data = body?.data;
+ if (!user || !data || typeof data !== "object") return [];
+ return describeUpdate(target, data as Record<string, unknown>, user).map(
+ (entry) => ({ ...entry, targetType: "user", targetId: target.id }),
+ );
+ }
+ case "/admin/set-role":
+ return same(target.role, user?.role)
+ ? []
+ : [about("user.role_changed", { from: target.role, to: user?.role })];
+ case "/admin/ban-user":
+ return [about("user.deactivated", deactivation(user))];
+ case "/admin/unban-user":
+ return [about("user.reactivated")];
+ case "/admin/remove-user":
+ return [about("user.deleted", { name: target.name })];
+ case "/admin/set-user-password":
+ return [about("user.password_set")];
+ case "/admin/impersonate-user":
+ return [about("user.impersonated")];
+ case "/admin/revoke-user-session":
+ return sessionId ? [about("session.revoked", { sessionId })] : [];
+ case "/admin/revoke-user-sessions":
+ return [about("session.revoked_all")];
+ default:
+ return [];
+ }
+}
diff --git a/apps/api/src/admin/audit/record-admin-action.ts b/apps/api/src/admin/audit/record-admin-action.ts
new file mode 100644
index 000000000..d5c661a68
--- /dev/null
+++ b/apps/api/src/admin/audit/record-admin-action.ts
@@ -0,0 +1,54 @@
+import { sql } from "drizzle-orm";
+import db, { schema } from "../../database";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+import { sanitizeAuditMetadata } from "./sanitize-audit-metadata";
+
+const MAX_USER_AGENT_LENGTH = 512;
+
+export type AdminActionInput = {
+ actorUserId: string | null;
+ /** Dotted `<area>.<verb>` name, for example `user.deleted`. */
+ action: string;
+ targetType: string;
+ targetId?: string | null;
+ targetLabel?: string | null;
+ /** Never put secrets, tokens, reset links, or key values here. */
+ metadata?: Record<string, unknown> | null;
+ ipAddress?: string | null;
+ userAgent?: string | null;
+};
+
+/**
+ * Append an entry to the admin audit log. Pass the transaction when the action
+ * has one so the entry commits (or rolls back) with it.
+ */
+export async function recordAdminAction(
+ input: AdminActionInput,
+ database: DbOrTx = db,
+) {
+ const actorId = input.actorUserId;
+ const actor = (column: "id" | "name" | "email") =>
+ actorId
+ ? sql`(SELECT ${sql.identifier(column)} FROM "user" WHERE "id" = ${actorId})`
+ : null;
+ const metadata = input.metadata
+ ? (sanitizeAuditMetadata(input.metadata) as Record<string, unknown>)
+ : null;
+
+ await database.insert(schema.adminAuditLogTable).values({
+ // Resolved in the insert so a concurrently deleted actor yields NULL
+ // instead of a foreign key error.
+ actorUserId: actor("id"),
+ actorName: actor("name"),
+ actorEmail: actor("email"),
+ action: input.action,
+ targetType: input.targetType,
+ targetId: input.targetId ?? null,
+ targetLabel: input.targetLabel ?? null,
+ metadata,
+ ipAddress: input.ipAddress ?? null,
+ userAgent: input.userAgent?.slice(0, MAX_USER_AGENT_LENGTH) ?? null,
+ });
+}
+
+export default recordAdminAction;
diff --git a/apps/api/src/admin/audit/record-auth-admin-audit.ts b/apps/api/src/admin/audit/record-auth-admin-audit.ts
new file mode 100644
index 000000000..9fb21a1e3
--- /dev/null
+++ b/apps/api/src/admin/audit/record-auth-admin-audit.ts
@@ -0,0 +1,32 @@
+import { type getSessionFromCtx, isAPIError } from "better-auth/api";
+import { takeAuthAdminAuditCapture } from "./capture-auth-admin-audit";
+import { describeAuthAdminAction } from "./describe-auth-admin-action";
+import { recordAdminAction } from "./record-admin-action";
+
+type AuthContext = Parameters<typeof getSessionFromCtx>[0];
+
+/** After an audited admin endpoint, record it if it succeeded. */
+export async function recordAuthAdminAudit(ctx: AuthContext) {
+ const capture = takeAuthAdminAuditCapture(ctx);
+ const returned = ctx.context.returned;
+ if (!capture || returned === undefined || isAPIError(returned)) return;
+
+ const entries = describeAuthAdminAction({
+ path: ctx.path,
+ body: ctx.body as Record<string, unknown> | undefined,
+ target: capture.target,
+ sessionId: capture.sessionId,
+ returned,
+ });
+ try {
+ for (const entry of entries) {
+ await recordAdminAction({ ...capture.request, ...entry });
+ }
+ } catch (error) {
+ // The change already committed; failing the response would not undo it.
+ console.error("Admin audit entry could not be recorded:", {
+ action: entries[0]?.action,
+ error: error instanceof Error ? error.name : typeof error,
+ });
+ }
+}
diff --git a/apps/api/src/admin/audit/record-workspace-member-action.ts b/apps/api/src/admin/audit/record-workspace-member-action.ts
new file mode 100644
index 000000000..5684253f7
--- /dev/null
+++ b/apps/api/src/admin/audit/record-workspace-member-action.ts
@@ -0,0 +1,53 @@
+import { eq } from "drizzle-orm";
+import { schema } from "../../database";
+import type { DbOrTx } from "../../project-access/db-or-tx";
+import type { AdminAuditRequest } from "./admin-audit-request";
+import { recordAdminAction } from "./record-admin-action";
+
+type WorkspaceMemberAction =
+ | "workspace.member_added"
+ | "workspace.member_removed"
+ | "workspace.member_role_changed"
+ | "workspace.owner_transferred";
+
+/** Record a membership change against the workspace, naming the member. */
+export async function recordWorkspaceMemberAction(
+ database: DbOrTx,
+ audit: AdminAuditRequest,
+ entry: {
+ action: WorkspaceMemberAction;
+ workspaceId: string;
+ userId: string;
+ metadata?: Record<string, unknown>;
+ },
+) {
+ const [names] = await database
+ .select({
+ workspaceName: schema.workspaceTable.name,
+ userName: schema.userTable.name,
+ userEmail: schema.userTable.email,
+ })
+ .from(schema.workspaceTable)
+ .leftJoin(schema.userTable, eq(schema.userTable.id, entry.userId))
+ .where(eq(schema.workspaceTable.id, entry.workspaceId))
+ .limit(1);
+
+ await recordAdminAction(
+ {
+ ...audit,
+ action: entry.action,
+ targetType: "workspace",
+ targetId: entry.workspaceId,
+ targetLabel: names?.workspaceName ?? null,
+ metadata: {
+ member: {
+ id: entry.userId,
+ name: names?.userName ?? null,
+ email: names?.userEmail ?? null,
+ },
+ ...entry.metadata,
+ },
+ },
+ database,
+ );
+}
diff --git a/apps/api/src/admin/audit/sanitize-audit-metadata.test.ts b/apps/api/src/admin/audit/sanitize-audit-metadata.test.ts
new file mode 100644
index 000000000..ee999654e
--- /dev/null
+++ b/apps/api/src/admin/audit/sanitize-audit-metadata.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vite-plus/test";
+import { sanitizeAuditMetadata } from "./sanitize-audit-metadata";
+
+describe("sanitizeAuditMetadata", () => {
+ it("drops credential-like keys at any depth", () => {
+ expect(
+ sanitizeAuditMetadata({
+ reason: "Left",
+ password: "hunter2",
+ newPassword: "hunter3",
+ sessionToken: "abc",
+ nested: { apiKey: "kn_1", api_key: "kn_2", key: "k", secret: "s" },
+ list: [{ token: "t", role: "admin" }],
+ }),
+ ).toEqual({ reason: "Left", nested: {}, list: [{ role: "admin" }] });
+ });
+
+ it("keeps ordinary values and removes undefined ones", () => {
+ expect(
+ sanitizeAuditMetadata({ role: "user", count: 2, gone: undefined }),
+ ).toEqual({ role: "user", count: 2 });
+ });
+});
diff --git a/apps/api/src/admin/audit/sanitize-audit-metadata.ts b/apps/api/src/admin/audit/sanitize-audit-metadata.ts
new file mode 100644
index 000000000..40ab77afd
--- /dev/null
+++ b/apps/api/src/admin/audit/sanitize-audit-metadata.ts
@@ -0,0 +1,25 @@
+const SECRET_KEY = /password|secret|token|api_?key|^key$|cookie/i;
+const MAX_DEPTH = 4;
+
+/**
+ * Callers never pass credentials, but metadata is permanent: drop any key that
+ * looks like one so a future mistake cannot write a secret into the log.
+ */
+export function sanitizeAuditMetadata(value: unknown, depth = 0): unknown {
+ if (Array.isArray(value)) {
+ return depth >= MAX_DEPTH
+ ? []
+ : value.map((item) => sanitizeAuditMetadata(item, depth + 1));
+ }
+ if (value === null || typeof value !== "object") {
+ return value;
+ }
+ if (depth >= MAX_DEPTH) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter(([key, item]) => !SECRET_KEY.test(key) && item !== undefined)
+ .map(([key, item]) => [key, sanitizeAuditMetadata(item, depth + 1)]),
+ );
+}
diff --git a/apps/api/src/admin/controllers/add-workspace-member.ts b/apps/api/src/admin/controllers/add-workspace-member.ts
index 1eacf51c4..cdf661d14 100644
--- a/apps/api/src/admin/controllers/add-workspace-member.ts
+++ b/apps/api/src/admin/controllers/add-workspace-member.ts
@@ -3,16 +3,21 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { userTable, workspaceUserTable } from "../../database/schema";
import { clearMemberProjectAccess } from "../../project-access/clear-member-project-access";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordWorkspaceMemberAction } from "../audit/record-workspace-member-action";
import { handleMemberAdded } from "../../workspace-members/handle-member-added";
import { isAssignableWorkspaceRole } from "../is-assignable-workspace-role";
import { lockWorkspace } from "../lock-workspace";
import listWorkspaceMembers from "./list-workspace-members";
-async function addWorkspaceMember(request: {
- workspaceId: string;
- userId: string;
- role: string;
-}) {
+async function addWorkspaceMember(
+ request: {
+ workspaceId: string;
+ userId: string;
+ role: string;
+ },
+ audit: AdminAuditRequest,
+) {
const { workspaceId, userId, role } = request;
await db.transaction(async (tx) => {
@@ -41,6 +46,12 @@ async function addWorkspaceMember(request: {
await tx
.insert(workspaceUserTable)
.values({ workspaceId, userId, role, joinedAt: new Date() });
+ await recordWorkspaceMemberAction(tx, audit, {
+ action: "workspace.member_added",
+ workspaceId,
+ userId,
+ metadata: { role },
+ });
});
await handleMemberAdded(workspaceId, userId);
diff --git a/apps/api/src/admin/controllers/list-audit-log.ts b/apps/api/src/admin/controllers/list-audit-log.ts
new file mode 100644
index 000000000..e163f83c6
--- /dev/null
+++ b/apps/api/src/admin/controllers/list-audit-log.ts
@@ -0,0 +1,66 @@
+import { and, count, desc, eq, like, or, type SQL } from "drizzle-orm";
+import db, { schema } from "../../database";
+import { escapeLikePattern } from "../../search/like-pattern";
+
+type ListAuditLogInput = {
+ action?: string;
+ actorId?: string;
+ targetType?: string;
+ targetId?: string;
+ page: number;
+ limit: number;
+};
+
+const log = schema.adminAuditLogTable;
+
+function actionFilter(action: string) {
+ return action.includes(".")
+ ? eq(log.action, action)
+ : or(
+ eq(log.action, action),
+ like(log.action, `${escapeLikePattern(action)}.%`),
+ );
+}
+
+export async function listAuditLog(input: ListAuditLogInput) {
+ const filters: (SQL | undefined)[] = [
+ input.action ? actionFilter(input.action) : undefined,
+ input.actorId ? eq(log.actorUserId, input.actorId) : undefined,
+ input.targetType ? eq(log.targetType, input.targetType) : undefined,
+ input.targetId ? eq(log.targetId, input.targetId) : undefined,
+ ];
+ const where = and(...filters);
+
+ const [rows, [totalRow]] = await Promise.all([
+ db
+ .select()
+ .from(log)
+ .where(where)
+ .orderBy(desc(log.createdAt), desc(log.id))
+ .limit(input.limit)
+ .offset((input.page - 1) * input.limit),
+ db.select({ value: count() }).from(log).where(where),
+ ]);
+
+ return {
+ entries: rows.map((row) => ({
+ id: row.id,
+ createdAt: row.createdAt.toISOString(),
+ action: row.action,
+ actor: {
+ id: row.actorUserId,
+ name: row.actorName,
+ email: row.actorEmail,
+ },
+ targetType: row.targetType,
+ targetId: row.targetId,
+ targetLabel: row.targetLabel,
+ metadata: row.metadata ?? null,
+ ipAddress: row.ipAddress,
+ userAgent: row.userAgent,
+ })),
+ total: totalRow?.value ?? 0,
+ };
+}
+
+export default listAuditLog;
diff --git a/apps/api/src/admin/controllers/remove-workspace-member.ts b/apps/api/src/admin/controllers/remove-workspace-member.ts
index 489b4758f..41e1ff1b2 100644
--- a/apps/api/src/admin/controllers/remove-workspace-member.ts
+++ b/apps/api/src/admin/controllers/remove-workspace-member.ts
@@ -3,14 +3,19 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { userTable, workspaceUserTable } from "../../database/schema";
import { isOwnerRole } from "../../project-access/is-owner-role";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordWorkspaceMemberAction } from "../audit/record-workspace-member-action";
import { handleMemberRemoved } from "../../workspace-members/handle-member-removed";
import { lockWorkspace } from "../lock-workspace";
import listWorkspaceMembers from "./list-workspace-members";
-async function removeWorkspaceMember(request: {
- workspaceId: string;
- userId: string;
-}) {
+async function removeWorkspaceMember(
+ request: {
+ workspaceId: string;
+ userId: string;
+ },
+ audit: AdminAuditRequest,
+) {
const { workspaceId, userId } = request;
await db.transaction(async (tx) => {
@@ -35,6 +40,12 @@ async function removeWorkspaceMember(request: {
eq(workspaceUserTable.userId, userId),
),
);
+ await recordWorkspaceMemberAction(tx, audit, {
+ action: "workspace.member_removed",
+ workspaceId,
+ userId,
+ metadata: { role: member.role },
+ });
});
const [user] = await db
diff --git a/apps/api/src/admin/controllers/transfer-workspace-ownership.ts b/apps/api/src/admin/controllers/transfer-workspace-ownership.ts
index 1a5f31b5e..49eea521f 100644
--- a/apps/api/src/admin/controllers/transfer-workspace-ownership.ts
+++ b/apps/api/src/admin/controllers/transfer-workspace-ownership.ts
@@ -5,13 +5,18 @@ import { workspaceUserTable } from "../../database/schema";
import { publishEvent } from "../../events";
import { clearMemberProjectAccess } from "../../project-access/clear-member-project-access";
import { isOwnerRole } from "../../project-access/is-owner-role";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordWorkspaceMemberAction } from "../audit/record-workspace-member-action";
import { lockWorkspace } from "../lock-workspace";
import listWorkspaceMembers from "./list-workspace-members";
-async function transferWorkspaceOwnership(request: {
- workspaceId: string;
- userId: string;
-}) {
+async function transferWorkspaceOwnership(
+ request: {
+ workspaceId: string;
+ userId: string;
+ },
+ audit: AdminAuditRequest,
+) {
const { workspaceId, userId } = request;
await db.transaction(async (tx) => {
@@ -51,6 +56,12 @@ async function transferWorkspaceOwnership(request: {
),
);
await clearMemberProjectAccess(workspaceId, userId, tx);
+ await recordWorkspaceMemberAction(tx, audit, {
+ action: "workspace.owner_transferred",
+ workspaceId,
+ userId,
+ metadata: { previousRole: target.role, previousOwnerIds: otherOwners },
+ });
});
await publishEvent("project_access.updated", { workspaceId, userId });
diff --git a/apps/api/src/admin/controllers/update-workspace-member-role.ts b/apps/api/src/admin/controllers/update-workspace-member-role.ts
index eb3ebbaf8..f5ba4e587 100644
--- a/apps/api/src/admin/controllers/update-workspace-member-role.ts
+++ b/apps/api/src/admin/controllers/update-workspace-member-role.ts
@@ -3,15 +3,20 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { workspaceUserTable } from "../../database/schema";
import { isOwnerRole } from "../../project-access/is-owner-role";
+import type { AdminAuditRequest } from "../audit/admin-audit-request";
+import { recordWorkspaceMemberAction } from "../audit/record-workspace-member-action";
import { isAssignableWorkspaceRole } from "../is-assignable-workspace-role";
import { lockWorkspace } from "../lock-workspace";
import listWorkspaceMembers from "./list-workspace-members";
-async function updateWorkspaceMemberRole(request: {
- workspaceId: string;
- userId: string;
- role: string;
-}) {
+async function updateWorkspaceMemberRole(
+ request: {
+ workspaceId: string;
+ userId: string;
+ role: string;
+ },
+ audit: AdminAuditRequest,
+) {
const { workspaceId, userId, role } = request;
await db.transaction(async (tx) => {
@@ -43,6 +48,14 @@ async function updateWorkspaceMemberRole(request: {
eq(workspaceUserTable.userId, userId),
),
);
+ if (member.role !== role) {
+ await recordWorkspaceMemberAction(tx, audit, {
+ action: "workspace.member_role_changed",
+ workspaceId,
+ userId,
+ metadata: { previousRole: member.role, role },
+ });
+ }
});
return listWorkspaceMembers(workspaceId);
diff --git a/apps/api/src/admin/index.ts b/apps/api/src/admin/index.ts
index 41ebb8c55..f2a2ea017 100644
--- a/apps/api/src/admin/index.ts
+++ b/apps/api/src/admin/index.ts
@@ -6,7 +6,9 @@ import {
} from "../openapi";
import { requireInstanceAdmin } from "../utils/require-instance-admin";
import { requireUserSession } from "../utils/require-user-session";
+import { adminAuditRequest } from "./audit/admin-audit-request";
import addWorkspaceMember from "./controllers/add-workspace-member";
+import listAuditLog from "./controllers/list-audit-log";
import listUsers from "./controllers/list-users";
import listWorkspaceMembers from "./controllers/list-workspace-members";
import listWorkspaceRoles from "./controllers/list-workspace-roles";
@@ -15,6 +17,7 @@ import removeWorkspaceMember from "./controllers/remove-workspace-member";
import transferWorkspaceOwnership from "./controllers/transfer-workspace-ownership";
import updateWorkspaceMemberRole from "./controllers/update-workspace-member-role";
import {
+ adminAuditLogSchema,
adminUserListSchema,
adminWorkspaceListSchema,
adminWorkspaceMemberListSchema,
@@ -24,6 +27,7 @@ import {
addAdminWorkspaceMemberBody,
adminWorkspaceMemberParam,
adminWorkspaceParam,
+ listAdminAuditLogQuery,
listAdminUsersQuery,
listAdminWorkspacesQuery,
transferAdminWorkspaceOwnershipBody,
@@ -213,6 +217,23 @@ const transferWorkspaceOwnershipRoute = createRoute({
},
});
+const listAuditLogRoute = createRoute({
+ method: "get",
+ operationId: "listAdminAuditLog",
+ path: "/audit-log",
+ tags: ["Admin"],
+ summary: "List the admin audit log",
+ description:
+ "Page through recorded administrative actions, newest first, optionally filtered by action or category, actor, or target. Entries never contain passwords, tokens, reset links, or API key values. Requires an instance administrator session; API keys are rejected.",
+ middleware: [requireUserSession, requireInstanceAdmin] as const,
+ request: { query: listAdminAuditLogQuery },
+ responses: {
+ 200: jsonResponse("Audit log entries, newest first", adminAuditLogSchema),
+ 400: errorResponse("Invalid filter, page, or limit"),
+ 403: forbidden,
+ },
+});
+
const admin = apiRouter()
.openapi(listUsersRoute, async (c) =>
c.json(await listUsers(c.req.valid("query")), 200),
@@ -228,33 +249,45 @@ const admin = apiRouter()
)
.openapi(addWorkspaceMemberRoute, async (c) =>
c.json(
- await addWorkspaceMember({
- workspaceId: c.req.valid("param").workspaceId,
- ...c.req.valid("json"),
- }),
+ await addWorkspaceMember(
+ {
+ workspaceId: c.req.valid("param").workspaceId,
+ ...c.req.valid("json"),
+ },
+ adminAuditRequest(c),
+ ),
200,
),
)
.openapi(updateWorkspaceMemberRoleRoute, async (c) =>
c.json(
- await updateWorkspaceMemberRole({
- ...c.req.valid("param"),
- role: c.req.valid("json").role,
- }),
+ await updateWorkspaceMemberRole(
+ { ...c.req.valid("param"), role: c.req.valid("json").role },
+ adminAuditRequest(c),
+ ),
200,
),
)
.openapi(removeWorkspaceMemberRoute, async (c) =>
- c.json(await removeWorkspaceMember(c.req.valid("param")), 200),
+ c.json(
+ await removeWorkspaceMember(c.req.valid("param"), adminAuditRequest(c)),
+ 200,
+ ),
)
.openapi(transferWorkspaceOwnershipRoute, async (c) =>
c.json(
- await transferWorkspaceOwnership({
- workspaceId: c.req.valid("param").workspaceId,
- userId: c.req.valid("json").userId,
- }),
+ await transferWorkspaceOwnership(
+ {
+ workspaceId: c.req.valid("param").workspaceId,
+ userId: c.req.valid("json").userId,
+ },
+ adminAuditRequest(c),
+ ),
200,
),
+ )
+ .openapi(listAuditLogRoute, async (c) =>
+ c.json(await listAuditLog(c.req.valid("query")), 200),
);
export default admin;
diff --git a/apps/api/src/admin/response.ts b/apps/api/src/admin/response.ts
index 6d576faa2..93c504818 100644
--- a/apps/api/src/admin/response.ts
+++ b/apps/api/src/admin/response.ts
@@ -73,3 +73,37 @@ export const adminWorkspaceMemberListSchema = z.array(
export const adminWorkspaceRoleListSchema = z.array(z.string()).openapi({
description: "Role names an administrator can assign in the workspace.",
});
+
+export const adminAuditLogEntrySchema = z
+ .object({
+ id: z.string(),
+ createdAt: isoTimestamp,
+ action: z.string().openapi({
+ description: "Dotted action name, for example `user.role_changed`.",
+ }),
+ actor: z.object({
+ id: z.string().nullable().openapi({
+ description: "Null when the administrator's account was deleted.",
+ }),
+ name: z.string().nullable(),
+ email: z.string().nullable(),
+ }),
+ targetType: z.string(),
+ targetId: z.string().nullable(),
+ targetLabel: z.string().nullable().openapi({
+ description: "The target's name or email when the action happened.",
+ }),
+ metadata: z.record(z.string(), z.unknown()).nullable(),
+ ipAddress: z.string().nullable(),
+ userAgent: z.string().nullable(),
+ })
+ .openapi("AdminAuditLogEntry");
+
+export const adminAuditLogSchema = z
+ .object({
+ entries: z.array(adminAuditLogEntrySchema),
+ total: z.number().int().openapi({
+ description: "Number of entries matching the filters, across all pages.",
+ }),
+ })
+ .openapi("AdminAuditLog");
diff --git a/apps/api/src/admin/schema.ts b/apps/api/src/admin/schema.ts
index c3ef017a3..c86f89f6f 100644
--- a/apps/api/src/admin/schema.ts
+++ b/apps/api/src/admin/schema.ts
@@ -43,3 +43,26 @@ export const transferAdminWorkspaceOwnershipBody = z.object({
"An existing member who becomes the only owner. Previous owners become admins.",
}),
});
+
+export const listAdminAuditLogQuery = z.object({
+ action: z
+ .string()
+ .max(100)
+ .regex(/^[a-z_]+(\.[a-z_]+)?$/, "Expected an action or action category")
+ .optional()
+ .openapi({
+ description:
+ "An exact action such as `user.deleted`, or a category such as `user` to match every `user.*` action.",
+ }),
+ actorId: z.string().max(200).optional().openapi({
+ description: "Only entries performed by this user id.",
+ }),
+ targetType: z.string().max(100).optional().openapi({
+ description: "Only entries about this kind of target, such as `user`.",
+ }),
+ targetId: z.string().max(200).optional().openapi({
+ description: "Only entries about this target id.",
+ }),
+ page: pagingNumber(1, 1_000_000, 1),
+ limit: pagingNumber(1, 100, 25),
+});
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index 2a5024b20..7bb72ebf8 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -74,6 +74,8 @@ import {
readableNativeOrganizations,
} from "./utils/native-organization-read-access";
import { satisfies } from "./utils/role-permissions";
+import { captureAuthAdminAudit } from "./admin/audit/capture-auth-admin-audit";
+import { recordAuthAdminAudit } from "./admin/audit/record-auth-admin-audit";
import clearEmailVerificationOnAdminChange from "./user/controllers/clear-email-verification-on-admin-change";
import deleteAccountData from "./user/controllers/delete-account-data";
import prepareAdminUserRemoval from "./user/controllers/prepare-admin-user-removal";
@@ -885,6 +887,8 @@ export const auth = betterAuth({
: await auth.api.getSession({ headers: new Headers(ctx.headers) });
await assertNativeOrganizationReadAllowed(ctx, organizationViewer);
}
+ // Before removal prep deletes account data the entry needs to name.
+ await captureAuthAdminAudit(ctx);
if (ctx.path === "/admin/remove-user") {
await prepareAdminUserRemoval(ctx);
}
@@ -1055,6 +1059,7 @@ export const auth = betterAuth({
}
}),
after: createAuthMiddleware(async (ctx) => {
+ await recordAuthAdminAudit(ctx);
if (
(ctx.path === "/organization/list" ||
ctx.path === "/organization/list-user-teams") &&
diff --git a/apps/api/src/utils/client-ip.ts b/apps/api/src/utils/client-ip.ts
index 0bd5a1a8e..b47780e66 100644
--- a/apps/api/src/utils/client-ip.ts
+++ b/apps/api/src/utils/client-ip.ts
@@ -73,3 +73,8 @@ export function clientIpMiddleware(config?: string): MiddlewareHandler {
await next();
};
}
+
+/** The client address resolved by `clientIpMiddleware`, if any. */
+export function readClientIp(headers: Headers | undefined) {
+ return headers?.get(CLIENT_IP_HEADER) || null;
+}
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 812176339..0f6a73de7 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -5515,6 +5515,117 @@
"role",
"joinedAt"
]
+ },
+ "AdminAuditLog": {
+ "type": "object",
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AdminAuditLogEntry"
+ }
+ },
+ "total": {
+ "type": "integer",
+ "description": "Number of entries matching the filters, across all pages."
+ }
+ },
+ "required": [
+ "entries",
+ "total"
+ ]
+ },
+ "AdminAuditLogEntry": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "action": {
+ "type": "string",
+ "description": "Dotted action name, for example `user.role_changed`."
+ },
+ "actor": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Null when the administrator's account was deleted."
+ },
+ "name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "email": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "email"
+ ]
+ },
+ "targetType": {
+ "type": "string"
+ },
+ "targetId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "targetLabel": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "The target's name or email when the action happened."
+ },
+ "metadata": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "additionalProperties": {}
+ },
+ "ipAddress": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "userAgent": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "createdAt",
+ "action",
+ "actor",
+ "targetType",
+ "targetId",
+ "targetLabel",
+ "metadata",
+ "ipAddress",
+ "userAgent"
+ ]
}
},
"parameters": {}
@@ -24707,6 +24818,130 @@
}
}
}
+ },
+ "/admin/audit-log": {
+ "get": {
+ "operationId": "listAdminAuditLog",
+ "tags": [
+ "Admin"
+ ],
+ "summary": "List the admin audit log",
+ "description": "Page through recorded administrative actions, newest first, optionally filtered by action or category, actor, or target. Entries never contain passwords, tokens, reset links, or API key values. Requires an instance administrator session; API keys are rejected.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string",
+ "maxLength": 100,
+ "pattern": "^[a-z_]+(\\.[a-z_]+)?$",
+ "description": "An exact action such as `user.deleted`, or a category such as `user` to match every `user.*` action."
+ },
+ "required": false,
+ "description": "An exact action such as `user.deleted`, or a category such as `user` to match every `user.*` action.",
+ "name": "action",
+ "in": "query"
+ },
+ {
+ "schema": {
+ "type": "string",
+ "maxLength": 200,
+ "description": "Only entries performed by this user id."
+ },
+ "required": false,
+ "description": "Only entries performed by this user id.",
+ "name": "actorId",
+ "in": "query"
+ },
+ {
+ "schema": {
+ "type": "string",
+ "maxLength": 100,
+ "description": "Only entries about this kind of target, such as `user`."
+ },
+ "required": false,
+ "description": "Only entries about this kind of target, such as `user`.",
+ "name": "targetType",
+ "in": "query"
+ },
+ {
+ "schema": {
+ "type": "string",
+ "maxLength": 200,
+ "description": "Only entries about this target id."
+ },
+ "required": false,
+ "description": "Only entries about this target id.",
+ "name": "targetId",
+ "in": "query"
+ },
+ {
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000,
+ "default": 1
+ },
+ "required": false,
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100,
+ "default": 25
+ },
+ "required": false,
+ "name": "limit",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Audit log entries, newest first",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AdminAuditLog"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid filter, page, or limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "The caller is not an instance administrator or is authenticated with an API key",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "429": {
+ "$ref": "#/components/responses/ApiKeyRateLimited"
+ }
+ }
+ }
}
},
"webhooks": {}
diff --git a/tests/api-integration/admin-audit-log-auth-actions.test.ts b/tests/api-integration/admin-audit-log-auth-actions.test.ts
new file mode 100644
index 000000000..0948a4e7b
--- /dev/null
+++ b/tests/api-integration/admin-audit-log-auth-actions.test.ts
@@ -0,0 +1,298 @@
+import { once } from "node:events";
+import type { AddressInfo } from "node:net";
+import { serve } from "@hono/node-server";
+import { eq } from "drizzle-orm";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vite-plus/test";
+import { auth } from "../../apps/api/src/auth";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { readAuditLog } from "./helpers/admin/read-audit-log";
+import { signUpWithSession } from "./helpers/auth-session";
+import { resetTestDatabase } from "./helpers/database";
+
+type App = ReturnType<typeof createApp>["app"];
+
+let app: App;
+let admin: { userId: string; cookies: string };
+let target: { userId: string; cookies: string };
+
+function call(path: string, body: unknown, headers: Record<string, string>) {
+ return app.request(`/api/auth/admin/${path}`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ origin: "http://localhost:5173",
+ "user-agent": "audit-test-agent",
+ ...headers,
+ },
+ body: JSON.stringify(body),
+ });
+}
+
+const asAdmin = (path: string, body: unknown) =>
+ call(path, body, { cookie: admin.cookies });
+
+async function expectOk(response: Response) {
+ expect(response.status, await response.clone().text()).toBe(200);
+}
+
+beforeEach(async () => {
+ await resetTestDatabase();
+ ({ app } = createApp());
+ admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Ada Admin",
+ role: "admin",
+ });
+ target = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Tom Target",
+ role: "user",
+ });
+});
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe("audit of better-auth admin endpoints", () => {
+ it("records role changes separately from other profile updates", async () => {
+ await expectOk(
+ await asAdmin("update-user", {
+ userId: target.userId,
+ data: { name: "Tim Target", email: "[email protected]", role: "admin" },
+ }),
+ );
+
+ const rows = await readAuditLog();
+ expect(rows).toHaveLength(2);
+ expect(rows[0]).toMatchObject({
+ action: "user.role_changed",
+ actorUserId: admin.userId,
+ actorName: "Ada Admin",
+ actorEmail: "[email protected]",
+ targetType: "user",
+ targetId: target.userId,
+ targetLabel: "[email protected]",
+ metadata: { from: "user", to: "admin" },
+ userAgent: "audit-test-agent",
+ });
+ expect(rows[1]).toMatchObject({
+ action: "user.updated",
+ targetId: target.userId,
+ metadata: {
+ fields: ["name", "email"],
+ changes: {
+ name: { from: "Tom Target", to: "Tim Target" },
+ email: { from: "[email protected]", to: "[email protected]" },
+ },
+ },
+ });
+ expect(rows[0].createdAt.getTime()).toBeGreaterThan(Date.now() - 60_000);
+ });
+
+ it("records nothing when an update changes nothing", async () => {
+ await expectOk(
+ await asAdmin("update-user", {
+ userId: target.userId,
+ data: { name: "Tom Target", email: "[email protected]", role: "user" },
+ }),
+ );
+
+ expect(await readAuditLog()).toEqual([]);
+ });
+
+ it("records set-role, deactivation, and reactivation", async () => {
+ await expectOk(
+ await asAdmin("set-role", { userId: target.userId, role: "admin" }),
+ );
+ await expectOk(
+ await asAdmin("ban-user", {
+ userId: target.userId,
+ banReason: "Left the company",
+ }),
+ );
+ await expectOk(await asAdmin("unban-user", { userId: target.userId }));
+
+ const rows = await readAuditLog();
+ expect(rows.map((row) => [row.action, row.metadata])).toEqual([
+ ["user.deactivated", { reason: "Left the company", expiresAt: null }],
+ ["user.reactivated", null],
+ ["user.role_changed", { from: "user", to: "admin" }],
+ ]);
+ expect(rows.every((row) => row.targetId === target.userId)).toBe(true);
+ });
+
+ it("keeps the label of a deleted user", async () => {
+ await expectOk(await asAdmin("remove-user", { userId: target.userId }));
+
+ const [row] = await readAuditLog();
+ expect(row).toMatchObject({
+ action: "user.deleted",
+ targetId: target.userId,
+ targetLabel: "[email protected]",
+ metadata: { name: "Tom Target" },
+ });
+ });
+
+ it("never stores passwords or session tokens", async () => {
+ const password = "a-brand-new-secret-password";
+ await expectOk(
+ await asAdmin("set-user-password", {
+ userId: target.userId,
+ newPassword: password,
+ }),
+ );
+ const created = await asAdmin("create-user", {
+ email: "[email protected]",
+ name: "New Person",
+ password,
+ role: "user",
+ });
+ await expectOk(created);
+ const { user: createdUser } = (await created.json()) as {
+ user: { id: string };
+ };
+ const [session] = await db
+ .select()
+ .from(schema.sessionTable)
+ .where(eq(schema.sessionTable.userId, target.userId));
+ await expectOk(
+ await asAdmin("revoke-user-session", { sessionToken: session.token }),
+ );
+ await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Again",
+ role: "user",
+ });
+ await expectOk(
+ await asAdmin("revoke-user-sessions", { userId: target.userId }),
+ );
+ const impersonation = await asAdmin("impersonate-user", {
+ userId: createdUser.id,
+ });
+ await expectOk(impersonation);
+ const { session: impersonated } = (await impersonation.json()) as {
+ session: { token: string };
+ };
+
+ const rows = await readAuditLog();
+ expect(rows.map((row) => row.action)).toEqual([
+ "session.revoked",
+ "session.revoked_all",
+ "user.created",
+ "user.impersonated",
+ "user.password_set",
+ ]);
+ expect(rows[0]).toMatchObject({
+ targetId: target.userId,
+ metadata: { sessionId: session.id },
+ });
+ expect(rows[2]).toMatchObject({
+ targetId: createdUser.id,
+ targetLabel: "[email protected]",
+ metadata: { name: "New Person", role: "user" },
+ });
+ const stored = JSON.stringify(rows);
+ expect(stored).not.toContain(password);
+ expect(stored).not.toContain(session.token);
+ expect(stored).not.toContain(impersonated.token);
+ expect(stored).not.toMatch(/password"|token"/i);
+ });
+
+ it("records nothing for forbidden or failed admin calls", async () => {
+ const asTarget = (path: string, body: unknown) =>
+ call(path, body, { cookie: target.cookies });
+
+ expect((await asTarget("ban-user", { userId: admin.userId })).status).toBe(
+ 403,
+ );
+ expect(
+ (await asTarget("set-role", { userId: admin.userId, role: "user" }))
+ .status,
+ ).toBe(403);
+ expect(
+ (await asTarget("remove-user", { userId: admin.userId })).status,
+ ).toBe(403);
+ expect((await asAdmin("ban-user", { userId: admin.userId })).status).toBe(
+ 400,
+ );
+ expect(
+ (
+ await asAdmin("update-user", {
+ userId: admin.userId,
+ data: { role: "user" },
+ })
+ ).status,
+ ).toBe(400);
+ expect(
+ (await asAdmin("unban-user", { userId: "missing-user" })).status,
+ ).toBe(404);
+ expect((await call("ban-user", { userId: target.userId }, {})).status).toBe(
+ 401,
+ );
+
+ const { key } = await auth.api.createApiKey({
+ body: { userId: admin.userId, name: "Audit test" },
+ });
+ expect(
+ (await call("ban-user", { userId: target.userId }, { "x-api-key": key }))
+ .status,
+ ).toBe(403);
+
+ expect(await readAuditLog()).toEqual([]);
+ });
+
+ it("keeps the actor snapshot after the administrator is deleted", async () => {
+ await expectOk(
+ await asAdmin("set-role", { userId: target.userId, role: "admin" }),
+ );
+ await db
+ .delete(schema.userTable)
+ .where(eq(schema.userTable.id, admin.userId));
+
+ const [row] = await readAuditLog();
+ expect(row).toMatchObject({
+ actorUserId: null,
+ actorName: "Ada Admin",
+ actorEmail: "[email protected]",
+ });
+ });
+
+ it("records the client address resolved from the transport", async () => {
+ vi.stubEnv("TRUSTED_PROXIES", "127.0.0.0/8");
+ ({ app } = createApp());
+ const server = serve({ fetch: app.fetch, hostname: "127.0.0.1", port: 0 });
+ await once(server, "listening");
+ try {
+ const { port } = server.address() as AddressInfo;
+ const response = await fetch(
+ `http://127.0.0.1:${port}/api/auth/admin/ban-user`,
+ {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ origin: "http://localhost:5173",
+ cookie: admin.cookies,
+ "x-kaneo-client-ip": "1.2.3.4",
+ "x-forwarded-for": "203.0.113.9",
+ },
+ body: JSON.stringify({ userId: target.userId }),
+ },
+ );
+ expect(response.status, await response.text()).toBe(200);
+ } finally {
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ }
+
+ const [row] = await readAuditLog();
+ expect(row.ipAddress).toBe("203.0.113.9");
+ });
+});
diff --git a/tests/api-integration/admin-audit-log-listing.test.ts b/tests/api-integration/admin-audit-log-listing.test.ts
new file mode 100644
index 000000000..1e24ee430
--- /dev/null
+++ b/tests/api-integration/admin-audit-log-listing.test.ts
@@ -0,0 +1,150 @@
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+import { recordAdminAction } from "../../apps/api/src/admin/audit/record-admin-action";
+import { auth } from "../../apps/api/src/auth";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";
+import { createInstanceAdmin } from "./helpers/admin/create-instance-admin";
+import { resetTestDatabase } from "./helpers/database";
+import { createWorkspaceMember } from "./helpers/fixtures";
+import { projectAccessApi } from "./helpers/project-access/project-access-api";
+
+type AuditLogPage = {
+ total: number;
+ entries: { id: string; action: string; actor: { id: string | null } }[];
+};
+
+async function list(query = "") {
+ const response = await projectAccessApi()(`/admin/audit-log${query}`);
+ expect(response.status, await response.clone().text()).toBe(200);
+ return (await response.json()) as AuditLogPage;
+}
+
+async function seed(actorId: string) {
+ const at = (minutes: number) => new Date(Date.UTC(2026, 0, 1, 12, minutes));
+ await db.insert(schema.adminAuditLogTable).values([
+ {
+ id: "oldest",
+ action: "user.deleted",
+ targetType: "user",
+ targetId: "u1",
+ createdAt: at(1),
+ },
+ {
+ id: "middle",
+ actorUserId: actorId,
+ action: "workspace.member_added",
+ targetType: "workspace",
+ targetId: "w1",
+ createdAt: at(2),
+ },
+ {
+ id: "newest",
+ actorUserId: actorId,
+ action: "user.role_changed",
+ targetType: "user",
+ targetId: "u2",
+ createdAt: at(3),
+ },
+ {
+ id: "lookalike",
+ action: "users_import.done",
+ targetType: "user",
+ createdAt: at(0),
+ },
+ ]);
+}
+
+beforeEach(resetTestDatabase);
+
+describe("GET /api/admin/audit-log", () => {
+ it("is limited to instance administrator sessions", async () => {
+ mockAnonymousSession();
+ expect((await projectAccessApi()("/admin/audit-log")).status).toBe(401);
+
+ const { user } = await createWorkspaceMember();
+ mockAuthenticatedSession(user);
+ expect((await projectAccessApi()("/admin/audit-log")).status).toBe(403);
+ });
+
+ it("rejects an administrator's API key", async () => {
+ const admin = await createInstanceAdmin();
+ const { key } = await auth.api.createApiKey({
+ body: { userId: admin.id, name: "Audit log test" },
+ });
+ const { app } = createApp();
+
+ for (const headers of [
+ { "x-api-key": key },
+ { authorization: `Bearer ${key}` },
+ ]) {
+ const response = await app.request("/api/admin/audit-log", { headers });
+ expect(response.status).toBe(403);
+ }
+ });
+
+ it("pages newest first and filters by category, action, actor, and target", async () => {
+ const admin = await createInstanceAdmin();
+ await seed(admin.id);
+ mockAuthenticatedSession(admin);
+ const ids = (page: AuditLogPage) => page.entries.map((entry) => entry.id);
+
+ const all = await list();
+ expect(ids(all)).toEqual(["newest", "middle", "oldest", "lookalike"]);
+ expect(all.total).toBe(4);
+
+ const second = await list("?limit=2&page=2");
+ expect(ids(second)).toEqual(["oldest", "lookalike"]);
+ expect(second.total).toBe(4);
+
+ expect(ids(await list("?action=user"))).toEqual(["newest", "oldest"]);
+ expect(ids(await list("?action=user.deleted"))).toEqual(["oldest"]);
+ expect(ids(await list(`?actorId=${admin.id}`))).toEqual([
+ "newest",
+ "middle",
+ ]);
+ expect(ids(await list("?targetType=workspace&targetId=w1"))).toEqual([
+ "middle",
+ ]);
+ });
+
+ it("returns recorded entries with actor snapshots", async () => {
+ const admin = await createInstanceAdmin();
+ await recordAdminAction({
+ actorUserId: admin.id,
+ action: "user.deactivated",
+ targetType: "user",
+ targetId: "someone",
+ targetLabel: "[email protected]",
+ metadata: { reason: "Left", apiKey: "kn_secret", password: "hunter2" },
+ ipAddress: "203.0.113.9",
+ userAgent: "agent",
+ });
+ mockAuthenticatedSession(admin);
+
+ const page = await list();
+ expect(page.entries).toEqual([
+ {
+ id: expect.any(String),
+ createdAt: expect.any(String),
+ action: "user.deactivated",
+ actor: { id: admin.id, name: admin.name, email: admin.email },
+ targetType: "user",
+ targetId: "someone",
+ targetLabel: "[email protected]",
+ metadata: { reason: "Left" },
+ ipAddress: "203.0.113.9",
+ userAgent: "agent",
+ },
+ ]);
+ });
+
+ it("rejects malformed filters", async () => {
+ const admin = await createInstanceAdmin();
+ mockAuthenticatedSession(admin);
+ const request = projectAccessApi();
+
+ expect((await request("/admin/audit-log?action=user%25")).status).toBe(400);
+ expect((await request("/admin/audit-log?limit=500")).status).toBe(400);
+ });
+});
diff --git a/tests/api-integration/admin-audit-log-workspace-actions.test.ts b/tests/api-integration/admin-audit-log-workspace-actions.test.ts
new file mode 100644
index 000000000..ba584bb7a
--- /dev/null
+++ b/tests/api-integration/admin-audit-log-workspace-actions.test.ts
@@ -0,0 +1,154 @@
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { createInstanceAdmin } from "./helpers/admin/create-instance-admin";
+import { readAuditLog } from "./helpers/admin/read-audit-log";
+import { resetTestDatabase } from "./helpers/database";
+import { createWorkspaceMember } from "./helpers/fixtures";
+import { createRestrictedWorkspace } from "./helpers/project-access/create-restricted-workspace";
+import { projectAccessApi } from "./helpers/project-access/project-access-api";
+
+beforeEach(resetTestDatabase);
+
+describe("audit of admin workspace membership changes", () => {
+ it("records add, role change, ownership transfer, and removal", async () => {
+ const ctx = await createRestrictedWorkspace();
+ const { user: outsider } = await createWorkspaceMember({
+ userName: "Outside Olive",
+ });
+ const admin = await createInstanceAdmin();
+ mockAuthenticatedSession(admin);
+ const request = projectAccessApi({ "user-agent": "audit-agent" });
+ const base = `/admin/workspaces/${ctx.workspace.id}`;
+
+ const steps = [
+ () =>
+ request(`${base}/members`, {
+ method: "POST",
+ body: { userId: outsider.id, role: "member" },
+ }),
+ () =>
+ request(`${base}/members/${outsider.id}/role`, {
+ method: "PUT",
+ body: { role: "admin" },
+ }),
+ () =>
+ request(`${base}/owner`, {
+ method: "PUT",
+ body: { userId: ctx.restricted.id },
+ }),
+ () => request(`${base}/members/${outsider.id}`, { method: "DELETE" }),
+ ];
+ for (const step of steps) {
+ expect((await step()).status).toBe(200);
+ }
+
+ const rows = await readAuditLog();
+ expect(rows.map((row) => [row.action, row.metadata])).toEqual([
+ [
+ "workspace.member_added",
+ {
+ member: {
+ id: outsider.id,
+ name: "Outside Olive",
+ email: outsider.email,
+ },
+ role: "member",
+ },
+ ],
+ [
+ "workspace.member_removed",
+ {
+ member: {
+ id: outsider.id,
+ name: "Outside Olive",
+ email: outsider.email,
+ },
+ role: "admin",
+ },
+ ],
+ [
+ "workspace.member_role_changed",
+ {
+ member: {
+ id: outsider.id,
+ name: "Outside Olive",
+ email: outsider.email,
+ },
+ previousRole: "member",
+ role: "admin",
+ },
+ ],
+ [
+ "workspace.owner_transferred",
+ {
+ member: {
+ id: ctx.restricted.id,
+ name: ctx.restricted.name,
+ email: ctx.restricted.email,
+ },
+ previousRole: "member",
+ previousOwnerIds: [ctx.owner.id],
+ },
+ ],
+ ]);
+ for (const row of rows) {
+ expect(row).toMatchObject({
+ actorUserId: admin.id,
+ actorName: admin.name,
+ actorEmail: admin.email,
+ targetType: "workspace",
+ targetId: ctx.workspace.id,
+ targetLabel: ctx.workspace.name,
+ userAgent: "audit-agent",
+ });
+ }
+ });
+
+ it("records nothing for rejected, forbidden, or unchanged requests", async () => {
+ const ctx = await createRestrictedWorkspace();
+ const base = `/admin/workspaces/${ctx.workspace.id}`;
+
+ mockAuthenticatedSession(ctx.owner);
+ expect(
+ (
+ await projectAccessApi()(`${base}/members/${ctx.restricted.id}`, {
+ method: "DELETE",
+ })
+ ).status,
+ ).toBe(403);
+
+ const admin = await createInstanceAdmin();
+ mockAuthenticatedSession(admin);
+ const request = projectAccessApi();
+ expect(
+ (await request(`${base}/members/${ctx.owner.id}`, { method: "DELETE" }))
+ .status,
+ ).toBe(409);
+ expect(
+ (
+ await request(`${base}/members`, {
+ method: "POST",
+ body: { userId: ctx.restricted.id, role: "member" },
+ })
+ ).status,
+ ).toBe(409);
+ expect(
+ (
+ await request(`${base}/members/${ctx.restricted.id}/role`, {
+ method: "PUT",
+ body: { role: "owner" },
+ })
+ ).status,
+ ).toBe(400);
+ expect(
+ (
+ await request(`${base}/members/${ctx.restricted.id}/role`, {
+ method: "PUT",
+ body: { role: "member" },
+ })
+ ).status,
+ ).toBe(200);
+
+ expect(await readAuditLog()).toEqual([]);
+ });
+});
diff --git a/tests/api-integration/helpers/admin/read-audit-log.ts b/tests/api-integration/helpers/admin/read-audit-log.ts
new file mode 100644
index 000000000..93e8b8780
--- /dev/null
+++ b/tests/api-integration/helpers/admin/read-audit-log.ts
@@ -0,0 +1,7 @@
+import { asc } from "drizzle-orm";
+import db, { schema } from "../../../../apps/api/src/database";
+
+export function readAuditLog() {
+ const log = schema.adminAuditLogTable;
+ return db.select().from(log).orderBy(asc(log.action), asc(log.createdAt));
+}