Answer stability round 1: 1 🔴, 2 🟡 (0 misread); empty a group once all its members are gone in a diamond, log the cascade, notice an emptied group

This commit is contained in:
2026-11-17 01:17:57 +01:00
parent 37e7227dea
commit f3500ff81d
6 changed files with 95 additions and 39 deletions
+7 -4
View File
@@ -14,7 +14,9 @@ The host's contract version is now 0.5.0, so discovery refuses a plugin whose `a
### `@plainpages/plugin-api` exports `KetoError` ### `@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`. A plugin that calls `ctx.system.keto` can tell a Keto failure from any other error with
`instanceof KetoError`, as it already can a `KratosError` or a `HydraError`. The error carries the HTTP
`status`. It adds to the plugin API, so an installed plugin needs no change.
### The core dashboard view is `dashboard`, not `index` ### The core dashboard view is `dashboard`, not `index`
@@ -43,9 +45,10 @@ back in every parent.
### The admin example removes a group's grants and parent memberships when its last member leaves ### 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 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 groups. This holds when the last member is removed, and the group page then says so. It also holds
no members, up through every ancestor that is left empty in turn. A group re-created with the same when deleting a group leaves its parent with no members, and so on up through each ancestor left
name used to get the old group's permissions and parents back. empty. A group re-created with the same name used to get the old group's permissions and parents back.
Groups already left empty by an earlier version keep theirs, and re-creating one still restores them.
### The admin example keeps a user's permissions section when it refuses a self-deactivate or self-delete ### The admin example keeps a user's permissions section when it refuses a self-deactivate or self-delete
+37 -21
View File
@@ -1,8 +1,9 @@
// Groups admin screen: list / create / delete Keto groups and manage membership. // Groups admin screen: list / create / delete Keto groups and manage membership.
// A group is a Keto subject set `Group:<name>#members`; a member is a user or a nested group (see // A group is a Keto subject set `Group:<name>#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 // 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 — or // exists exactly while it has ≥1 member, so create writes its first-member tuple, and removing the
// 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 // last member deletes the group (see `withEmptiedGroups`).
// 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, // per-route handlers (keyed on ctx.params) over a shared `withGroups` gate — admin-only, CSRF-guarded,
// each returning a RouteResult. // each returning a RouteResult.
@@ -369,7 +370,7 @@ async function groupDetailPage({ ctx, keto, kratosAdmin }: GroupsDeps, name: str
// GET /auth-admin/groups/:name — the detail + membership page. // GET /auth-admin/groups/:name — the detail + membership page.
export const groupsDetail = withGroupName((deps, name) => export const groupsDetail = withGroupName((deps, name) =>
groupDetailPage(deps, name, { notice: grantsNotice(deps.ctx.url, deps.ctx.t) ?? "" })); groupDetailPage(deps, name, { notice: grantsNotice(deps.ctx.url, deps.ctx.t) ?? emptiedNotice(deps.ctx.url, deps.ctx.t) ?? "" }));
// POST /auth-admin/groups/:name/permissions — the submitted checkboxes are the desired set. Members hold // POST /auth-admin/groups/:name/permissions — the submitted checkboxes are the desired set. Members hold
// a group's permissions transitively, so the change reaches them at their next login or re-mint — // a group's permissions transitively, so the change reaches them at their next login or re-mint —
@@ -419,44 +420,56 @@ export const groupsDeleteConfirm = withGroupName(async (deps, name) => {
}) }, view: "confirm" }; }) }, view: "confirm" };
}, "write"); }, "write");
const EMPTIED_NOTICE = "group-emptied"; // the `info-msg` that removing a group's last member redirects with
const emptiedNotice = (url: URL, t: Translate): string | undefined =>
url.searchParams.get("info-msg") === EMPTIED_NOTICE ? t("admin.groups.emptied") : undefined;
const tupleId =(t: RelationTuple): string => { 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; 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}`; 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 // A group exists only through its members. Once `removing` leaves one of `groups` with none, the
// on its name — its grants and its memberships in other groups — must go too, or re-creating the name // grants on its name and its memberships in other groups must go too, or re-creating the name would
// would restore them. Returns `removing` plus those tuples. Emptying a group can empty its parents in // restore them. Emptying a group can empty its parents, so the walk climbs from each emptied group to
// turn, so the walk climbs until it meets a group that keeps a member; `seen` ends it on a nesting cycle. // the groups it is in, and a group left with a member ends that branch. Returns every tuple to delete
async function withEmptiedGroups(keto: KetoClient, removing: readonly RelationTuple[], groups: readonly string[]): Promise<RelationTuple[]> { // (`removing` and those) and the emptied groups. A member added by another admin between these reads
// and the transaction lands in a stripped group: Keto has no conditional write.
async function withEmptiedGroups(keto: KetoClient, removing: readonly RelationTuple[], groups: readonly string[]): Promise<{ delete: RelationTuple[]; emptied: string[] }> {
const doomed = new Map(removing.map((t) => [tupleId(t), t])); const doomed = new Map(removing.map((t) => [tupleId(t), t]));
const pending = [...groups]; const pending = [...groups];
const seen = new Set<string>(); const emptied = new Set<string>(); // also ends the walk on a nesting cycle
for (let group = pending.pop(); group !== undefined; group = pending.pop()) { for (let group = pending.pop(); group !== undefined; group = pending.pop()) {
if (seen.has(group)) continue; if (emptied.has(group)) continue;
seen.add(group);
const members = await pagedTuples(keto, { namespace: GROUP_NS, object: group, relation: MEMBERS }); const members = await pagedTuples(keto, { namespace: GROUP_NS, object: group, relation: MEMBERS });
if (members.some((m) => !doomed.has(tupleId(m)))) continue; if (members.some((m) => !doomed.has(tupleId(m)))) continue; // may be reached again, by a sibling emptied later
emptied.add(group);
const subject = groupSubject(group); const subject = groupSubject(group);
const grants = (await heldPermissions(keto, subject)).map((permission) => grantTuple(permission, subject)); const grants = (await heldPermissions(keto, subject)).map((permission) => grantTuple(permission, subject));
const inParents = await pagedTuples(keto, { namespace: GROUP_NS, relation: MEMBERS, ...subject }); const inParents = await pagedTuples(keto, { namespace: GROUP_NS, relation: MEMBERS, ...subject });
for (const t of [...grants, ...inParents]) doomed.set(tupleId(t), t); for (const t of [...grants, ...inParents]) doomed.set(tupleId(t), t);
pending.push(...inParents.map((t) => t.object)); pending.push(...inParents.map((t) => t.object));
} }
return [...doomed.values()]; return { delete: [...doomed.values()], emptied: [...emptied] };
}
// Logged with the groups that lost their grants, since the screen doesn't list them.
function logEmptied(deps: GroupsDeps, event: string, name: string, cascade: { delete: RelationTuple[]; emptied: string[] }): void {
const revoked = new Set(cascade.delete.filter((t) => t.namespace !== GROUP_NS).map((t) => t.object));
deps.ctx.log.info(event, { actor: deps.user.id, emptied: cascade.emptied.join(","), group: name, revoked: [...revoked].sort().join(",") });
} }
// POST /auth-admin/groups/:name/delete — one Keto transaction removes the group's member tuples and // 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. // everything `withEmptiedGroups` finds, so a Keto failure leaves the group as it was.
export const groupsDelete = withGroupName(async (deps, name) => { export const groupsDelete = withGroupName(async (deps, name) => {
const { ctx, keto, user } = deps; const { ctx, keto } = deps;
await guardedForm(ctx); // CSRF-verify the POST await guardedForm(ctx); // CSRF-verify the POST
const lost = await lostOnDelete(deps, name); const lost = await lostOnDelete(deps, name);
if (lost.length > 0) return refuseSelfLockout(deps, name, "delete", lost); if (lost.length > 0) return refuseSelfLockout(deps, name, "delete", lost);
const held = await heldPermissions(keto, groupSubject(name));
const members = await pagedTuples(keto, { namespace: GROUP_NS, object: name, relation: MEMBERS }); const members = await pagedTuples(keto, { namespace: GROUP_NS, object: name, relation: MEMBERS });
await keto.transactTuples({ delete: await withEmptiedGroups(keto, members, [name]), insert: [] }); const cascade = await withEmptiedGroups(keto, members, [name]);
ctx.log.info("admin: group deleted", { actor: user.id, group: name, revoked: held.join(",") }); await keto.transactTuples({ delete: cascade.delete, insert: [] });
logEmptied(deps, "admin: group deleted", name, cascade);
return { redirect: ADMIN_GROUPS_BASE }; return { redirect: ADMIN_GROUPS_BASE };
}); });
@@ -470,6 +483,9 @@ 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 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) : []; const lost = removesSelf ? await lostOnLeaving(deps, name) : [];
if (lost.length > 0) return refuseSelfLockout(deps, name, "remove", lost); if (lost.length > 0) return refuseSelfLockout(deps, name, "remove", lost);
await keto.transactTuples({ delete: await withEmptiedGroups(keto, [tuple], [name]), insert: [] }); const cascade = await withEmptiedGroups(keto, [tuple], [name]);
return { redirect: detailHref(name) }; await keto.transactTuples({ delete: cascade.delete, insert: [] });
if (cascade.emptied.length === 0) return { redirect: detailHref(name) };
logEmptied(deps, "admin: last group member removed", name, cascade);
return { redirect: `${detailHref(name)}?info-msg=${EMPTIED_NOTICE}` };
}); });
@@ -71,6 +71,7 @@ const messages = {
"admin.groups.create": "Create group", "admin.groups.create": "Create group",
"admin.groups.delete": "Delete group", "admin.groups.delete": "Delete group",
"admin.groups.deleteMessage": "Delete group {{name}}? This can't be undone.", "admin.groups.deleteMessage": "Delete group {{name}}? This can't be undone.",
"admin.groups.emptied": "That was the last member, so the group no longer exists and its permissions and parent groups are removed.",
"admin.groups.error.duplicate":"A group with that name already exists.", "admin.groups.error.duplicate":"A group with that name already exists.",
"admin.groups.error.selfLockout": "This change would lock you out of {{permissions}}, which you hold through this group. Ask another administrator to make it.", "admin.groups.error.selfLockout": "This change would lock you out of {{permissions}}, which you hold through this group. Ask another administrator to make it.",
"admin.groups.field.name": "Group name", "admin.groups.field.name": "Group name",
@@ -71,6 +71,7 @@ const messages: AdminMessages = {
"admin.groups.create": "Skapa grupp", "admin.groups.create": "Skapa grupp",
"admin.groups.delete": "Radera grupp", "admin.groups.delete": "Radera grupp",
"admin.groups.deleteMessage": "Ta bort gruppen {{name}}? Det går inte att ångra.", "admin.groups.deleteMessage": "Ta bort gruppen {{name}}? Det går inte att ångra.",
"admin.groups.emptied": "Det var den sista medlemmen, så gruppen finns inte längre och dess behörigheter och föräldragrupper är borttagna.",
"admin.groups.error.duplicate":"Det finns redan en grupp med det namnet.", "admin.groups.error.duplicate":"Det finns redan en grupp med det namnet.",
"admin.groups.error.selfLockout": "Ändringen skulle låsa ute dig från {{permissions}}, som du har genom den här gruppen. Be en annan administratör att göra den.", "admin.groups.error.selfLockout": "Ändringen skulle låsa ute dig från {{permissions}}, som du har genom den här gruppen. Be en annan administratör att göra den.",
"admin.groups.field.name": "Gruppnamn", "admin.groups.field.name": "Gruppnamn",
+44 -6
View File
@@ -446,8 +446,7 @@ 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" })]); 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 // Tuples a group keeps after it loses its last member would be restored by re-creating its name.
// its memberships with it: otherwise re-creating the name hands every new member the old ones.
const ADA = randomUUID(); const ADA = randomUUID();
const groupTuple = (object: string, subject: Partial<RelationTuple>): RelationTuple => ({ namespace: "Group", object, relation: "members", ...subject } as RelationTuple); const groupTuple = (object: string, subject: Partial<RelationTuple>): RelationTuple => ({ namespace: "Group", object, relation: "members", ...subject } as RelationTuple);
const inGroup = (object: string) => ({ subject_set: { namespace: "Group", object, relation: "members" } }); const inGroup = (object: string) => ({ subject_set: { namespace: "Group", object, relation: "members" } });
@@ -479,6 +478,18 @@ test("admin group delete: a nesting cycle ends the cascade at a group that keeps
assert.deepEqual(tuples, [groupTuple("c", { subject_id: "user:other" }), grantTo("c", "groups:read")]); assert.deepEqual(tuples, [groupTuple("c", { subject_id: "user:other" }), grantTo("c", "groups:read")]);
}); });
test("admin group delete: a diamond of nested groups empties the top once both its members are gone", async (t) => {
const tuples: RelationTuple[] = [
groupTuple("eng", { subject_id: `user:${ADA}` }),
groupTuple("left", inGroup("eng")), groupTuple("right", inGroup("eng")),
groupTuple("top", inGroup("left")), groupTuple("top", inGroup("right")), grantTo("top"),
];
const { post, token } = await groupsAdminHarness(t, tuples);
assert.equal((await post("/auth-admin/groups/eng/delete", `_csrf=${token}`)).status, 303);
assert.deepEqual(tuples, []);
});
test("admin group member removal: the last member leaving takes the group's grants and parent memberships with it", async (t) => { test("admin group member removal: the last member leaving takes the group's grants and parent memberships with it", async (t) => {
const tuples: RelationTuple[] = [ const tuples: RelationTuple[] = [
groupTuple("eng", { subject_id: `user:${ADA}` }), grantTo("eng"), groupTuple("eng", { subject_id: `user:${ADA}` }), grantTo("eng"),
@@ -487,20 +498,47 @@ test("admin group member removal: the last member leaving takes the group's gran
]; ];
const { post, token } = await groupsAdminHarness(t, tuples); const { post, token } = await groupsAdminHarness(t, tuples);
assert.equal((await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${randomUUID()}`)).status, 303); const res = await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${ADA}`);
assert.equal(tuples.length, 6, "removing a non-member changes nothing"); assert.equal(res.headers.get("location"), "/auth-admin/groups/eng?info-msg=group-emptied");
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")]); assert.deepEqual(tuples, [groupTuple("org", { subject_id: "user:other" }), groupTuple("solo", inGroup("org")), grantTo("solo", "users:write")]);
}); });
test("admin group member removal: removing someone who isn't a member changes nothing", async (t) => {
const tuples: RelationTuple[] = [groupTuple("eng", { subject_id: `user:${ADA}` }), grantTo("eng")];
const { post, token } = await groupsAdminHarness(t, tuples);
const res = await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${randomUUID()}`);
assert.equal(res.headers.get("location"), "/auth-admin/groups/eng");
assert.equal(tuples.length, 2);
});
test("admin group member removal: a group that keeps a member keeps its grants and parents", async (t) => { 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 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); const { post, token } = await groupsAdminHarness(t, tuples);
assert.equal((await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${ADA}`)).status, 303); const res = await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${ADA}`);
assert.equal(res.headers.get("location"), "/auth-admin/groups/eng");
assert.equal(tuples.length, 3); assert.equal(tuples.length, 3);
}); });
test("admin group member removal: a parent that keeps another nested group keeps its grants", async (t) => {
const tuples: RelationTuple[] = [
groupTuple("eng", { subject_id: `user:${ADA}` }),
groupTuple("left", inGroup("eng")), groupTuple("right", { subject_id: "user:other" }),
groupTuple("top", inGroup("left")), groupTuple("top", inGroup("right")), grantTo("top"),
];
const { post, token } = await groupsAdminHarness(t, tuples);
await post("/auth-admin/groups/eng/members/delete", `_csrf=${token}&member=user:${ADA}`);
assert.deepEqual(tuples, [groupTuple("right", { subject_id: "user:other" }), groupTuple("top", inGroup("right")), grantTo("top")]);
});
test("admin group member removal: the group page shows the notice that the group is gone", async (t) => {
const { get } = await groupsAdminHarness(t, []);
assert.match(await (await get("/auth-admin/groups/eng?info-msg=group-emptied")).text(), /That was the last member/);
});
// A double-clicked Save posts twice from one page; the second post finds the first one's result. // 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. // 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) => { test("admin permission grants: a save that changes nothing is not refused for a stale page and leaves live tokens alone", async (t) => {
+2 -5
View File
@@ -23,12 +23,9 @@ test("plugin-api re-exports the stable author value surface", () => {
assert.equal(api.definePlugin({ apiVersion: "1.0.0" }).apiVersion, "1.0.0"); // identity helper works through the barrel 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. // A plugin matches a Keto failure with `instanceof`, so the barrel must export the class `ctx.system.keto` throws.
test("plugin-api re-exports the Ory error classes a ctx.system client throws", async () => { test("plugin-api re-exports the KetoError class the Keto client throws", async () => {
const { KetoError } = await import("../auth/keto-client.ts"); const { KetoError } = await import("../auth/keto-client.ts");
assert.equal(api.KetoError, KetoError); assert.equal(api.KetoError, KetoError);
for (const name of ["KratosError", "HydraError", "KetoError"] as const) {
assert.equal(typeof api[name], "function", `missing export: ${name}`);
}
}); });