feat(authz): add request middleware, can(), and guardPermission
Installs a per-request authz resolver via authzMiddleware and exposes can()/decideFor()/guardPermission()/filterCan() as free functions (not Context members, so @wrnexus/core stays free of an authz dependency). All four route through resolver.decide(), never permissionsFor(), so resource-scoped policy denials can't be bypassed via the coarse permission set. Per-request results are memoised keyed on (permission, resource) to avoid re-hitting the store within a request without leaking one resource's verdict onto another.
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { Context } from "@wrnexus/core";
|
||||
import { defineAuthz } from "../src/registry.ts";
|
||||
import { mergeCatalogs } from "../src/catalog.ts";
|
||||
import { memoryPermissionStore } from "../src/store.ts";
|
||||
import { authzMiddleware, can, filterCan, guardPermission } from "../src/middleware.ts";
|
||||
|
||||
const catalog = mergeCatalogs([
|
||||
{
|
||||
source: "t.ts",
|
||||
module: defineAuthz({
|
||||
permissions: { "post:read": { public: true }, "post:write": {}, "post:delete": {} },
|
||||
roles: { editor: ["post:write"] },
|
||||
policies: {
|
||||
ownsPost: async (s: { id?: string }, r?: { authorId?: string }) =>
|
||||
r?.authorId === s?.id ? { allowed: true } : { allowed: false, reason: "not owner" },
|
||||
},
|
||||
bindings: { "post:delete": ["ownsPost"] },
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
/** Minimal Context stand-in; the middleware only touches user, tenant, locals. */
|
||||
function makeCtx(user: unknown, tenantId?: string): Context {
|
||||
return {
|
||||
user,
|
||||
tenant: tenantId ? { id: tenantId } : undefined,
|
||||
locals: {},
|
||||
url: new URL("http://localhost/x"),
|
||||
req: new Request("http://localhost/x"),
|
||||
} as unknown as Context;
|
||||
}
|
||||
|
||||
const withMiddleware = async (ctx: Context, store = memoryPermissionStore()) => {
|
||||
await authzMiddleware({ catalog, store, strict: false })(ctx, async () => new Response("ok"));
|
||||
return store;
|
||||
};
|
||||
|
||||
describe("authzMiddleware + can", () => {
|
||||
test("can() resolves through the middleware-installed resolver", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
const store = memoryPermissionStore();
|
||||
await store.assignRole("u1", "editor");
|
||||
await withMiddleware(ctx, store);
|
||||
expect(await can(ctx, "post:write")).toBe(true);
|
||||
expect(await can(ctx, "post:delete", { authorId: "u1" })).toBe(false);
|
||||
});
|
||||
|
||||
test("can() throws a clear setup error without the middleware", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
await expect(can(ctx, "post:read")).rejects.toThrow(/authzMiddleware/);
|
||||
});
|
||||
|
||||
test("results are memoised per request", async () => {
|
||||
const inner = memoryPermissionStore();
|
||||
let reads = 0;
|
||||
const counting = {
|
||||
...inner,
|
||||
assignmentsFor: (id: string, scope?: { tenantId?: string }) => {
|
||||
reads++;
|
||||
return inner.assignmentsFor(id, scope);
|
||||
},
|
||||
};
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
await authzMiddleware({ catalog, store: counting, strict: false })(
|
||||
ctx,
|
||||
async () => new Response("ok"),
|
||||
);
|
||||
await can(ctx, "post:write");
|
||||
await can(ctx, "post:write");
|
||||
expect(reads).toBe(1);
|
||||
});
|
||||
|
||||
test("memoisation keys on the resource, not just the permission", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
const store = memoryPermissionStore();
|
||||
await store.grant("u1", "post:delete", "allow");
|
||||
await withMiddleware(ctx, store);
|
||||
expect(await can(ctx, "post:delete", { authorId: "u1" })).toBe(true);
|
||||
expect(await can(ctx, "post:delete", { authorId: "other" })).toBe(false);
|
||||
});
|
||||
|
||||
test("the tenant on the context becomes the scope", async () => {
|
||||
const ctx = makeCtx({ id: "u1" }, "t1");
|
||||
const store = memoryPermissionStore();
|
||||
await store.assignRole("u1", "editor", { tenantId: "t1" });
|
||||
await withMiddleware(ctx, store);
|
||||
expect(await can(ctx, "post:write")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("guardPermission", () => {
|
||||
test("calls next when allowed", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
const store = memoryPermissionStore();
|
||||
await store.assignRole("u1", "editor");
|
||||
await withMiddleware(ctx, store);
|
||||
const res = await guardPermission("post:write")(ctx, async () => new Response("passed"));
|
||||
expect(await res.text()).toBe("passed");
|
||||
});
|
||||
|
||||
test("returns 403 without leaking the reason by default", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
await withMiddleware(ctx);
|
||||
const res = await guardPermission("post:write")(ctx, async () => new Response("passed"));
|
||||
expect(res.status).toBe(403);
|
||||
const body = (await res.json()) as Record<string, unknown>;
|
||||
expect(body).toEqual({ ok: false, error: "Forbidden" });
|
||||
});
|
||||
|
||||
test("exposeReason opts into diagnostics", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
await withMiddleware(ctx);
|
||||
const res = await guardPermission("post:write", { exposeReason: true })(
|
||||
ctx,
|
||||
async () => new Response("passed"),
|
||||
);
|
||||
const body = (await res.json()) as Record<string, unknown>;
|
||||
expect(body.reason).toBe("Missing permission");
|
||||
});
|
||||
|
||||
test("getResource feeds the bound policy", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
const store = memoryPermissionStore();
|
||||
await store.grant("u1", "post:delete", "allow");
|
||||
await withMiddleware(ctx, store);
|
||||
const guard = guardPermission("post:delete", { getResource: () => ({ authorId: "u1" }) });
|
||||
const res = await guard(ctx, async () => new Response("passed"));
|
||||
expect(await res.text()).toBe("passed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterCan", () => {
|
||||
test("keeps only the items the subject may act on", async () => {
|
||||
const ctx = makeCtx({ id: "u1" });
|
||||
const store = memoryPermissionStore();
|
||||
await store.grant("u1", "post:delete", "allow");
|
||||
await withMiddleware(ctx, store);
|
||||
const posts = [{ authorId: "u1" }, { authorId: "other" }, { authorId: "u1" }];
|
||||
expect(await filterCan(ctx, "post:delete", posts)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user