diff --git a/CHANGELOG.md b/CHANGELOG.md index 37ed0ef..e8abdbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ The host's contract version is now 0.5.0, so discovery refuses a plugin whose `a `0.4.x`. Change the literal in each plugin's manifest when you upgrade, and add `assetHref` to any `RequestContext` your tests build by hand: `assetHref: (href) => href`. +### `@plainpages/plugin-api` exports `KetoError` + +A plugin that calls `ctx.system.keto` can tell a Keto failure apart with `instanceof KetoError`, as it already can for `KratosError` and `HydraError`. The error carries the HTTP `status`. + ### The core dashboard view is `dashboard`, not `index` `views/index.ejs` is now `views/dashboard.ejs`. The `apiVersion` check can't see this: a plugin view @@ -34,8 +38,14 @@ and answers with the error page. It used to leave some grants gone and the membe Deleting a group now also removes it from every group it was a member of, in the same Keto transaction as the rest. It used to stay listed there, so a group re-created with the same name was -back in every parent. A parent whose only member was the deleted group is left with no members, and -so no longer exists as a group. +back in every parent. + +### The admin example removes a group's grants and parent memberships when its last member leaves + +A group with no members no longer exists, and now neither do its grants or its memberships in other +groups. This holds when the last member is removed, and when deleting a group leaves a parent with +no members, up through every ancestor that is left empty in turn. A group re-created with the same +name used to get the old group's permissions and parents back. ### The admin example keeps a user's permissions section when it refuses a self-deactivate or self-delete diff --git a/docs/reading-cost.md b/docs/reading-cost.md index ad60726..8e6fddb 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -581,3 +581,20 @@ Read most (opens and searches): - `src/function-limits.test.ts` 2 - `AGENTS.md` 1 - `CHANGELOG.md` 1 + +## Reading cost, chunk f1bfd1c341a4, finished 2026-11-09T00:42:43Z + +84281 new input tokens before the first commit. + +Read most (opens and searches): + +- `todo.md` 9 +- `README.md` 5 +- `examples/plugins/auth-admin/admin-groups.ts` 5 +- `examples/plugins/auth-admin/admin-shared.ts` 5 +- `src/auth/keto-client.ts` 5 +- `AGENTS.md` 3 +- `examples/plugins/auth-admin/admin-users.ts` 3 +- `src/auth/hydra-admin.ts` 3 +- `src/http/app-admin.test.ts` 3 +- `CHANGELOG.md` 2 diff --git a/examples/plugins/auth-admin/admin-groups.ts b/examples/plugins/auth-admin/admin-groups.ts index 4b869fc..765a652 100644 --- a/examples/plugins/auth-admin/admin-groups.ts +++ b/examples/plugins/auth-admin/admin-groups.ts @@ -1,8 +1,8 @@ // Groups admin screen: list / create / delete Keto groups and manage membership. // A group is a Keto subject set `Group:#members`; a member is a user or a nested group (see // parseSubject). Writes go only to Keto (README "stateless"). Keto has no "create object" — a group -// exists exactly while it has ≥1 member, so create writes its first-member tuple and delete removes -// every tuple that makes it a group or puts it in another. Pure builders turn tuples + the request URL into view models; below them are thin +// exists exactly while it has ≥1 member, so create writes its first-member tuple, and delete — or +// removing the last member — removes every tuple that makes it a group or puts it in another. Pure builders turn tuples + the request URL into view models; below them are thin // per-route handlers (keyed on ctx.params) over a shared `withGroups` gate — admin-only, CSRF-guarded, // each returning a RouteResult. @@ -419,25 +419,43 @@ export const groupsDeleteConfirm = withGroupName(async (deps, name) => { }) }, view: "confirm" }; }, "write"); -// POST /auth-admin/groups/:name/delete — one Keto transaction removes the group's member tuples, -// the tuples naming it as a member of a parent group, and the grants it holds, so a Keto failure -// leaves the group as it was. +const tupleId = (t: RelationTuple): string => { + const subject = t.subject_set ? `${t.subject_set.namespace}:${t.subject_set.object}#${t.subject_set.relation}` : t.subject_id; + return `${t.namespace}:${t.object}#${t.relation}@${subject}`; +}; + +// A group exists only through its members, so once `removing` leaves one with none, what still hangs +// on its name — its grants and its memberships in other groups — must go too, or re-creating the name +// would restore them. Returns `removing` plus those tuples. Emptying a group can empty its parents in +// turn, so the walk climbs until it meets a group that keeps a member; `seen` ends it on a nesting cycle. +async function withEmptiedGroups(keto: KetoClient, removing: readonly RelationTuple[], groups: readonly string[]): Promise { + const doomed = new Map(removing.map((t) => [tupleId(t), t])); + const pending = [...groups]; + const seen = new Set(); + for (let group = pending.pop(); group !== undefined; group = pending.pop()) { + if (seen.has(group)) continue; + seen.add(group); + const members = await pagedTuples(keto, { namespace: GROUP_NS, object: group, relation: MEMBERS }); + if (members.some((m) => !doomed.has(tupleId(m)))) continue; + const subject = groupSubject(group); + const grants = (await heldPermissions(keto, subject)).map((permission) => grantTuple(permission, subject)); + const inParents = await pagedTuples(keto, { namespace: GROUP_NS, relation: MEMBERS, ...subject }); + for (const t of [...grants, ...inParents]) doomed.set(tupleId(t), t); + pending.push(...inParents.map((t) => t.object)); + } + return [...doomed.values()]; +} + +// POST /auth-admin/groups/:name/delete — one Keto transaction removes the group's member tuples and +// what hangs on its name (see `withEmptiedGroups`), so a Keto failure leaves the group as it was. export const groupsDelete = withGroupName(async (deps, name) => { const { ctx, keto, user } = deps; await guardedForm(ctx); // CSRF-verify the POST const lost = await lostOnDelete(deps, name); if (lost.length > 0) return refuseSelfLockout(deps, name, "delete", lost); - // A Keto set exists only through its tuples, so leaving the grants or the parents' membership - // tuples behind would resurrect every permission and parent membership the moment someone - // re-created a group with the same name. A parent that had only this group as a member is left - // with none and so ceases to exist, as when its last member is removed by hand; its own grants - // and parent memberships stay (todo.md). - const subject = groupSubject(name); - const held = await heldPermissions(keto, subject); - const grants = held.map((permission) => grantTuple(permission, subject)); + const held = await heldPermissions(keto, groupSubject(name)); const members = await pagedTuples(keto, { namespace: GROUP_NS, object: name, relation: MEMBERS }); - const inParents = await pagedTuples(keto, { namespace: GROUP_NS, relation: MEMBERS, ...subject }); - await keto.transactTuples({ delete: [...grants, ...members, ...inParents], insert: [] }); + await keto.transactTuples({ delete: await withEmptiedGroups(keto, members, [name]), insert: [] }); ctx.log.info("admin: group deleted", { actor: user.id, group: name, revoked: held.join(",") }); return { redirect: ADMIN_GROUPS_BASE }; }); @@ -452,6 +470,6 @@ export const groupsRemoveMember = withGroupName(async (deps, name) => { const removesSelf = tuple.subject_set ? await isMember(keto, user.id, tuple.subject_set.object) : tuple.subject_id === `user:${user.id}`; const lost = removesSelf ? await lostOnLeaving(deps, name) : []; if (lost.length > 0) return refuseSelfLockout(deps, name, "remove", lost); - await keto.deleteTuple(tuple); + await keto.transactTuples({ delete: await withEmptiedGroups(keto, [tuple], [name]), insert: [] }); return { redirect: detailHref(name) }; }); diff --git a/src/http/app-admin.test.ts b/src/http/app-admin.test.ts index 33837e4..d7a8447 100644 --- a/src/http/app-admin.test.ts +++ b/src/http/app-admin.test.ts @@ -446,6 +446,61 @@ test("admin group delete: removes the group from every parent, so re-creating th assert.deepEqual(tuples, [member("org", { subject_id: `user:${ada}` }), member("staff", { subject_id: "user:other" })]); }); +// A group exists only while it has a member, so one left with none must take its grants and +// its memberships with it: otherwise re-creating the name hands every new member the old ones. +const ADA = randomUUID(); +const groupTuple = (object: string, subject: Partial): RelationTuple => ({ namespace: "Group", object, relation: "members", ...subject } as RelationTuple); +const inGroup = (object: string) => ({ subject_set: { namespace: "Group", object, relation: "members" } }); +const grantTo = (group: string, permission = "users:read"): RelationTuple => ({ namespace: "Permission", object: permission, relation: "granted", ...inGroup(group) }); +const groupsAdminHarness = (t: TestContext, tuples: RelationTuple[]) => adminHarness(t, { keto: fakeKeto(tuples), kratosAdmin: stubAdmin({}) }); + +test("admin group delete: a parent left with no members loses its grants and memberships, all the way up", async (t) => { + const tuples: RelationTuple[] = [ + groupTuple("eng", { subject_id: `user:${ADA}` }), + groupTuple("org", inGroup("eng")), grantTo("org"), + groupTuple("company", inGroup("org")), grantTo("company", "users:write"), + groupTuple("everyone", inGroup("company")), groupTuple("everyone", { subject_id: "user:other" }), grantTo("everyone", "groups:read"), + ]; + const { post, token } = await groupsAdminHarness(t, tuples); + + assert.equal((await post("/auth-admin/groups/eng/delete", `_csrf=${token}`)).status, 303); + assert.deepEqual(tuples, [groupTuple("everyone", { subject_id: "user:other" }), grantTo("everyone", "groups:read")]); +}); + +test("admin group delete: a nesting cycle ends the cascade at a group that keeps a member", async (t) => { + const tuples: RelationTuple[] = [ + groupTuple("a", { subject_id: `user:${ADA}` }), groupTuple("a", inGroup("b")), + groupTuple("b", inGroup("a")), grantTo("b"), + groupTuple("c", inGroup("b")), groupTuple("c", { subject_id: "user:other" }), grantTo("c", "groups:read"), + ]; + const { post, token } = await groupsAdminHarness(t, tuples); + + assert.equal((await post("/auth-admin/groups/a/delete", `_csrf=${token}`)).status, 303); + assert.deepEqual(tuples, [groupTuple("c", { subject_id: "user:other" }), grantTo("c", "groups:read")]); +}); + +test("admin group member removal: the last member leaving takes the group's grants and parent memberships with it", async (t) => { + const tuples: RelationTuple[] = [ + groupTuple("eng", { subject_id: `user:${ADA}` }), grantTo("eng"), + groupTuple("org", inGroup("eng")), groupTuple("org", { subject_id: "user:other" }), + groupTuple("solo", inGroup("org")), grantTo("solo", "users:write"), + ]; + const { post, token } = await groupsAdminHarness(t, tuples); + + assert.equal((await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${randomUUID()}`)).status, 303); + assert.equal(tuples.length, 6, "removing a non-member changes nothing"); + assert.equal((await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${ADA}`)).status, 303); + assert.deepEqual(tuples, [groupTuple("org", { subject_id: "user:other" }), groupTuple("solo", inGroup("org")), grantTo("solo", "users:write")]); +}); + +test("admin group member removal: a group that keeps a member keeps its grants and parents", async (t) => { + const tuples: RelationTuple[] = [groupTuple("eng", { subject_id: `user:${ADA}` }), groupTuple("eng", { subject_id: "user:bob" }), grantTo("eng"), groupTuple("org", inGroup("eng"))]; + const { post, token } = await groupsAdminHarness(t, tuples); + + assert.equal((await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${ADA}`)).status, 303); + assert.equal(tuples.length, 3); +}); + // A double-clicked Save posts twice from one page; the second post finds the first one's result. // A save that changes nothing has nothing to refuse and nothing to revoke. test("admin permission grants: a save that changes nothing is not refused for a stale page and leaves live tokens alone", async (t) => { diff --git a/src/plugin-host/plugin-api.test.ts b/src/plugin-host/plugin-api.test.ts index 7e42cea..1700036 100644 --- a/src/plugin-host/plugin-api.test.ts +++ b/src/plugin-host/plugin-api.test.ts @@ -22,3 +22,13 @@ test("plugin-api re-exports the stable author value surface", () => { assert.equal(api.safeUrl("javascript:alert(1)"), "#"); // the URL sanitiser for rendering untrusted hrefs assert.equal(api.definePlugin({ apiVersion: "1.0.0" }).apiVersion, "1.0.0"); // identity helper works through the barrel }); + +// A system plugin tells an Ory failure apart by `instanceof`; each client's error class must be the barrel's. +test("plugin-api re-exports the Ory error classes a ctx.system client throws", async () => { + const { KetoError } = await import("../auth/keto-client.ts"); + + assert.equal(api.KetoError, KetoError); + for (const name of ["KratosError", "HydraError", "KetoError"] as const) { + assert.equal(typeof api[name], "function", `missing export: ${name}`); + } +}); diff --git a/src/plugin-host/plugin-api.ts b/src/plugin-host/plugin-api.ts index 86cadd7..15c4b75 100644 --- a/src/plugin-host/plugin-api.ts +++ b/src/plugin-host/plugin-api.ts @@ -46,6 +46,7 @@ export type { ExpandTree, KetoClient, RelationQuery, RelationTuple, SubjectSet } export type { HydraAdmin, OAuth2Client } from "../auth/hydra-admin.ts"; export { KratosError } from "../auth/kratos-public.ts"; export { HydraError } from "../auth/hydra-admin.ts"; +export { KetoError } from "../auth/keto-client.ts"; // Sanitise an untrusted URL (upstream/user data) before rendering it in an href/src — partials // escape text but not URL schemes, so a `javascript:`/`data:` URL would be live XSS (see docs). export { safeUrl } from "../http/safe-url.ts";