Check if a browser cookie should be sent with a request to the given URL. Evaluates expiry, domain, path, and secure attribute matching per RFC 6265. Args: cookie: A cookie dict from driver.get_cookies(). url: The target request URL. default_domain: Fallback domain
(cookie: dict, url: str, default_domain: str = "")
| 99 | |
| 100 | |
| 101 | def _cookie_matches(cookie: dict, url: str, default_domain: str = "") -> bool: |
| 102 | """Check if a browser cookie should be sent with a request to the given URL. |
| 103 | |
| 104 | Evaluates expiry, domain, path, and secure attribute matching per RFC 6265. |
| 105 | |
| 106 | Args: |
| 107 | cookie: A cookie dict from driver.get_cookies(). |
| 108 | url: The target request URL. |
| 109 | default_domain: Fallback domain for host-only cookies (no domain attribute). |
| 110 | When a cookie has no domain, it only matches if the request hostname |
| 111 | equals this value. If empty and cookie has no domain, the cookie is skipped. |
| 112 | |
| 113 | Returns: |
| 114 | True if the cookie matches the URL. |
| 115 | """ |
| 116 | # Expiry check — skip expired cookies |
| 117 | expiry = cookie.get("expiry") |
| 118 | if expiry is not None and expiry <= int(time.time()): |
| 119 | return False |
| 120 | |
| 121 | parsed = urllib.parse.urlparse(url) |
| 122 | hostname = parsed.hostname or "" |
| 123 | path = parsed.path or "/" |
| 124 | scheme = parsed.scheme or "http" |
| 125 | |
| 126 | # Domain matching (RFC 6265 section 5.1.3) |
| 127 | cookie_domain = cookie.get("domain", "") |
| 128 | if not cookie_domain: |
| 129 | # Host-only cookie — must match the origin host exactly |
| 130 | if not default_domain or hostname != default_domain: |
| 131 | return False |
| 132 | elif cookie_domain.startswith("."): |
| 133 | # .example.com matches example.com and sub.example.com |
| 134 | if not (hostname == cookie_domain[1:] or hostname.endswith(cookie_domain)): |
| 135 | return False |
| 136 | else: |
| 137 | if hostname != cookie_domain: |
| 138 | return False |
| 139 | |
| 140 | # Path matching (RFC 6265 section 5.1.4) |
| 141 | cookie_path = cookie.get("path", "/") |
| 142 | if cookie_path == "/": |
| 143 | pass # root path matches everything |
| 144 | elif path != cookie_path and not path.startswith(cookie_path + "/"): |
| 145 | return False |
| 146 | |
| 147 | # Secure matching |
| 148 | if cookie.get("secure", False) and scheme != "https": |
| 149 | return False |
| 150 | |
| 151 | return True |
| 152 | |
| 153 | |
| 154 | def _parse_set_cookie(header_value: str) -> dict: |