feat(auth): centralize ThothII permission enforcement
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
import { expect, test } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import { authPreHandler, getPrincipal } from "../src/auth/auth.js";
|
||||
import { hasPermission } from "../src/auth/authorization.js";
|
||||
import type { PrincipalContext } from "../src/auth/principal.js";
|
||||
import type { Permission } from "../src/auth/types.js";
|
||||
|
||||
const noRole: PrincipalContext = {
|
||||
issuer: "oidc", subject: "no-role", roles: [], permissions: [], isAdmin: false,
|
||||
};
|
||||
const user: PrincipalContext = {
|
||||
issuer: "oidc", subject: "user", roles: ["user"], permissions: ["session.use"], isAdmin: false,
|
||||
};
|
||||
const admin: PrincipalContext = {
|
||||
issuer: "oidc", subject: "admin", roles: ["admin"],
|
||||
permissions: [
|
||||
"session.use", "session.read_all", "session.manage_all", "settings.manage",
|
||||
"workspace.manage", "workspace.secrets.manage", "pi.manage", "auth.diagnostics.read",
|
||||
],
|
||||
isAdmin: true,
|
||||
};
|
||||
|
||||
const catalog: readonly Permission[] = [
|
||||
"session.use", "session.read_all", "session.manage_all", "settings.manage",
|
||||
"workspace.manage", "workspace.secrets.manage", "pi.manage", "auth.diagnostics.read",
|
||||
];
|
||||
|
||||
test("permission matrix gives role-less identities no access, users session use, and admins every catalog permission", () => {
|
||||
for (const permission of catalog) {
|
||||
expect(hasPermission(noRole, permission)).toBe(false);
|
||||
expect(hasPermission(user, permission)).toBe(permission === "session.use");
|
||||
expect(hasPermission(admin, permission)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("compatibility adapters derive roles and permissions before routes inspect a principal", async () => {
|
||||
const app = Fastify();
|
||||
app.addHook("preHandler", authPreHandler("mock"));
|
||||
app.get("/me", async (request) => getPrincipal(request));
|
||||
|
||||
const response = await app.inject({ method: "GET", url: "/me", headers: { "x-mock-user": "alice" } });
|
||||
|
||||
expect(response.json()).toEqual({
|
||||
issuer: "mock", subject: "alice", displayName: "alice",
|
||||
roles: ["user"], permissions: ["session.use"], isAdmin: false,
|
||||
});
|
||||
|
||||
const elevated = await app.inject({
|
||||
method: "GET", url: "/me", headers: { "x-mock-user": "operator", "x-thoth-is-admin": "true" },
|
||||
});
|
||||
const malformed = await app.inject({
|
||||
method: "GET", url: "/me", headers: { "x-mock-user": "mallory", "x-thoth-is-admin": "yes" },
|
||||
});
|
||||
expect(elevated.json()).toMatchObject({ roles: ["admin"], isAdmin: true });
|
||||
expect(malformed.json()).toMatchObject({ roles: ["user"], isAdmin: false });
|
||||
});
|
||||
Reference in New Issue
Block a user