Skip to content

A local-first personal finance app

fix: reject invalid category group updates (#8856) (#9374)

EMAD BASHARI5897cfa65afe
diff --git a/packages/api/methods.test.ts b/packages/api/methods.test.ts
index 552c6b4195..d3b1c663ab 100644
--- a/packages/api/methods.test.ts
+++ b/packages/api/methods.test.ts
@@ -333,6 +333,140 @@ describe('API CRUD operations', () => {
);
});
+ test.each([
+ { invalidGroupId: null, label: 'null' },
+ { invalidGroupId: '', label: 'empty string' },
+ ])(
+ 'Categories: reject invalid group_id ($label)',
+ async ({ invalidGroupId }) => {
+ const groupId = await api.createCategoryGroup({
+ name: 'test-valid-group',
+ });
+
+ const categoryId = await api.createCategory({
+ name: 'test-category',
+ group_id: groupId,
+ });
+
+ await expect(
+ api.updateCategory(categoryId, {
+ // @ts-expect-error - Testing invalid runtime input
+ group_id: invalidGroupId,
+ }),
+ ).rejects.toThrow();
+
+ const categories = await api.getCategories();
+
+ expect(categories).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: categoryId,
+ group_id: groupId,
+ }),
+ ]),
+ );
+ },
+ );
+
+ test.each(['nope', '00000000-0000-4000-8000-000000000123'])(
+ 'Categories: reject non-existent group_id (%s)',
+ async invalidGroupId => {
+ const groupId = await api.createCategoryGroup({
+ name: 'valid-group-for-invalid-id-test',
+ });
+
+ const categoryId = await api.createCategory({
+ name: 'category-with-valid-group',
+ group_id: groupId,
+ });
+
+ await expect(
+ api.updateCategory(categoryId, {
+ group_id: invalidGroupId,
+ }),
+ ).rejects.toThrow('category group does not exist');
+
+ const categories = await api.getCategories();
+
+ expect(categories).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: categoryId,
+ group_id: groupId,
+ }),
+ ]),
+ );
+ },
+ );
+
+ test('Categories: reject deleted category group', async () => {
+ const validGroupId = await api.createCategoryGroup({
+ name: 'valid-group-for-deleted-group-test',
+ });
+
+ const deletedGroupId = await api.createCategoryGroup({
+ name: 'group-to-be-deleted',
+ });
+
+ const categoryId = await api.createCategory({
+ name: 'category-to-preserve',
+ group_id: validGroupId,
+ });
+
+ await api.deleteCategoryGroup(deletedGroupId);
+
+ await expect(
+ api.updateCategory(categoryId, {
+ group_id: deletedGroupId,
+ }),
+ ).rejects.toThrow('category group does not exist');
+
+ const categories = await api.getCategories();
+
+ expect(categories).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: categoryId,
+ group_id: validGroupId,
+ }),
+ ]),
+ );
+ });
+
+ test('Categories: partial update preserves existing group', async () => {
+ const groupId = await api.createCategoryGroup({
+ name: 'partial-update-group',
+ });
+
+ const categoryId = await api.createCategory({
+ name: 'original-category',
+ group_id: groupId,
+ });
+
+ // Update the name without providing group_id
+ await api.updateCategory(categoryId, {
+ name: 'renamed-category',
+ });
+
+ // Update another field without providing group_id
+ await api.updateCategory(categoryId, {
+ hidden: true,
+ });
+
+ const categories = await api.getCategories();
+
+ expect(categories).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: categoryId,
+ name: 'renamed-category',
+ group_id: groupId,
+ hidden: true,
+ }),
+ ]),
+ );
+ });
+
// apis: setBudgetAmount, setBudgetCarryover, getBudgetMonth
test('Budgets: successfully update budgets', async () => {
const month = '2023-10';
diff --git a/packages/loot-core/src/server/budget/app.test.ts b/packages/loot-core/src/server/budget/app.test.ts
index e43bdc76b0..cd777392db 100644
--- a/packages/loot-core/src/server/budget/app.test.ts
+++ b/packages/loot-core/src/server/budget/app.test.ts
@@ -16,6 +16,8 @@ describe('category-update', () => {
// caller changing only the group never sends `name`. Trimming it
// unconditionally raised "Cannot read properties of undefined (reading
// 'trim')" for every such update (#8857).
+ vi.mocked(db.first).mockResolvedValueOnce({ id: 'new-group-id' });
+
await app.handlers['category-update']({
id: 'category-id',
group: 'new-group-id',
diff --git a/packages/loot-core/src/server/budget/app.ts b/packages/loot-core/src/server/budget/app.ts
index 7ef3c87f40..1891ec3454 100644
--- a/packages/loot-core/src/server/budget/app.ts
+++ b/packages/loot-core/src/server/budget/app.ts
@@ -334,14 +334,33 @@ async function updateCategory(category: CategoryEntity): Promise<void> {
// The API types `fields` as a Partial, and db.update() only writes the
// keys it is given, so a partial that omits `name` must stay omitted
// rather than being trimmed into a TypeError (#8857).
+ if (category.group !== undefined) {
+ if (!category.group) {
+ throw APIError('Updating a category: groupId is required');
+ }
+
+ const existingGroup = await db.first<{ id: string }>(
+ `SELECT id FROM category_groups
+ WHERE id = ? AND tombstone = 0`,
+ [category.group],
+ );
+
+ if (!existingGroup) {
+ throw APIError('Updating a category: category group does not exist');
+ }
+ }
+
const payload = {
...category,
- ...(category.name !== undefined && { name: category.name.trim() }),
+ ...(category.name !== undefined && {
+ name: category.name.trim(),
+ }),
};
- // Convert first so ignored/underscore fields are dropped before we decide
- // whether anything writable remains (e.g. `{ id, _ignored: true }` → `{ id }`).
+
const update = categoryModel.toDb(payload, { update: true });
+
const hasWritableField = Object.keys(update).some(key => key !== 'id');
+
if (!hasWritableField) {
throw APIError('No fields to update');
}
diff --git a/upcoming-release-notes/fix-8856-category-group-guard.md b/upcoming-release-notes/fix-8856-category-group-guard.md
new file mode 100644
index 0000000000..0b4d6505ab
--- /dev/null
+++ b/upcoming-release-notes/fix-8856-category-group-guard.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [emadleo13]
+---
+
+Prevent categories from becoming orphaned when updated with an invalid group ID.