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:
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* API key edge-case tests — name validation, delete behavior, key revocation.
|
||||
*/
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
const uid = () => `akec_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
// Helper: register a user, clear mustChangePassword, return credentials + token
|
||||
async function createUserAndLogin(
|
||||
opts: { role?: string } = {},
|
||||
): Promise<{ username: string; password: string; id: string; token: string }> {
|
||||
const username = uid();
|
||||
const password = "ValidPass1";
|
||||
const regRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username, password, ...opts },
|
||||
});
|
||||
if (regRes.statusCode !== 201) {
|
||||
throw new Error(`createUserAndLogin register failed: ${regRes.statusCode} ${regRes.body}`);
|
||||
}
|
||||
const regBody = JSON.parse(regRes.body);
|
||||
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, username))
|
||||
.run();
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username, password },
|
||||
});
|
||||
const loginBody = JSON.parse(loginRes.body);
|
||||
if (!loginBody.token) {
|
||||
throw new Error(`createUserAndLogin login failed: ${loginRes.body}`);
|
||||
}
|
||||
|
||||
return { username, password, id: regBody.id, token: loginBody.token };
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Creation validation
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("API key creation validation", () => {
|
||||
it("rejects name longer than 100 chars", async () => {
|
||||
const longName = "x".repeat(101);
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: longName },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("uses default name when body is empty", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.name).toBe("Default API Key");
|
||||
});
|
||||
|
||||
it("trims whitespace from name", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: " padded-name " },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.name).toBe("padded-name");
|
||||
});
|
||||
|
||||
it("returns raw key starting with si_ only on creation", async () => {
|
||||
const createRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "raw-key-check" },
|
||||
});
|
||||
expect(createRes.statusCode).toBe(201);
|
||||
const createBody = JSON.parse(createRes.body);
|
||||
expect(createBody.key).toBeDefined();
|
||||
expect(createBody.key.startsWith("si_")).toBe(true);
|
||||
|
||||
// GET list must NOT include the raw key
|
||||
const listRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const listBody = JSON.parse(listRes.body);
|
||||
const match = listBody.apiKeys.find((k: any) => k.id === createBody.id);
|
||||
expect(match).toBeDefined();
|
||||
expect(match.key).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects invalid expiresAt format", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "bad-date-key", expiresAt: "not-a-date" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Delete behavior
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("API key delete behavior", () => {
|
||||
it("user can delete own key", async () => {
|
||||
const createRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "delete-me" },
|
||||
});
|
||||
const keyId = JSON.parse(createRes.body).id;
|
||||
|
||||
const delRes = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/api-keys/${keyId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(delRes.statusCode).toBe(200);
|
||||
const body = JSON.parse(delRes.body);
|
||||
expect(body.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("user cannot delete another user's key", async () => {
|
||||
// Admin creates a key
|
||||
const adminKeyRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "admin-owned-key" },
|
||||
});
|
||||
const adminKeyId = JSON.parse(adminKeyRes.body).id;
|
||||
|
||||
// Create a separate user
|
||||
const other = await createUserAndLogin({ role: "user" });
|
||||
|
||||
// Other user tries to delete admin's key
|
||||
const delRes = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/api-keys/${adminKeyId}`,
|
||||
headers: { authorization: `Bearer ${other.token}` },
|
||||
});
|
||||
expect(delRes.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("delete non-existent key returns 404", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: "/api/v1/api-keys/00000000-0000-0000-0000-000000000000",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("deleted key stops working immediately", async () => {
|
||||
// Create a key and verify it works
|
||||
const createRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "revoke-test-key" },
|
||||
});
|
||||
const { id: keyId, key: rawKey } = JSON.parse(createRes.body);
|
||||
|
||||
// Use the key — should succeed
|
||||
const beforeRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${rawKey}` },
|
||||
});
|
||||
expect(beforeRes.statusCode).toBe(200);
|
||||
|
||||
// Delete the key
|
||||
const delRes = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/api-keys/${keyId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(delRes.statusCode).toBe(200);
|
||||
|
||||
// Use the key again — should fail
|
||||
const afterRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${rawKey}` },
|
||||
});
|
||||
expect(afterRes.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
describe("API key permission scoping", () => {
|
||||
it("creates a key with scoped permissions", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "scoped-key", permissions: ["tools:use", "files:own"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.permissions).toEqual(["tools:use", "files:own"]);
|
||||
expect(body.key).toBeTruthy();
|
||||
});
|
||||
|
||||
it("rejects permissions the user does not have", async () => {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "scopetest", password: "ScopeTest1", role: "user" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, "scopetest"))
|
||||
.run();
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "scopetest", password: "ScopeTest1" },
|
||||
});
|
||||
const userToken = JSON.parse(loginRes.body).token;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
payload: { name: "bad-scope", permissions: ["users:manage"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("scoped API key is restricted to its permissions", async () => {
|
||||
const createRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "readonly-key", permissions: ["tools:use", "settings:read"] },
|
||||
});
|
||||
const apiKey = JSON.parse(createRes.body).key;
|
||||
|
||||
const settingsRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
});
|
||||
expect(settingsRes.statusCode).toBe(200);
|
||||
|
||||
const writeRes = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
payload: { appName: "hacked" },
|
||||
});
|
||||
expect(writeRes.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("null permissions inherits all from user role", async () => {
|
||||
const createRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "full-key" },
|
||||
});
|
||||
const body = JSON.parse(createRes.body);
|
||||
expect(body.permissions).toBeNull();
|
||||
|
||||
const writeRes = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${body.key}` },
|
||||
payload: { testSetting: "value" },
|
||||
});
|
||||
expect(writeRes.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("GET /api/v1/api-keys returns permissions field", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.apiKeys.length).toBeGreaterThan(0);
|
||||
const scopedKey = body.apiKeys.find((k: any) => k.name === "scoped-key");
|
||||
expect(scopedKey).toBeDefined();
|
||||
expect(scopedKey.permissions).toEqual(["tools:use", "files:own"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("API key expiration", () => {
|
||||
it("creates key with expiration", async () => {
|
||||
const future = new Date(Date.now() + 86400000).toISOString(); // 24h from now
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "expiring-key", expiresAt: future },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.expiresAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it("rejects past expiration date", async () => {
|
||||
const past = new Date(Date.now() - 86400000).toISOString();
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "past-key", expiresAt: past },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("expired key returns 401", async () => {
|
||||
// Create a key, then manually set its expiration to the past
|
||||
const createRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "will-expire", expiresAt: new Date(Date.now() + 86400000).toISOString() },
|
||||
});
|
||||
const apiKey = JSON.parse(createRes.body).key;
|
||||
const keyId = JSON.parse(createRes.body).id;
|
||||
|
||||
// Manually expire the key in DB
|
||||
db.update(schema.apiKeys)
|
||||
.set({ expiresAt: new Date(Date.now() - 1000) })
|
||||
.where(eq(schema.apiKeys.id, keyId))
|
||||
.run();
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("GET returns expiresAt field", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
const expiringKey = body.apiKeys.find((k: any) => k.name === "expiring-key");
|
||||
expect(expiringKey).toBeDefined();
|
||||
expect(expiringKey.expiresAt).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Helper */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function fetchAuditLog(
|
||||
qs = "",
|
||||
): Promise<{ entries: any[]; total: number; page: number; limit: number }> {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/audit-log${qs ? `?${qs}` : ""}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return JSON.parse(res.body);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Event recording */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("audit log event recording", () => {
|
||||
it("LOGIN_SUCCESS recorded after login", async () => {
|
||||
const body = await fetchAuditLog("action=LOGIN_SUCCESS");
|
||||
expect(body.entries.length).toBeGreaterThan(0);
|
||||
expect(body.entries[0].action).toBe("LOGIN_SUCCESS");
|
||||
});
|
||||
|
||||
it("USER_CREATED recorded after register", async () => {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
username: "audit_edge_user",
|
||||
password: "AuditEdge1",
|
||||
role: "user",
|
||||
},
|
||||
});
|
||||
|
||||
const body = await fetchAuditLog("action=USER_CREATED");
|
||||
expect(body.entries.length).toBeGreaterThan(0);
|
||||
expect(body.entries.some((e: any) => e.action === "USER_CREATED")).toBe(true);
|
||||
});
|
||||
|
||||
it("API_KEY_CREATED recorded after key creation", async () => {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "audit-edge-key" },
|
||||
});
|
||||
|
||||
const body = await fetchAuditLog("action=API_KEY_CREATED");
|
||||
expect(body.entries.length).toBeGreaterThan(0);
|
||||
expect(body.entries.some((e: any) => e.action === "API_KEY_CREATED")).toBe(true);
|
||||
});
|
||||
|
||||
it("ROLE_CREATED recorded after role creation", async () => {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
name: "audit-edge-role",
|
||||
description: "role for audit edge test",
|
||||
permissions: ["tools:use"],
|
||||
},
|
||||
});
|
||||
|
||||
const body = await fetchAuditLog("action=ROLE_CREATED");
|
||||
expect(body.entries.length).toBeGreaterThan(0);
|
||||
expect(body.entries.some((e: any) => e.action === "ROLE_CREATED")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Pagination edge cases */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("audit log pagination edge cases", () => {
|
||||
it("page=0 clamped to 1", async () => {
|
||||
const body = await fetchAuditLog("page=0");
|
||||
expect(body.page).toBe(1);
|
||||
});
|
||||
|
||||
it("negative page clamped to 1", async () => {
|
||||
const body = await fetchAuditLog("page=-5");
|
||||
expect(body.page).toBe(1);
|
||||
});
|
||||
|
||||
it("limit=500 clamped to 100", async () => {
|
||||
const body = await fetchAuditLog("limit=500");
|
||||
expect(body.limit).toBe(100);
|
||||
});
|
||||
|
||||
it("limit=0 falls back to default (50)", async () => {
|
||||
const body = await fetchAuditLog("limit=0");
|
||||
expect(body.limit).toBe(50);
|
||||
});
|
||||
|
||||
it("non-numeric values use defaults", async () => {
|
||||
const body = await fetchAuditLog("page=abc&limit=xyz");
|
||||
expect(body.page).toBe(1);
|
||||
expect(body.limit).toBe(50);
|
||||
});
|
||||
|
||||
it("high page number returns empty entries", async () => {
|
||||
const body = await fetchAuditLog("page=99999");
|
||||
expect(body.entries).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Entry structure */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("audit log entry structure", () => {
|
||||
it("each entry has id, actorUsername, action, createdAt (valid ISO date)", async () => {
|
||||
const body = await fetchAuditLog("limit=10");
|
||||
expect(body.entries.length).toBeGreaterThan(0);
|
||||
|
||||
for (const entry of body.entries) {
|
||||
expect(entry).toHaveProperty("id");
|
||||
expect(typeof entry.id).toBe("string");
|
||||
|
||||
expect(entry).toHaveProperty("actorUsername");
|
||||
expect(typeof entry.actorUsername).toBe("string");
|
||||
|
||||
expect(entry).toHaveProperty("action");
|
||||
expect(typeof entry.action).toBe("string");
|
||||
|
||||
expect(entry).toHaveProperty("createdAt");
|
||||
expect(typeof entry.createdAt).toBe("string");
|
||||
const parsed = new Date(entry.createdAt);
|
||||
expect(Number.isNaN(parsed.getTime())).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
describe("audit log", () => {
|
||||
it("records login events in database", async () => {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "admin", password: "Adminpass1" },
|
||||
});
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/audit-log",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.entries).toBeDefined();
|
||||
expect(body.entries.length).toBeGreaterThan(0);
|
||||
expect(body.entries.some((e: any) => e.action === "LOGIN_SUCCESS")).toBe(true);
|
||||
});
|
||||
|
||||
it("requires audit:read permission", async () => {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
username: "auditnoread",
|
||||
password: "AuditTest1",
|
||||
role: "user",
|
||||
},
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, "auditnoread"))
|
||||
.run();
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "auditnoread", password: "AuditTest1" },
|
||||
});
|
||||
const userToken = JSON.parse(loginRes.body).token;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/audit-log",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("supports pagination", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/audit-log?limit=2&page=1",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.entries.length).toBeLessThanOrEqual(2);
|
||||
expect(body.total).toBeDefined();
|
||||
expect(body.page).toBe(1);
|
||||
expect(body.limit).toBe(2);
|
||||
});
|
||||
|
||||
it("supports action filter", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/audit-log?action=LOGIN_SUCCESS",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
for (const entry of body.entries) {
|
||||
expect(entry.action).toBe("LOGIN_SUCCESS");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,404 @@
|
||||
/**
|
||||
* Auth route edge-case tests — login failures, session expiry,
|
||||
* password-change side effects, register validation.
|
||||
*/
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
const uid = () => `auth_test_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
// Helper: register a user, clear mustChangePassword, return { username, password }
|
||||
async function createUser(
|
||||
opts: { role?: string; team?: string } = {},
|
||||
): Promise<{ username: string; password: string; id: string }> {
|
||||
const username = uid();
|
||||
const password = "ValidPass1";
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username, password, ...opts },
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
if (res.statusCode !== 201) {
|
||||
throw new Error(`createUser failed: ${res.statusCode} ${res.body}`);
|
||||
}
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, username))
|
||||
.run();
|
||||
return { username, password, id: body.id };
|
||||
}
|
||||
|
||||
// Helper: login and return token
|
||||
async function loginAs(username: string, password: string): Promise<string> {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username, password },
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
if (!body.token) throw new Error(`loginAs failed: ${res.body}`);
|
||||
return body.token as string;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// LOGIN FAILURES
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("Login failures", () => {
|
||||
it("empty body returns 400", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("missing username returns 400", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { password: "Anything1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("missing password returns 400", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "admin" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("unknown username returns 401", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: `nonexistent_${Date.now()}`, password: "Whatever1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("wrong password returns 401", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "admin", password: "WrongPass1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("failed logins generate LOGIN_FAILED audit events", async () => {
|
||||
const marker = uid();
|
||||
// Trigger a failed login with a unique username
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: marker, password: "Whatever1" },
|
||||
});
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/audit-log?action=LOGIN_FAILED&limit=50",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
const match = body.entries.find(
|
||||
(e: any) => e.action === "LOGIN_FAILED" && e.details?.username === marker,
|
||||
);
|
||||
expect(match).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// SESSION EDGE CASES
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("Session edge cases", () => {
|
||||
it("no token on session endpoint returns 401", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("expired session token returns 401", async () => {
|
||||
// Login to get a valid session
|
||||
const token = await loginAs("admin", "Adminpass1");
|
||||
|
||||
// Manually expire the session in the DB
|
||||
db.update(schema.sessions)
|
||||
.set({ expiresAt: new Date(Date.now() - 60_000) })
|
||||
.where(eq(schema.sessions.id, token))
|
||||
.run();
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// PASSWORD CHANGE SIDE EFFECTS
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("Password change side effects", () => {
|
||||
it("changing password invalidates other sessions", async () => {
|
||||
const { username, password } = await createUser();
|
||||
|
||||
// Create two sessions
|
||||
const token1 = await loginAs(username, password);
|
||||
const token2 = await loginAs(username, password);
|
||||
|
||||
// Verify both sessions work
|
||||
const check1 = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${token1}` },
|
||||
});
|
||||
expect(check1.statusCode).toBe(200);
|
||||
|
||||
const check2 = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${token2}` },
|
||||
});
|
||||
expect(check2.statusCode).toBe(200);
|
||||
|
||||
// Change password via session 1
|
||||
const changeRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/change-password",
|
||||
headers: { authorization: `Bearer ${token1}` },
|
||||
payload: { currentPassword: password, newPassword: "NewValid1" },
|
||||
});
|
||||
expect(changeRes.statusCode).toBe(200);
|
||||
|
||||
// Session 1 should still work (it's the current session)
|
||||
const after1 = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${token1}` },
|
||||
});
|
||||
expect(after1.statusCode).toBe(200);
|
||||
|
||||
// Session 2 should now be invalid
|
||||
const after2 = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${token2}` },
|
||||
});
|
||||
expect(after2.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("changing password revokes API keys", async () => {
|
||||
const { username, password } = await createUser();
|
||||
const token = await loginAs(username, password);
|
||||
|
||||
// Create an API key
|
||||
const createKeyRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { name: "test-key" },
|
||||
});
|
||||
expect(createKeyRes.statusCode).toBe(201);
|
||||
const apiKey = JSON.parse(createKeyRes.body).key;
|
||||
|
||||
// Verify the key works (hit a public-ish endpoint that still reads auth)
|
||||
const keyCheck = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
});
|
||||
expect(keyCheck.statusCode).toBe(200);
|
||||
|
||||
// Change password
|
||||
const changeRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/change-password",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { currentPassword: password, newPassword: "NewValid2" },
|
||||
});
|
||||
expect(changeRes.statusCode).toBe(200);
|
||||
|
||||
// API key should now be revoked
|
||||
const keyAfter = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
});
|
||||
expect(keyAfter.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// PASSWORD RESET SIDE EFFECTS (admin resets another user)
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("Password reset side effects", () => {
|
||||
it("admin reset invalidates target user sessions", async () => {
|
||||
const { username, password, id } = await createUser();
|
||||
const userToken = await loginAs(username, password);
|
||||
|
||||
// Verify user session works
|
||||
const before = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
});
|
||||
expect(before.statusCode).toBe(200);
|
||||
|
||||
// Admin resets the user's password
|
||||
const resetRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: `/api/auth/users/${id}/reset-password`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { newPassword: "ResetPass1" },
|
||||
});
|
||||
expect(resetRes.statusCode).toBe(200);
|
||||
|
||||
// User session should now be invalid
|
||||
const after = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
});
|
||||
expect(after.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("admin reset revokes target user API keys", async () => {
|
||||
const { username, password, id } = await createUser();
|
||||
const userToken = await loginAs(username, password);
|
||||
|
||||
// Create an API key for the target user
|
||||
const createKeyRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
payload: { name: "target-key" },
|
||||
});
|
||||
expect(createKeyRes.statusCode).toBe(201);
|
||||
const apiKey = JSON.parse(createKeyRes.body).key;
|
||||
|
||||
// Verify the key works
|
||||
const keyBefore = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
});
|
||||
expect(keyBefore.statusCode).toBe(200);
|
||||
|
||||
// Admin resets the user's password
|
||||
const resetRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: `/api/auth/users/${id}/reset-password`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { newPassword: "ResetPass2" },
|
||||
});
|
||||
expect(resetRes.statusCode).toBe(200);
|
||||
|
||||
// API key should now be revoked
|
||||
const keyAfter = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
});
|
||||
expect(keyAfter.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// REGISTER VALIDATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("Register validation", () => {
|
||||
it("invalid username chars returns 400", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "bad user!@#", password: "ValidPass1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("username too short (2 chars) returns 400", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "ab", password: "ValidPass1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("weak password returns 400", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: uid(), password: "weak" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("non-existent team name returns 400", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
username: uid(),
|
||||
password: "ValidPass1",
|
||||
team: `ghost_team_${Date.now()}`,
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("unknown role defaults to user", async () => {
|
||||
const username = uid();
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username, password: "ValidPass1", role: "bogus" },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.role).toBe("user");
|
||||
});
|
||||
|
||||
it("delete non-existent user returns 404", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: "/api/auth/users/00000000-0000-0000-0000-000000000000",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,280 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Create a custom role and return its id. */
|
||||
async function createRole(
|
||||
name: string,
|
||||
permissions: string[],
|
||||
description?: string,
|
||||
): Promise<string> {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name, permissions, description },
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
if (res.statusCode !== 201) {
|
||||
throw new Error(`createRole failed (${res.statusCode}): ${res.body}`);
|
||||
}
|
||||
return body.id as string;
|
||||
}
|
||||
|
||||
/** Register a user, clear mustChangePassword, return a session token. */
|
||||
async function createUserAndLogin(
|
||||
username: string,
|
||||
password: string,
|
||||
role: string,
|
||||
): Promise<string> {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username, password, role },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, username))
|
||||
.run();
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username, password },
|
||||
});
|
||||
return JSON.parse(loginRes.body).token as string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Name validation (5 tests)
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("name validation", () => {
|
||||
it("rejects name shorter than 2 chars", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "x", permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("rejects name longer than 30 chars", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "a".repeat(31), permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("rejects name with spaces", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "bad role", permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("normalizes uppercase to lowercase", async () => {
|
||||
const suffix = Date.now();
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: `UpperCase${suffix}`, permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.name).toBe(`uppercase${suffix}`);
|
||||
});
|
||||
|
||||
it("accepts hyphen and underscore", async () => {
|
||||
const suffix = Date.now();
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: `ok-role_${suffix}`, permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.name).toBe(`ok-role_${suffix}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Permission validation (3 tests)
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("permission validation", () => {
|
||||
it("rejects invalid permission names", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: `inv-${Date.now()}`, permissions: ["fly:to-moon"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).error).toContain("Invalid permissions");
|
||||
});
|
||||
|
||||
it("rejects missing permissions field", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: `noperms-${Date.now()}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("rejects missing name field", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CRUD edge cases (5 tests)
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("CRUD edge cases", () => {
|
||||
it("PUT non-existent role returns 404", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/v1/roles/00000000-0000-0000-0000-000000000000",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("DELETE non-existent role returns 404", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: "/api/v1/roles/00000000-0000-0000-0000-000000000000",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("updates role description", async () => {
|
||||
const id = await createRole(`desc-${Date.now()}`, ["tools:use"], "original");
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/v1/roles/${id}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { description: "updated description" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("rejects invalid permissions on update", async () => {
|
||||
const id = await createRole(`upd-${Date.now()}`, ["tools:use"]);
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/v1/roles/${id}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { permissions: ["nonexistent:perm"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).error).toContain("Invalid permissions");
|
||||
});
|
||||
|
||||
it("multiple users on deleted role all get reassigned to user", async () => {
|
||||
const suffix = Date.now();
|
||||
const roleName = `multi-${suffix}`;
|
||||
const roleId = await createRole(roleName, ["tools:use", "files:own"]);
|
||||
|
||||
// Register three users on this role
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
username: `multi-u${i}-${suffix}`,
|
||||
password: "TestPass1",
|
||||
role: roleName,
|
||||
},
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, `multi-u${i}-${suffix}`))
|
||||
.run();
|
||||
}
|
||||
|
||||
// Delete the role
|
||||
const delRes = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/roles/${roleId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(delRes.statusCode).toBe(200);
|
||||
|
||||
// Verify all three users were reassigned to "user"
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: `multi-u${i}-${suffix}`, password: "TestPass1" },
|
||||
});
|
||||
const body = JSON.parse(loginRes.body);
|
||||
expect(body.user.role).toBe("user");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functional permissions (1 test)
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("functional permissions", () => {
|
||||
it("custom role with only settings:read can read settings but not audit log", async () => {
|
||||
const suffix = Date.now();
|
||||
const roleName = `readonly-${suffix}`;
|
||||
await createRole(roleName, ["settings:read"]);
|
||||
|
||||
const token = await createUserAndLogin(`ro-user-${suffix}`, "ReadOnly1", roleName);
|
||||
|
||||
// Can read settings (GET /api/v1/settings requires only authentication)
|
||||
const settingsRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/settings",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(settingsRes.statusCode).toBe(200);
|
||||
|
||||
// Cannot access audit log (requires audit:read permission)
|
||||
const auditRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/audit-log",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(auditRes.statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
describe("custom roles", () => {
|
||||
let customRoleId: string;
|
||||
|
||||
it("lists built-in roles", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.roles.length).toBeGreaterThanOrEqual(3);
|
||||
expect(body.roles.some((r: any) => r.name === "admin" && r.isBuiltin)).toBe(true);
|
||||
expect(body.roles.some((r: any) => r.name === "editor" && r.isBuiltin)).toBe(true);
|
||||
expect(body.roles.some((r: any) => r.name === "user" && r.isBuiltin)).toBe(true);
|
||||
});
|
||||
|
||||
it("creates a custom role", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
name: "reviewer",
|
||||
description: "Can view all files and pipelines",
|
||||
permissions: ["files:all", "pipelines:all", "settings:read"],
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.name).toBe("reviewer");
|
||||
expect(body.permissions).toEqual(["files:all", "pipelines:all", "settings:read"]);
|
||||
customRoleId = body.id;
|
||||
});
|
||||
|
||||
it("cannot create duplicate role name", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "admin", permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(409);
|
||||
});
|
||||
|
||||
it("can assign custom role to user", async () => {
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "customroleuser", password: "CustomRole1", role: "reviewer" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, "customroleuser"))
|
||||
.run();
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "customroleuser", password: "CustomRole1" },
|
||||
});
|
||||
const body = JSON.parse(loginRes.body);
|
||||
expect(body.user.role).toBe("reviewer");
|
||||
expect(body.user.permissions).toContain("files:all");
|
||||
expect(body.user.permissions).not.toContain("tools:use");
|
||||
});
|
||||
|
||||
it("updates custom role permissions", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/v1/roles/${customRoleId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { permissions: ["files:all", "pipelines:all", "settings:read", "tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("cannot modify built-in roles", async () => {
|
||||
const listRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const builtinRole = JSON.parse(listRes.body).roles.find((r: any) => r.name === "admin");
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/v1/roles/${builtinRole.id}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { permissions: ["tools:use"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("cannot delete built-in roles", async () => {
|
||||
const listRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const builtinRole = JSON.parse(listRes.body).roles.find((r: any) => r.name === "admin");
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/roles/${builtinRole.id}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("deleting custom role reassigns users to user", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/roles/${customRoleId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "customroleuser", password: "CustomRole1" },
|
||||
});
|
||||
const body = JSON.parse(loginRes.body);
|
||||
expect(body.user.role).toBe("user");
|
||||
});
|
||||
|
||||
it("requires users:manage to create roles", async () => {
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "customroleuser", password: "CustomRole1" },
|
||||
});
|
||||
const userToken = JSON.parse(loginRes.body).token;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
payload: { name: "hacker", permissions: ["users:manage"] },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
const ts = Date.now();
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
/**
|
||||
* Helper: register a user via the admin endpoint and return the response.
|
||||
*/
|
||||
async function registerUser(token: string, username: string, role: string, password = "Testpass1") {
|
||||
return testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { username, password, role },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: log in as a given user and return the session token.
|
||||
*/
|
||||
async function loginAs(username: string, password = "Testpass1"): Promise<string> {
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, username))
|
||||
.run();
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username, password },
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
if (!body.token) {
|
||||
throw new Error(`loginAs(${username}) failed: ${res.body}`);
|
||||
}
|
||||
return body.token as string;
|
||||
}
|
||||
|
||||
// ── Register route escalation ─────────────────────────────────────
|
||||
|
||||
describe("register route escalation", () => {
|
||||
it("1. admin can create an admin user (201)", async () => {
|
||||
const res = await registerUser(adminToken, `adm_${ts}_1`, "admin");
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(JSON.parse(res.body).role).toBe("admin");
|
||||
});
|
||||
|
||||
it("2. admin can create an editor user (201)", async () => {
|
||||
const res = await registerUser(adminToken, `edt_${ts}_2`, "editor");
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(JSON.parse(res.body).role).toBe("editor");
|
||||
});
|
||||
|
||||
it("3. admin can create a regular user (201)", async () => {
|
||||
const res = await registerUser(adminToken, `usr_${ts}_3`, "user");
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(JSON.parse(res.body).role).toBe("user");
|
||||
});
|
||||
|
||||
it("4. editor cannot register anyone (403 — lacks users:manage)", async () => {
|
||||
await registerUser(adminToken, `edt_${ts}_4`, "editor");
|
||||
const editorToken = await loginAs(`edt_${ts}_4`);
|
||||
|
||||
const res = await registerUser(editorToken, `blocked_${ts}_4`, "user");
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("5. user cannot register anyone (403 — lacks users:manage)", async () => {
|
||||
await registerUser(adminToken, `usr_${ts}_5`, "user");
|
||||
const userToken = await loginAs(`usr_${ts}_5`);
|
||||
|
||||
const res = await registerUser(userToken, `blocked_${ts}_5`, "user");
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("6. unauthenticated cannot register (401)", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `anon_${ts}_6`, password: "Testpass1", role: "user" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Update user role escalation ───────────────────────────────────
|
||||
|
||||
describe("update user role escalation", () => {
|
||||
let targetUserId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await registerUser(adminToken, `target_${ts}_upd`, "user");
|
||||
targetUserId = JSON.parse(res.body).id;
|
||||
});
|
||||
|
||||
it("7. admin can promote user -> editor (200)", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${targetUserId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "editor" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("8. admin can promote user -> admin (200)", async () => {
|
||||
// Reset target to user first
|
||||
await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${targetUserId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "user" },
|
||||
});
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${targetUserId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "admin" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("9. admin can demote editor -> user (200)", async () => {
|
||||
// Set target to editor
|
||||
await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${targetUserId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "editor" },
|
||||
});
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${targetUserId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "user" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("10. admin cannot self-demote (400 SELF_DEMOTE)", async () => {
|
||||
const sessionRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const adminId = JSON.parse(sessionRes.body).user.id;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${adminId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "user" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("SELF_DEMOTE");
|
||||
});
|
||||
|
||||
it("11. last admin cannot be demoted (400 LAST_ADMIN)", async () => {
|
||||
// To test the LAST_ADMIN guard we need: actor is admin, target is a
|
||||
// different admin, and target is the sole admin. The actor being admin
|
||||
// means adminCount >= 2, so the guard normally won't fire through the
|
||||
// API. We use DB manipulation to demote all other admins except the
|
||||
// target, keeping the actor's session alive (middleware reads role from
|
||||
// the users table at request time, so we temporarily set the actor back
|
||||
// to admin just for the request by doing the role swap around the call).
|
||||
//
|
||||
// Simpler approach: demote every admin except the original to non-admin
|
||||
// via DB, then verify self-demote blocks the last admin. SELF_DEMOTE
|
||||
// fires first in the code, which is correct — both guards protect the
|
||||
// last admin.
|
||||
|
||||
const sessionRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const originalAdminId = JSON.parse(sessionRes.body).user.id;
|
||||
|
||||
// Demote ALL admins except the original via DB
|
||||
const allUsers = db.select().from(schema.users).all();
|
||||
for (const u of allUsers) {
|
||||
if (u.role === "admin" && u.id !== originalAdminId) {
|
||||
db.update(schema.users).set({ role: "user" }).where(eq(schema.users.id, u.id)).run();
|
||||
}
|
||||
}
|
||||
|
||||
// Confirm only 1 admin exists
|
||||
const usersRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/users",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const admins = JSON.parse(usersRes.body).users.filter(
|
||||
(u: { role: string }) => u.role === "admin",
|
||||
);
|
||||
expect(admins.length).toBe(1);
|
||||
|
||||
// Attempt to demote the sole admin (self-demote fires first, which is
|
||||
// the correct behavior — the last admin is protected)
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${originalAdminId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "user" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
// SELF_DEMOTE fires before LAST_ADMIN because the code checks id === admin.id first
|
||||
expect(["SELF_DEMOTE", "LAST_ADMIN"]).toContain(JSON.parse(res.body).code);
|
||||
});
|
||||
|
||||
it("12. admin can demote another admin when 2+ admins exist (200)", async () => {
|
||||
const res2 = await registerUser(adminToken, `adm2_${ts}_12`, "admin");
|
||||
const admin2Id = JSON.parse(res2.body).id;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${admin2Id}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "user" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Self-delete prevention ────────────────────────────────────────
|
||||
|
||||
describe("self-delete prevention", () => {
|
||||
it("13. admin cannot delete themselves (400 SELF_DELETE)", async () => {
|
||||
const sessionRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const adminId = JSON.parse(sessionRes.body).user.id;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/auth/users/${adminId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("SELF_DELETE");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
/**
|
||||
* Cross-user ownership enforcement tests.
|
||||
*
|
||||
* Validates that files and pipelines are properly scoped per-user,
|
||||
* that editors (files:all, pipelines:all) can see everything,
|
||||
* and that API key scoping respects ownership boundaries.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, createMultipartPayload, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
|
||||
// Unique suffix to avoid collisions with other test files sharing the DB
|
||||
const ts = Date.now();
|
||||
const userAName = `own_userA_${ts}`;
|
||||
const userBName = `own_userB_${ts}`;
|
||||
const editorName = `own_editor_${ts}`;
|
||||
|
||||
let userAToken: string;
|
||||
let userBToken: string;
|
||||
let editorToken: string;
|
||||
|
||||
// Shared state across tests
|
||||
let userAFileId: string;
|
||||
let userAPipelineId: string;
|
||||
|
||||
// Load test fixture
|
||||
const fixtureBuffer = readFileSync(join(import.meta.dirname, "..", "fixtures", "test-1x1.png"));
|
||||
|
||||
/** Register a user, clear mustChangePassword, log in, return token. */
|
||||
async function createAndLogin(
|
||||
app: TestApp["app"],
|
||||
token: string,
|
||||
username: string,
|
||||
role: "user" | "editor" | "admin",
|
||||
): Promise<string> {
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { username, password: "TestPass1", role },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, username))
|
||||
.run();
|
||||
const loginRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username, password: "TestPass1" },
|
||||
});
|
||||
const body = JSON.parse(loginRes.body);
|
||||
if (!body.token) throw new Error(`Login failed for ${username}: ${loginRes.body}`);
|
||||
return body.token as string;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
|
||||
// Create three actors: userA (user), userB (user), editor
|
||||
userAToken = await createAndLogin(testApp.app, adminToken, userAName, "user");
|
||||
userBToken = await createAndLogin(testApp.app, adminToken, userBName, "user");
|
||||
editorToken = await createAndLogin(testApp.app, adminToken, editorName, "editor");
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
// ── File ownership ────────────────────────────────────────────────────
|
||||
|
||||
describe("file ownership enforcement", () => {
|
||||
it("1. user A uploads a file -> 201", async () => {
|
||||
const { body, contentType } = createMultipartPayload([
|
||||
{
|
||||
name: "file",
|
||||
filename: "userA-image.png",
|
||||
contentType: "image/png",
|
||||
content: fixtureBuffer,
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/files/upload",
|
||||
headers: {
|
||||
"content-type": contentType,
|
||||
authorization: `Bearer ${userAToken}`,
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const parsed = JSON.parse(res.body);
|
||||
expect(parsed.files).toHaveLength(1);
|
||||
userAFileId = parsed.files[0].id;
|
||||
});
|
||||
|
||||
it("2. user A can access their own file -> 200", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/files/${userAFileId}`,
|
||||
headers: { authorization: `Bearer ${userAToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
expect(parsed.file.id).toBe(userAFileId);
|
||||
});
|
||||
|
||||
it("3. user B cannot access user A's file -> 404", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/files/${userAFileId}`,
|
||||
headers: { authorization: `Bearer ${userBToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("4. editor can access user A's file (has files:all) -> 200", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/files/${userAFileId}`,
|
||||
headers: { authorization: `Bearer ${editorToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
expect(parsed.file.id).toBe(userAFileId);
|
||||
});
|
||||
|
||||
it("5. admin can access user A's file -> 200", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/files/${userAFileId}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
expect(parsed.file.id).toBe(userAFileId);
|
||||
});
|
||||
|
||||
it("6. user B's file list does NOT contain user A's files", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/files",
|
||||
headers: { authorization: `Bearer ${userBToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
const ids = parsed.files.map((f: { id: string }) => f.id);
|
||||
expect(ids).not.toContain(userAFileId);
|
||||
});
|
||||
|
||||
it("7. editor's file list DOES contain user A's files", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/files",
|
||||
headers: { authorization: `Bearer ${editorToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
const ids = parsed.files.map((f: { id: string }) => f.id);
|
||||
expect(ids).toContain(userAFileId);
|
||||
});
|
||||
|
||||
it("8. user B cannot download user A's file -> 404", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/files/${userAFileId}/download`,
|
||||
headers: { authorization: `Bearer ${userBToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Pipeline ownership ────────────────────────────────────────────────
|
||||
|
||||
describe("pipeline ownership enforcement", () => {
|
||||
it("9. user A saves a pipeline -> 201", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/pipeline/save",
|
||||
headers: { authorization: `Bearer ${userAToken}` },
|
||||
payload: {
|
||||
name: `Pipeline-A-${ts}`,
|
||||
steps: [{ toolId: "rotate", settings: { angle: 90 } }],
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const parsed = JSON.parse(res.body);
|
||||
userAPipelineId = parsed.id;
|
||||
});
|
||||
|
||||
it("10. user B's pipeline list does NOT include user A's pipeline", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/pipeline/list",
|
||||
headers: { authorization: `Bearer ${userBToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
const ids = parsed.pipelines.map((p: { id: string }) => p.id);
|
||||
expect(ids).not.toContain(userAPipelineId);
|
||||
});
|
||||
|
||||
it("11. editor CAN see user A's pipeline (has pipelines:all)", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/pipeline/list",
|
||||
headers: { authorization: `Bearer ${editorToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
const ids = parsed.pipelines.map((p: { id: string }) => p.id);
|
||||
expect(ids).toContain(userAPipelineId);
|
||||
});
|
||||
|
||||
it("12. user B cannot delete user A's pipeline -> 403", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/pipeline/${userAPipelineId}`,
|
||||
headers: { authorization: `Bearer ${userBToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("13. editor can delete user A's pipeline (has pipelines:all) -> 200", async () => {
|
||||
// Save a second pipeline for user A so test 13 doesn't conflict with later tests
|
||||
const saveRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/pipeline/save",
|
||||
headers: { authorization: `Bearer ${userAToken}` },
|
||||
payload: {
|
||||
name: `Pipeline-A-Deletable-${ts}`,
|
||||
steps: [{ toolId: "rotate", settings: { angle: 180 } }],
|
||||
},
|
||||
});
|
||||
const deletableId = JSON.parse(saveRes.body).id;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/v1/pipeline/${deletableId}`,
|
||||
headers: { authorization: `Bearer ${editorToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(res.body);
|
||||
expect(parsed.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("14. delete non-existent pipeline -> 404", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: "/api/v1/pipeline/00000000-0000-0000-0000-000000000000",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
// ── API key scoped ownership ──────────────────────────────────────────
|
||||
|
||||
describe("API key scoped ownership", () => {
|
||||
it("15. admin scoped key without files:all behaves like restricted user for file listing", async () => {
|
||||
// Create an API key for admin that only has files:own (not files:all)
|
||||
const createRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
name: `scoped-no-files-all-${ts}`,
|
||||
permissions: ["tools:use", "files:own", "settings:read"],
|
||||
},
|
||||
});
|
||||
expect(createRes.statusCode).toBe(201);
|
||||
const apiKey = JSON.parse(createRes.body).key;
|
||||
|
||||
// List files using the scoped key -- should NOT see user A's files
|
||||
// because the key only has files:own, scoping to the admin's own files
|
||||
const listRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/files",
|
||||
headers: { authorization: `Bearer ${apiKey}` },
|
||||
});
|
||||
expect(listRes.statusCode).toBe(200);
|
||||
const parsed = JSON.parse(listRes.body);
|
||||
const ids = parsed.files.map((f: { id: string }) => f.id);
|
||||
// user A's file should not appear because the scoped key lacks files:all
|
||||
expect(ids).not.toContain(userAFileId);
|
||||
});
|
||||
});
|
||||
@@ -515,6 +515,88 @@ describe("file ownership scoping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("escalation prevention", () => {
|
||||
it("editor cannot create admin users", async () => {
|
||||
// First create an editor
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "esceditor", password: "EscEditor1", role: "editor" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, "esceditor"))
|
||||
.run();
|
||||
|
||||
const editorLogin = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "esceditor", password: "EscEditor1" },
|
||||
});
|
||||
const editorToken = JSON.parse(editorLogin.body).token;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${editorToken}` },
|
||||
payload: { username: "escalated", password: "Escalated1", role: "admin" },
|
||||
});
|
||||
// Editor doesn't have users:manage, so gets 403
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("cannot demote the last admin", async () => {
|
||||
const listRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/users",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const users = JSON.parse(listRes.body).users;
|
||||
const adminUser = users.find((u: any) => u.username === "admin");
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${adminUser.id}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "user" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.code).toMatch(/SELF_DEMOTE|LAST_ADMIN/);
|
||||
});
|
||||
|
||||
it("admin can demote another admin when multiple admins exist", async () => {
|
||||
// Create a second admin
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "admin2esc", password: "Admin2Esc1", role: "admin" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, "admin2esc"))
|
||||
.run();
|
||||
|
||||
const listRes = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/users",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const users = JSON.parse(listRes.body).users;
|
||||
const secondAdmin = users.find((u: any) => u.username === "admin2esc");
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/auth/users/${secondAdmin.id}`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { role: "editor" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pipeline ownership scoping", () => {
|
||||
let userToken: string;
|
||||
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* Comprehensive RBAC route permission matrix.
|
||||
*
|
||||
* Tests every route × every role (admin, editor, user, unauthenticated)
|
||||
* to verify the correct HTTP status code is returned. Also validates
|
||||
* cross-role session isolation and token edge cases.
|
||||
*/
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
let editorToken: string;
|
||||
let userToken: string;
|
||||
|
||||
const runId = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
|
||||
// Create editor
|
||||
const editorUsername = `full_editor_${runId}`;
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: editorUsername, password: "EditorPass1", role: "editor" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, editorUsername))
|
||||
.run();
|
||||
const editorLogin = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: editorUsername, password: "EditorPass1" },
|
||||
});
|
||||
editorToken = JSON.parse(editorLogin.body).token;
|
||||
|
||||
// Create user
|
||||
const userUsername = `full_user_${runId}`;
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: userUsername, password: "UserPass12", role: "user" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, userUsername))
|
||||
.run();
|
||||
const userLogin = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: userUsername, password: "UserPass12" },
|
||||
});
|
||||
userToken = JSON.parse(userLogin.body).token;
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Route permission matrix
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface RouteTest {
|
||||
method: "GET" | "POST" | "PUT" | "DELETE";
|
||||
url: string;
|
||||
payload?: unknown | (() => unknown);
|
||||
admin: number;
|
||||
editor: number;
|
||||
user: number;
|
||||
unauth: number;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
const routes: RouteTest[] = [
|
||||
// --- Public routes (no auth required) ---
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/health",
|
||||
admin: 200,
|
||||
editor: 200,
|
||||
user: 200,
|
||||
unauth: 200,
|
||||
label: "public health check",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/config/auth",
|
||||
admin: 200,
|
||||
editor: 200,
|
||||
user: 200,
|
||||
unauth: 200,
|
||||
label: "public auth config",
|
||||
},
|
||||
|
||||
// --- Auth-only routes (any authenticated user) ---
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/settings",
|
||||
admin: 200,
|
||||
editor: 200,
|
||||
user: 200,
|
||||
unauth: 401,
|
||||
label: "settings:read",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/files",
|
||||
admin: 200,
|
||||
editor: 200,
|
||||
user: 200,
|
||||
unauth: 401,
|
||||
label: "requireAuth",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/pipeline/list",
|
||||
admin: 200,
|
||||
editor: 200,
|
||||
user: 200,
|
||||
unauth: 401,
|
||||
label: "requireAuth",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
admin: 200,
|
||||
editor: 200,
|
||||
user: 200,
|
||||
unauth: 401,
|
||||
label: "requireAuth",
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
payload: { name: `test-key-${runId}` },
|
||||
admin: 201,
|
||||
editor: 201,
|
||||
user: 201,
|
||||
unauth: 401,
|
||||
label: "requireAuth (create api key)",
|
||||
},
|
||||
|
||||
// --- Admin-only routes ---
|
||||
{
|
||||
method: "PUT",
|
||||
url: "/api/v1/settings",
|
||||
payload: { _test: "v" },
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "settings:write",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/auth/users",
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "users:manage",
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: () => ({
|
||||
username: `reg_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
|
||||
password: "TempPass1",
|
||||
role: "user",
|
||||
}),
|
||||
admin: 201,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "users:manage (register)",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/teams",
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "teams:manage",
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
url: "/api/v1/teams",
|
||||
payload: () => ({
|
||||
name: `team_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
|
||||
}),
|
||||
admin: 201,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "teams:manage (create)",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/roles",
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "audit:read (roles list)",
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
url: "/api/v1/roles",
|
||||
payload: () => ({
|
||||
name: `role_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
|
||||
permissions: ["tools:use", "files:own"],
|
||||
}),
|
||||
admin: 201,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "users:manage (create role)",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/audit-log",
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "audit:read",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
url: "/api/v1/admin/health",
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "system:health",
|
||||
},
|
||||
{
|
||||
method: "DELETE",
|
||||
url: "/api/v1/settings/logo",
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
label: "branding:manage (delete logo)",
|
||||
},
|
||||
];
|
||||
|
||||
describe("RBAC route permission matrix (full)", () => {
|
||||
for (const route of routes) {
|
||||
for (const [role, expectedStatus] of Object.entries({
|
||||
admin: route.admin,
|
||||
editor: route.editor,
|
||||
user: route.user,
|
||||
unauth: route.unauth,
|
||||
})) {
|
||||
const suffix = route.label ? ` [${route.label}]` : "";
|
||||
it(`${route.method} ${route.url} -> ${role} = ${expectedStatus}${suffix}`, async () => {
|
||||
const headers: Record<string, string> = {};
|
||||
const token =
|
||||
role === "admin"
|
||||
? adminToken
|
||||
: role === "editor"
|
||||
? editorToken
|
||||
: role === "user"
|
||||
? userToken
|
||||
: undefined;
|
||||
if (token) {
|
||||
headers.authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const payload = typeof route.payload === "function" ? route.payload() : route.payload;
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: route.method,
|
||||
url: route.url,
|
||||
headers,
|
||||
...(payload ? { payload } : {}),
|
||||
});
|
||||
expect(res.statusCode).toBe(expectedStatus);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cross-role isolation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("Cross-role isolation", () => {
|
||||
it("editor session returns correct role and permissions", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${editorToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.user.role).toBe("editor");
|
||||
expect(body.user.permissions).toEqual(
|
||||
expect.arrayContaining([
|
||||
"tools:use",
|
||||
"files:own",
|
||||
"files:all",
|
||||
"apikeys:own",
|
||||
"pipelines:own",
|
||||
"pipelines:all",
|
||||
"settings:read",
|
||||
]),
|
||||
);
|
||||
// Must NOT have admin-only permissions
|
||||
expect(body.user.permissions).not.toContain("settings:write");
|
||||
expect(body.user.permissions).not.toContain("users:manage");
|
||||
expect(body.user.permissions).not.toContain("teams:manage");
|
||||
expect(body.user.permissions).not.toContain("branding:manage");
|
||||
expect(body.user.permissions).not.toContain("features:manage");
|
||||
expect(body.user.permissions).not.toContain("system:health");
|
||||
expect(body.user.permissions).not.toContain("audit:read");
|
||||
});
|
||||
|
||||
it("user session returns correct role and permissions", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.user.role).toBe("user");
|
||||
expect(body.user.permissions).toEqual(
|
||||
expect.arrayContaining([
|
||||
"tools:use",
|
||||
"files:own",
|
||||
"apikeys:own",
|
||||
"pipelines:own",
|
||||
"settings:read",
|
||||
]),
|
||||
);
|
||||
// Must NOT have editor or admin permissions
|
||||
expect(body.user.permissions).not.toContain("files:all");
|
||||
expect(body.user.permissions).not.toContain("pipelines:all");
|
||||
expect(body.user.permissions).not.toContain("settings:write");
|
||||
expect(body.user.permissions).not.toContain("users:manage");
|
||||
expect(body.user.permissions).not.toContain("teams:manage");
|
||||
});
|
||||
|
||||
it("invalid token returns 401", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: "Bearer totally-bogus-token-value" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("expired session returns 401", async () => {
|
||||
// Create a session, then manually expire it in the DB
|
||||
const expiredUsername = `expired_${runId}`;
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: expiredUsername, password: "ExpiredPass1", role: "user" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, expiredUsername))
|
||||
.run();
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: expiredUsername, password: "ExpiredPass1" },
|
||||
});
|
||||
const expiredToken = JSON.parse(loginRes.body).token;
|
||||
|
||||
// Manually expire the session
|
||||
db.update(schema.sessions)
|
||||
.set({ expiresAt: new Date(Date.now() - 60_000) })
|
||||
.where(eq(schema.sessions.id, expiredToken))
|
||||
.run();
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/session",
|
||||
headers: { authorization: `Bearer ${expiredToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { buildTestApp, loginAsAdmin, type TestApp } from "./test-server.js";
|
||||
|
||||
let testApp: TestApp;
|
||||
let adminToken: string;
|
||||
let editorToken: string;
|
||||
let userToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
adminToken = await loginAsAdmin(testApp.app);
|
||||
|
||||
// Create editor
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "matrix_editor", password: "EditorPass1", role: "editor" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, "matrix_editor"))
|
||||
.run();
|
||||
const editorLogin = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "matrix_editor", password: "EditorPass1" },
|
||||
});
|
||||
editorToken = JSON.parse(editorLogin.body).token;
|
||||
|
||||
// Create user
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username: "matrix_user", password: "UserPass12", role: "user" },
|
||||
});
|
||||
db.update(schema.users)
|
||||
.set({ mustChangePassword: false })
|
||||
.where(eq(schema.users.username, "matrix_user"))
|
||||
.run();
|
||||
const userLogin = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "matrix_user", password: "UserPass12" },
|
||||
});
|
||||
userToken = JSON.parse(userLogin.body).token;
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
interface RouteTest {
|
||||
method: "GET" | "POST" | "PUT" | "DELETE";
|
||||
url: string;
|
||||
payload?: unknown;
|
||||
admin: number;
|
||||
editor: number;
|
||||
user: number;
|
||||
unauth: number;
|
||||
}
|
||||
|
||||
const routes: RouteTest[] = [
|
||||
// Settings
|
||||
{ method: "GET", url: "/api/v1/settings", admin: 200, editor: 200, user: 200, unauth: 401 },
|
||||
{
|
||||
method: "PUT",
|
||||
url: "/api/v1/settings",
|
||||
payload: { _test: "v" },
|
||||
admin: 200,
|
||||
editor: 403,
|
||||
user: 403,
|
||||
unauth: 401,
|
||||
},
|
||||
|
||||
// Users management
|
||||
{ method: "GET", url: "/api/auth/users", admin: 200, editor: 403, user: 403, unauth: 401 },
|
||||
|
||||
// Teams
|
||||
{ method: "GET", url: "/api/v1/teams", admin: 200, editor: 403, user: 403, unauth: 401 },
|
||||
|
||||
// Audit log
|
||||
{ method: "GET", url: "/api/v1/audit-log", admin: 200, editor: 403, user: 403, unauth: 401 },
|
||||
|
||||
// Admin health
|
||||
{ method: "GET", url: "/api/v1/admin/health", admin: 200, editor: 403, user: 403, unauth: 401 },
|
||||
|
||||
// Files
|
||||
{ method: "GET", url: "/api/v1/files", admin: 200, editor: 200, user: 200, unauth: 401 },
|
||||
|
||||
// Pipelines
|
||||
{ method: "GET", url: "/api/v1/pipeline/list", admin: 200, editor: 200, user: 200, unauth: 401 },
|
||||
|
||||
// API keys
|
||||
{ method: "GET", url: "/api/v1/api-keys", admin: 200, editor: 200, user: 200, unauth: 401 },
|
||||
|
||||
// Health (public)
|
||||
{ method: "GET", url: "/api/v1/health", admin: 200, editor: 200, user: 200, unauth: 200 },
|
||||
];
|
||||
|
||||
describe("RBAC permission matrix", () => {
|
||||
for (const route of routes) {
|
||||
for (const [role, expectedStatus] of Object.entries({
|
||||
admin: route.admin,
|
||||
editor: route.editor,
|
||||
user: route.user,
|
||||
unauth: route.unauth,
|
||||
})) {
|
||||
it(`${route.method} ${route.url} → ${role} = ${expectedStatus}`, async () => {
|
||||
const headers: Record<string, string> = {};
|
||||
const token =
|
||||
role === "admin"
|
||||
? adminToken
|
||||
: role === "editor"
|
||||
? editorToken
|
||||
: role === "user"
|
||||
? userToken
|
||||
: undefined;
|
||||
if (token) {
|
||||
headers.authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: route.method,
|
||||
url: route.url,
|
||||
headers,
|
||||
...(route.payload ? { payload: route.payload } : {}),
|
||||
});
|
||||
expect(res.statusCode).toBe(expectedStatus);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -29,20 +29,18 @@ import Fastify from "fastify";
|
||||
import { env } from "../../apps/api/src/config.js";
|
||||
import { db, schema } from "../../apps/api/src/db/index.js";
|
||||
import { runMigrations } from "../../apps/api/src/db/migrate.js";
|
||||
import {
|
||||
authMiddleware,
|
||||
authRoutes,
|
||||
ensureDefaultAdmin,
|
||||
requireAdmin,
|
||||
} from "../../apps/api/src/plugins/auth.js";
|
||||
import { requirePermission } from "../../apps/api/src/permissions.js";
|
||||
import { authMiddleware, authRoutes, ensureDefaultAdmin } from "../../apps/api/src/plugins/auth.js";
|
||||
import { registerUpload } from "../../apps/api/src/plugins/upload.js";
|
||||
import { apiKeyRoutes } from "../../apps/api/src/routes/api-keys.js";
|
||||
import { auditLogRoutes } from "../../apps/api/src/routes/audit-log.js";
|
||||
import { registerBatchRoutes } from "../../apps/api/src/routes/batch.js";
|
||||
import { brandingRoutes } from "../../apps/api/src/routes/branding.js";
|
||||
import { docsRoutes } from "../../apps/api/src/routes/docs.js";
|
||||
import { fileRoutes } from "../../apps/api/src/routes/files.js";
|
||||
import { registerPipelineRoutes } from "../../apps/api/src/routes/pipeline.js";
|
||||
import { registerProgressRoutes } from "../../apps/api/src/routes/progress.js";
|
||||
import { rolesRoutes } from "../../apps/api/src/routes/roles.js";
|
||||
import { settingsRoutes } from "../../apps/api/src/routes/settings.js";
|
||||
import { teamsRoutes } from "../../apps/api/src/routes/teams.js";
|
||||
import { registerToolRoutes } from "../../apps/api/src/routes/tools/index.js";
|
||||
@@ -116,6 +114,12 @@ export async function buildTestApp(): Promise<TestApp> {
|
||||
// Teams routes
|
||||
await teamsRoutes(app);
|
||||
|
||||
// Audit log routes
|
||||
await auditLogRoutes(app);
|
||||
|
||||
// Roles management routes
|
||||
await rolesRoutes(app);
|
||||
|
||||
// API docs (Scalar)
|
||||
await docsRoutes(app);
|
||||
|
||||
@@ -127,7 +131,7 @@ export async function buildTestApp(): Promise<TestApp> {
|
||||
|
||||
// Admin health check (full diagnostics)
|
||||
app.get("/api/v1/admin/health", async (request, reply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("system:health")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
let dbOk = false;
|
||||
|
||||
Reference in New Issue
Block a user