fix: keep updates from moving rows to another group or household (#8965)
This commit is contained in:
1 parent
d51175b486
commit
cf0c0f4ffe
5 files changed
+134
-11
No files matched your search
@@ -9,7 +9,6 @@ from typing import Any
|
||||
from fastapi import HTTPException
|
||||
from pydantic import UUID4, BaseModel
|
||||
from sqlalchemy import ColumnElement, Select, case, delete, func, nulls_first, nulls_last, select
|
||||
from sqlalchemy.ext.associationproxy import AssociationProxyInstance
|
||||
from sqlalchemy.orm.session import Session
|
||||
|
||||
from mealie.core.root_logger import get_logger
|
||||
@@ -76,13 +75,6 @@ class RepositoryGeneric[Schema: MealieModel, Model: SqlAlchemyBase]:
|
||||
|
||||
def _query(self, override_schema: type[MealieModel] | None = None, with_options=True):
|
||||
q = select(self.model)
|
||||
|
||||
try:
|
||||
if isinstance(self.model.household_id, AssociationProxyInstance):
|
||||
q.filter(self.model.household_id.is_not(None))
|
||||
except AttributeError, NotImplementedError:
|
||||
pass
|
||||
|
||||
if with_options:
|
||||
schema = override_schema or self.schema
|
||||
return q.options(*schema.loader_options())
|
||||
@@ -99,6 +91,17 @@ class RepositoryGeneric[Schema: MealieModel, Model: SqlAlchemyBase]:
|
||||
|
||||
return {**dct, **kwargs}
|
||||
|
||||
def _keep_scope(self, entry: Model, new_data: dict) -> dict:
|
||||
"""
|
||||
Overwrites the scope fields in `new_data` with the stored values, so an update can't move a row
|
||||
out of the group or household this repo is scoped to.
|
||||
"""
|
||||
for field, scope in (("group_id", self.group_id), ("household_id", self.household_id)):
|
||||
if scope and field in new_data:
|
||||
new_data[field] = getattr(entry, field)
|
||||
|
||||
return new_data
|
||||
|
||||
def get_all(
|
||||
self,
|
||||
limit: int | None = None,
|
||||
@@ -222,7 +225,7 @@ class RepositoryGeneric[Schema: MealieModel, Model: SqlAlchemyBase]:
|
||||
new_data = new_data if isinstance(new_data, dict) else new_data.model_dump()
|
||||
|
||||
entry = self._query_one(match_value=match_value)
|
||||
entry.update(session=self.session, **new_data)
|
||||
entry.update(session=self.session, **self._keep_scope(entry, new_data))
|
||||
|
||||
self.session.commit()
|
||||
return self.schema.model_validate(entry)
|
||||
@@ -242,7 +245,7 @@ class RepositoryGeneric[Schema: MealieModel, Model: SqlAlchemyBase]:
|
||||
|
||||
updated_documents = []
|
||||
for document_to_update in documents_to_update:
|
||||
data = document_data_by_id[document_to_update.id] # type: ignore
|
||||
data = self._keep_scope(document_to_update, document_data_by_id[document_to_update.id]) # type: ignore
|
||||
document_to_update.update(session=self.session, **data) # type: ignore
|
||||
updated_documents.append(document_to_update)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from pydantic import UUID4, BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from mealie.db.models.household import GroupMealPlan
|
||||
@@ -9,6 +10,12 @@ from .repository_generic import HouseholdRepositoryGeneric
|
||||
|
||||
|
||||
class RepositoryMeals(HouseholdRepositoryGeneric[ReadPlanEntry, GroupMealPlan]):
|
||||
def update(self, match_value: str | int | UUID4, new_data: dict | BaseModel) -> ReadPlanEntry:
|
||||
# The plan's household comes from its user, so a client-supplied user_id could move it to another household
|
||||
new_data = new_data if isinstance(new_data, dict) else new_data.model_dump()
|
||||
new_data["user_id"] = self._query_one(match_value=match_value).user_id
|
||||
return super().update(match_value, new_data)
|
||||
|
||||
def get_today(self, tz=UTC) -> list[ReadPlanEntry]:
|
||||
if not self.household_id:
|
||||
raise Exception("household_id not set")
|
||||
|
||||
@@ -203,6 +203,14 @@ class ShoppingListController(BaseCrudController):
|
||||
|
||||
@router.put("/{item_id}", response_model=ShoppingListOut)
|
||||
def update_one(self, item_id: UUID4, data: ShoppingListUpdate):
|
||||
# The list belongs to its owner's household, so a new owner would move it to their household
|
||||
owner = self.repos.users.get_one(data.user_id)
|
||||
if owner is None or owner.household_id != self.household_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="the list owner must be a member of your household",
|
||||
)
|
||||
|
||||
shopping_list = self.mixins.update_one(data, item_id)
|
||||
self.publish_event(
|
||||
event_type=EventTypes.shopping_list_updated,
|
||||
|
||||
Vendored
+3
-1
@@ -270,7 +270,9 @@ def unique_user(session: Session, api_client: TestClient):
|
||||
@fixture(scope="module")
|
||||
def unique_admin(session: Session, api_client: TestClient, unique_user: utils.TestUser):
|
||||
admin_user = next(_unique_user(session, api_client))
|
||||
admin_user.repos.users.patch(admin_user.user_id, {"admin": True, "group_id": unique_user.group_id})
|
||||
# Moving a user to another group needs an unscoped repo, as the admin routes use
|
||||
unscoped_repos = get_repositories(session, group_id=None, household_id=None)
|
||||
unscoped_repos.users.patch(admin_user.user_id, {"admin": True, "group_id": unique_user.group_id})
|
||||
yield admin_user
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.schema.household.group_events import GroupEventNotifierCreate
|
||||
from mealie.schema.labels.multi_purpose_label import MultiPurposeLabelSave
|
||||
from tests.utils import api_routes
|
||||
from tests.utils.factories import random_string
|
||||
from tests.utils.fixture_schemas import TestUser
|
||||
|
||||
|
||||
def test_notifier_update_cannot_move_household(api_client: TestClient, unique_user: TestUser, h2_user: TestUser):
|
||||
payload = GroupEventNotifierCreate(name=random_string(), apprise_url=random_string()).model_dump(by_alias=True)
|
||||
response = api_client.post(api_routes.households_events_notifications, json=payload, headers=unique_user.token)
|
||||
assert response.status_code == 201
|
||||
notifier = response.json()
|
||||
|
||||
notifier["householdId"] = str(h2_user.household_id)
|
||||
response = api_client.put(
|
||||
api_routes.households_events_notifications_item_id(notifier["id"]), json=notifier, headers=unique_user.token
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
assert unique_user.repos.group_event_notifier.get_one(notifier["id"])
|
||||
assert h2_user.repos.group_event_notifier.get_one(notifier["id"]) is None
|
||||
|
||||
|
||||
def test_label_update_cannot_move_group(api_client: TestClient, unique_user: TestUser, g2_user: TestUser):
|
||||
response = api_client.post(api_routes.groups_labels, json={"name": random_string()}, headers=unique_user.token)
|
||||
assert response.status_code == 200
|
||||
label = response.json()
|
||||
|
||||
label["groupId"] = str(g2_user.group_id)
|
||||
response = api_client.put(api_routes.groups_labels_item_id(label["id"]), json=label, headers=unique_user.token)
|
||||
assert response.status_code == 200
|
||||
|
||||
assert unique_user.repos.group_multi_purpose_labels.get_one(label["id"])
|
||||
assert g2_user.repos.group_multi_purpose_labels.get_one(label["id"]) is None
|
||||
|
||||
|
||||
def test_update_many_cannot_move_group(unique_user: TestUser, g2_user: TestUser):
|
||||
label = unique_user.repos.group_multi_purpose_labels.create(
|
||||
MultiPurposeLabelSave(name=random_string(), group_id=unique_user.group_id)
|
||||
)
|
||||
|
||||
unique_user.repos.group_multi_purpose_labels.update_many([{**label.model_dump(), "group_id": g2_user.group_id}])
|
||||
|
||||
assert unique_user.repos.group_multi_purpose_labels.get_one(label.id)
|
||||
assert g2_user.repos.group_multi_purpose_labels.get_one(label.id) is None
|
||||
|
||||
|
||||
def test_unscoped_repo_can_move_group(session: Session, unique_user: TestUser, g2_user: TestUser):
|
||||
label = unique_user.repos.group_multi_purpose_labels.create(
|
||||
MultiPurposeLabelSave(name=random_string(), group_id=unique_user.group_id)
|
||||
)
|
||||
|
||||
unscoped = get_repositories(session, group_id=None, household_id=None)
|
||||
moved = unscoped.group_multi_purpose_labels.update(label.id, {**label.model_dump(), "group_id": g2_user.group_id})
|
||||
|
||||
assert str(moved.group_id) == str(g2_user.group_id)
|
||||
|
||||
|
||||
def test_mealplan_update_keeps_owner(api_client: TestClient, unique_user: TestUser, h2_user: TestUser):
|
||||
payload = {"date": datetime.now(UTC).date().strftime("%Y-%m-%d"), "entryType": "dinner", "title": random_string()}
|
||||
response = api_client.post(api_routes.households_mealplans, json=payload, headers=unique_user.token)
|
||||
assert response.status_code == 201
|
||||
plan = response.json()
|
||||
|
||||
plan["userId"] = str(h2_user.user_id)
|
||||
response = api_client.put(api_routes.households_mealplans_item_id(plan["id"]), json=plan, headers=unique_user.token)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["userId"] == str(unique_user.user_id)
|
||||
|
||||
response = api_client.get(api_routes.households_mealplans_item_id(plan["id"]), headers=h2_user.token)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_shopping_list_owner_must_be_in_household(
|
||||
api_client: TestClient, unique_user: TestUser, unprivileged_user: TestUser, h2_user: TestUser
|
||||
):
|
||||
response = api_client.post(
|
||||
api_routes.households_shopping_lists, json={"name": random_string()}, headers=unique_user.token
|
||||
)
|
||||
assert response.status_code == 201
|
||||
shopping_list = response.json()
|
||||
route = api_routes.households_shopping_lists_item_id(shopping_list["id"])
|
||||
|
||||
shopping_list["userId"] = str(h2_user.user_id)
|
||||
response = api_client.put(route, json=shopping_list, headers=unique_user.token)
|
||||
assert response.status_code == 400
|
||||
assert h2_user.repos.group_shopping_lists.get_one(shopping_list["id"]) is None
|
||||
|
||||
shopping_list["userId"] = str(uuid4())
|
||||
response = api_client.put(route, json=shopping_list, headers=unique_user.token)
|
||||
assert response.status_code == 400
|
||||
|
||||
shopping_list["userId"] = str(unprivileged_user.user_id)
|
||||
response = api_client.put(route, json=shopping_list, headers=unique_user.token)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["userId"] == str(unprivileged_user.user_id)
|
||||
Reference in new issue
Block a user