"""Separate device-owned inbox requests from trusted service operations.""" import hmac import os import re from fastapi import HTTPException, Request async def require_access(request: Request): expected = os.getenv('NOTIFY_INTERNAL_TOKEN', '') supplied = request.headers.get('x-notify-internal-token', '') if expected and hmac.compare_digest(expected, supplied): return path = request.url.path.removeprefix('/api/notify/v1').strip('/') if path == 'health': return guest = request.headers.get('x-social-guest-id', '') if not re.fullmatch(r'[A-Za-z0-9_-]{1,80}', guest): raise HTTPException(401, 'guest_identity_required') if path in ('inbox', 'inbox/unread') and request.method == 'GET': target = request.query_params.get('subscriber_id', 'guest') elif path == 'inbox/read-all' and request.method == 'POST': try: target = (await request.json()).get('subscriber_id', 'guest') except (ValueError, AttributeError): raise HTTPException(400, 'invalid_body') elif re.fullmatch(r'subscribers/[^/]+/preferences', path) and request.method in ('GET', 'PUT'): target = request.path_params.get('subscriber_id') elif re.fullmatch(r'inbox/[^/]+', path) and request.method in ('PATCH', 'DELETE'): from notify_svc.pb_store import get_message message = get_message(request.path_params['message_id']) if not message: raise HTTPException(404, 'message_not_found') target = message.get('subscriber_id') else: raise HTTPException(403, 'notify_management_requires_admin') if target != guest: raise HTTPException(403, 'subscriber_identity_mismatch')