_security_headers. Internal helper function. This docstring was expanded to make future maintenance easier. Args: resp: Parameter. Returns: Varies.
(resp)
| 1614 | |
| 1615 | # If neither header is present, don't block legitimate requests. |
| 1616 | if not origin and not ref: |
| 1617 | return True |
| 1618 | |
| 1619 | def _netloc(h: str) -> Optional[str]: |
| 1620 | try: |
| 1621 | p = urlparse(h) |
| 1622 | return (p.netloc or "").lower() |
| 1623 | except Exception: |
| 1624 | return None |
| 1625 | |
| 1626 | if origin: |
| 1627 | n = _netloc(origin) |
| 1628 | if not n: |
| 1629 | return False |
| 1630 | if n != expected: |
| 1631 | return False |
| 1632 | |
| 1633 | if ref: |
| 1634 | n = _netloc(ref) |
| 1635 | if not n: |
| 1636 | return False |
| 1637 | if n != expected: |
| 1638 | return False |
| 1639 | |
| 1640 | return True |
| 1641 | return True |
| 1642 | |
| 1643 | @app.before_request |
| 1644 | def _set_security_context(): |
| 1645 | # Nonce is useful if you later decide to tighten CSP (remove unsafe-inline). |
| 1646 | """_set_security_context. |
| 1647 | |
| 1648 | Internal helper function. |
| 1649 | |
| 1650 | This docstring was expanded to make future maintenance easier. |
| 1651 | |
| 1652 | Returns: |
| 1653 | Varies. |
| 1654 | """ |
| 1655 | # Nonce is useful if you later decide to tighten CSP (remove unsafe-inline). |
| 1656 | g.csp_nonce = secrets.token_urlsafe(16) |
| 1657 | # Ensure token exists early so templates can reference it. |
| 1658 | g.csrf_token = csrf_token() |
| 1659 | |
| 1660 | @app.before_request |
| 1661 | def _validate_host_header(): |
| 1662 | try: |
| 1663 | host = (request.host or "").split(":", 1)[0].strip().strip("[]") |
| 1664 | except Exception: |
| 1665 | host = "" |
| 1666 | if not _host_is_allowed(host): |
| 1667 | log_security_event("blocked_host_header", detail=f"host={host or '?'}", level="warning") |
| 1668 | abort(400) |
| 1669 | return None |
| 1670 | |
| 1671 | @app.before_request |
| 1672 | def _csrf_protect(): |
| 1673 | """_csrf_protect. |
nothing calls this directly
no test coverage detected