Validate that the webhook request actually came from Twilio and return form data. Prevents attackers from spoofing webhooks to pair or message arbitrary numbers. Returns the parsed form data as a dict.
(request: Request)
| 137 | return phone |
| 138 | |
| 139 | async def validate_twilio_request(request: Request) -> dict: |
| 140 | """ |
| 141 | Validate that the webhook request actually came from Twilio and return form data. |
| 142 | Prevents attackers from spoofing webhooks to pair or message arbitrary numbers. |
| 143 | Returns the parsed form data as a dict. |
| 144 | """ |
| 145 | # Get Twilio auth token |
| 146 | auth_token = os.getenv("TWILIO_AUTH_TOKEN") |
| 147 | if not auth_token: |
| 148 | logger.error("TWILIO_AUTH_TOKEN not configured - cannot validate webhooks!") |
| 149 | raise HTTPException(status_code=500, detail="Server configuration error") |
| 150 | |
| 151 | # Create validator |
| 152 | validator = RequestValidator(auth_token) |
| 153 | |
| 154 | # Get the signature from headers |
| 155 | signature = request.headers.get('X-Twilio-Signature', '') |
| 156 | if not signature: |
| 157 | logger.warning(f"Webhook received without X-Twilio-Signature header from {request.client.host}") |
| 158 | raise HTTPException(status_code=403, detail="Missing Twilio signature") |
| 159 | |
| 160 | # Get form data (FastAPI's FormData object) |
| 161 | form_data = await request.form() |
| 162 | |
| 163 | # Reconstruct the public URL as Twilio signed it. |
| 164 | # Behind a reverse proxy, request.url uses the internal scheme (http), |
| 165 | # but Twilio signs the external HTTPS URL. Use X-Forwarded-Proto if present. |
| 166 | forwarded_proto = request.headers.get("X-Forwarded-Proto", "") |
| 167 | url = str(request.url) |
| 168 | if forwarded_proto == "https" and url.startswith("http://"): |
| 169 | url = "https://" + url[len("http://"):] |
| 170 | |
| 171 | # Debug logging |
| 172 | logger.info(f"Validating Twilio request: URL={url}, Signature={signature[:20]}..., Form keys={list(form_data.keys())}") |
| 173 | |
| 174 | # Validate the signature using Twilio's official method |
| 175 | # Pass FormData object directly (not a parsed dict!) |
| 176 | is_valid = validator.validate(url, form_data, signature) |
| 177 | |
| 178 | if not is_valid: |
| 179 | logger.error(f"Invalid Twilio signature from {request.client.host} for URL {url}") |
| 180 | logger.error(f"Rejecting potentially malicious webhook request") |
| 181 | raise HTTPException(status_code=403, detail="Invalid Twilio signature - request rejected") |
| 182 | |
| 183 | logger.info(f"Twilio signature validated successfully for {url}") |
| 184 | |
| 185 | # Return FormData as a simple dict - much cleaner! |
| 186 | return dict(form_data) |
| 187 | |
| 188 | def _compress_jpeg(image_b64: str) -> bytes: |
| 189 | """ |