mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat: production-grade RBAC with editor role, custom roles, API key scoping, and audit log (#89)
* feat(rbac): add editor role, 3 new permissions, ownership helper * feat(rbac): add audit_log table, apiKeys.permissions column, editor role to schema * feat(rbac): wire requirePermission into all routes, add editor role support * refactor(rbac): replace ad-hoc role checks with permission-based ownership * feat(rbac): add audit log DB writes + query endpoint Dual-write audit events to stdout (existing) and SQLite audit_log table. Add GET /api/v1/audit-log with pagination, action filter, and date range filtering, gated behind audit:read permission. * feat(rbac): add API key permission scoping with ceiling enforcement * feat(rbac): add escalation prevention and last-admin protection * feat(rbac): add editor role to UI, API key permission scoping in settings * test(rbac): add full permission matrix integration test * test(rbac): add editor role E2E tests * feat(rbac): add custom roles with CRUD API and DB-backed permission lookup * feat(rbac): add API key expiration * feat(rbac): add roles management UI and API key expiration to settings * feat(rbac): add audit log UI to settings * fix: remove any cast in API key permission validation * test(rbac): add unit tests for username validation rules * test(rbac): add unit tests for effective permissions and ownership * test(rbac): add comprehensive route permission matrix (all routes × all roles) * test(rbac): add auth route edge case tests (login failures, session expiry, password side effects) * test(rbac): add escalation prevention tests (register, update, self-demote, last-admin) * test(rbac): add ownership enforcement tests (files, pipelines, editor access, cross-user isolation) * test(rbac): add API key edge cases (name validation, delete behavior, key revocation) * test(rbac): add audit log edge cases (all events, pagination clamping, structure) * test(rbac): add custom roles edge case tests (validation, CRUD, functional permissions) * test(rbac): add comprehensive E2E tests (roles UI, audit log, custom role, API key scoping)
This commit is contained in:
@@ -10,6 +10,7 @@ import { and, eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { auditLog } from "../lib/audit.js";
|
||||
import { getPermissions, hasEffectivePermission } from "../permissions.js";
|
||||
import { computeKeyPrefix, hashPassword, requireAuth } from "../plugins/auth.js";
|
||||
|
||||
export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
@@ -18,7 +19,11 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
const user = requireAuth(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const body = request.body as { name?: string } | null;
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
permissions?: string[];
|
||||
expiresAt?: string;
|
||||
} | null;
|
||||
const name = body?.name?.trim() || "Default API Key";
|
||||
|
||||
if (name.length > 100) {
|
||||
@@ -28,6 +33,36 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
let scopedPermissions: string[] | null = null;
|
||||
if (Array.isArray(body?.permissions) && body.permissions.length > 0) {
|
||||
const userPerms = getPermissions(user.role);
|
||||
const permSet = new Set<string>(userPerms);
|
||||
const invalid = body.permissions.filter((p: string) => !permSet.has(p));
|
||||
if (invalid.length > 0) {
|
||||
return reply.status(400).send({
|
||||
error: `Cannot scope key with permissions you don't have: ${invalid.join(", ")}`,
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
scopedPermissions = body.permissions;
|
||||
}
|
||||
|
||||
let expiresAt: Date | null = null;
|
||||
if (body?.expiresAt) {
|
||||
const parsed = new Date(body.expiresAt);
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Invalid expiresAt date", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
if (parsed <= new Date()) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "expiresAt must be in the future", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
expiresAt = parsed;
|
||||
}
|
||||
|
||||
// Generate a raw API key: "si_" prefix + 48 random bytes as hex
|
||||
const rawKey = `si_${randomBytes(48).toString("hex")}`;
|
||||
const keyHash = await hashPassword(rawKey);
|
||||
@@ -41,6 +76,8 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
keyHash,
|
||||
keyPrefix,
|
||||
name,
|
||||
permissions: scopedPermissions ? JSON.stringify(scopedPermissions) : null,
|
||||
expiresAt,
|
||||
})
|
||||
.run();
|
||||
|
||||
@@ -51,6 +88,8 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
id,
|
||||
key: rawKey,
|
||||
name,
|
||||
permissions: scopedPermissions,
|
||||
expiresAt: expiresAt?.toISOString() ?? null,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
@@ -63,24 +102,27 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
const selectFields = {
|
||||
id: schema.apiKeys.id,
|
||||
name: schema.apiKeys.name,
|
||||
permissions: schema.apiKeys.permissions,
|
||||
createdAt: schema.apiKeys.createdAt,
|
||||
lastUsedAt: schema.apiKeys.lastUsedAt,
|
||||
expiresAt: schema.apiKeys.expiresAt,
|
||||
};
|
||||
const keys =
|
||||
user.role === "admin"
|
||||
? db.select(selectFields).from(schema.apiKeys).all()
|
||||
: db
|
||||
.select(selectFields)
|
||||
.from(schema.apiKeys)
|
||||
.where(eq(schema.apiKeys.userId, user.id))
|
||||
.all();
|
||||
const keys = hasEffectivePermission(user, "apikeys:all")
|
||||
? db.select(selectFields).from(schema.apiKeys).all()
|
||||
: db
|
||||
.select(selectFields)
|
||||
.from(schema.apiKeys)
|
||||
.where(eq(schema.apiKeys.userId, user.id))
|
||||
.all();
|
||||
|
||||
return reply.send({
|
||||
apiKeys: keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name,
|
||||
permissions: k.permissions ? JSON.parse(k.permissions) : null,
|
||||
createdAt: k.createdAt.toISOString(),
|
||||
lastUsedAt: k.lastUsedAt?.toISOString() ?? null,
|
||||
expiresAt: k.expiresAt?.toISOString() ?? null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { and, desc, eq, gte, lte, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
export async function auditLogRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get(
|
||||
"/api/v1/audit-log",
|
||||
async (
|
||||
request: FastifyRequest<{
|
||||
Querystring: {
|
||||
page?: string;
|
||||
limit?: string;
|
||||
action?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
};
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) => {
|
||||
const user = requirePermission("audit:read")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const page = Math.max(1, parseInt(request.query.page ?? "1", 10) || 1);
|
||||
const limit = Math.min(100, Math.max(1, parseInt(request.query.limit ?? "50", 10) || 50));
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const conditions = [];
|
||||
|
||||
if (request.query.action) {
|
||||
conditions.push(eq(schema.auditLog.action, request.query.action));
|
||||
}
|
||||
if (request.query.from) {
|
||||
const fromDate = new Date(request.query.from);
|
||||
if (!Number.isNaN(fromDate.getTime())) {
|
||||
conditions.push(gte(schema.auditLog.createdAt, fromDate));
|
||||
}
|
||||
}
|
||||
if (request.query.to) {
|
||||
const toDate = new Date(request.query.to);
|
||||
if (!Number.isNaN(toDate.getTime())) {
|
||||
conditions.push(lte(schema.auditLog.createdAt, toDate));
|
||||
}
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? and(...conditions) : undefined;
|
||||
|
||||
const entries = db
|
||||
.select()
|
||||
.from(schema.auditLog)
|
||||
.where(where)
|
||||
.orderBy(desc(schema.auditLog.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
.all();
|
||||
|
||||
const countResult = db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(schema.auditLog)
|
||||
.where(where)
|
||||
.get();
|
||||
|
||||
return reply.send({
|
||||
entries: entries.map((e) => ({
|
||||
id: e.id,
|
||||
actorId: e.actorId,
|
||||
actorUsername: e.actorUsername,
|
||||
action: e.action,
|
||||
targetType: e.targetType,
|
||||
targetId: e.targetId,
|
||||
details: e.details ? JSON.parse(e.details) : null,
|
||||
ipAddress: e.ipAddress,
|
||||
createdAt: e.createdAt.toISOString(),
|
||||
})),
|
||||
total: countResult?.count ?? 0,
|
||||
page,
|
||||
limit,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
app.log.info("Audit log routes registered");
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import sharp from "sharp";
|
||||
import { env } from "../config.js";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { ensureSharpCompat } from "../lib/heic-converter.js";
|
||||
import { requireAdmin } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
const BRANDING_DIR = join(process.cwd(), "data", "branding");
|
||||
const LOGO_PATH = join(BRANDING_DIR, "logo.png");
|
||||
@@ -35,7 +35,7 @@ function upsertSetting(key: string, value: string): void {
|
||||
export async function brandingRoutes(app: FastifyInstance): Promise<void> {
|
||||
// POST /api/v1/settings/logo — Upload logo (admin only)
|
||||
app.post("/api/v1/settings/logo", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("branding:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const file = await request.file();
|
||||
@@ -90,7 +90,7 @@ export async function brandingRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// DELETE /api/v1/settings/logo — Remove logo (admin only)
|
||||
app.delete("/api/v1/settings/logo", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("branding:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
if (existsSync(LOGO_PATH)) {
|
||||
|
||||
@@ -27,7 +27,8 @@ import {
|
||||
releaseInstallLock,
|
||||
setInstallProgress,
|
||||
} from "../lib/feature-status.js";
|
||||
import { requireAdmin, requireAuth } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
import { requireAuth } from "../plugins/auth.js";
|
||||
import { updateSingleFileProgress } from "./progress.js";
|
||||
|
||||
const venvPath = process.env.PYTHON_VENV_PATH || "/opt/venv";
|
||||
@@ -110,7 +111,7 @@ export async function registerFeatureRoutes(app: FastifyInstance): Promise<void>
|
||||
app.post(
|
||||
"/api/v1/admin/features/:bundleId/install",
|
||||
async (request: FastifyRequest<{ Params: BundleIdParams }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("features:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { bundleId } = request.params;
|
||||
@@ -215,7 +216,7 @@ export async function registerFeatureRoutes(app: FastifyInstance): Promise<void>
|
||||
app.post(
|
||||
"/api/v1/admin/features/:bundleId/uninstall",
|
||||
async (request: FastifyRequest<{ Params: BundleIdParams }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("features:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { bundleId } = request.params;
|
||||
@@ -271,7 +272,7 @@ export async function registerFeatureRoutes(app: FastifyInstance): Promise<void>
|
||||
app.get(
|
||||
"/api/v1/admin/features/disk-usage",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("features:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const totalBytes = getDirSize(getAiDir());
|
||||
|
||||
@@ -26,6 +26,7 @@ import { sanitizeFilename } from "../lib/filename.js";
|
||||
import { decodeToSharpCompat, needsCliDecode } from "../lib/format-decoders.js";
|
||||
import { decodeHeic } from "../lib/heic-converter.js";
|
||||
import { createWorkspace } from "../lib/workspace.js";
|
||||
import { hasEffectivePermission } from "../permissions.js";
|
||||
import { requireAuth } from "../plugins/auth.js";
|
||||
import { type JobProgress, updateJobProgress } from "./progress.js";
|
||||
import { getRegisteredToolIds, getToolConfig } from "./tool-factory.js";
|
||||
@@ -335,10 +336,9 @@ export async function registerPipelineRoutes(app: FastifyInstance): Promise<void
|
||||
|
||||
// Admins see all pipelines; regular users see their own + legacy (no owner)
|
||||
const allRows = db.select().from(schema.pipelines).all();
|
||||
const rows =
|
||||
user.role === "admin"
|
||||
? allRows
|
||||
: allRows.filter((row) => !row.userId || row.userId === user.id);
|
||||
const rows = hasEffectivePermission(user, "pipelines:all")
|
||||
? allRows
|
||||
: allRows.filter((row) => !row.userId || row.userId === user.id);
|
||||
|
||||
const pipelines = rows.map((row) => ({
|
||||
id: row.id,
|
||||
@@ -371,7 +371,11 @@ export async function registerPipelineRoutes(app: FastifyInstance): Promise<void
|
||||
}
|
||||
|
||||
// Only the owner (or admin) can delete; legacy pipelines (no owner) can be deleted by anyone
|
||||
if (existing.userId && existing.userId !== user.id && user.role !== "admin") {
|
||||
if (
|
||||
existing.userId &&
|
||||
existing.userId !== user.id &&
|
||||
!hasEffectivePermission(user, "pipelines:all")
|
||||
) {
|
||||
return reply.status(403).send({ error: "Not authorized to delete this pipeline" });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Permission } from "@ashim/shared";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { auditLog } from "../lib/audit.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
const ALL_PERMISSIONS: Permission[] = [
|
||||
"tools:use",
|
||||
"files:own",
|
||||
"files:all",
|
||||
"apikeys:own",
|
||||
"apikeys:all",
|
||||
"pipelines:own",
|
||||
"pipelines:all",
|
||||
"settings:read",
|
||||
"settings:write",
|
||||
"users:manage",
|
||||
"teams:manage",
|
||||
"branding:manage",
|
||||
"features:manage",
|
||||
"system:health",
|
||||
"audit:read",
|
||||
];
|
||||
|
||||
export async function rolesRoutes(app: FastifyInstance): Promise<void> {
|
||||
// GET /api/v1/roles — List all roles (requires audit:read to view)
|
||||
app.get("/api/v1/roles", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requirePermission("audit:read")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const roles = db.select().from(schema.roles).all();
|
||||
const userCounts = db
|
||||
.select({
|
||||
role: schema.users.role,
|
||||
count: sql<number>`COUNT(*)`,
|
||||
})
|
||||
.from(schema.users)
|
||||
.groupBy(schema.users.role)
|
||||
.all();
|
||||
const countMap = new Map(userCounts.map((r) => [r.role, r.count]));
|
||||
|
||||
return reply.send({
|
||||
roles: roles.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
description: r.description,
|
||||
permissions: JSON.parse(r.permissions),
|
||||
isBuiltin: r.isBuiltin,
|
||||
userCount: countMap.get(r.name) ?? 0,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
updatedAt: r.updatedAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/v1/roles — Create custom role
|
||||
app.post("/api/v1/roles", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requirePermission("users:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
description?: string;
|
||||
permissions?: string[];
|
||||
} | null;
|
||||
if (!body?.name || !Array.isArray(body?.permissions)) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Name and permissions are required", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
const name = body.name.trim().toLowerCase();
|
||||
if (name.length < 2 || name.length > 30) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Role name must be 2-30 characters", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
if (!/^[a-z0-9_-]+$/.test(name)) {
|
||||
return reply.status(400).send({
|
||||
error: "Role name can only contain lowercase letters, numbers, hyphens, and underscores",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
const invalid = body.permissions.filter((p) => !ALL_PERMISSIONS.includes(p as Permission));
|
||||
if (invalid.length > 0) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: `Invalid permissions: ${invalid.join(", ")}`, code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
const existing = db.select().from(schema.roles).where(eq(schema.roles.name, name)).get();
|
||||
if (existing) {
|
||||
return reply.status(409).send({ error: "Role name already exists", code: "CONFLICT" });
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
db.insert(schema.roles)
|
||||
.values({
|
||||
id,
|
||||
name,
|
||||
description: body.description?.trim() ?? "",
|
||||
permissions: JSON.stringify(body.permissions),
|
||||
isBuiltin: false,
|
||||
createdBy: user.id,
|
||||
})
|
||||
.run();
|
||||
|
||||
auditLog(request.log, "ROLE_CREATED", { adminId: user.id, roleId: id, roleName: name });
|
||||
|
||||
return reply.status(201).send({
|
||||
id,
|
||||
name,
|
||||
description: body.description?.trim() ?? "",
|
||||
permissions: body.permissions,
|
||||
isBuiltin: false,
|
||||
});
|
||||
});
|
||||
|
||||
// PUT /api/v1/roles/:id — Update custom role
|
||||
app.put(
|
||||
"/api/v1/roles/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const user = requirePermission("users:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const { id } = request.params;
|
||||
const role = db.select().from(schema.roles).where(eq(schema.roles.id, id)).get();
|
||||
if (!role) {
|
||||
return reply.status(404).send({ error: "Role not found", code: "NOT_FOUND" });
|
||||
}
|
||||
if (role.isBuiltin) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Cannot modify built-in roles", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
description?: string;
|
||||
permissions?: string[];
|
||||
} | null;
|
||||
const updates: Record<string, unknown> = { updatedAt: new Date() };
|
||||
|
||||
if (body?.name) {
|
||||
const name = body.name.trim().toLowerCase();
|
||||
if (name.length < 2 || name.length > 30) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Role name must be 2-30 characters", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
const dup = db.select().from(schema.roles).where(eq(schema.roles.name, name)).get();
|
||||
if (dup && dup.id !== id) {
|
||||
return reply.status(409).send({ error: "Role name already exists", code: "CONFLICT" });
|
||||
}
|
||||
// Update users on old role name to new name
|
||||
db.update(schema.users).set({ role: name }).where(eq(schema.users.role, role.name)).run();
|
||||
updates.name = name;
|
||||
}
|
||||
if (body?.description !== undefined) {
|
||||
updates.description = body.description.trim();
|
||||
}
|
||||
if (Array.isArray(body?.permissions)) {
|
||||
const invalid = body.permissions.filter((p) => !ALL_PERMISSIONS.includes(p as Permission));
|
||||
if (invalid.length > 0) {
|
||||
return reply.status(400).send({
|
||||
error: `Invalid permissions: ${invalid.join(", ")}`,
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
updates.permissions = JSON.stringify(body.permissions);
|
||||
}
|
||||
|
||||
db.update(schema.roles).set(updates).where(eq(schema.roles.id, id)).run();
|
||||
auditLog(request.log, "ROLE_UPDATED", { adminId: user.id, roleId: id });
|
||||
|
||||
return reply.send({ ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /api/v1/roles/:id — Delete custom role
|
||||
app.delete(
|
||||
"/api/v1/roles/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const user = requirePermission("users:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const { id } = request.params;
|
||||
const role = db.select().from(schema.roles).where(eq(schema.roles.id, id)).get();
|
||||
if (!role) {
|
||||
return reply.status(404).send({ error: "Role not found", code: "NOT_FOUND" });
|
||||
}
|
||||
if (role.isBuiltin) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Cannot delete built-in roles", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
db.update(schema.users)
|
||||
.set({ role: "user", updatedAt: new Date() })
|
||||
.where(eq(schema.users.role, role.name))
|
||||
.run();
|
||||
|
||||
db.delete(schema.roles).where(eq(schema.roles.id, id)).run();
|
||||
auditLog(request.log, "ROLE_DELETED", {
|
||||
adminId: user.id,
|
||||
roleId: id,
|
||||
roleName: role.name,
|
||||
});
|
||||
|
||||
return reply.send({ ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
app.log.info("Roles routes registered");
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { requireAdmin, requireAuth } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
import { requireAuth } from "../plugins/auth.js";
|
||||
|
||||
const HTML_TAG_PATTERN = /<[a-z/!][^>]*>/i;
|
||||
|
||||
@@ -31,7 +32,7 @@ export async function settingsRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// PUT /api/v1/settings — Save settings (admin only)
|
||||
app.put("/api/v1/settings", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("settings:write")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const body = request.body as Record<string, unknown> | null;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { requireAdmin } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
function validateTeamName(name: unknown): string | null {
|
||||
if (typeof name !== "string") return "Team name is required";
|
||||
@@ -24,7 +24,7 @@ function validateTeamName(name: unknown): string | null {
|
||||
export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// GET /api/v1/teams — List all teams with member count (admin only)
|
||||
app.get("/api/v1/teams", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requireAdmin(request, reply);
|
||||
const user = requirePermission("teams:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const teams = db
|
||||
@@ -47,7 +47,7 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// POST /api/v1/teams — Create team (admin only)
|
||||
app.post("/api/v1/teams", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("teams:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const body = request.body as { name?: string } | null;
|
||||
@@ -81,7 +81,7 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.put(
|
||||
"/api/v1/teams/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("teams:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { id } = request.params;
|
||||
@@ -122,7 +122,7 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.delete(
|
||||
"/api/v1/teams/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("teams:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { id } = request.params;
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
import { validateImageBuffer } from "../lib/file-validation.js";
|
||||
import { sanitizeFilename } from "../lib/filename.js";
|
||||
import { ensureSharpCompat } from "../lib/heic-converter.js";
|
||||
import { hasEffectivePermission } from "../permissions.js";
|
||||
import { getAuthUser, requireAuth } from "../plugins/auth.js";
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────
|
||||
@@ -115,8 +116,8 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
// Build the where clauses
|
||||
const conditions = [latestCondition];
|
||||
|
||||
// Non-admin users only see their own files; admins see all
|
||||
if (user.role !== "admin") {
|
||||
// Users without files:all only see their own files
|
||||
if (!hasEffectivePermission(user, "files:all")) {
|
||||
conditions.push(eq(schema.userFiles.userId, user.id));
|
||||
}
|
||||
|
||||
@@ -241,7 +242,7 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
const file = db.select().from(schema.userFiles).where(eq(schema.userFiles.id, id)).get();
|
||||
|
||||
if (!file || (user.role !== "admin" && file.userId !== user.id)) {
|
||||
if (!file || (file.userId !== user.id && !hasEffectivePermission(user, "files:all"))) {
|
||||
return reply.status(404).send({ error: "File not found" });
|
||||
}
|
||||
|
||||
@@ -321,7 +322,7 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
const file = db.select().from(schema.userFiles).where(eq(schema.userFiles.id, id)).get();
|
||||
|
||||
if (!file || (user.role !== "admin" && file.userId !== user.id)) {
|
||||
if (!file || (file.userId !== user.id && !hasEffectivePermission(user, "files:all"))) {
|
||||
return reply.status(404).send({ error: "File not found" });
|
||||
}
|
||||
|
||||
@@ -422,7 +423,8 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
for (const id of ids) {
|
||||
// Ownership check: non-admin users can only delete their own files
|
||||
const file = db.select().from(schema.userFiles).where(eq(schema.userFiles.id, id)).get();
|
||||
if (!file || (user.role !== "admin" && file.userId !== user.id)) continue;
|
||||
if (!file || (file.userId !== user.id && !hasEffectivePermission(user, "files:all")))
|
||||
continue;
|
||||
// Collect all files in the chain using a recursive CTE
|
||||
const chainRows = sqlite
|
||||
.prepare(`
|
||||
|
||||
Reference in New Issue
Block a user