Strip existing Access-Control-* headers and inject permissive ones. Keeps the body untouched; only rewrites the header block. Using the exact browser-supplied Origin (rather than "*") is required when the request is credentialed (cookies, Authorization).
(response: bytes, origin: str)
| 288 | |
| 289 | |
| 290 | def inject_cors_headers(response: bytes, origin: str) -> bytes: |
| 291 | """Strip existing Access-Control-* headers and inject permissive ones. |
| 292 | |
| 293 | Keeps the body untouched; only rewrites the header block. Using the |
| 294 | exact browser-supplied Origin (rather than "*") is required when the |
| 295 | request is credentialed (cookies, Authorization). |
| 296 | """ |
| 297 | sep = b"\r\n\r\n" |
| 298 | if sep not in response: |
| 299 | return response |
| 300 | header_section, body = response.split(sep, 1) |
| 301 | lines = header_section.decode(errors="replace").split("\r\n") |
| 302 | lines = [ln for ln in lines if not ln.lower().startswith("access-control-")] |
| 303 | allow_origin = origin or "*" |
| 304 | lines += [ |
| 305 | f"Access-Control-Allow-Origin: {allow_origin}", |
| 306 | "Access-Control-Allow-Credentials: true", |
| 307 | "Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS", |
| 308 | "Access-Control-Allow-Headers: *", |
| 309 | "Access-Control-Expose-Headers: *", |
| 310 | "Vary: Origin", |
| 311 | ] |
| 312 | return ("\r\n".join(lines) + "\r\n\r\n").encode() + body |
no outgoing calls
no test coverage detected