feat: enforce route permission helpers with semgrep in CI (#8769)
This commit is contained in:
1 parent
c701777c25
commit
a2149447d9
27 files changed
+185
-105
No files matched your search
@@ -107,6 +107,10 @@ jobs:
|
||||
run: |
|
||||
task py:mypy
|
||||
|
||||
- name: Semgrep (authz rules)
|
||||
run: |
|
||||
task py:semgrep
|
||||
|
||||
- name: Pytest
|
||||
env:
|
||||
DB_ENGINE: ${{ matrix.Database }}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Test cases for authz.yml. Run with `task py:semgrep`.
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from mealie.routes._base.permissions import forbidden, not_found
|
||||
from mealie.schema.response import ErrorResponse
|
||||
|
||||
|
||||
def flag_checks(self, user, target_user, permissions):
|
||||
# ruleid: mealie-permission-flag-in-handler
|
||||
if not self.user.can_invite:
|
||||
raise forbidden()
|
||||
|
||||
# ruleid: mealie-permission-flag-in-handler
|
||||
if self.user.admin or user.can_manage_household:
|
||||
pass
|
||||
|
||||
# ok: mealie-permission-flag-in-handler
|
||||
target_user.can_organize = permissions.can_organize
|
||||
|
||||
|
||||
def raw_errors():
|
||||
# ruleid: mealie-use-forbidden-not-found
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
# ruleid: mealie-use-forbidden-not-found
|
||||
raise HTTPException(status_code=404)
|
||||
|
||||
# ruleid: mealie-use-forbidden-not-found
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail=ErrorResponse.respond(message="Not found."))
|
||||
|
||||
# ruleid: mealie-use-forbidden-not-found
|
||||
raise HTTPException(status_code=403, detail=ErrorResponse(message="Permission Denied"))
|
||||
|
||||
# ok: mealie-use-forbidden-not-found
|
||||
raise HTTPException(404, "food not found")
|
||||
|
||||
# ok: mealie-use-forbidden-not-found
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=ErrorResponse.respond("Bad request"))
|
||||
|
||||
# ok: mealie-use-forbidden-not-found
|
||||
raise not_found("Not found.")
|
||||
@@ -0,0 +1,46 @@
|
||||
rules:
|
||||
- id: mealie-permission-flag-in-handler
|
||||
languages: [python]
|
||||
severity: ERROR
|
||||
message: >-
|
||||
Declare the permission on the route with `dependencies=[require(Perm.X)]` instead of checking
|
||||
`$FLAG` in the handler. The route table test in tests/integration_tests/test_route_permissions.py
|
||||
then shows the permission.
|
||||
paths:
|
||||
include:
|
||||
- /mealie/routes/
|
||||
exclude:
|
||||
- /mealie/routes/_base/permissions.py
|
||||
patterns:
|
||||
- pattern: |
|
||||
if <... $USER.$FLAG ...>:
|
||||
...
|
||||
- metavariable-regex:
|
||||
metavariable: $FLAG
|
||||
regex: ^can_(organize|manage|manage_household|invite)$
|
||||
|
||||
- id: mealie-use-forbidden-not-found
|
||||
languages: [python]
|
||||
severity: ERROR
|
||||
message: >-
|
||||
Raise `forbidden()` or `not_found()` from mealie/routes/_base/permissions.py. Answer 404 when the caller
|
||||
cannot see the resource and 403 when they can see it but may not change it.
|
||||
paths:
|
||||
include:
|
||||
- /mealie/routes/
|
||||
exclude:
|
||||
- /mealie/routes/_base/permissions.py
|
||||
patterns:
|
||||
- pattern-either:
|
||||
- pattern: HTTPException($STATUS)
|
||||
- pattern: HTTPException(status_code=$STATUS)
|
||||
- pattern: HTTPException($STATUS, ErrorResponse.respond($MSG))
|
||||
- pattern: HTTPException($STATUS, detail=ErrorResponse.respond($MSG))
|
||||
- pattern: HTTPException($STATUS, detail=ErrorResponse.respond(message=$MSG))
|
||||
- pattern: HTTPException(status_code=$STATUS, detail=ErrorResponse.respond($MSG))
|
||||
- pattern: HTTPException(status_code=$STATUS, detail=ErrorResponse.respond(message=$MSG))
|
||||
- pattern: HTTPException($STATUS, detail=ErrorResponse(message=$MSG))
|
||||
- pattern: HTTPException(status_code=$STATUS, detail=ErrorResponse(message=$MSG))
|
||||
- metavariable-regex:
|
||||
metavariable: $STATUS
|
||||
regex: ^(403|404|status\.HTTP_403_FORBIDDEN|status\.HTTP_404_NOT_FOUND)$
|
||||
@@ -121,11 +121,21 @@ tasks:
|
||||
cmds:
|
||||
- uv run ruff check mealie
|
||||
|
||||
py:semgrep:
|
||||
desc: runs the authz semgrep rules in .semgrep and their tests
|
||||
vars:
|
||||
# semgrep still imports pkg_resources and does not support every Python version uv picks.
|
||||
SEMGREP: uvx --python 3.12 --with setuptools semgrep==1.179.0
|
||||
cmds:
|
||||
- "{{ .SEMGREP }} scan --test --metrics off --config .semgrep/authz.yml .semgrep/authz.py"
|
||||
- "{{ .SEMGREP }} scan --error --metrics off --config .semgrep mealie"
|
||||
|
||||
py:check:
|
||||
desc: runs all linters, type checkers, and formatters
|
||||
deps:
|
||||
- py:format
|
||||
- py:lint
|
||||
- py:semgrep
|
||||
- py:mypy
|
||||
- py:test
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ class HttpRepo[C: BaseModel, R: BaseModel, U: BaseModel]:
|
||||
item = self.repo.get_one(item_id, key)
|
||||
|
||||
if not item:
|
||||
raise not_found()
|
||||
raise not_found("Not found.")
|
||||
|
||||
return item
|
||||
|
||||
@@ -116,7 +116,7 @@ class HttpRepo[C: BaseModel, R: BaseModel, U: BaseModel]:
|
||||
item = self.repo.get_one(item_id)
|
||||
|
||||
if not item:
|
||||
raise not_found()
|
||||
raise not_found("Not found.")
|
||||
|
||||
try:
|
||||
item = self.repo.update(item_id, data) # type: ignore
|
||||
@@ -129,7 +129,7 @@ class HttpRepo[C: BaseModel, R: BaseModel, U: BaseModel]:
|
||||
item = self.repo.get_one(item_id)
|
||||
|
||||
if not item:
|
||||
raise not_found()
|
||||
raise not_found("Not found.")
|
||||
|
||||
try:
|
||||
item = self.repo.patch(item_id, data.model_dump(exclude_unset=True, exclude_defaults=True))
|
||||
|
||||
@@ -31,14 +31,21 @@ _GRANTED_BY: dict[Perm, Callable[[PrivateUser], bool]] = {
|
||||
}
|
||||
|
||||
|
||||
def forbidden() -> HTTPException:
|
||||
def _error(status_code: int, message: str | None) -> HTTPException:
|
||||
# The frontend shows `detail.message` as a toast, so a message is only sent when one is given.
|
||||
if message is None:
|
||||
return HTTPException(status_code)
|
||||
return HTTPException(status_code, detail=ErrorResponse.respond(message=message))
|
||||
|
||||
|
||||
def forbidden(message: str | None = None) -> HTTPException:
|
||||
"""The caller can see the resource but may not perform the action."""
|
||||
return HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
return _error(status.HTTP_403_FORBIDDEN, message)
|
||||
|
||||
|
||||
def not_found(message: str = "Not found.") -> HTTPException:
|
||||
def not_found(message: str | None = None) -> HTTPException:
|
||||
"""The caller cannot see the resource. Use it for missing and inaccessible resources alike."""
|
||||
return HTTPException(status.HTTP_404_NOT_FOUND, detail=ErrorResponse.respond(message=message))
|
||||
return _error(status.HTTP_404_NOT_FOUND, message)
|
||||
|
||||
|
||||
class RequirePermission:
|
||||
|
||||
@@ -9,6 +9,7 @@ from mealie.core.root_logger import get_logger
|
||||
from mealie.core.security import create_file_token
|
||||
from mealie.pkgs.stats.fs_stats import pretty_size
|
||||
from mealie.routes._base import BaseAdminController, controller
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema.admin.backup import AllBackups, BackupFile
|
||||
from mealie.schema.response.responses import ErrorResponse, FileTokenResponse, SuccessResponse
|
||||
|
||||
@@ -60,7 +61,7 @@ class AdminBackupController(BaseAdminController):
|
||||
file = self._backup_path(file_name)
|
||||
|
||||
if not file.exists():
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
||||
raise not_found()
|
||||
|
||||
return FileTokenResponse.respond(create_file_token(file))
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from pydantic import UUID4
|
||||
from mealie.core import security
|
||||
from mealie.routes._base import BaseAdminController, controller
|
||||
from mealie.routes._base.mixins import HttpRepo
|
||||
from mealie.routes._base.permissions import forbidden
|
||||
from mealie.schema.response.pagination import PaginationQuery
|
||||
from mealie.schema.response.responses import ErrorResponse
|
||||
from mealie.schema.user.auth import UnlockResults
|
||||
@@ -65,7 +66,7 @@ class AdminUserManagementRoutes(BaseAdminController):
|
||||
def update_one(self, item_id: UUID4, data: UserOut):
|
||||
# Prevent self demotion
|
||||
if self.user.id == item_id and self.user.admin != data.admin:
|
||||
raise HTTPException(status_code=403, detail=ErrorResponse.respond("you cannot demote yourself"))
|
||||
raise forbidden("you cannot demote yourself")
|
||||
|
||||
return self.mixins.update_one(data, item_id)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import mimetypes
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.orm.session import Session
|
||||
|
||||
@@ -9,6 +9,7 @@ from mealie.core.settings.static import APP_VERSION
|
||||
from mealie.db.db_setup import generate_session
|
||||
from mealie.db.models.users.users import User
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema.admin.about import AppInfo, AppStartupInfo, AppTheme
|
||||
|
||||
router = APIRouter(prefix="/about")
|
||||
@@ -85,7 +86,7 @@ def get_app_branding_logo():
|
||||
|
||||
logo_file = settings.branding.logo_file
|
||||
if logo_file is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
||||
raise not_found()
|
||||
|
||||
media_type = mimetypes.guess_type(logo_file)[0]
|
||||
return FileResponse(logo_file, media_type=media_type, headers={"Cache-Control": "public, max-age=604800"})
|
||||
@@ -19,6 +19,7 @@ from mealie.core.security.providers.reverse_proxy_provider import ReverseProxyPr
|
||||
from mealie.core.security.security import get_auth_provider
|
||||
from mealie.db.db_setup import generate_session
|
||||
from mealie.lang import get_locale_provider
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.routes._base.routers import UserAPIRouter
|
||||
from mealie.schema.user import PrivateUser
|
||||
from mealie.schema.user.auth import CredentialsRequestForm, NativeOIDCTokenRequest, OIDCNativeConfig
|
||||
@@ -341,7 +342,7 @@ async def reverse_proxy_login(
|
||||
):
|
||||
"""Authenticate a user using a username forwarded by a trusted reverse proxy header"""
|
||||
if not settings.REVERSE_PROXY_AUTH_READY:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
||||
raise not_found()
|
||||
|
||||
if settings.REVERSE_PROXY_AUTH_SECRET:
|
||||
provided_secret = request.headers.get(settings.REVERSE_PROXY_AUTH_SECRET_HEADER, "")
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from functools import cached_property
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import UUID4
|
||||
|
||||
from mealie.routes._base.base_controllers import BaseUserController
|
||||
from mealie.routes._base.controller import controller
|
||||
from mealie.routes._base.mixins import HttpRepo
|
||||
from mealie.routes._base.permissions import forbidden
|
||||
from mealie.schema.recipe.recipe_comments import (
|
||||
RecipeCommentCreate,
|
||||
RecipeCommentOut,
|
||||
@@ -14,7 +15,7 @@ from mealie.schema.recipe.recipe_comments import (
|
||||
RecipeCommentUpdate,
|
||||
)
|
||||
from mealie.schema.response.pagination import PaginationQuery
|
||||
from mealie.schema.response.responses import ErrorResponse, SuccessResponse
|
||||
from mealie.schema.response.responses import SuccessResponse
|
||||
|
||||
router = APIRouter(prefix="/comments", tags=["Recipe: Comments"])
|
||||
|
||||
@@ -35,10 +36,7 @@ class RecipeCommentRoutes(BaseUserController):
|
||||
def _check_comment_belongs_to_user(self, item_id: UUID4) -> None:
|
||||
comment = self.repo.get_one(item_id)
|
||||
if comment.user_id != self.user.id and not self.user.admin:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=ErrorResponse(message="Comment does not belong to user"),
|
||||
)
|
||||
raise forbidden("Comment does not belong to user")
|
||||
|
||||
@router.get("", response_model=RecipeCommentPagination)
|
||||
def get_all(self, q: PaginationQuery = Depends(PaginationQuery)):
|
||||
|
||||
@@ -2,13 +2,14 @@ from collections import defaultdict
|
||||
from functools import cached_property
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import UUID4
|
||||
|
||||
from mealie.core.exceptions import mealie_registered_exceptions
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.routes._base import BaseCrudController, controller
|
||||
from mealie.routes._base.mixins import HttpRepo
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.routes._base.routers import MealieCrudRoute
|
||||
from mealie.schema import mapper
|
||||
from mealie.schema.cookbook import CreateCookBook, ReadCookBook, SaveCookBook, UpdateCookBook
|
||||
@@ -115,7 +116,7 @@ class GroupCookbookController(BaseCrudController):
|
||||
# Allow fetching other households' cookbooks
|
||||
cookbook = self.group_cookbooks.get_one(item_id, match_attr)
|
||||
if cookbook is None:
|
||||
raise HTTPException(status_code=404)
|
||||
raise not_found()
|
||||
|
||||
return cookbook
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from mealie.pkgs import safehttp
|
||||
from mealie.routes._base.base_controllers import BaseUserController
|
||||
from mealie.routes._base.controller import controller
|
||||
from mealie.routes._base.mixins import HttpRepo
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema.household.group_recipe_action import (
|
||||
CreateGroupRecipeAction,
|
||||
GroupRecipeActionOut,
|
||||
@@ -74,10 +75,7 @@ class GroupRecipeActionController(BaseUserController):
|
||||
) -> None:
|
||||
recipe_action = self.repos.group_recipe_actions.get_one(item_id)
|
||||
if not recipe_action:
|
||||
raise HTTPException(
|
||||
status.HTTP_404_NOT_FOUND,
|
||||
detail=ErrorResponse.respond(message="Not found."),
|
||||
)
|
||||
raise not_found("Not found.")
|
||||
|
||||
if recipe_action.action_type == GroupRecipeActionType.post.value:
|
||||
task_action = safehttp.post
|
||||
@@ -91,10 +89,7 @@ class GroupRecipeActionController(BaseUserController):
|
||||
try:
|
||||
recipe = recipe_service.get_one(recipe_slug)
|
||||
except NoEntryFound as e:
|
||||
raise HTTPException(
|
||||
status.HTTP_404_NOT_FOUND,
|
||||
detail=ErrorResponse.respond(message="Not found."),
|
||||
) from e
|
||||
raise not_found("Not found.") from e
|
||||
|
||||
settings = get_app_settings()
|
||||
payload = GroupRecipeActionPayload(action=recipe_action, content=recipe, recipe_scale=recipe_scale)
|
||||
|
||||
@@ -5,6 +5,7 @@ from fastapi import APIRouter, Header, HTTPException, status
|
||||
from mealie.core.config import get_app_settings
|
||||
from mealie.core.security import url_safe_token
|
||||
from mealie.routes._base import BaseUserController, controller
|
||||
from mealie.routes._base.permissions import Perm, require
|
||||
from mealie.schema.household.invite_token import (
|
||||
CreateInviteToken,
|
||||
EmailInitationResponse,
|
||||
@@ -30,7 +31,12 @@ class GroupInvitationsController(BaseUserController):
|
||||
|
||||
return self.repos.group_invite_tokens.page_all(PaginationQuery(page=1, per_page=-1)).items
|
||||
|
||||
@router.post("", response_model=ReadInviteToken, status_code=status.HTTP_201_CREATED)
|
||||
@router.post(
|
||||
"",
|
||||
response_model=ReadInviteToken,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[require(Perm.GROUP_INVITE)],
|
||||
)
|
||||
def create_invite_token(self, body: CreateInviteToken):
|
||||
settings = get_app_settings()
|
||||
if not settings.ALLOW_PASSWORD_LOGIN:
|
||||
@@ -39,12 +45,6 @@ class GroupInvitationsController(BaseUserController):
|
||||
detail="Invitation tokens are disabled when password login is not allowed",
|
||||
)
|
||||
|
||||
if not self.user.can_invite:
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
detail="User is not allowed to create invite tokens",
|
||||
)
|
||||
|
||||
body.group_id = body.group_id or self.group_id
|
||||
body.household_id = body.household_id or self.household_id
|
||||
|
||||
@@ -59,7 +59,7 @@ class GroupInvitationsController(BaseUserController):
|
||||
)
|
||||
return self.repos.group_invite_tokens.create(token)
|
||||
|
||||
@router.post("/email", response_model=EmailInitationResponse)
|
||||
@router.post("/email", response_model=EmailInitationResponse, dependencies=[require(Perm.GROUP_INVITE)])
|
||||
def email_invitation(
|
||||
self,
|
||||
invite: EmailInvitation,
|
||||
@@ -72,12 +72,6 @@ class GroupInvitationsController(BaseUserController):
|
||||
detail="Invitation email are disabled when password login is not allowed",
|
||||
)
|
||||
|
||||
if not self.user.can_invite:
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
detail="This user can't send email invitations",
|
||||
)
|
||||
|
||||
email_service = EmailService(locale=accept_language)
|
||||
url = f"{self.settings.BASE_URL}/register?token={invite.token}"
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ from datetime import date
|
||||
from functools import cached_property
|
||||
|
||||
from dateutil.tz import tzlocal
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from mealie.core.exceptions import mealie_registered_exceptions
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
@@ -10,13 +10,13 @@ from mealie.repos.repository_meals import RepositoryMeals
|
||||
from mealie.routes._base import controller
|
||||
from mealie.routes._base.base_controllers import BaseCrudController
|
||||
from mealie.routes._base.mixins import HttpRepo
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema import mapper
|
||||
from mealie.schema.meal_plan import CreatePlanEntry, ReadPlanEntry, SavePlanEntry, UpdatePlanEntry
|
||||
from mealie.schema.meal_plan.new_meal import CreateRandomEntry, PlanEntryPagination, PlanEntryType
|
||||
from mealie.schema.meal_plan.plan_rules import PlanRulesDay
|
||||
from mealie.schema.recipe.recipe import Recipe
|
||||
from mealie.schema.response.pagination import PaginationQuery
|
||||
from mealie.schema.response.responses import ErrorResponse
|
||||
from mealie.services.event_bus_service.event_types import (
|
||||
EventMealplanData,
|
||||
EventOperation,
|
||||
@@ -143,9 +143,7 @@ class GroupMealplanController(BaseCrudController):
|
||||
"""
|
||||
random_recipes = self._get_random_recipes_from_mealplan(data.date, data.entry_type)
|
||||
if not random_recipes:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=ErrorResponse.respond(message=self.t("mealplan.no-recipes-match-your-rules"))
|
||||
)
|
||||
raise not_found(self.t("mealplan.no-recipes-match-your-rules"))
|
||||
|
||||
recipe = random_recipes[0]
|
||||
result = self.mixins.create_one(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from fastapi import APIRouter, Depends, Query, Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from mealie.core.security import url_safe_token
|
||||
@@ -9,9 +9,8 @@ from mealie.lang import get_locale_provider
|
||||
from mealie.lang.providers import Translator
|
||||
from mealie.routes._base.base_controllers import BaseUserController
|
||||
from mealie.routes._base.controller import controller
|
||||
from mealie.routes._base.permissions import Perm, require
|
||||
from mealie.routes._base.permissions import Perm, not_found, require
|
||||
from mealie.schema.meal_plan.mealplan_ical import ReadMealPlanICalToken
|
||||
from mealie.schema.response.responses import ErrorResponse
|
||||
from mealie.services.household_services.mealplan_ical_service import MealPlanICalQuery, MealPlanICalService
|
||||
|
||||
router = APIRouter(prefix="/households/mealplans/ical", tags=["Households: Meal Plans"])
|
||||
@@ -26,7 +25,7 @@ class MealplanICalController(BaseUserController):
|
||||
self.household_id, key="household_id", override_schema=ReadMealPlanICalToken
|
||||
)
|
||||
if not prefs:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail=ErrorResponse.respond("Household not found"))
|
||||
raise not_found("Household not found")
|
||||
return prefs
|
||||
|
||||
def _set_token(self, token: str | None) -> ReadMealPlanICalToken:
|
||||
@@ -62,7 +61,7 @@ def get_mealplan_ical_feed(
|
||||
"""
|
||||
feed = MealPlanICalService(session, translator).get_feed(token, query)
|
||||
if feed is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail=ErrorResponse.respond("Calendar not found"))
|
||||
raise not_found("Calendar not found")
|
||||
|
||||
return Response(
|
||||
content=feed,
|
||||
|
||||
@@ -4,6 +4,7 @@ from fastapi import APIRouter, HTTPException, status
|
||||
from pydantic import UUID4
|
||||
from starlette.responses import FileResponse
|
||||
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema.recipe import Recipe
|
||||
from mealie.schema.recipe.recipe_timeline_events import RecipeTimelineEventOut
|
||||
|
||||
@@ -27,7 +28,7 @@ async def get_recipe_img(recipe_id: UUID4, file_name: ImageType = ImageType.orig
|
||||
if recipe_image.exists():
|
||||
return FileResponse(recipe_image, media_type="image/webp")
|
||||
else:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
||||
raise not_found()
|
||||
|
||||
|
||||
@router.get("/{recipe_id}/images/timeline/{timeline_event_id}/{file_name}")
|
||||
@@ -45,7 +46,7 @@ async def get_recipe_timeline_event_img(
|
||||
if timeline_event_image.exists():
|
||||
return FileResponse(timeline_event_image, media_type="image/webp")
|
||||
else:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
||||
raise not_found()
|
||||
|
||||
|
||||
@router.get("/{recipe_id}/assets/{file_name}")
|
||||
@@ -67,4 +68,4 @@ async def get_recipe_asset(recipe_id: UUID4, file_name: str):
|
||||
headers={"X-Content-Type-Options": "nosniff"},
|
||||
)
|
||||
else:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
||||
raise not_found()
|
||||
@@ -2,6 +2,7 @@ from fastapi import APIRouter, HTTPException, status
|
||||
from pydantic import UUID4
|
||||
from starlette.responses import FileResponse
|
||||
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema.user import PrivateUser
|
||||
|
||||
router = APIRouter(prefix="/users")
|
||||
@@ -20,4 +21,4 @@ async def get_user_image(user_id: UUID4, file_name: str):
|
||||
if recipe_image.exists():
|
||||
return FileResponse(recipe_image, media_type="image/webp")
|
||||
else:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
||||
raise not_found()
|
||||
@@ -1,13 +1,14 @@
|
||||
from functools import cached_property
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import UUID4
|
||||
|
||||
from mealie.core.dependencies.dependencies import get_temporary_zip_path
|
||||
from mealie.core.exceptions import PermissionDenied
|
||||
from mealie.core.security import create_file_token
|
||||
from mealie.routes._base import BaseUserController, controller
|
||||
from mealie.routes._base.permissions import forbidden
|
||||
from mealie.schema.group.group_exports import GroupDataExport
|
||||
from mealie.schema.recipe.recipe_bulk_actions import (
|
||||
AssignCategories,
|
||||
@@ -16,7 +17,7 @@ from mealie.schema.recipe.recipe_bulk_actions import (
|
||||
DeleteRecipes,
|
||||
ExportRecipes,
|
||||
)
|
||||
from mealie.schema.response.responses import ErrorResponse, SuccessResponse
|
||||
from mealie.schema.response.responses import SuccessResponse
|
||||
from mealie.services.recipe.recipe_bulk_service import RecipeBulkActionsService
|
||||
from mealie.services.recipe.recipe_service import RecipeService
|
||||
|
||||
@@ -53,9 +54,7 @@ class RecipeBulkActionsController(BaseUserController):
|
||||
self.recipe_service.delete_many(delete_recipes.recipes)
|
||||
except PermissionDenied as e:
|
||||
self.logger.error("Permission Denied on recipe controller action")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail=ErrorResponse.respond(message="Permission Denied")
|
||||
) from e
|
||||
raise forbidden("Permission Denied") from e
|
||||
|
||||
@router.post("/export", status_code=202)
|
||||
def bulk_export_recipes(self, export_recipes: ExportRecipes):
|
||||
|
||||
@@ -33,6 +33,7 @@ from mealie.core.dependencies import (
|
||||
from mealie.pkgs import cache, safehttp
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.routes._base import controller
|
||||
from mealie.routes._base.permissions import forbidden, not_found
|
||||
from mealie.routes._base.routers import MealieCrudRoute, UserAPIRouter
|
||||
from mealie.schema.cookbook.cookbook import ReadCookBook
|
||||
from mealie.schema.make_dependable import make_dependable
|
||||
@@ -142,14 +143,10 @@ class RecipeController(BaseRecipeController):
|
||||
|
||||
if thrownType == exceptions.PermissionDenied:
|
||||
self.logger.error("Permission Denied on recipe controller action")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail=ErrorResponse.respond(message="Permission Denied")
|
||||
)
|
||||
raise forbidden("Permission Denied")
|
||||
elif thrownType == exceptions.NoEntryFound:
|
||||
self.logger.error("No Entry Found on recipe controller action")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=ErrorResponse.respond(message="No Entry Found")
|
||||
)
|
||||
raise not_found("No Entry Found")
|
||||
elif thrownType == sqlalchemy.exc.IntegrityError:
|
||||
self.logger.error("SQL Integrity Error on recipe controller action")
|
||||
raise HTTPException(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from zipfile import ZipFile
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import UUID4
|
||||
from sqlalchemy.orm.session import Session
|
||||
from starlette.background import BackgroundTask
|
||||
@@ -10,9 +10,9 @@ from mealie.core.dependencies import get_temporary_zip_path
|
||||
from mealie.core.root_logger import get_logger
|
||||
from mealie.db.db_setup import generate_session
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema.recipe import Recipe
|
||||
from mealie.schema.recipe.recipe_image_types import RecipeImageTypes
|
||||
from mealie.schema.response import ErrorResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -34,7 +34,7 @@ def get_shared_recipe(token_id: UUID4, session: Session = Depends(generate_sessi
|
||||
token_summary = None
|
||||
|
||||
if token_summary is None:
|
||||
raise HTTPException(status_code=404, detail=ErrorResponse.respond("Token Not Found"))
|
||||
raise not_found("Token Not Found")
|
||||
|
||||
return token_summary.recipe
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from fastapi import HTTPException, status
|
||||
from pydantic import UUID4
|
||||
|
||||
from mealie.schema.response.responses import ErrorResponse
|
||||
from mealie.routes._base.permissions import forbidden
|
||||
from mealie.schema.user.user import PrivateUser, UserBase
|
||||
|
||||
permission_attrs = ["can_invite", "can_manage", "can_manage_household", "can_organize", "admin"]
|
||||
@@ -10,27 +9,19 @@ permission_attrs = ["can_invite", "can_manage", "can_manage_household", "can_org
|
||||
def _assert_non_admin_user_change_allowed(user_id: UUID4, current_user: PrivateUser, new_data: UserBase):
|
||||
if current_user.id != user_id:
|
||||
# User is trying to edit another user
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, ErrorResponse.respond("User cannot edit other users"))
|
||||
raise forbidden("User cannot edit other users")
|
||||
|
||||
if any(getattr(current_user, p) != getattr(new_data, p) for p in permission_attrs):
|
||||
# User is trying to change their own permissions
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
ErrorResponse.respond("User cannot change their own permissions"),
|
||||
)
|
||||
raise forbidden("User cannot change their own permissions")
|
||||
|
||||
if current_user.group != new_data.group:
|
||||
# prevent a regular user from changing their group
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN, ErrorResponse.respond("User doesn't have permission to change their group")
|
||||
)
|
||||
raise forbidden("User doesn't have permission to change their group")
|
||||
|
||||
if current_user.household != new_data.household:
|
||||
# prevent a regular user from changing their household
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
ErrorResponse.respond("User doesn't have permission to change their household"),
|
||||
)
|
||||
raise forbidden("User doesn't have permission to change their household")
|
||||
|
||||
|
||||
def assert_user_change_allowed(user_id: UUID4, current_user: PrivateUser, new_data: UserBase):
|
||||
@@ -39,11 +30,9 @@ def assert_user_change_allowed(user_id: UUID4, current_user: PrivateUser, new_da
|
||||
return
|
||||
|
||||
if current_user.id != user_id:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, ErrorResponse.respond("Use the Admin API to update other users"))
|
||||
raise forbidden("Use the Admin API to update other users")
|
||||
|
||||
# Admin is trying to edit themselves
|
||||
if any(getattr(current_user, p) != getattr(new_data, p) for p in permission_attrs):
|
||||
# prevent an admin from excalating their own permissions
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN, ErrorResponse.respond("Admins can't change their own permissions")
|
||||
)
|
||||
raise forbidden("Admins can't change their own permissions")
|
||||
@@ -4,6 +4,7 @@ from fastapi import HTTPException, status
|
||||
|
||||
from mealie.core.security import create_access_token
|
||||
from mealie.routes._base import BaseUserController, controller
|
||||
from mealie.routes._base.permissions import forbidden
|
||||
from mealie.routes._base.routers import UserAPIRouter
|
||||
from mealie.schema.user import (
|
||||
CreateToken,
|
||||
@@ -60,4 +61,4 @@ class UserApiTokensController(BaseUserController):
|
||||
deleted_token = self.repos.api_tokens.delete(token_id)
|
||||
return DeleteTokenResponse(token_delete=deleted_token.name)
|
||||
else:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
raise forbidden()
|
||||
@@ -5,6 +5,7 @@ from mealie.core.security import hash_password
|
||||
from mealie.core.security.providers.credentials_provider import CredentialsProvider
|
||||
from mealie.db.models.users.users import AuthMethod
|
||||
from mealie.routes._base import BaseUserController, controller
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.routes._base.routers import UserAPIRouter
|
||||
from mealie.routes.users._helpers import assert_user_change_allowed
|
||||
from mealie.schema.response import ErrorResponse, SuccessResponse
|
||||
@@ -30,10 +31,7 @@ class UserController(BaseUserController):
|
||||
if user_rating:
|
||||
return user_rating
|
||||
else:
|
||||
raise HTTPException(
|
||||
status.HTTP_404_NOT_FOUND,
|
||||
ErrorResponse.respond("User has not rated this recipe"),
|
||||
)
|
||||
raise not_found("User has not rated this recipe")
|
||||
|
||||
@user_router.get("/self/favorites", response_model=UserRatings[UserRatingSummary])
|
||||
def get_logged_in_user_favorites(self):
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
from functools import cached_property
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from pydantic import UUID4
|
||||
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.routes._base import BaseUserController, controller
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.routes._base.routers import UserAPIRouter
|
||||
from mealie.routes.users._helpers import assert_user_change_allowed
|
||||
from mealie.schema.response.responses import ErrorResponse
|
||||
from mealie.schema.user.user import UserRatingCreate, UserRatingOut, UserRatings, UserRatingUpdate
|
||||
|
||||
router = UserAPIRouter()
|
||||
@@ -34,10 +33,7 @@ class UserRatingsController(BaseUserController):
|
||||
recipe = self.group_recipes.get_one(slug_or_id, key="slug")
|
||||
|
||||
if not recipe:
|
||||
raise HTTPException(
|
||||
status.HTTP_404_NOT_FOUND,
|
||||
detail=ErrorResponse.respond(message="Not found."),
|
||||
)
|
||||
raise not_found("Not found.")
|
||||
|
||||
return recipe
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
|
||||
from mealie.core.config import get_app_settings
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.routes._base import BasePublicController, controller
|
||||
from mealie.schema.response import ErrorResponse
|
||||
from mealie.routes._base.permissions import forbidden
|
||||
from mealie.schema.user.registration import CreateUserRegistration
|
||||
from mealie.schema.user.user import UserOut
|
||||
from mealie.services.event_bus_service.event_bus_service import EventBusService
|
||||
@@ -22,10 +22,7 @@ class RegistrationController(BasePublicController):
|
||||
settings = get_app_settings()
|
||||
|
||||
if not settings.ALLOW_SIGNUP and data.group_token is None or data.group_token == "":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=ErrorResponse.respond("User Registration is Disabled"),
|
||||
)
|
||||
raise forbidden("User Registration is Disabled")
|
||||
|
||||
registration_service = RegistrationService(
|
||||
self.logger,
|
||||
|
||||
@@ -46,6 +46,10 @@ EXPECTED_ROUTE_PERMISSIONS: dict[Perm, set[str]] = {
|
||||
"GET /api/households/members",
|
||||
"PUT /api/households/permissions",
|
||||
},
|
||||
Perm.GROUP_INVITE: {
|
||||
"POST /api/households/invitations",
|
||||
"POST /api/households/invitations/email",
|
||||
},
|
||||
Perm.HOUSEHOLD_MANAGE: {
|
||||
"POST /api/households/mealplans/ical",
|
||||
"DELETE /api/households/mealplans/ical",
|
||||
|
||||
Reference in new issue
Block a user