fix(permissions): keep create permissions grantable and stop silent escalation

The matrix could not represent board-create, app-create, integration-create,
search-engine-create or media-upload, and savePermissions force-bundled every
create key with its modify/full parent. Together that meant a group with
board-create was silently upgraded to board-full-all on the next save, and the
common "members may create their own boards" setup became unreachable.

- permissionMatrix models create/upload as an orthogonal capability next to the
  ordered access levels, so all 20 permission keys round-trip losslessly
- savePermissions stores exactly what was selected
- the matrix UI gets a per-category create checkbox, auto-checked and disabled
  when the chosen level already implies it
- a management section is reachable when the user can do at least one thing in
  it; nav, pages and stat cards now share one access helper
This commit is contained in:
Thomas Camlong committed 2026-08-18 15:40:28 +02:00
1 parent 8caf00da79
commit 6728d0a63d
12 files changed
+534 -177

No files matched your search

+3 -16
View File
@@ -9,7 +9,6 @@ import type { Database } from "@homarr/db";
import { and, eq, handleTransactionsAsync, like, not } from "@homarr/db";
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
import { groupMembers, groupPermissions, groups, onboarding, users } from "@homarr/db/schema";
import type { GroupPermissionKey } from "@homarr/definitions";
import { everyoneGroup } from "@homarr/definitions";
import { byIdSchema, paginatedSchema } from "@homarr/validation/common";
import {
@@ -23,13 +22,6 @@ import {
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, protectedProcedure } from "../trpc";
const createPermissionParents = new Map<GroupPermissionKey, GroupPermissionKey>([
["app-create", "app-modify-all"],
["integration-create", "integration-full-all"],
["board-create", "board-full-all"],
["search-engine-create", "search-engine-modify-all"],
]);
export const groupRouter = createTRPCRouter({
getAll: permissionRequiredProcedure.requiresPermission("admin").query(async ({ ctx }) => {
const dbGroups = await ctx.db.query.groups.findMany({
@@ -310,14 +302,9 @@ export const groupRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
const permissions = [
...new Set(
input.permissions.flatMap((permission) => {
const parent = createPermissionParents.get(permission);
return parent ? [permission, parent] : [permission];
}),
),
];
// Stored exactly as selected - implied permissions are resolved at read time through
// getPermissionsWithChildren, so nothing is silently escalated here.
const permissions = [...new Set(input.permissions)];
await handleTransactionsAsync(ctx.db, {
async handleAsync(db, schema) {
+7 -3
View File
@@ -123,12 +123,15 @@ export const homeRouter = createTRPCRouter({
});
}
// These mirror the access rules of /manage/integrations and /manage/apps exactly: a card is only
// shown when the page behind it is reachable, and it counts only what the user is allowed to see.
const hasGlobalFullIntegrationAccess = ctx.session?.user.permissions.includes("integration-full-all") ?? false;
const canCreateIntegrations = ctx.session?.user.permissions.includes("integration-create") ?? false;
const fullAccessIntegrationIds =
hasGlobalFullIntegrationAccess || !ctx.session?.user
? []
: await getFullAccessIntegrationIdsAsync(ctx.db, ctx.session.user.id);
if (hasGlobalFullIntegrationAccess || fullAccessIntegrationIds.length > 0) {
if (hasGlobalFullIntegrationAccess || canCreateIntegrations || fullAccessIntegrationIds.length > 0) {
statistics.push({
titleKey: "integration",
subtitleKey: "resources",
@@ -137,11 +140,12 @@ export const homeRouter = createTRPCRouter({
});
}
if (ctx.session?.user.permissions.includes("app-modify-all")) {
const canManageAllApps = ctx.session?.user.permissions.includes("app-modify-all") ?? false;
if (canManageAllApps || (ctx.session?.user.permissions.includes("app-create") ?? false)) {
statistics.push({
titleKey: "app",
subtitleKey: "resources",
count: await db.$count(apps),
count: canManageAllApps ? await db.$count(apps) : 0,
path: "/manage/apps",
});
}
+74 -27
View File
@@ -449,7 +449,7 @@ describe("savePermissions should save permissions for group", () => {
expect(permissions.map(({ permission }) => permission)).toEqual(["integration-use-all", "board-full-all"]);
});
test("with a create permission it should also persist its parent permission", async () => {
test("with a standalone create permission it should not escalate to its parent permission", async () => {
// Arrange
const db = createDb();
const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
@@ -464,7 +464,7 @@ describe("savePermissions should save permissions for group", () => {
// Act
await caller.savePermissions({
groupId,
permissions: ["app-create"],
permissions: ["board-create"],
});
// Assert
@@ -472,37 +472,34 @@ describe("savePermissions should save permissions for group", () => {
where: eq(groupPermissions.groupId, groupId),
});
expect(permissions.map(({ permission }) => permission).toSorted()).toEqual(["app-create", "app-modify-all"]);
expect(permissions.map(({ permission }) => permission)).toEqual(["board-create"]);
});
test("with an integration create permission it should persist its parent permission", async () => {
// Arrange
const db = createDb();
const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
test.each([["app-create"], ["integration-create"], ["search-engine-create"], ["media-upload"]] as const)(
"with %s alone it should persist exactly that permission",
async (permission) => {
// Arrange
const db = createDb();
const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
const groupId = createId();
await db.insert(groups).values({
id: groupId,
name: "Group",
position: 1,
});
const groupId = createId();
await db.insert(groups).values({
id: groupId,
name: "Group",
position: 1,
});
// Act
await caller.savePermissions({
groupId,
permissions: ["integration-create"],
});
// Act
await caller.savePermissions({ groupId, permissions: [permission] });
// Assert
const permissions = await db.query.groupPermissions.findMany({
where: eq(groupPermissions.groupId, groupId),
});
// Assert
const permissions = await db.query.groupPermissions.findMany({
where: eq(groupPermissions.groupId, groupId),
});
expect(permissions.map(({ permission }) => permission).toSorted()).toEqual([
"integration-create",
"integration-full-all",
]);
});
expect(permissions.map(({ permission: key }) => key)).toEqual([permission]);
},
);
test("with a create permission and its parent it should persist exactly two rows", async () => {
// Arrange
@@ -531,6 +528,56 @@ describe("savePermissions should save permissions for group", () => {
expect(permissions.map(({ permission }) => permission).toSorted()).toEqual(["app-create", "app-modify-all"]);
});
test("with duplicate permissions it should persist each permission only once", async () => {
// Arrange
const db = createDb();
const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
const groupId = createId();
await db.insert(groups).values({
id: groupId,
name: "Group",
position: 1,
});
// Act
await caller.savePermissions({
groupId,
permissions: ["board-view-all", "board-view-all", "board-modify-all"],
});
// Assert
const permissions = await db.query.groupPermissions.findMany({
where: eq(groupPermissions.groupId, groupId),
});
expect(permissions.map(({ permission }) => permission).toSorted()).toEqual(["board-modify-all", "board-view-all"]);
});
test("saving the same permissions twice should be idempotent", async () => {
// Arrange
const db = createDb();
const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
const groupId = createId();
await db.insert(groups).values({
id: groupId,
name: "Group",
position: 1,
});
// Act
await caller.savePermissions({ groupId, permissions: ["board-create", "media-upload"] });
await caller.savePermissions({ groupId, permissions: ["board-create", "media-upload"] });
// Assert
const permissions = await db.query.groupPermissions.findMany({
where: eq(groupPermissions.groupId, groupId),
});
expect(permissions.map(({ permission }) => permission).toSorted()).toEqual(["board-create", "media-upload"]);
});
test("with an empty permission list it should clear all existing permissions", async () => {
// Arrange
const db = createDb();
+53 -13
View File
@@ -119,23 +119,53 @@ export const groupPermissionKeys = objectKeys(groupPermissions).reduce((acc, key
}, [] as GroupPermissionKey[]);
/**
* Ordered access levels per category used by the group permission matrix UI.
* Each level entry is a full {@link GroupPermissionKey}; higher levels imply the lower ones
* through {@link groupPermissionParents}.
* Describes how each permission category is presented in the group permission matrix UI.
*
* `levels` is an ordered escalation of access: picking level N grants every key up to N.
* `create` is orthogonal to `levels` - it is the "may add new resources" capability and can be
* granted on its own (e.g. "members may create their own boards but not see anyone else's").
* Some levels already imply the create key through {@link groupPermissionParents}; use
* {@link isCreateImpliedByLevel} to detect that instead of hard-coding it.
*
* Together, `levels` and `create` cover every key in {@link groupPermissionKeys}, so the matrix
* is a lossless representation of a group's permissions.
*/
export const permissionMatrix = {
board: { levels: ["board-view-all", "board-modify-all", "board-full-all"] },
app: { levels: ["app-use-all", "app-modify-all", "app-full-all"] },
integration: { levels: ["integration-use-all", "integration-interact-all", "integration-full-all"] },
"search-engine": { levels: ["search-engine-modify-all", "search-engine-full-all"] },
media: { levels: ["media-view-all", "media-full-all"] },
other: { levels: ["other-view-logs"] },
admin: { levels: ["admin"] },
} as const satisfies Record<string, { levels: readonly GroupPermissionKey[] }>;
board: { levels: ["board-view-all", "board-modify-all", "board-full-all"], create: "board-create" },
app: { levels: ["app-use-all", "app-modify-all", "app-full-all"], create: "app-create" },
integration: {
levels: ["integration-use-all", "integration-interact-all", "integration-full-all"],
create: "integration-create",
},
"search-engine": { levels: ["search-engine-modify-all", "search-engine-full-all"], create: "search-engine-create" },
media: { levels: ["media-view-all", "media-full-all"], create: "media-upload" },
other: { levels: ["other-view-logs"], create: null },
admin: { levels: ["admin"], create: null },
} as const satisfies Record<string, { levels: readonly GroupPermissionKey[]; create: GroupPermissionKey | null }>;
export type PermissionMatrixCategory = keyof typeof permissionMatrix;
export type PermissionMatrixState = Record<PermissionMatrixCategory, { level: number }>;
export interface PermissionMatrixCategoryState {
/** 0 = no access, N = every key up to `permissionMatrix[category].levels[N - 1]` */
level: number;
/** Whether the category's create/upload key is granted */
create: boolean;
}
export type PermissionMatrixState = Record<PermissionMatrixCategory, PermissionMatrixCategoryState>;
/**
* Whether the given level already grants the category's create key through permission inheritance.
* For example board level 3 (`board-full-all`) implies `board-create`.
*/
export const isCreateImpliedByLevel = (category: PermissionMatrixCategory, level: number) => {
const createKey = permissionMatrix[category].create;
if (createKey === null || level <= 0) {
return false;
}
return getPermissionsWithChildren([...permissionMatrix[category].levels.slice(0, level)]).includes(createKey);
};
export const permissionsToMatrixState = (permissions: GroupPermissionKey[]): PermissionMatrixState => {
const permissionSet = new Set(permissions);
@@ -147,7 +177,11 @@ export const permissionsToMatrixState = (permissions: GroupPermissionKey[]): Per
level = index + 1;
}
});
acc[category] = { level };
const createKey = permissionMatrix[category].create;
acc[category] = {
level,
create: createKey !== null && (permissionSet.has(createKey) || isCreateImpliedByLevel(category, level)),
};
return acc;
}, {} as PermissionMatrixState);
};
@@ -155,6 +189,12 @@ export const permissionsToMatrixState = (permissions: GroupPermissionKey[]): Per
export const matrixStateToPermissions = (state: PermissionMatrixState): GroupPermissionKey[] => {
return objectKeys(permissionMatrix).reduce((acc, category) => {
acc.push(...permissionMatrix[category].levels.slice(0, state[category].level));
// Skip the create key when the chosen level already implies it, so the stored permissions
// stay minimal and a state -> permissions -> state round-trip is exact.
const createKey = permissionMatrix[category].create;
if (createKey !== null && state[category].create && !isCreateImpliedByLevel(category, state[category].level)) {
acc.push(createKey);
}
return acc;
}, [] as GroupPermissionKey[]);
};
@@ -1,13 +1,27 @@
import { describe, expect, test } from "vitest";
import type { GroupPermissionKey } from "../permissions";
import type { GroupPermissionKey, PermissionMatrixState } from "../permissions";
import {
getPermissionsWithChildren,
getPermissionsWithParents,
groupPermissionKeys,
isCreateImpliedByLevel,
matrixStateToPermissions,
permissionMatrix,
permissionsToMatrixState,
} from "../permissions";
const emptyState = (overrides: Partial<PermissionMatrixState> = {}): PermissionMatrixState => ({
board: { level: 0, create: false },
app: { level: 0, create: false },
integration: { level: 0, create: false },
"search-engine": { level: 0, create: false },
media: { level: 0, create: false },
other: { level: 0, create: false },
admin: { level: 0, create: false },
...overrides,
});
describe("getPermissionsWithParents should return the correct permissions", () => {
test.each([
[["board-view-all"], ["board-view-all", "board-modify-all", "board-full-all", "admin"]],
@@ -51,10 +65,23 @@ describe("getPermissionsWithChildren should return the correct permissions", ()
});
});
describe("the matrix must be able to represent every permission", () => {
test("every group permission key is covered by exactly one category", () => {
const covered = Object.values(permissionMatrix).flatMap(({ levels, create }) => [
...levels,
...(create === null ? [] : [create]),
]);
expect(covered.toSorted()).toEqual(groupPermissionKeys.toSorted());
});
test.each(groupPermissionKeys.map((key) => [key]))("expect %s to survive a round-trip on its own", (key) => {
expect(matrixStateToPermissions(permissionsToMatrixState([key]))).toContain(key);
});
});
describe("permissionsToMatrixState should resolve the highest present level per category", () => {
test("resolves the highest present level key", () => {
const state = permissionsToMatrixState(["board-view-all", "board-modify-all"]);
expect(state.board.level).toBe(2);
expect(permissionsToMatrixState(["board-view-all", "board-modify-all"]).board.level).toBe(2);
});
test("resolves the admin category", () => {
@@ -63,35 +90,74 @@ describe("permissionsToMatrixState should resolve the highest present level per
test("resolves an empty selection to all zero", () => {
const state = permissionsToMatrixState([]);
expect(Object.values(state).every(({ level }) => level === 0)).toBe(true);
expect(Object.values(state).every(({ level, create }) => level === 0 && !create)).toBe(true);
});
test("resolves a standalone create key without granting any level", () => {
expect(permissionsToMatrixState(["board-create"]).board).toEqual({ level: 0, create: true });
});
test("marks create as granted when the level implies it", () => {
expect(permissionsToMatrixState(["board-full-all"]).board.create).toBe(true);
expect(permissionsToMatrixState(["app-modify-all"]).app.create).toBe(true);
expect(permissionsToMatrixState(["media-full-all"]).media.create).toBe(true);
});
test("does not mark create as granted for a level that does not imply it", () => {
expect(permissionsToMatrixState(["board-modify-all"]).board.create).toBe(false);
expect(permissionsToMatrixState(["integration-interact-all"]).integration.create).toBe(false);
});
});
describe("isCreateImpliedByLevel", () => {
test.each([
["board", 0, false],
["board", 1, false],
["board", 2, false],
["board", 3, true],
["app", 1, false],
["app", 2, true],
["integration", 2, false],
["integration", 3, true],
["search-engine", 1, true],
["media", 1, false],
["media", 2, true],
["other", 1, false],
["admin", 1, false],
] satisfies [keyof typeof permissionMatrix, number, boolean][])(
"expect %s at level %i to imply create: %s",
(category, level, expected) => {
expect(isCreateImpliedByLevel(category, level)).toBe(expected);
},
);
});
describe("matrixStateToPermissions should expand levels into permission keys", () => {
test("expands a level into the ordered level keys", () => {
const permissions = matrixStateToPermissions({
board: { level: 2 },
app: { level: 0 },
integration: { level: 0 },
"search-engine": { level: 0 },
media: { level: 0 },
other: { level: 0 },
admin: { level: 0 },
});
expect(permissions).toEqual(["board-view-all", "board-modify-all"]);
expect(matrixStateToPermissions(emptyState({ board: { level: 2, create: false } }))).toEqual([
"board-view-all",
"board-modify-all",
]);
});
test("expands the admin category into the admin key", () => {
const permissions = matrixStateToPermissions({
board: { level: 0 },
app: { level: 0 },
integration: { level: 0 },
"search-engine": { level: 0 },
media: { level: 0 },
other: { level: 0 },
admin: { level: 1 },
});
expect(permissions).toEqual(["admin"]);
expect(matrixStateToPermissions(emptyState({ admin: { level: 1, create: false } }))).toEqual(["admin"]);
});
test("emits a standalone create key without any level", () => {
expect(matrixStateToPermissions(emptyState({ board: { level: 0, create: true } }))).toEqual(["board-create"]);
});
test("emits media-upload as the create key of the media category", () => {
expect(matrixStateToPermissions(emptyState({ media: { level: 0, create: true } }))).toEqual(["media-upload"]);
});
test("omits a create key that the chosen level already implies", () => {
expect(matrixStateToPermissions(emptyState({ board: { level: 3, create: true } }))).toEqual([
"board-view-all",
"board-modify-all",
"board-full-all",
]);
});
});
@@ -111,6 +177,10 @@ describe("matrix helpers should round-trip stably", () => {
"other-view-logs",
],
],
[["board-create"]],
[["media-upload"]],
[["board-create", "app-create", "integration-create", "search-engine-create", "media-upload"]],
[["board-create", "board-view-all"]],
] satisfies [GroupPermissionKey[]][])("expect %s to round-trip", (permissions) => {
const roundTripped = matrixStateToPermissions(permissionsToMatrixState(permissions));
expect(roundTripped).toEqual(expect.arrayContaining(permissions));
@@ -118,7 +188,10 @@ describe("matrix helpers should round-trip stably", () => {
});
test("expect a single higher-level key to expand to its full set on round-trip", () => {
const roundTripped = matrixStateToPermissions(permissionsToMatrixState(["board-full-all"]));
expect(roundTripped).toEqual(["board-view-all", "board-modify-all", "board-full-all"]);
expect(matrixStateToPermissions(permissionsToMatrixState(["board-full-all"]))).toEqual([
"board-view-all",
"board-modify-all",
"board-full-all",
]);
});
});
+22 -8
View File
@@ -655,20 +655,32 @@
}
},
"matrix": {
"none": "None",
"impliedHint": "also grants: {permissions}",
"grantedViaAdmin": "Granted via Administrator",
"none": "No access",
"impliedHint": "Also grants: {permissions}",
"grantedViaAdmin": "Administrators already have this. Set Admin to “No access” to configure it separately.",
"preset": {
"label": "Presets",
"viewer": "Viewer",
"viewerDescription": "Read-only: view boards and medias, use apps and integrations that already exist.",
"editor": "Editor",
"editorDescription": "Day-to-day management: create and edit boards, apps, integrations and search engines.",
"admin": "Admin",
"adminDescription": "Unrestricted access to every feature and setting, including user management.",
"custom": "Custom"
},
"effective": {
"title": "Effective permissions",
"description": "Everything members of this group will be able to do, including implied permissions",
"description": "The full, de-duplicated set of actions members of this group can perform, including permissions granted indirectly.",
"empty": "No permissions selected"
},
"noneDescription": "Members get no access to this area.",
"createIncluded": "Already included in “{level}”",
"level": {
"view": "View",
"use": "Use",
"interact": "Interact",
"modify": "Modify",
"full": "Full"
}
}
},
@@ -796,7 +808,9 @@
"action": "Create your first app",
"filteredTitle": "No apps match your search",
"filteredDescription": "No apps match \"{search}\". Try another name or URL.",
"clearSearch": "Clear search"
"clearSearch": "Clear search",
"createOnlyTitle": "You can only add apps",
"createOnlyDescription": "Your permissions let you create apps but not browse existing ones. Ask an administrator for app management access to see the full list."
}
},
"create": {
@@ -1598,7 +1612,7 @@
"title": "Integrations",
"ariaLabel": "Configured integrations",
"search": "Search integrations",
"scopedNote": "Showing only integrations you have full access to",
"scopedNote": "Showing only the integrations you are allowed to manage.",
"action": {
"edit": "Edit {name}",
"delete": "Delete {name}"
@@ -1610,8 +1624,8 @@
"filteredTitle": "No integrations match your search",
"filteredDescription": "No integrations match \"{search}\". Try another name, type, or URL.",
"clearSearch": "Clear search",
"noPermissionTitle": "No manageable integrations",
"noPermissionDescription": "You don't have full management access to any integrations. Ask your administrator."
"createOnlyTitle": "You can only add integrations",
"createOnlyDescription": "Your permissions let you create integrations but not manage existing ones. Ask an administrator for access to the ones you need."
}
},
"create": {