feat: SQLite RBAC, granular permissions, 100-VPS seeder, DM pagination

This commit is contained in:
khuongnguyen committed 2026-12-02 10:26:56 +07:00
1 parent 41d9e9e8eb
commit 4ccb35a44c
16 files changed
+1690 -327

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
import { describe, it, expect } from "vitest";
import { createVPSListPages, DISCORD_EMBED_LIMITS } from "../src/utils/embeds.js";
import { VPS } from "../src/types/vps.js";
function generateMockVPSList(count: number): VPS[] {
return Array.from({ length: count }, (_, i) => ({
id: `vps-${String(i + 1).padStart(3, "0")}`,
name: `node-prod-${String(i + 1).padStart(3, "0")}`,
provider: i % 2 === 0 ? "Vultr" : "DigitalOcean",
region: "Singapore",
environment: i % 3 === 0 ? "Production" : i % 3 === 1 ? "Staging" : "Development",
cpu: 4,
ramGB: 8,
diskGB: 160,
}));
}
describe("Embed Pagination for Large VPS Lists", () => {
it("should return a single empty-state embed when inventory is empty", () => {
const pages = createVPSListPages([]);
expect(pages).toHaveLength(1);
expect(pages[0].data.description).toContain("No VPS records found");
});
it("should split 100 VPS records into multiple pages respecting Discord Embed limits", () => {
const servers = generateMockVPSList(100);
const pages = createVPSListPages(servers);
expect(pages.length).toBeGreaterThan(1);
expect(pages).toHaveLength(10); // 100 items / 10 per page = 10 pages
let totalFieldsAcrossPages = 0;
for (const page of pages) {
const json = page.toJSON();
const fieldCount = json.fields?.length ?? 0;
totalFieldsAcrossPages += fieldCount;
expect(fieldCount).toBeLessThanOrEqual(DISCORD_EMBED_LIMITS.MAX_FIELDS);
expect(page.length).toBeLessThanOrEqual(DISCORD_EMBED_LIMITS.MAX_TOTAL_CHARS);
}
expect(totalFieldsAcrossPages).toBe(100);
expect(pages[0].data.footer?.text).toBe("Page 1/10 • Total Servers: 100");
expect(pages[9].data.footer?.text).toBe("Page 10/10 • Total Servers: 100");
});
});
+184 -53
View File
@@ -1,113 +1,244 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { PermissionFlagsBits, PermissionsBitField } from "discord.js";
import { isDevOpsOrAdmin, checkDevOpsAuthorization } from "../src/utils/permissions.js";
import { PermissionRepository } from "../src/repositories/permission.repository.js";
import {
ALL_VPS_PERMISSIONS,
authorizeAction,
createDefaultPermissionConfig,
getMemberPermissions,
hasPermission,
RolePermissionConfig,
} from "../src/utils/permissions.js";
describe("Permissions Utilities", () => {
describe("Granular Action-Based Permissions System", () => {
const DEVOPS_ROLE_ID = "role-devops-123";
const VIEWER_ROLE_ID = "role-viewer-456";
const defaultConfig = createDefaultPermissionConfig(DEVOPS_ROLE_ID);
describe("isDevOpsOrAdmin", () => {
it("should return false if member is null or undefined", () => {
expect(isDevOpsOrAdmin(null as any, DEVOPS_ROLE_ID)).toBe(false);
expect(isDevOpsOrAdmin(undefined as any, DEVOPS_ROLE_ID)).toBe(false);
describe("getMemberPermissions & hasPermission (in-memory config)", () => {
it("should return empty set if member is null or undefined", () => {
expect(getMemberPermissions(null as any, defaultConfig).size).toBe(0);
expect(hasPermission(undefined as any, "vps:list", defaultConfig)).toBe(false);
});
it("should return true if member has Administrator permission via PermissionsBitField", () => {
it("should grant all 10 granular permissions to Server Administrator", () => {
const member = {
permissions: new PermissionsBitField(PermissionFlagsBits.Administrator),
roles: { cache: new Map() },
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
for (const perm of ALL_VPS_PERMISSIONS) {
expect(hasPermission(member as any, perm, defaultConfig)).toBe(true);
}
});
it("should return true if member has Administrator permission via string bitfield", () => {
it("should grant all permissions to Administrator via string bitfield", () => {
const bitfield = new PermissionsBitField(PermissionFlagsBits.Administrator).bitfield.toString();
const member = {
permissions: bitfield,
roles: [],
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
expect(hasPermission(member as any, "vps:connect", defaultConfig)).toBe(true);
expect(hasPermission(member as any, "vps:delete", defaultConfig)).toBe(true);
});
it("should return true if member has the DevOps role via cache.has", () => {
const roleMap = new Map();
roleMap.set(DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID, name: "DevOps" });
it("should grant DevOps role all 10 granular VPS permissions via role cache", () => {
const roleMap = new Map([[DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID }]]);
const member = {
permissions: new PermissionsBitField(),
roles: {
cache: {
has: (id: string) => roleMap.has(id),
},
},
roles: { cache: roleMap },
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
for (const perm of ALL_VPS_PERMISSIONS) {
expect(hasPermission(member as any, perm, defaultConfig)).toBe(true);
}
});
it("should return true if member has the DevOps role via string array (APIInteractionGuildMember)", () => {
const member = {
permissions: "0",
roles: ["other-role", DEVOPS_ROLE_ID],
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
});
it("should return false if member does not have DevOps role or Admin", () => {
it("should grant new/regular guild members zero permissions by default (zero-trust)", () => {
const member = {
permissions: new PermissionsBitField(),
roles: {
cache: {
has: (_id: string) => false,
},
},
roles: ["some-other-role"],
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(false);
for (const perm of ALL_VPS_PERMISSIONS) {
expect(hasPermission(member as any, perm, defaultConfig)).toBe(false);
}
});
it("should fail securely (return false) if devopsRoleId is empty or not provided and member is not admin", () => {
it("should support per-feature Role -> Permission mappings", () => {
const granularConfig: RolePermissionConfig = {
defaultGuildPermissions: [],
rolePermissions: {
[VIEWER_ROLE_ID]: ["vps:list", "vps:info"],
[DEVOPS_ROLE_ID]: [...ALL_VPS_PERMISSIONS],
},
adminBypass: true,
};
const noRoleMember = { permissions: "0", roles: [] };
const viewerMember = { permissions: "0", roles: [VIEWER_ROLE_ID] };
expect(hasPermission(noRoleMember as any, "vps:list", granularConfig)).toBe(false);
expect(hasPermission(viewerMember as any, "vps:list", granularConfig)).toBe(true);
expect(hasPermission(viewerMember as any, "vps:info", granularConfig)).toBe(true);
expect(hasPermission(viewerMember as any, "vps:search", granularConfig)).toBe(false);
expect(hasPermission(viewerMember as any, "vps:filter", granularConfig)).toBe(false);
expect(hasPermission(viewerMember as any, "vps:stats", granularConfig)).toBe(false);
expect(hasPermission(viewerMember as any, "vps:connect", granularConfig)).toBe(false);
});
it("should fail securely when devopsRoleId is missing", () => {
const configWithoutDevops = createDefaultPermissionConfig(undefined);
const member = {
permissions: new PermissionsBitField(),
roles: ["some-role"],
};
expect(isDevOpsOrAdmin(member as any, undefined)).toBe(false);
expect(isDevOpsOrAdmin(member as any, "")).toBe(false);
expect(hasPermission(member as any, "vps:connect", configWithoutDevops)).toBe(false);
});
});
describe("checkDevOpsAuthorization", () => {
it("should deny access when command is executed outside a guild (e.g. DM)", () => {
const mockInteraction = {
guildId: null,
member: null,
};
const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID);
describe("authorizeAction (in-memory config)", () => {
it("should deny access when executed outside a guild (e.g. DM)", () => {
const mockInteraction = { guildId: null, member: null };
const result = authorizeAction(mockInteraction as any, "vps:list", defaultConfig);
expect(result.authorized).toBe(false);
expect(result.reason).toContain("only be executed within an authorized Discord Server");
});
it("should deny access when member does not hold DevOps or Admin permissions", () => {
it("should deny vps:connect for unassigned member and include missing permission in reason", () => {
const mockInteraction = {
guildId: "guild-123",
member: {
permissions: new PermissionsBitField(),
roles: { cache: { has: () => false } },
roles: { cache: new Map() },
},
};
const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID);
const result = authorizeAction(mockInteraction as any, "vps:connect", defaultConfig);
expect(result.authorized).toBe(false);
expect(result.reason).toContain("Permission Denied");
expect(result.reason).toContain("vps:connect");
});
it("should grant access when member has DevOps role in a guild", () => {
it("should allow vps:connect for member with DevOps role", () => {
const mockInteraction = {
guildId: "guild-123",
member: {
permissions: new PermissionsBitField(),
roles: { cache: { has: (id: string) => id === DEVOPS_ROLE_ID } },
roles: { cache: new Map([[DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID }]]) },
},
};
const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID);
const result = authorizeAction(mockInteraction as any, "vps:connect", defaultConfig);
expect(result.authorized).toBe(true);
expect(result.reason).toBeUndefined();
});
});
describe("SQLite PermissionRepository integration", () => {
let permRepo: PermissionRepository;
beforeEach(() => {
permRepo = new PermissionRepository(":memory:");
permRepo.init();
permRepo.seedIfEmpty(DEVOPS_ROLE_ID);
});
afterEach(() => {
permRepo.close();
});
it("should enforce zero-trust for new members and grant DevOps role all 10 permissions", () => {
const newMember = { permissions: "0", roles: ["unassigned-role"] };
const devopsMember = { permissions: "0", roles: [DEVOPS_ROLE_ID] };
expect(hasPermission(newMember as any, "vps:list", permRepo)).toBe(false);
expect(hasPermission(newMember as any, "vps:connect", permRepo)).toBe(false);
for (const perm of ALL_VPS_PERMISSIONS) {
expect(hasPermission(devopsMember as any, perm, permRepo)).toBe(true);
}
});
it("should isolate individual feature permissions (list vs info vs search vs add/update/delete)", () => {
const customRole = "role-custom-999";
const customMember = { permissions: "0", roles: [customRole] };
permRepo.grantRolePermission(customRole, "vps:list");
permRepo.grantRolePermission(customRole, "vps:add");
expect(hasPermission(customMember as any, "vps:list", permRepo)).toBe(true);
expect(hasPermission(customMember as any, "vps:add", permRepo)).toBe(true);
expect(hasPermission(customMember as any, "vps:info", permRepo)).toBe(false);
expect(hasPermission(customMember as any, "vps:search", permRepo)).toBe(false);
expect(hasPermission(customMember as any, "vps:update", permRepo)).toBe(false);
expect(hasPermission(customMember as any, "vps:delete", permRepo)).toBe(false);
permRepo.revokeRolePermission(customRole, "vps:list");
expect(hasPermission(customMember as any, "vps:list", permRepo)).toBe(false);
permRepo.revokeAllRolePermissions(customRole);
expect(hasPermission(customMember as any, "vps:add", permRepo)).toBe(false);
});
it("should deny new members and authorize roles assigned in SQLite", () => {
const newMemberInteraction = {
guildId: "guild-123",
member: { permissions: "0", roles: [] },
};
const devopsInteraction = {
guildId: "guild-123",
member: { permissions: "0", roles: [DEVOPS_ROLE_ID] },
};
expect(authorizeAction(newMemberInteraction as any, "vps:list", permRepo).authorized).toBe(false);
expect(authorizeAction(newMemberInteraction as any, "vps:connect", permRepo).authorized).toBe(false);
expect(authorizeAction(devopsInteraction as any, "vps:list", permRepo).authorized).toBe(true);
expect(authorizeAction(devopsInteraction as any, "vps:connect", permRepo).authorized).toBe(true);
});
it("should enforce strict foreign keys on role_permissions (roles and permissions)", () => {
const db = permRepo.getDb();
expect(() =>
db
.prepare("INSERT INTO role_permissions (role_id, permission_name) VALUES (?, ?)")
.run("non-existent-role", "vps:list")
).toThrow(/FOREIGN KEY constraint failed/);
expect(() =>
db
.prepare("INSERT INTO role_permissions (role_id, permission_name) VALUES (?, ?)")
.run(DEVOPS_ROLE_ID, "invalid:perm")
).toThrow(/FOREIGN KEY constraint failed/);
});
it("should join role names and record audit logs", () => {
permRepo.grantRolePermission("role-auditor-777", "vps:info", {
roleName: "Auditor",
grantedBy: "admin-1",
});
const entries = permRepo.listRolePermissions();
const auditorEntry = entries.find((e) => e.roleId === "role-auditor-777");
expect(auditorEntry).toBeDefined();
expect(auditorEntry?.roleName).toBe("Auditor");
expect(auditorEntry?.grantedBy).toBe("admin-1");
permRepo.logAudit({
actorId: "user-1",
actorTag: "khuong#0001",
action: "vps:connect",
target: "shop-prod-01",
status: "ALLOWED",
});
const logs = permRepo.getRecentAuditLogs(5);
expect(logs).toHaveLength(1);
expect(logs[0].action).toBe("vps:connect");
expect(logs[0].status).toBe("ALLOWED");
});
});
});
+79 -45
View File
@@ -1,34 +1,93 @@
import { describe, it, expect, beforeEach } from "vitest";
import path from "node:path";
import { VPSRepository } from "../src/repositories/vps.repository.js";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { SEED_VPS_RECORDS, VPSRepository } from "../src/repositories/vps.repository.js";
import { VPSService } from "../src/services/vps.service.js";
import { VPS } from "../src/types/vps.js";
describe("VPS Repository and Service", () => {
const CORE_FIXTURE: VPS[] = [
{
id: "vps-001",
name: "shop-prod-01",
provider: "Vultr",
region: "Singapore",
environment: "Production",
cpu: 4,
ramGB: 8,
diskGB: 160,
ip: "203.0.113.10",
sshUser: "deploy",
sshPort: 22,
},
{
id: "vps-002",
name: "staging-01",
provider: "DigitalOcean",
region: "Singapore",
environment: "Staging",
cpu: 2,
ramGB: 4,
diskGB: 80,
ip: "198.51.100.20",
sshUser: "ubuntu",
sshPort: 2222,
},
{
id: "vps-003",
name: "db-prod-01",
provider: "Vultr",
region: "Singapore",
environment: "Production",
cpu: 4,
ramGB: 16,
diskGB: 320,
ip: "192.0.2.30",
},
];
describe("SQLite VPS Repository and Service", () => {
let repository: VPSRepository;
let service: VPSService;
beforeEach(() => {
// Point to data/vps.json
const seedPath = path.resolve(process.cwd(), "data/vps.json");
repository = new VPSRepository(seedPath);
repository = new VPSRepository(":memory:");
repository.init();
repository.seedIfEmpty(CORE_FIXTURE);
service = new VPSService(repository);
});
describe("Repository loading and validation", () => {
it("should load exactly the 3 seed VPS records", () => {
const all = repository.getAll();
expect(all).toHaveLength(3);
afterEach(() => {
repository.close();
});
describe("SQLite initialization and 100-VPS seeding", () => {
it("should seed 100 sample VPS records when default SEED_VPS_RECORDS is used", () => {
const fullRepo = new VPSRepository(":memory:");
fullRepo.init();
const inserted = fullRepo.seedIfEmpty();
expect(SEED_VPS_RECORDS).toHaveLength(100);
expect(inserted).toBe(100);
expect(fullRepo.getAll()).toHaveLength(100);
expect(fullRepo.getByName("shop-prod-01")?.id).toBe("vps-001");
expect(fullRepo.getById("vps-100")).toBeDefined();
fullRepo.close();
});
it("should throw a descriptive error when file is missing", () => {
const invalidRepo = new VPSRepository("non-existent-path.json");
expect(() => invalidRepo.getAll()).toThrow("Inventory data file not found");
it("should not duplicate records if seedIfEmpty is called multiple times", () => {
const inserted = repository.seedIfEmpty(CORE_FIXTURE);
expect(inserted).toBe(0);
expect(repository.getAll()).toHaveLength(3);
});
it("should find a VPS by exact ID", () => {
const vps = repository.getById("vps-002");
expect(vps).toBeDefined();
expect(vps?.name).toBe("staging-01");
});
});
describe("listAll", () => {
it("should return all three VPS with correct properties", () => {
it("should return all fixture VPS with correct properties", () => {
const list = service.listAll();
expect(list).toHaveLength(3);
@@ -88,31 +147,12 @@ describe("VPS Repository and Service", () => {
expect(results[0].name).toBe("staging-01");
});
it("should search by IP address when IP is configured", () => {
// Mock repository with an IP configured
const mockRepo = new VPSRepository();
const mockVPSList: VPS[] = [
{
id: "vps-test",
name: "test-vps",
provider: "AWS",
region: "Tokyo",
environment: "Development",
cpu: 2,
ramGB: 4,
diskGB: 40,
ip: "192.0.2.15",
},
];
mockRepo.getAll = () => mockVPSList;
const testService = new VPSService(mockRepo);
const byIp = testService.search("192.0.2", true);
it("should search by IP address when IP is configured and allowed", () => {
const byIp = service.search("203.0.113", true);
expect(byIp).toHaveLength(1);
expect(byIp[0].name).toBe("test-vps");
expect(byIp[0].name).toBe("shop-prod-01");
// When IP search is not permitted (e.g. unauthenticated)
const noIp = testService.search("192.0.2", false);
const noIp = service.search("203.0.113", false);
expect(noIp).toHaveLength(0);
});
@@ -169,25 +209,19 @@ describe("VPS Repository and Service", () => {
});
describe("getStats", () => {
it("should accurately compute all aggregate statistics for seed data", () => {
it("should accurately compute all aggregate statistics for fixture data", () => {
const stats = service.getStats();
// Verified exact calculations:
// shop-prod-01: 4 CPU, 8 RAM, 160 Disk
// staging-01: 2 CPU, 4 RAM, 80 Disk
// db-prod-01: 4 CPU, 16 RAM, 320 Disk
expect(stats.totalVPS).toBe(3);
expect(stats.totalVCPU).toBe(10);
expect(stats.totalRamGB).toBe(28);
expect(stats.totalDiskGB).toBe(560);
// Environment breakdown
expect(stats.byEnvironment).toEqual({
Production: 2,
Staging: 1,
});
// Provider breakdown
expect(stats.byProvider).toEqual({
Vultr: 2,
DigitalOcean: 1,