Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
feat(technical): transport_check.py for TLS certificates, security headers and redirects
Agrici Daniel218ef626f984
diff --git a/scripts/transport_check.py b/scripts/transport_check.pynew file mode 100644index 0000000..2e54a6a--- /dev/null+++ b/scripts/transport_check.py@@ -0,0 +1,1025 @@+#!/usr/bin/env python3+"""+TLS certificate, security header and HTTPS redirect check for one site.++Reads the certificate a site presents, grades the security and transport+headers on its response, and follows the http to https and www / non-www+redirects. Output is one JSON object on stdout.++What this means for SEO+=======================+Security headers are a security and trust matter. They are not a confirmed+Google ranking signal, and this script does not claim otherwise. HTTPS itself+is a lightweight ranking signal, per Google's page experience documentation.+The findings that matter most for search are the ones that stop a browser or+a crawler from reaching the page at all: an expired or mismatched certificate,+http that never reaches https, and www / non-www hosts that both answer.++Usage::++ python transport_check.py https://example.com+ python transport_check.py https://example.com/pricing --timeout 15++Result JSON::++ {+ "url": "<requested URL>",+ "host": "<normalized host>",+ "tls": {+ "host", "port", "connected_ip",+ "verified": <bool>, # system trust store and hostname+ "verify_error": <str|null>, # OpenSSL text when verified is false+ "verify_code": <int|null>,+ "certificate_read": <bool>,+ "subject": {"common_name", "organization"},+ "issuer": {"common_name", "organization"},+ "not_before", "not_after", # ISO 8601, UTC+ "days_until_expiry": <int>, "expired": <bool>, "not_yet_valid": <bool>,+ "san": ["<name>", ...], "san_count": <int>,+ "covers_host": <bool>, "sibling_host": <str|null>,+ "covers_sibling": <bool|null>,+ "protocol": "TLSv1.3", "cipher": "<name>", "cipher_bits": <int>,+ "error": "<only when the handshake did not complete>",+ "certificate_error": "<only when an unverified certificate was unreadable>"+ }, # or {"skipped": "<reason>"}+ "headers": {+ "url", "status", "https",+ "hsts": {"present", "value", "max_age", "include_subdomains",+ "preload", "meets_preload_requirements", "preload_gaps",+ "preload_scope_note", "issues"},+ "csp": {"present", "report_only", "policies", "issues"},+ "x_content_type_options": {"present", "value", "ok"},+ "framing": {"x_frame_options", "frame_ancestors", "ok"},+ "referrer_policy": {"present", "value", "ok"},+ "permissions_policy": {"present", "feature_policy_present"},+ "cookies": [{"name", "secure", "http_only", "same_site", "issues"}]+ }, # or {"error": "<reason>"}+ "redirects": {+ "http_to_https": {"checked_url", "redirects_to_https", "one_hop",+ "first_hop_status", "first_hop_target",+ "first_hop_same_host", "permanent", "hops",+ "final_url", "error"},+ "www": {"host", "sibling_host", "host_final_url",+ "sibling_final_url", "sibling_resolves", "same_final_url",+ "error"}+ },+ "findings": [{"id", "severity", "message", "evidence"}],+ "summary": {"critical", "high", "medium", "low", "info"}+ }++A refused or malformed target prints ``{"url": ..., "error": ...}`` instead.+Cookies are reported by NAME only. A cookie value never enters the output.++Safety+======+The target is validated with ``url_safety.validate_url_strict`` before any+connection. The TLS socket connects to the IP address that call returned,+never to the hostname, so a DNS answer cannot change between the check and+the connection. The hostname is used only for SNI and for certificate+matching. Nothing is written to or read from the socket beyond the handshake,+and it is closed in a ``finally`` block. When the certificate does not verify,+one more handshake without verification reads the certificate so the report+can say why (expired, wrong host); no data is sent on it either. Header and+redirect checks go through ``url_safety.safe_requests_get`` only. When a proxy+environment variable is set, the raw socket would bypass the proxy, so the+TLS section is skipped.++Exit status::++ 0 report printed (whatever the findings)+ 2 the URL was refused or could not be parsed+"""++from __future__ import annotations++import argparse+import ipaddress+import json+import os+import re+import socket+import ssl+import sys+import time+from datetime import datetime, timezone+from typing import Optional+from urllib.parse import urlparse++_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+from url_safety import ( # noqa: E402+ URLSafetyError,+ normalize_hostname,+ safe_requests_get,+ validate_url_strict,+)++EXPIRY_WARN_DAYS = 14+ONE_YEAR = 31536000 # hstspreload.org minimum max-age, in seconds+OLD_PROTOCOLS = ("SSLv3", "TLSv1", "TLSv1.1")+PROXY_ENV_VARS = ("HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy")+SEVERITIES = ("Critical", "High", "Medium", "Low", "Info")+MAX_SAN_REPORTED = 100+MAX_COOKIES = 40++# OpenSSL X509_V_ERR_* codes carried by ssl.SSLCertVerificationError.+_ERR_NOT_YET_VALID = 9+_ERR_EXPIRED = 10+_ERR_HOST_MISMATCH = (62, 64) # hostname, IP address++PRELOAD_SCOPE_NOTE = (+ "Covers the header directives, the certificate and the same-host HTTP "+ "redirect when those sections ran. Not checked: that every subdomain "+ "serves HTTPS, and that this host is the registrable domain the preload "+ "list requires."+)+++def _clip(value, limit: int = 200) -> Optional[str]:+ return None if value is None else str(value)[:limit]+++def _iso(seconds: Optional[float]) -> Optional[str]:+ if seconds is None:+ return None+ stamp = datetime.fromtimestamp(seconds, timezone.utc)+ return stamp.isoformat(timespec="seconds").replace("+00:00", "Z")+++# ---------------------------------------------------------------------------+# Certificate parsing+# ---------------------------------------------------------------------------+#+# ``SSLSocket.getpeercert()`` returns a parsed dict only for a certificate+# that verified. For one that did not, the standard library hands back DER+# bytes and offers no public decoder, so the few fields this report needs+# (names, validity, subjectAltName) are read with the small bounds-checked+# walker below. The input is whatever the remote server sent: every length is+# checked against the buffer and any surprise raises ValueError.++_OID_COMMON_NAME = b"\x55\x04\x03"+_OID_ORGANIZATION = b"\x55\x04\x0a"+_OID_SUBJECT_ALT_NAME = b"\x55\x1d\x11"+_MAX_DER_BYTES = 256 * 1024+++def _tlv(data: bytes, pos: int) -> tuple[int, int, int]:+ """Return ``(tag, value_start, value_end)`` for the DER element at ``pos``."""+ if pos + 2 > len(data):+ raise ValueError("DER element is truncated")+ tag, first = data[pos], data[pos + 1]+ if tag & 0x1F == 0x1F:+ raise ValueError("multi-byte DER tags are not supported")+ start = pos + 2+ if first & 0x80:+ count = first & 0x7F+ if count == 0 or count > 4 or start + count > len(data):+ raise ValueError("bad DER length")+ length = int.from_bytes(data[start:start + count], "big")+ start += count+ else:+ length = first+ end = start + length+ if end > len(data):+ raise ValueError("DER element runs past the buffer")+ return tag, start, end+++def _children(data: bytes, start: int, end: int) -> list[tuple[int, int, int]]:+ out, pos = [], start+ while pos < end:+ tag, value_start, value_end = _tlv(data, pos)+ if value_end > end:+ raise ValueError("DER child runs past its parent")+ out.append((tag, value_start, value_end))+ pos = value_end+ return out+++def _der_text(tag: int, raw: bytes) -> str:+ if tag == 0x1E: # BMPString+ return raw.decode("utf-16-be", errors="replace")+ if tag == 0x1C: # UniversalString+ return raw.decode("utf-32-be", errors="replace")+ if tag == 0x14: # TeletexString+ return raw.decode("latin-1")+ return raw.decode("utf-8", errors="replace")+++def _der_time(tag: int, raw: bytes) -> float:+ text = raw.decode("ascii")+ digits = text[:-1]+ if not text.endswith("Z") or not digits.isdigit():+ raise ValueError("unsupported certificate time format")+ if tag == 0x17 and len(digits) == 12: # UTCTime, two-digit year (RFC 5280)+ year = int(digits[:2])+ year += 2000 if year < 50 else 1900+ rest = digits[2:]+ elif tag == 0x18 and len(digits) == 14: # GeneralizedTime+ year, rest = int(digits[:4]), digits[4:]+ else:+ raise ValueError("unsupported certificate time format")+ month, day, hour, minute, second = (int(rest[i:i + 2]) for i in range(0, 10, 2))+ return datetime(year, month, day, hour, minute, second, tzinfo=timezone.utc).timestamp()+++def _der_name(data: bytes, start: int, end: int) -> dict:+ name = {"common_name": None, "organization": None}+ for _set_tag, set_start, set_end in _children(data, start, end):+ for _seq_tag, seq_start, seq_end in _children(data, set_start, set_end):+ parts = _children(data, seq_start, seq_end)+ if len(parts) < 2:+ continue+ oid = data[parts[0][1]:parts[0][2]]+ key = {_OID_COMMON_NAME: "common_name", _OID_ORGANIZATION: "organization"}.get(oid)+ if key and name[key] is None:+ name[key] = _clip(_der_text(parts[1][0], data[parts[1][1]:parts[1][2]]))+ return name+++def _der_san(data: bytes, start: int, end: int) -> list[str]:+ """dNSName and iPAddress entries from the extensions block, if any."""+ names: list[str] = []+ wrapper = _children(data, start, end)+ if not wrapper:+ return names+ for _tag, ext_start, ext_end in _children(data, wrapper[0][1], wrapper[0][2]):+ parts = _children(data, ext_start, ext_end)+ if len(parts) < 2 or data[parts[0][1]:parts[0][2]] != _OID_SUBJECT_ALT_NAME:+ continue+ general_names = _children(data, parts[-1][1], parts[-1][2])+ if not general_names:+ continue+ for tag, name_start, name_end in _children(data, general_names[0][1], general_names[0][2]):+ raw = data[name_start:name_end]+ if tag == 0x82:+ names.append(raw.decode("ascii", errors="replace"))+ elif tag == 0x87 and len(raw) in (4, 16):+ names.append(str(ipaddress.ip_address(raw)))+ return names+++def parse_der_certificate(der: bytes) -> dict:+ """Read names, validity and subjectAltName from a DER X.509 certificate.++ Returns ``{"subject", "issuer", "not_before", "not_after", "san"}`` with+ times as epoch seconds. Raises ``ValueError`` for anything malformed.+ """+ if not der or len(der) > _MAX_DER_BYTES:+ raise ValueError("no certificate, or certificate too large")+ try:+ _tag, start, end = _tlv(der, 0)+ tbs = _children(der, start, end)[0]+ fields = _children(der, tbs[1], tbs[2])+ if fields and fields[0][0] == 0xA0: # explicit version+ fields = fields[1:]+ _serial, _algorithm, issuer, validity, subject = fields[:5]+ times = _children(der, validity[1], validity[2])+ san: list[str] = []+ for tag, field_start, field_end in fields[6:]:+ if tag == 0xA3: # extensions+ san = _der_san(der, field_start, field_end)+ return {+ "subject": _der_name(der, subject[1], subject[2]),+ "issuer": _der_name(der, issuer[1], issuer[2]),+ "not_before": _der_time(times[0][0], der[times[0][1]:times[0][2]]),+ "not_after": _der_time(times[1][0], der[times[1][1]:times[1][2]]),+ "san": san,+ }+ except (IndexError, UnicodeError, OverflowError) as exc:+ raise ValueError(f"malformed certificate: {exc}") from exc+++def _from_peercert(cert: dict) -> dict:+ """Normalize a ``getpeercert()`` dict to the ``parse_der_certificate`` shape."""+ def name(dn) -> dict:+ out = {"common_name": None, "organization": None}+ for rdn in dn or ():+ for key, value in rdn:+ slot = {"commonName": "common_name", "organizationName": "organization"}.get(key)+ if slot and out[slot] is None:+ out[slot] = _clip(value)+ return out++ def seconds(key: str) -> Optional[float]:+ try:+ return float(ssl.cert_time_to_seconds(cert[key]))+ except (KeyError, ValueError):+ return None++ return {+ "subject": name(cert.get("subject")),+ "issuer": name(cert.get("issuer")),+ "not_before": seconds("notBefore"),+ "not_after": seconds("notAfter"),+ "san": [str(value) for kind, value in cert.get("subjectAltName", ())+ if kind in ("DNS", "IP Address")],+ }+++def _name_matches(pattern: str, host: str) -> bool:+ """SAN match as browsers do it: a wildcard covers exactly one label."""+ pattern, host = pattern.lower().rstrip("."), host.lower().rstrip(".")+ try:+ return ipaddress.ip_address(pattern) == ipaddress.ip_address(host)+ except ValueError:+ pass+ if pattern.startswith("*."):+ return host.endswith(pattern[1:]) and host.count(".") == pattern.count(".")+ return pattern == host+++def _is_ip(host: str) -> bool:+ try:+ ipaddress.ip_address(host)+ except ValueError:+ return False+ return True+++def sibling_host(host: str) -> Optional[str]:+ """The www / non-www counterpart of ``host``; None for IPs and bare labels."""+ if _is_ip(host) or "." not in host:+ return None+ return host[4:] if host.startswith("www.") and host.count(".") >= 2 else f"www.{host}"+++# ---------------------------------------------------------------------------+# TLS handshake+# ---------------------------------------------------------------------------++def proxy_configured() -> bool:+ return any(os.environ.get(name, "").strip() for name in PROXY_ENV_VARS)+++def _pinned_address(value) -> str:+ """Return the validated address as a bare IP literal, or raise ValueError.++ ``validate_url_strict`` returns an IPv4 or IPv6 literal. Insisting on one+ here means a hostname can never reach ``connect()``, whatever a future+ change to the validator returns.+ """+ return str(ipaddress.ip_address(str(value).strip().strip("[]")))+++def _handshake(ip: str, port: int, server_hostname: str, timeout: float, *, verify: bool) -> dict:+ """One TLS handshake to ``ip``. Sends and reads nothing after it.++ ``timeout`` bounds the TCP connect and the handshake together. With+ ``verify=False`` the certificate is not checked: that mode exists only to+ read the certificate of a site whose verified handshake already failed.+ """+ context = ssl.create_default_context()+ if verify:+ if getattr(ssl, "HAS_NEVER_CHECK_COMMON_NAME", False):+ # Browsers match subjectAltName only; do the same.+ context.hostname_checks_common_name = False+ else:+ context.check_hostname = False+ context.verify_mode = ssl.CERT_NONE+ deadline = time.monotonic() + timeout+ raw = socket.create_connection((ip, port), timeout=timeout)+ tls = None+ try:+ raw.settimeout(max(0.1, deadline - time.monotonic()))+ tls = context.wrap_socket(raw, server_hostname=server_hostname)+ cipher = tls.cipher() or (None, None, None)+ return {+ "cert": tls.getpeercert() if verify else None,+ "der": None if verify else tls.getpeercert(binary_form=True),+ "protocol": tls.version(),+ "cipher": cipher[0],+ "cipher_bits": cipher[2],+ }+ finally:+ if tls is not None:+ tls.close()+ raw.close() # a no-op once wrap_socket has taken the descriptor+++def check_tls(url: str, timeout: float = 10.0, *, now: Optional[float] = None) -> dict:+ """Read and judge the certificate ``url``'s host presents.++ Raises ``URLSafetyError`` when the target is not a permitted public+ address; no socket is opened in that case. Every other failure is+ reported inside the returned dict.+ """+ parsed = urlparse(url)+ if parsed.scheme != "https":+ return {"skipped": "not an https URL, so there is no certificate to read; "+ "pass the https:// address to check TLS"}+ if proxy_configured():+ return {"skipped": "proxy configured"}++ _validated_url, pinned = validate_url_strict(url)+ host = normalize_hostname(parsed.hostname or "")+ port = parsed.port or 443+ sibling = sibling_host(host)+ result: dict = {+ "host": host, "port": port, "connected_ip": None,+ "verified": False, "verify_error": None, "verify_code": None,+ "certificate_read": False,+ "subject": None, "issuer": None, "not_before": None, "not_after": None,+ "days_until_expiry": None, "expired": None, "not_yet_valid": None,+ "san": [], "san_count": 0,+ "covers_host": None, "sibling_host": sibling, "covers_sibling": None,+ "protocol": None, "cipher": None, "cipher_bits": None,+ }+ try:+ ip = _pinned_address(pinned)+ except ValueError:+ result["error"] = "the validated address is not an IP literal, so no connection was made"+ return result+ result["connected_ip"] = ip++ cert: Optional[dict] = None+ shake: Optional[dict] = None+ try:+ shake = _handshake(ip, port, host, timeout, verify=True)+ result["verified"] = True+ cert = _from_peercert(shake["cert"] or {})+ except ssl.SSLCertVerificationError as exc:+ result["verify_error"] = _clip(getattr(exc, "verify_message", "") or str(exc), 300)+ result["verify_code"] = getattr(exc, "verify_code", None)+ try:+ shake = _handshake(ip, port, host, timeout, verify=False)+ cert = parse_der_certificate(shake["der"] or b"")+ except (ssl.SSLError, OSError, ValueError) as inner:+ result["certificate_error"] = _clip(f"{type(inner).__name__}: {inner}", 300)+ except (ssl.SSLError, OSError, ValueError) as exc:+ result["error"] = _clip(f"{type(exc).__name__}: {exc}", 300)+ return result++ if shake:+ result.update(protocol=shake["protocol"], cipher=shake["cipher"],+ cipher_bits=shake["cipher_bits"])+ if cert is None:+ return result++ current = time.time() if now is None else now+ names = cert["san"]+ result.update(+ certificate_read=True,+ subject=cert["subject"], issuer=cert["issuer"],+ not_before=_iso(cert["not_before"]), not_after=_iso(cert["not_after"]),+ san=[_clip(name) for name in names[:MAX_SAN_REPORTED]], san_count=len(names),+ # A verified handshake already matched the host; OpenSSL is the judge.+ covers_host=True if result["verified"] else any(_name_matches(n, host) for n in names),+ )+ if sibling:+ result["covers_sibling"] = any(_name_matches(n, sibling) for n in names)+ if cert["not_after"] is not None:+ result["days_until_expiry"] = int((cert["not_after"] - current) // 86400)+ result["expired"] = cert["not_after"] < current+ if cert["not_before"] is not None:+ result["not_yet_valid"] = cert["not_before"] > current+ return result+++# ---------------------------------------------------------------------------+# Header grading (pure parsing, no requests)+# ---------------------------------------------------------------------------++def split_set_cookie(value: str) -> list[str]:+ """Split a comma-folded Set-Cookie header without breaking Expires dates."""+ if not value:+ return []+ parts = re.split(r",\s*(?=[^;,=\s]+=[^;,]*)", value)+ return [part.strip() for part in parts if part.strip()]+++def set_cookie_values(response) -> list[str]:+ """Raw Set-Cookie lines from a requests Response, one per cookie."""+ raw_headers = getattr(getattr(response, "raw", None), "headers", None)+ getlist = getattr(raw_headers, "getlist", None)+ if callable(getlist):+ try:+ values = [str(v) for v in getlist("Set-Cookie")]+ except Exception:+ values = []+ if values:+ return values+ for key, value in (getattr(response, "headers", None) or {}).items():+ if str(key).lower() == "set-cookie":+ return split_set_cookie(str(value))+ return []+++def _parse_cookie(raw: str, https: bool) -> dict:+ """Flags for one cookie. Only the NAME is kept; the value is dropped here."""+ pieces = [piece.strip() for piece in raw.split(";")]+ # "abc" with no "=" is a nameless cookie whose VALUE is "abc": report no name.+ name = pieces[0].split("=", 1)[0].strip() if "=" in pieces[0] else ""+ attrs = {}+ for piece in pieces[1:]:+ key, _sep, value = piece.partition("=")+ attrs[key.strip().lower()] = value.strip()+ same_site = attrs.get("samesite")+ cookie = {+ "name": name[:80] or "(unnamed)",+ "secure": "secure" in attrs,+ "http_only": "httponly" in attrs,+ "same_site": same_site.capitalize()[:10] if same_site else None,+ "issues": [],+ }+ if https and not cookie["secure"]:+ cookie["issues"].append("Missing Secure on an HTTPS site.")+ if not cookie["http_only"]:+ cookie["issues"].append("Missing HttpOnly; fine only if scripts must read this cookie.")+ if same_site is None:+ cookie["issues"].append("No SameSite attribute; browsers default to Lax.")+ elif same_site.lower() == "none" and not cookie["secure"]:+ cookie["issues"].append("SameSite=None without Secure is rejected by browsers.")+ return cookie+++def _grade_hsts(raw: Optional[str], https: bool) -> dict:+ hsts = {"present": raw is not None, "value": _clip(raw), "max_age": None,+ "include_subdomains": False, "preload": False,+ "meets_preload_requirements": False, "preload_gaps": [],+ "preload_scope_note": PRELOAD_SCOPE_NOTE, "issues": []}+ if raw is None:+ hsts["preload_gaps"].append("No Strict-Transport-Security header.")+ if https:+ hsts["issues"].append("Strict-Transport-Security was not sent.")+ return hsts+ directives: dict[str, str] = {}+ # Browsers act on the first header only (RFC 6797); requests joins repeats with commas.+ for part in raw.split(",")[0].split(";"):+ key, _sep, value = part.strip().partition("=")+ if key.strip():+ directives.setdefault(key.strip().lower(), value.strip().strip('"'))+ max_age = directives.get("max-age", "")+ hsts["max_age"] = int(max_age) if max_age.isascii() and max_age.isdigit() else None+ hsts["include_subdomains"] = "includesubdomains" in directives+ hsts["preload"] = "preload" in directives+ if hsts["max_age"] is None:+ hsts["issues"].append("max-age is missing, so browsers ignore the header.")+ elif hsts["max_age"] == 0:+ hsts["issues"].append("max-age=0 switches HSTS off.")+ elif hsts["max_age"] < ONE_YEAR:+ hsts["issues"].append("max-age is below one year.")+ if not hsts["include_subdomains"]:+ hsts["issues"].append("includeSubDomains is not set.")+ if (hsts["max_age"] or 0) < ONE_YEAR:+ hsts["preload_gaps"].append("max-age is below 31536000 seconds (one year).")+ if not hsts["include_subdomains"]:+ hsts["preload_gaps"].append("includeSubDomains is missing.")+ if not hsts["preload"]:+ hsts["preload_gaps"].append("The preload directive is missing.")+ hsts["meets_preload_requirements"] = not hsts["preload_gaps"]+ return hsts+++def _parse_csp(value: str) -> dict[str, list[str]]:+ directives: dict[str, list[str]] = {}+ for chunk in value.split(";"):+ tokens = chunk.strip().split()+ if tokens:+ directives.setdefault(tokens[0].lower(), [t.lower() for t in tokens[1:]])+ return directives+++def _csp_issues(directives: dict[str, list[str]]) -> list[str]:+ issues = []+ script_name = next((n for n in ("script-src", "default-src") if n in directives), None)+ if script_name is None:+ issues.append("No script-src or default-src, so scripts are unrestricted.")+ else:+ sources = directives[script_name]+ strict = any(s.startswith(("'nonce-", "'sha256-", "'sha384-", "'sha512-")) for s in sources)+ if "'unsafe-inline'" in sources and not strict:+ issues.append(f"'unsafe-inline' in {script_name}.")+ if "'unsafe-eval'" in sources:+ issues.append(f"'unsafe-eval' in {script_name}.")+ for loose in ("*", "https:", "http:", "data:"):+ if loose in sources:+ issues.append(f"{loose} in {script_name} allows scripts from almost anywhere.")+ if "object-src" not in directives and directives.get("default-src") != ["'none'"]:+ issues.append("No object-src restriction.")+ if "base-uri" not in directives:+ issues.append("No base-uri restriction.")+ return issues+++_REFERRER_POLICIES = frozenset({+ "no-referrer", "no-referrer-when-downgrade", "origin", "origin-when-cross-origin",+ "same-origin", "strict-origin", "strict-origin-when-cross-origin", "unsafe-url",+})+++def analyze_headers(headers: Optional[dict], set_cookies: Optional[list[str]] = None,+ *, https: bool = True) -> dict:+ """Grade the security headers of one response. Makes no requests.++ ``headers`` is a plain mapping; ``set_cookies`` is one raw Set-Cookie line+ per cookie. Cookie values are read here and never returned.+ """+ low = {str(k).lower(): str(v) for k, v in (headers or {}).items()}++ enforced = low.get("content-security-policy")+ report_only = low.get("content-security-policy-report-only")+ policy = enforced if enforced is not None else report_only+ csp = {"present": enforced is not None,+ "report_only": enforced is None and report_only is not None,+ "policies": 0, "issues": []}+ directives: dict[str, list[str]] = {}+ if policy is None:+ csp["issues"].append("Content-Security-Policy was not sent.")+ else:+ policies = [p for p in policy.split(",") if p.strip()]+ csp["policies"] = len(policies)+ directives = _parse_csp(policies[0]) if policies else {}+ csp["issues"].extend(_csp_issues(directives))+ if len(policies) > 1:+ csp["issues"].append("More than one policy was sent; only the first is graded.")+ if csp["report_only"]:+ csp["issues"].insert(0, "Only a report-only policy was sent, so nothing is enforced.")++ nosniff = low.get("x-content-type-options")+ xfo = low.get("x-frame-options")+ xfo_ok = xfo is not None and xfo.strip().upper() in ("DENY", "SAMEORIGIN")+ frame_ancestors = enforced is not None and "frame-ancestors" in directives++ referrer = low.get("referrer-policy")+ known = [t.strip().lower() for t in (referrer or "").split(",")+ if t.strip().lower() in _REFERRER_POLICIES]+ effective = known[-1] if known else None # browsers use the last value they recognise++ return {+ "hsts": _grade_hsts(low.get("strict-transport-security"), https),+ "csp": csp,+ "x_content_type_options": {+ "present": nosniff is not None, "value": _clip(nosniff, 60),+ "ok": nosniff is not None and nosniff.strip().lower() == "nosniff"},+ "framing": {"x_frame_options": _clip(xfo, 60), "frame_ancestors": frame_ancestors,+ "ok": xfo_ok or frame_ancestors},+ "referrer_policy": {"present": referrer is not None, "value": _clip(referrer, 120),+ "ok": effective is not None and effective != "unsafe-url"},+ "permissions_policy": {"present": "permissions-policy" in low,+ "feature_policy_present": "feature-policy" in low},+ "cookies": [_parse_cookie(line, https)+ for line in (set_cookies or [])[:MAX_COOKIES] if line.strip()],+ }+++# ---------------------------------------------------------------------------+# Fetching (url_safety helpers only) and redirect checks+# ---------------------------------------------------------------------------++def _fetch(url: str, timeout: float) -> dict:+ """GET ``url`` through ``safe_requests_get`` and keep headers and hops only.++ The body is never read (``stream=True``). The Set-Cookie header is kept+ apart from ``headers`` so a cookie value cannot ride along into output.+ """+ record: dict = {"url": url, "final_url": None, "status": None, "hops": [],+ "headers": {}, "set_cookies": [], "error": None}+ response = None+ try:+ response = safe_requests_get(url, timeout=timeout, allow_redirects=True, stream=True)+ chain = [*response.history, response]+ record["hops"] = [+ {"url": _clip(hop.url, 500), "status": hop.status_code,+ "target": _clip(chain[index + 1].url, 500),+ "hsts": any(str(k).lower() == "strict-transport-security" for k in hop.headers)}+ for index, hop in enumerate(response.history)+ ]+ record["final_url"] = _clip(response.url, 500)+ record["status"] = response.status_code+ record["headers"] = {str(k).lower(): str(v) for k, v in response.headers.items()+ if str(k).lower() != "set-cookie"}+ record["set_cookies"] = set_cookie_values(response)+ except URLSafetyError as exc:+ record["error"] = _clip(f"url_safety: {exc}", 300)+ except Exception as exc: # requests / urllib3 errors: report, never raise+ record["error"] = _clip(f"{type(exc).__name__}: {exc}", 300)+ finally:+ if response is not None:+ response.close()+ return record+++def _url_host(host: str) -> str:+ return f"[{host}]" if ":" in host else host+++def _same_url(left: Optional[str], right: Optional[str]) -> Optional[bool]:+ if not left or not right:+ return None+ a, b = urlparse(left), urlparse(right)+ return ((a.scheme, a.netloc.lower(), a.path or "/", a.query)+ == (b.scheme, b.netloc.lower(), b.path or "/", b.query))+++def check_redirects(url: str, timeout: float = 10.0, primary: Optional[dict] = None) -> dict:+ """http to https, and www / non-www consolidation, for ``url``'s host.++ ``primary`` is an earlier ``_fetch`` record of ``url``; it is reused when+ it already covers one of the URLs checked here.+ """+ parsed = urlparse(url)+ host = normalize_hostname(parsed.hostname or "")+ port = parsed.port+ port_part = f":{port}" if port else ""++ seen: dict[str, dict] = {}++ def fetch(target: str) -> dict:+ if primary is not None and _same_url(primary.get("url"), target):+ return primary+ if target not in seen:+ seen[target] = _fetch(target, timeout)+ return seen[target]++ # http to https+ if parsed.scheme == "https" and port not in (None, 443):+ http_check: dict = {"skipped": "https on a non-default port has no http counterpart"}+ else:+ http_url = f"http://{_url_host(host)}{port_part if parsed.scheme == 'http' else ''}/"+ record = fetch(http_url)+ hops = record["hops"]+ first = hops[0] if hops else None+ first_target = urlparse(first["target"]) if first else None+ http_check = {+ "checked_url": http_url,+ "redirects_to_https": bool(record["final_url"]+ and record["final_url"].startswith("https://")),+ "one_hop": bool(first_target and first_target.scheme == "https"),+ "first_hop_status": first["status"] if first else None,+ "first_hop_target": first["target"] if first else None,+ "first_hop_same_host": (first_target.hostname or "").lower() == host+ if first_target else None,+ "permanent": first["status"] in (301, 308) if first else None,+ "hops": len(hops),+ "final_url": record["final_url"],+ "error": record["error"],+ }++ # www / non-www+ sibling = sibling_host(host)+ if sibling is None:+ www_check: dict = {"skipped": "no www counterpart for an IP address or a bare label"}+ else:+ host_record = fetch(f"{parsed.scheme}://{_url_host(host)}{port_part}/")+ sibling_url = f"{parsed.scheme}://{sibling}{port_part}/"+ www_check = {"host": host, "sibling_host": sibling,+ "host_final_url": host_record["final_url"],+ "sibling_final_url": None, "sibling_resolves": False,+ "same_final_url": None, "error": host_record["error"]}+ try:+ validate_url_strict(sibling_url)+ except URLSafetyError as exc:+ www_check["error"] = www_check["error"] or _clip(f"url_safety: {exc}", 300)+ else:+ www_check["sibling_resolves"] = True+ sibling_record = _fetch(sibling_url, timeout)+ www_check["sibling_final_url"] = sibling_record["final_url"]+ www_check["error"] = www_check["error"] or sibling_record["error"]+ www_check["same_final_url"] = _same_url(host_record["final_url"],+ sibling_record["final_url"])+ return {"http_to_https": http_check, "www": www_check}+++def _apply_preload_context(headers: dict, tls: dict, redirects: dict, hops: list[dict]) -> None:+ """Add the non-header hstspreload.org requirements this run could observe."""+ hsts = headers.get("hsts")+ if not hsts or not hsts["present"]:+ return+ gaps = hsts["preload_gaps"]+ if tls.get("verified") is False and "skipped" not in tls:+ gaps.append("The certificate did not verify.")+ http_check = redirects.get("http_to_https", {})+ if http_check.get("final_url") and not (http_check.get("one_hop")+ and http_check.get("first_hop_same_host")):+ gaps.append("HTTP does not redirect to HTTPS on the same host first.")+ if any(hop["url"].startswith("https://") and not hop["hsts"] for hop in hops):+ gaps.append("An HTTPS redirect on the way to the page does not send the HSTS header.")+ hsts["meets_preload_requirements"] = not gaps+++# ---------------------------------------------------------------------------+# Findings+# ---------------------------------------------------------------------------++def _finding(fid: str, severity: str, message: str, evidence: Optional[dict] = None) -> dict:+ return {"id": fid, "severity": severity, "message": message, "evidence": evidence or {}}+++def _tls_findings(tls: dict, redirects: dict) -> list[dict]:+ if not tls or "skipped" in tls:+ return []+ if tls.get("error"):+ return [_finding("tls-handshake-failed", "High",+ "The TLS handshake with the site did not complete.",+ {"error": tls["error"]})]+ out = []+ code = tls.get("verify_code")+ verify = {"verify_error": tls.get("verify_error")}+ expired = bool(tls.get("expired")) or code == _ERR_EXPIRED+ not_yet = bool(tls.get("not_yet_valid")) or code == _ERR_NOT_YET_VALID+ mismatch = not tls["verified"] and (tls.get("covers_host") is False+ or code in _ERR_HOST_MISMATCH)+ if expired:+ message = ("The TLS certificate has expired." if tls.get("expired")+ else "A certificate in the site's chain has expired.")+ out.append(_finding("tls-cert-expired", "Critical", message,+ {"not_after": tls.get("not_after"),+ "days_until_expiry": tls.get("days_until_expiry"), **verify}))+ if not_yet:+ out.append(_finding("tls-cert-not-yet-valid", "Critical",+ "The TLS certificate is not valid yet.",+ {"not_before": tls.get("not_before"), **verify}))+ if mismatch:+ out.append(_finding("tls-cert-hostname-mismatch", "Critical",+ "The TLS certificate does not cover the requested host.",+ {"host": tls["host"], "san": tls.get("san", [])[:10], **verify}))+ if not tls["verified"] and not (expired or not_yet or mismatch):+ out.append(_finding("tls-cert-not-trusted", "High",+ "The certificate chain did not verify against the system trust store.",+ verify))+ days = tls.get("days_until_expiry")+ if not expired and days is not None and 0 <= days <= EXPIRY_WARN_DAYS:+ out.append(_finding("tls-cert-expiring-soon", "High",+ f"The TLS certificate expires within {EXPIRY_WARN_DAYS} days.",+ {"days_until_expiry": days, "not_after": tls.get("not_after")}))+ if tls.get("protocol") in OLD_PROTOCOLS:+ out.append(_finding("tls-old-protocol", "Medium",+ "The server negotiated a TLS version older than 1.2.",+ {"protocol": tls["protocol"]}))+ if tls.get("covers_sibling") is False and redirects.get("www", {}).get("sibling_resolves"):+ out.append(_finding("tls-sibling-not-covered", "Medium",+ "The certificate does not cover the www or non-www counterpart, "+ "which resolves in DNS.",+ {"sibling_host": tls.get("sibling_host")}))+ return out+++def _header_findings(headers: dict) -> list[dict]:+ if headers.get("error"):+ return [_finding("headers-not-checked", "Info",+ "The page could not be fetched, so its response headers were not graded.",+ {"error": headers["error"]})]+ out = []+ https = headers.get("https", True)+ hsts = headers["hsts"]+ if https and not hsts["present"]:+ out.append(_finding("hsts-missing", "Medium",+ "The HTTPS response does not send a Strict-Transport-Security header."))+ elif https and not hsts["max_age"]:+ out.append(_finding("hsts-disabled", "Medium",+ "The Strict-Transport-Security header has no effect because max-age "+ "is missing or zero.", {"value": hsts["value"]}))+ elif https and hsts["issues"]:+ out.append(_finding("hsts-weak", "Low", "The Strict-Transport-Security header is weak.",+ {"value": hsts["value"], "issues": hsts["issues"]}))+ csp = headers["csp"]+ if not csp["present"] and not csp["report_only"]:+ out.append(_finding("csp-missing", "Low", "No Content-Security-Policy header is sent."))+ elif csp["report_only"]:+ out.append(_finding("csp-report-only", "Low",+ "The Content-Security-Policy is report-only, so nothing is enforced.",+ {"issues": csp["issues"]}))+ elif csp["issues"]:+ out.append(_finding("csp-weak", "Low", "The Content-Security-Policy has obvious gaps.",+ {"issues": csp["issues"]}))+ nosniff = headers["x_content_type_options"]+ if not nosniff["ok"]:+ out.append(_finding("nosniff-missing", "Low",+ "X-Content-Type-Options is not set to nosniff.",+ {"value": nosniff["value"]}))+ framing = headers["framing"]+ if not framing["ok"]:+ out.append(_finding("clickjacking-protection-missing", "Low",+ "Neither X-Frame-Options nor a CSP frame-ancestors directive limits "+ "framing of the page.",+ {"x_frame_options": framing["x_frame_options"]}))+ referrer = headers["referrer_policy"]+ if not referrer["present"]:+ out.append(_finding("referrer-policy-missing", "Info",+ "No Referrer-Policy header is sent, so the browser default applies."))+ elif not referrer["ok"]:+ out.append(_finding("referrer-policy-unsafe", "Low",+ "The Referrer-Policy is unsafe-url or not a recognised value.",+ {"value": referrer["value"]}))+ if not headers["permissions_policy"]["present"]:+ out.append(_finding("permissions-policy-missing", "Info",+ "No Permissions-Policy header is sent."))++ def names(text: str) -> list[str]:+ return [c["name"] for c in headers["cookies"] if any(text in i for i in c["issues"])]++ insecure = sorted(set(names("Missing Secure") + names("SameSite=None")))+ if insecure:+ out.append(_finding("cookie-missing-secure", "Low",+ "One or more cookies are set without the Secure flag.",+ {"cookies": insecure}))+ if names("HttpOnly"):+ out.append(_finding("cookie-missing-httponly", "Info",+ "One or more cookies are readable by scripts because HttpOnly is "+ "not set.", {"cookies": names("HttpOnly")}))+ if names("No SameSite"):+ out.append(_finding("cookie-missing-samesite", "Info",+ "One or more cookies set no SameSite attribute.",+ {"cookies": names("No SameSite")}))+ return out+++def _redirect_findings(redirects: dict) -> list[dict]:+ out = []+ http_check = redirects.get("http_to_https", {})+ if http_check.get("final_url"):+ evidence = {key: http_check[key] for key in+ ("checked_url", "first_hop_status", "first_hop_target", "hops", "final_url")}+ if not http_check["redirects_to_https"]:+ out.append(_finding("http-no-https-redirect", "High",+ "The http:// address does not redirect to https://.", evidence))+ elif not http_check["one_hop"]:+ out.append(_finding("http-https-redirect-chain", "Low",+ "The http:// address reaches https:// only after more than "+ "one redirect.", evidence))+ elif not http_check["permanent"]:+ out.append(_finding("http-https-redirect-temporary", "Low",+ "The http to https redirect is temporary, not a 301 or 308.",+ evidence))+ www = redirects.get("www", {})+ if www.get("same_final_url") is False:+ out.append(_finding("www-not-consolidated", "Medium",+ "The www and non-www hosts end on different URLs.",+ {key: www[key] for key in ("host", "sibling_host", "host_final_url",+ "sibling_final_url")}))+ elif "sibling_host" in www and www.get("host_final_url") and not www.get("sibling_final_url"):+ out.append(_finding("www-sibling-unreachable", "Info",+ "The www or non-www counterpart of the host did not answer.",+ {"sibling_host": www["sibling_host"], "error": www.get("error")}))+ return out+++def build_findings(tls: dict, headers: dict, redirects: dict) -> list[dict]:+ findings = (_tls_findings(tls, redirects) + _redirect_findings(redirects)+ + _header_findings(headers))+ return sorted(findings, key=lambda f: SEVERITIES.index(f["severity"]))+++def summarize(findings: list[dict]) -> dict:+ return {level.lower(): sum(1 for f in findings if f["severity"] == level)+ for level in SEVERITIES}+++# ---------------------------------------------------------------------------+# Orchestration and CLI+# ---------------------------------------------------------------------------++def run(url: str, timeout: float = 10.0, *, now: Optional[float] = None) -> dict:+ """Run every check for ``url`` and return the JSON-serializable report."""+ url = (url or "").strip()+ if "://" not in url:+ url = f"https://{url}"+ # Validate first: a refused target stops here, before any socket or request.+ try:+ validate_url_strict(url)+ parsed = urlparse(url)+ host = normalize_hostname(parsed.hostname or "")+ tls = check_tls(url, timeout, now=now)+ except URLSafetyError as exc:+ return {"url": url, "error": f"url_safety: {exc}"}+ except ValueError as exc:+ return {"url": url, "error": f"invalid URL: {exc}"}++ primary = _fetch(url, timeout)+ redirects = check_redirects(url, timeout, primary)+ if primary["error"]:+ headers: dict = {"url": url, "error": primary["error"]}+ else:+ https = (primary["final_url"] or "").startswith("https://")+ headers = {"url": primary["final_url"], "status": primary["status"], "https": https,+ **analyze_headers(primary["headers"], primary["set_cookies"], https=https)}+ _apply_preload_context(headers, tls, redirects, primary["hops"])++ findings = build_findings(tls, headers, redirects)+ return {"url": url, "host": host, "tls": tls, "headers": headers, "redirects": redirects,+ "findings": findings, "summary": summarize(findings)}+++def main(argv: Optional[list[str]] = None) -> int:+ parser = argparse.ArgumentParser(+ description="Read a site's TLS certificate, grade its security and transport "+ "headers, and check its http to https and www redirects. JSON on stdout."+ )+ parser.add_argument("url", help="Site or page URL, for example https://example.com")+ parser.add_argument("--timeout", type=float, default=10.0, metavar="N",+ help="Seconds allowed per connection or request (1 to 60, default 10)")+ parser.add_argument("--json", action="store_true",+ help="Accepted for consistency with the other scripts; "+ "output is always JSON")+ args = parser.parse_args(argv)++ report = run(args.url, timeout=min(max(args.timeout, 1.0), 60.0))+ json.dump(report, sys.stdout, indent=2)+ sys.stdout.write("\n")+ return 2 if "error" in report else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_transport_check.py b/tests/test_transport_check.pynew file mode 100644index 0000000..47d1b18--- /dev/null+++ b/tests/test_transport_check.py@@ -0,0 +1,869 @@+"""+Tests for scripts/transport_check.py: TLS certificate, security header and+redirect checks.++Nothing here touches the network. ``socket.create_connection``,+``ssl.SSLContext.wrap_socket`` and the ``url_safety`` fetch helper are+replaced by recorders, so each test can also assert what the script would+have connected to. The fake sockets raise on any use beyond the handshake+surface, which is how "no data is sent or read" is enforced.+"""++from __future__ import annotations++import base64+import json+import os+import re+import socket+import ssl+import sys+from datetime import datetime, timezone++import pytest++_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++import transport_check as tc # noqa: E402+from url_safety import URLSafetyError # noqa: E402++PUBLIC_IP = "93.184.216.34"+NOW = datetime(2026, 6, 1, tzinfo=timezone.utc).timestamp()+DAY = 86400++# Self-signed throwaway certificate (the private key was discarded), DER, base64.+# Subject and issuer: CN=fixture.example.test, O=Fixture Org+# Valid 2020-01-01 to 2021-01-01 UTC.+# subjectAltName: fixture.example.test, www.fixture.example.test,+# *.wild.example.test, 192.0.2.7, 2001:db8::7+FIXTURE_DER = base64.b64decode(+ "MIICKDCCAc+gAwIBAgIUDJc2dXhK+lixzsOhiwZXgcIFpqMwCgYIKoZIzj0EAwIwNTEdMBsGA1UE"+ "AwwUZml4dHVyZS5leGFtcGxlLnRlc3QxFDASBgNVBAoMC0ZpeHR1cmUgT3JnMB4XDTIwMDEwMTAw"+ "MDAwMFoXDTIxMDEwMTAwMDAwMFowNTEdMBsGA1UEAwwUZml4dHVyZS5leGFtcGxlLnRlc3QxFDAS"+ "BgNVBAoMC0ZpeHR1cmUgT3JnMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE6ZxflPBKM8/NBTya"+ "2fsWODv9DdBIXHNVANGSzZKG23GUmA6+GnEwrRFRP9BE6icWbhr2LECOe5eHkrH2CAEl0qOBvDCB"+ "uTAdBgNVHQ4EFgQUSiGbxgVgxLfdPiMYm1lSjOj48mEwHwYDVR0jBBgwFoAUSiGbxgVgxLfdPiMY"+ "m1lSjOj48mEwDwYDVR0TAQH/BAUwAwEB/zBmBgNVHREEXzBdghRmaXh0dXJlLmV4YW1wbGUudGVz"+ "dIIYd3d3LmZpeHR1cmUuZXhhbXBsZS50ZXN0ghMqLndpbGQuZXhhbXBsZS50ZXN0hwTAAAIHhxAg"+ "AQ24AAAAAAAAAAAAAAAHMAoGCCqGSM49BAMCA0cAMEQCIGzAsWjlsio52r/hXabfJ6MZTx0i0H6X"+ "ZyCm4a9cjCWjAiBBJ5sapBLddkeZNfMR24mvcxiAoFZF29Hs0pDdCvj7qw=="+)+FIXTURE_MID_VALIDITY = datetime(2020, 6, 1, tzinfo=timezone.utc).timestamp()++GOOD_HSTS = "max-age=63072000; includeSubDomains; preload"+GOOD_HEADERS = {+ "Strict-Transport-Security": GOOD_HSTS,+ "Content-Security-Policy": "default-src 'self'; script-src 'self' 'nonce-r4nd'; "+ "object-src 'none'; base-uri 'self'; frame-ancestors 'none'",+ "X-Content-Type-Options": "nosniff",+ "Referrer-Policy": "strict-origin-when-cross-origin",+ "Permissions-Policy": "geolocation=()",+}+++# ---------------------------------------------------------------------------+# Fakes+# ---------------------------------------------------------------------------++class FakeSock:+ """A raw TCP socket that only tolerates settimeout() and close()."""++ def __init__(self) -> None:+ self.closed = False+ self.timeouts: list[float] = []++ def settimeout(self, value: float) -> None:+ self.timeouts.append(value)++ def close(self) -> None:+ self.closed = True++ def __getattr__(self, name: str):+ raise AssertionError(f"raw socket .{name} must not be used")+++class FakeTLS:+ """A wrapped socket that only tolerates the read-the-handshake surface."""++ def __init__(self, cert=None, der=None, protocol="TLSv1.3",+ cipher=("TLS_AES_256_GCM_SHA384", "TLSv1.3", 256)) -> None:+ self._cert, self._der, self._protocol, self._cipher = cert, der, protocol, cipher+ self.closed = False++ def getpeercert(self, binary_form: bool = False):+ return self._der if binary_form else self._cert++ def version(self):+ return self._protocol++ def cipher(self):+ return self._cipher++ def close(self) -> None:+ self.closed = True++ def __getattr__(self, name: str):+ raise AssertionError(f"TLS socket .{name} must not be used (no data may be sent or read)")+++class Net:+ """What the script connected to, and what each handshake should answer."""++ def __init__(self) -> None:+ self.connects: list[tuple] = []+ self.socks: list[FakeSock] = []+ self.wraps: list[dict] = []+ self.verified = None # FakeTLS or an exception, for the verifying handshake+ self.unverified = None # the same, for the certificate-reading handshake+++def net(monkeypatch) -> Net:+ for name in (*tc.PROXY_ENV_VARS, "CLAUDE_SEO_LOCAL_TARGETS"):+ monkeypatch.delenv(name, raising=False)+ state = Net()++ def create_connection(address, timeout=None, **_kwargs):+ state.connects.append((address, timeout))+ sock = FakeSock()+ state.socks.append(sock)+ return sock++ def wrap_socket(self, sock, server_hostname=None, **_kwargs):+ verify = self.verify_mode != ssl.CERT_NONE+ state.wraps.append({"verify": verify, "server_hostname": server_hostname, "sock": sock})+ outcome = state.verified if verify else state.unverified+ if isinstance(outcome, BaseException):+ raise outcome+ assert outcome is not None, "unexpected handshake"+ return outcome++ monkeypatch.setattr(socket, "create_connection", create_connection)+ monkeypatch.setattr(ssl.SSLContext, "wrap_socket", wrap_socket)+ return state+++def public(monkeypatch):+ """Make the validator answer PUBLIC_IP for every name, with no DNS."""+ unresolvable: set[str] = set()++ def fake_validate(url: str):+ host = tc.urlparse(url).hostname+ if host in unresolvable:+ raise URLSafetyError(f"DNS resolution failed for {host}")+ return url, PUBLIC_IP++ monkeypatch.setattr(tc, "validate_url_strict", fake_validate)+ return unresolvable+++class FakeRawHeaders:+ def __init__(self, cookies) -> None:+ self._cookies = list(cookies)++ def getlist(self, name: str):+ return list(self._cookies) if name.lower() == "set-cookie" else []+++class FakeRaw:+ def __init__(self, cookies) -> None:+ self.headers = FakeRawHeaders(cookies)+++class FakeResponse:+ """A requests.Response stand-in with no body attributes at all."""++ def __init__(self, url, status=200, headers=None, cookies=(), history=(), raw=True) -> None:+ self.url, self.status_code = url, status+ self.headers = dict(headers or {})+ self.history = list(history)+ self.closed = False+ if raw:+ self.raw = FakeRaw(cookies)++ def close(self) -> None:+ self.closed = True+++def redirect(url, target, status=301, headers=None):+ return FakeResponse(url, status, {"Location": target, **(headers or {})})+++def site(host="example.com", headers=None, cookies=()):+ """Routes for a tidy site: http and www both go to https://host/ in one hop."""+ headers = GOOD_HEADERS if headers is None else headers+ home = f"https://{host}/"+ return {+ home: FakeResponse(home, 200, headers, cookies),+ f"http://{host}/": FakeResponse(+ home, 200, headers, cookies, history=[redirect(f"http://{host}/", home)]),+ f"https://www.{host}/": FakeResponse(+ home, 200, headers, cookies,+ history=[redirect(f"https://www.{host}/", home,+ headers={"Strict-Transport-Security": GOOD_HSTS})]),+ }+++def web(monkeypatch):+ """Install URL routes for safe_requests_get; returns (install, calls)."""+ calls: list[str] = []+ routes: dict = {}++ def fake_get(url, **kwargs):+ calls.append(url)+ assert kwargs.get("stream") is True, "the body must not be downloaded"+ outcome = routes.get(url)+ if outcome is None:+ raise OSError(f"no route to {url}")+ if isinstance(outcome, BaseException):+ raise outcome+ return outcome++ monkeypatch.setattr(tc, "safe_requests_get", fake_get)++ def install(new_routes: dict) -> list[str]:+ routes.clear()+ routes.update(new_routes)+ return calls++ return install+++def peercert(*names, not_before=NOW - 30 * DAY, not_after=NOW + 60 * DAY) -> dict:+ def stamp(seconds: float) -> str:+ return datetime.fromtimestamp(seconds, timezone.utc).strftime("%b %d %H:%M:%S %Y GMT")++ return {+ "subject": ((("commonName", names[0]),),),+ "issuer": ((("countryName", "US"),), (("organizationName", "Example Trust"),),+ (("commonName", "Example CA 1"),)),+ "notBefore": stamp(not_before),+ "notAfter": stamp(not_after),+ "subjectAltName": tuple(("DNS", name) for name in names),+ }+++def verify_error(code: int, message: str) -> ssl.SSLCertVerificationError:+ exc = ssl.SSLCertVerificationError(+ 1, f"[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: {message}")+ exc.verify_code, exc.verify_message = code, message+ return exc+++def ids(report_or_findings) -> list[str]:+ findings = (report_or_findings["findings"] if isinstance(report_or_findings, dict)+ else report_or_findings)+ return [finding["id"] for finding in findings]+++def by_id(report: dict) -> dict:+ return {finding["id"]: finding for finding in report["findings"]}+++# ---------------------------------------------------------------------------+# Refusals: nothing is opened for a blocked target+# ---------------------------------------------------------------------------+[email protected]("url", [+ "https://127.0.0.1/",+ "https://localhost/",+ "https://10.0.0.5/",+ "https://192.168.1.10:8443/admin",+ "https://169.254.169.254/latest/meta-data/",+ "https://[::1]/",+ "https://100.100.100.200/",+ "http://127.0.0.1/",+ "http://localhost:8080/",+ "ftp://example.com/",+ "https://user:[email protected]/",+])+def test_blocked_target_is_refused_before_any_socket_or_request(url, net, web) -> None:+ calls = web({})+ report = tc.run(url, now=NOW)+ assert set(report) == {"url", "error"}+ assert report["error"].startswith("url_safety:")+ assert net.connects == [] and net.wraps == []+ assert calls == []+++def test_check_tls_refuses_a_private_target_on_its_own(net) -> None:+ with pytest.raises(URLSafetyError):+ tc.check_tls("https://10.0.0.5/", now=NOW)+ assert net.connects == []+++def test_cli_prints_error_json_and_exits_2_for_a_refused_target(net, web, capsys) -> None:+ web({})+ assert tc.main(["https://127.0.0.1/"]) == 2+ out = json.loads(capsys.readouterr().out)+ assert "error" in out and out["url"] == "https://127.0.0.1/"+ assert net.connects == []+++# ---------------------------------------------------------------------------+# The socket goes to the validated IP, never to the hostname+# ---------------------------------------------------------------------------++def test_socket_connects_to_validated_ip_and_hostname_is_sni_only(net, public, monkeypatch) -> None:+ def no_dns(*_args, **_kwargs):+ raise AssertionError("check_tls must not resolve the hostname itself")++ monkeypatch.setattr(socket, "getaddrinfo", no_dns)+ net.verified = FakeTLS(cert=peercert("example.com", "www.example.com"))+ tls = tc.check_tls("https://Example.COM./pricing", timeout=7, now=NOW)++ assert net.connects == [((PUBLIC_IP, 443), 7)]+ assert all("example" not in str(address) for address, _timeout in net.connects)+ assert [w["server_hostname"] for w in net.wraps] == ["example.com"]+ assert tls["connected_ip"] == PUBLIC_IP and tls["verified"] is True+ assert net.socks[0].timeouts and 0 < net.socks[0].timeouts[0] <= 7+ assert net.verified.closed and net.socks[0].closed+++def test_ipv6_validated_address_and_explicit_port_are_used(net, monkeypatch) -> None:+ monkeypatch.setattr(tc, "validate_url_strict", lambda url: (url, "2606:2800:220:1::1946"))+ net.verified = FakeTLS(cert=peercert("example.com"))+ tls = tc.check_tls("https://example.com:8443/", now=NOW)+ assert net.connects[0][0] == ("2606:2800:220:1::1946", 8443)+ assert tls["port"] == 8443 and tls["connected_ip"] == "2606:2800:220:1::1946"+++def test_a_validator_answer_that_is_not_an_ip_literal_is_never_dialled(net, monkeypatch) -> None:+ monkeypatch.setattr(tc, "validate_url_strict", lambda url: (url, "evil.example.net"))+ tls = tc.check_tls("https://example.com/", now=NOW)+ assert net.connects == []+ assert "not an IP literal" in tls["error"]+++def test_certificate_reading_handshake_reuses_the_same_validated_ip(net, public) -> None:+ net.verified = verify_error(10, "certificate has expired")+ net.unverified = FakeTLS(der=FIXTURE_DER)+ tc.check_tls("https://fixture.example.test/", now=NOW)+ assert [address for address, _timeout in net.connects] == [(PUBLIC_IP, 443), (PUBLIC_IP, 443)]+ assert [w["verify"] for w in net.wraps] == [True, False]+ assert all(w["server_hostname"] == "fixture.example.test" for w in net.wraps)+ assert all(sock.closed for sock in net.socks) and net.unverified.closed+++# ---------------------------------------------------------------------------+# Certificate verdicts+# ---------------------------------------------------------------------------++def test_valid_certificate_is_reported_in_full(net, public) -> None:+ net.verified = FakeTLS(cert=peercert("example.com", "www.example.com"))+ tls = tc.check_tls("https://example.com/", now=NOW)+ assert tls["verified"] is True and tls["verify_error"] is None+ assert tls["subject"] == {"common_name": "example.com", "organization": None}+ assert tls["issuer"] == {"common_name": "Example CA 1", "organization": "Example Trust"}+ assert tls["not_before"] == "2026-05-02T00:00:00Z"+ assert tls["not_after"] == "2026-07-31T00:00:00Z"+ assert tls["days_until_expiry"] == 60 and tls["expired"] is False+ assert tls["covers_host"] is True+ assert tls["sibling_host"] == "www.example.com" and tls["covers_sibling"] is True+ assert (tls["protocol"], tls["cipher"], tls["cipher_bits"]) == (+ "TLSv1.3", "TLS_AES_256_GCM_SHA384", 256)+ assert tc._tls_findings(tls, {}) == []+++def test_expired_certificate_is_critical(net, public) -> None:+ net.verified = verify_error(10, "certificate has expired")+ net.unverified = FakeTLS(der=FIXTURE_DER)+ tls = tc.check_tls("https://fixture.example.test/", now=NOW)+ assert tls["verified"] is False+ assert tls["verify_error"] == "certificate has expired" and tls["verify_code"] == 10+ assert tls["certificate_read"] is True and tls["expired"] is True+ assert tls["not_after"] == "2021-01-01T00:00:00Z" and tls["days_until_expiry"] < 0+ assert tls["covers_host"] is True+ findings = tc._tls_findings(tls, {})+ assert ids(findings) == ["tls-cert-expired"]+ assert findings[0]["severity"] == "Critical"+ assert findings[0]["evidence"]["not_after"] == "2021-01-01T00:00:00Z"+++def test_hostname_mismatch_is_critical(net, public) -> None:+ net.verified = verify_error(+ 62, "Hostname mismatch, certificate is not valid for 'shop.example.org'.")+ net.unverified = FakeTLS(der=FIXTURE_DER)+ tls = tc.check_tls("https://shop.example.org/", now=FIXTURE_MID_VALIDITY)+ assert tls["verified"] is False and tls["covers_host"] is False+ assert tls["expired"] is False+ findings = tc._tls_findings(tls, {})+ assert ids(findings) == ["tls-cert-hostname-mismatch"]+ assert findings[0]["severity"] == "Critical"+ assert "fixture.example.test" in findings[0]["evidence"]["san"]++[email protected]("days_left, expected", [+ (0.5, ["tls-cert-expiring-soon"]),+ (7.5, ["tls-cert-expiring-soon"]),+ (14.5, ["tls-cert-expiring-soon"]),+ (15.5, []),+ (90.5, []),+])+def test_expiry_within_14_days_is_high(days_left, expected, net, public) -> None:+ net.verified = FakeTLS(cert=peercert("example.com", "www.example.com",+ not_after=NOW + days_left * DAY))+ tls = tc.check_tls("https://example.com/", now=NOW)+ findings = tc._tls_findings(tls, {})+ assert ids(findings) == expected+ assert tls["days_until_expiry"] == int(days_left)+ if findings:+ assert findings[0]["severity"] == "High"+++def test_untrusted_chain_is_high_and_the_certificate_is_still_described(net, public) -> None:+ net.verified = verify_error(18, "self-signed certificate")+ net.unverified = FakeTLS(der=FIXTURE_DER)+ tls = tc.check_tls("https://fixture.example.test/", now=FIXTURE_MID_VALIDITY)+ assert tls["issuer"] == {"common_name": "fixture.example.test", "organization": "Fixture Org"}+ findings = tc._tls_findings(tls, {})+ assert [(f["id"], f["severity"]) for f in findings] == [("tls-cert-not-trusted", "High")]+ assert findings[0]["evidence"]["verify_error"] == "self-signed certificate"+++def test_verdict_falls_back_to_the_openssl_code_when_the_certificate_cannot_be_read(+ net, public) -> None:+ net.verified = verify_error(10, "certificate has expired")+ net.unverified = ConnectionResetError("reset during handshake")+ tls = tc.check_tls("https://example.com/", now=NOW)+ assert tls["certificate_read"] is False and "ConnectionResetError" in tls["certificate_error"]+ assert ids(tc._tls_findings(tls, {})) == ["tls-cert-expired"]+ assert all(sock.closed for sock in net.socks)+++def test_unreadable_certificate_bytes_do_not_raise(net, public) -> None:+ net.verified = verify_error(18, "self-signed certificate")+ net.unverified = FakeTLS(der=b"\x30\x82\xff\xff garbage")+ tls = tc.check_tls("https://example.com/", now=NOW)+ assert tls["certificate_read"] is False+ assert ids(tc._tls_findings(tls, {})) == ["tls-cert-not-trusted"]++[email protected]("failure", [+ TimeoutError("timed out"),+ ConnectionRefusedError("refused"),+ ssl.SSLError(1, "[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version"),+])+def test_failed_handshake_is_reported_and_the_socket_is_closed(failure, net, public) -> None:+ net.verified = failure+ tls = tc.check_tls("https://example.com/", now=NOW)+ assert type(failure).__name__ in tls["error"]+ assert [sock.closed for sock in net.socks] == [True]+ findings = tc._tls_findings(tls, {})+ assert [(f["id"], f["severity"]) for f in findings] == [("tls-handshake-failed", "High")]+++def test_old_protocol_is_flagged(net, public) -> None:+ net.verified = FakeTLS(cert=peercert("example.com", "www.example.com"), protocol="TLSv1.1")+ tls = tc.check_tls("https://example.com/", now=NOW)+ assert ids(tc._tls_findings(tls, {})) == ["tls-old-protocol"]+++# ---------------------------------------------------------------------------+# http URLs and proxies+# ---------------------------------------------------------------------------++def test_http_url_skips_tls_with_a_clear_message_but_still_checks_redirects(+ net, public, web) -> None:+ calls = web(site())+ report = tc.run("http://example.com/", now=NOW)+ assert set(report["tls"]) == {"skipped"} and "not an https URL" in report["tls"]["skipped"]+ assert net.connects == []+ assert calls.count("http://example.com/") == 1 # one fetch serves all three checks+ assert report["headers"]["https"] is True and report["headers"]["hsts"]["present"] is True+ assert report["redirects"]["http_to_https"]["redirects_to_https"] is True+ assert report["redirects"]["http_to_https"]["one_hop"] is True++[email protected]("variable", ["HTTPS_PROXY", "https_proxy", "ALL_PROXY"])+def test_proxy_configured_skips_the_raw_socket(variable, net, public, web, monkeypatch) -> None:+ monkeypatch.setenv(variable, "http://proxy.example.net:3128")+ web(site())+ report = tc.run("https://example.com/", now=NOW)+ assert report["tls"] == {"skipped": "proxy configured"}+ assert net.connects == [] and net.wraps == []+ assert report["headers"]["hsts"]["present"] is True # header checks still run+ assert not [i for i in ids(report) if i.startswith("tls-")]+++# ---------------------------------------------------------------------------+# Header grading+# ---------------------------------------------------------------------------+[email protected]("value, max_age, subdomains, preload, meets, finding", [+ (None, None, False, False, False, "hsts-missing"),+ ("max-age=63072000; includeSubDomains; preload", 63072000, True, True, True, None),+ ("MAX-AGE=\"31536000\" ; INCLUDESUBDOMAINS ; PRELOAD", 31536000, True, True, True, None),+ ("max-age=31536000; includeSubDomains", 31536000, True, False, False, None),+ ("max-age=31535999; includeSubDomains; preload", 31535999, True, True, False, "hsts-weak"),+ ("max-age=300", 300, False, False, False, "hsts-weak"),+ ("max-age=63072000; preload", 63072000, False, True, False, "hsts-weak"),+ ("max-age=0; includeSubDomains", 0, True, False, False, "hsts-disabled"),+ ("includeSubDomains; preload", None, True, True, False, "hsts-disabled"),+ ("max-age=abc", None, False, False, False, "hsts-disabled"),+ ("max-age=63072000; includeSubDomains; preload, max-age=1", 63072000, True, True, True, None),+])+def test_hsts_variants(value, max_age, subdomains, preload, meets, finding) -> None:+ headers = {k: v for k, v in GOOD_HEADERS.items() if k != "Strict-Transport-Security"}+ if value is not None:+ headers["strict-transport-security"] = value+ graded = tc.analyze_headers(headers, [])+ hsts = graded["hsts"]+ assert (hsts["max_age"], hsts["include_subdomains"], hsts["preload"]) == (+ max_age, subdomains, preload)+ assert hsts["meets_preload_requirements"] is meets+ assert bool(hsts["preload_gaps"]) is not meets+ found = tc._header_findings({"https": True, **graded})+ assert ids(found) == ([finding] if finding else [])+ if finding:+ severity = {"hsts-missing": "Medium", "hsts-disabled": "Medium", "hsts-weak": "Low"}+ assert found[0]["severity"] == severity[finding]+++def test_missing_hsts_is_not_a_finding_on_a_plain_http_response() -> None:+ graded = tc.analyze_headers({}, ["sid=1"], https=False)+ found = ids(tc._header_findings({"https": False, **graded}))+ assert "hsts-missing" not in found and "cookie-missing-secure" not in found+++def test_strong_headers_produce_no_findings() -> None:+ graded = tc.analyze_headers(GOOD_HEADERS, ["sid=1; Secure; HttpOnly; SameSite=Lax"])+ assert tc._header_findings({"https": True, **graded}) == []+ assert graded["framing"] == {"x_frame_options": None, "frame_ancestors": True, "ok": True}+++def test_csp_gaps() -> None:+ weak = tc.analyze_headers({"Content-Security-Policy": "script-src 'self' 'unsafe-inline' *"})+ joined = " ".join(weak["csp"]["issues"])+ for fragment in ("'unsafe-inline' in script-src", "* in script-src", "object-src", "base-uri"):+ assert fragment in joined+ no_script = tc.analyze_headers({"Content-Security-Policy": "img-src 'self'"})+ assert "No script-src or default-src" in no_script["csp"]["issues"][0]+ nonce = tc.analyze_headers(+ {"Content-Security-Policy": "script-src 'unsafe-inline' 'nonce-x'; object-src 'none'; "+ "base-uri 'none'"})+ assert nonce["csp"]["issues"] == []++ def csp_finding(headers):+ return [f for f in ids(tc._header_findings({"https": True, **tc.analyze_headers(headers)}))+ if f.startswith("csp-")]++ assert csp_finding({}) == ["csp-missing"]+ assert csp_finding({"Content-Security-Policy": "img-src 'self'"}) == ["csp-weak"]+ assert csp_finding(+ {"Content-Security-Policy-Report-Only": "default-src 'self'"}) == ["csp-report-only"]+++def test_report_only_frame_ancestors_does_not_count_as_framing_protection() -> None:+ graded = tc.analyze_headers(+ {"Content-Security-Policy-Report-Only": "frame-ancestors 'none'"})+ assert graded["framing"]["ok"] is False+++def test_hygiene_headers_are_low_or_info() -> None:+ graded = tc.analyze_headers({+ "Strict-Transport-Security": GOOD_HSTS,+ "X-Content-Type-Options": "sniff",+ "X-Frame-Options": "ALLOW-FROM https://x.example",+ "Referrer-Policy": "no-referrer, unsafe-url",+ })+ found = {f["id"]: f["severity"] for f in tc._header_findings({"https": True, **graded})}+ assert found == {+ "csp-missing": "Low",+ "nosniff-missing": "Low",+ "clickjacking-protection-missing": "Low",+ "referrer-policy-unsafe": "Low",+ "permissions-policy-missing": "Info",+ }+ absent = tc.analyze_headers({"X-Frame-Options": "sameorigin"})+ found = {f["id"]: f["severity"] for f in tc._header_findings({"https": True, **absent})}+ assert found["referrer-policy-missing"] == "Info"+ assert "clickjacking-protection-missing" not in found+++# ---------------------------------------------------------------------------+# Cookies: flags per name, values never leave the parser+# ---------------------------------------------------------------------------++def test_cookie_without_secure_is_reported_by_name() -> None:+ graded = tc.analyze_headers(GOOD_HEADERS, [+ "session_id=abc123; Path=/; HttpOnly; SameSite=Lax",+ "prefs=dark; Secure; HttpOnly; SameSite=Strict",+ "track=1; SameSite=None",+ ])+ assert [(c["name"], c["secure"], c["http_only"], c["same_site"]) for c in graded["cookies"]] == [+ ("session_id", False, True, "Lax"),+ ("prefs", True, True, "Strict"),+ ("track", False, False, "None"),+ ]+ found = {f["id"]: f for f in tc._header_findings({"https": True, **graded})}+ assert found["cookie-missing-secure"]["severity"] == "Low"+ assert found["cookie-missing-secure"]["evidence"] == {"cookies": ["session_id", "track"]}+ assert found["cookie-missing-httponly"]["evidence"] == {"cookies": ["track"]}+++def test_cookie_values_never_appear_in_the_output(net, public, web, capsys) -> None:+ secrets = ["S3CRET-SESSION-VALUE", "TOPSECRET456", "NAMELESSSECRET789", "eyJhbGciOiJIUzI1NiJ9"]+ cookies = [+ f"session_id={secrets[0]}; Path=/; HttpOnly",+ f"prefs={secrets[1]}; Secure",+ secrets[2], # no "=": a nameless cookie whose whole text is the value+ f"jwt={secrets[3]}; Expires=Wed, 21 Oct 2026 07:28:00 GMT; SameSite=None",+ ]+ net.verified = FakeTLS(cert=peercert("example.com", "www.example.com"))+ web(site(cookies=cookies))+ assert tc.main(["https://example.com/"]) == 0+ printed = capsys.readouterr().out+ report = json.loads(printed)+ assert [c["name"] for c in report["headers"]["cookies"]] == [+ "session_id", "prefs", "(unnamed)", "jwt"]+ for secret in secrets:+ assert secret not in printed+ assert "cookie-missing-secure" in ids(report)+++def test_folded_set_cookie_header_is_split_and_values_stay_out(net, public, web) -> None:+ folded = ("a=FOLDEDSECRET1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Secure, "+ "b=FOLDEDSECRET2; Path=/")+ routes = site()+ home = "https://example.com/"+ # No urllib3 raw headers: only the comma-folded mapping value is available.+ routes[home] = FakeResponse(home, 200, {**GOOD_HEADERS, "Set-Cookie": folded}, raw=False)+ net.verified = FakeTLS(cert=peercert("example.com", "www.example.com"))+ web(routes)+ report = tc.run(home, now=NOW)+ assert [(c["name"], c["secure"]) for c in report["headers"]["cookies"]] == [+ ("a", True), ("b", False)]+ assert "FOLDEDSECRET" not in json.dumps(report)+++# ---------------------------------------------------------------------------+# Redirects+# ---------------------------------------------------------------------------++def good_tls(net) -> None:+ net.verified = FakeTLS(cert=peercert("example.com", "www.example.com"))+++def test_tidy_site_has_no_findings_and_fetches_each_url_once(net, public, web) -> None:+ good_tls(net)+ routes = site()+ routes["https://example.com"] = routes["https://example.com/"] # as typed, no slash+ calls = web(routes)+ report = tc.run("https://example.com", now=NOW)+ assert report["findings"] == []+ assert report["summary"] == {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0}+ assert sorted(calls) == ["http://example.com/", "https://example.com",+ "https://www.example.com/"]+ http = report["redirects"]["http_to_https"]+ assert (http["redirects_to_https"], http["one_hop"], http["permanent"], http["hops"]) == (+ True, True, True, 1)+ assert http["first_hop_same_host"] is True+ www = report["redirects"]["www"]+ assert www["same_final_url"] is True and www["sibling_resolves"] is True+ assert report["headers"]["hsts"]["meets_preload_requirements"] is True+++def test_http_that_stays_on_http_is_high(net, public, web) -> None:+ good_tls(net)+ routes = site()+ routes["http://example.com/"] = FakeResponse("http://example.com/", 200, {})+ web(routes)+ report = tc.run("https://example.com/", now=NOW)+ assert by_id(report)["http-no-https-redirect"]["severity"] == "High"+ assert report["redirects"]["http_to_https"]["one_hop"] is False+ hsts = report["headers"]["hsts"]+ assert hsts["meets_preload_requirements"] is False+ assert "HTTP does not redirect to HTTPS on the same host first." in hsts["preload_gaps"]+++def test_http_reaching_https_after_two_hops_is_a_chain(net, public, web) -> None:+ good_tls(net)+ routes = site()+ home = "https://example.com/"+ routes["http://example.com/"] = FakeResponse(home, 200, GOOD_HEADERS, history=[+ redirect("http://example.com/", "http://www.example.com/"),+ redirect("http://www.example.com/", home),+ ])+ web(routes)+ report = tc.run(home, now=NOW)+ http = report["redirects"]["http_to_https"]+ assert (http["redirects_to_https"], http["one_hop"], http["hops"]) == (True, False, 2)+ assert by_id(report)["http-https-redirect-chain"]["severity"] == "Low"+++def test_temporary_http_to_https_redirect_is_low(net, public, web) -> None:+ good_tls(net)+ routes = site()+ home = "https://example.com/"+ routes["http://example.com/"] = FakeResponse(home, 200, GOOD_HEADERS, history=[+ redirect("http://example.com/", home, status=302)])+ web(routes)+ report = tc.run(home, now=NOW)+ assert by_id(report)["http-https-redirect-temporary"]["severity"] == "Low"+++def test_closed_port_80_is_not_a_finding(net, public, web) -> None:+ good_tls(net)+ routes = site()+ routes["http://example.com/"] = ConnectionRefusedError("refused")+ web(routes)+ report = tc.run("https://example.com/", now=NOW)+ assert "ConnectionRefusedError" in report["redirects"]["http_to_https"]["error"]+ assert not [i for i in ids(report) if i.startswith("http-")]+++def test_www_and_bare_host_on_different_final_urls_is_medium(net, public, web) -> None:+ good_tls(net)+ routes = site()+ routes["https://www.example.com/"] = FakeResponse("https://www.example.com/", 200, GOOD_HEADERS)+ web(routes)+ report = tc.run("https://example.com/", now=NOW)+ finding = by_id(report)["www-not-consolidated"]+ assert finding["severity"] == "Medium"+ assert finding["evidence"]["sibling_final_url"] == "https://www.example.com/"+ assert report["redirects"]["www"]["same_final_url"] is False+++def test_sibling_that_does_not_resolve_is_info_and_no_certificate_finding(+ net, public, web) -> None:+ public.add("www.blog.example.com")+ net.verified = FakeTLS(cert=peercert("blog.example.com"))+ calls = web(site("blog.example.com"))+ report = tc.run("https://blog.example.com/", now=NOW)+ assert report["tls"]["covers_sibling"] is False+ assert report["redirects"]["www"]["sibling_resolves"] is False+ assert "https://www.blog.example.com/" not in calls+ assert ids(report) == ["www-sibling-unreachable"]+ assert report["findings"][0]["severity"] == "Info"+++def test_sibling_that_resolves_but_is_not_on_the_certificate_is_medium(net, public, web) -> None:+ net.verified = FakeTLS(cert=peercert("example.com"))+ routes = site()+ routes["https://www.example.com/"] = ssl.SSLError(1, "certificate verify failed")+ web(routes)+ report = tc.run("https://example.com/", now=NOW)+ assert by_id(report)["tls-sibling-not-covered"]["severity"] == "Medium"+ assert report["redirects"]["www"]["sibling_resolves"] is True+++def test_www_input_uses_the_bare_domain_as_sibling() -> None:+ assert tc.sibling_host("www.example.com") == "example.com"+ assert tc.sibling_host("example.com") == "www.example.com"+ assert tc.sibling_host("www.com") == "www.www.com"+ assert tc.sibling_host("93.184.216.34") is None+ assert tc.sibling_host("2606:2800:220:1::1946") is None+ assert tc.sibling_host("intranet") is None+++def test_page_fetch_failure_is_reported_not_raised(net, public, web) -> None:+ good_tls(net)+ web({})+ report = tc.run("https://example.com/", now=NOW)+ assert "error" in report["headers"] and "error" not in report+ assert "headers-not-checked" in ids(report)+++def test_https_redirect_hop_without_hsts_is_a_preload_gap(net, public, web) -> None:+ good_tls(net)+ routes = site()+ start, home = "https://example.com/old", "https://example.com/"+ routes[start] = FakeResponse(home, 200, GOOD_HEADERS, history=[redirect(start, home)])+ web(routes)+ report = tc.run(start, now=NOW)+ hsts = report["headers"]["hsts"]+ assert hsts["meets_preload_requirements"] is False+ assert any("HTTPS redirect" in gap for gap in hsts["preload_gaps"])+++# ---------------------------------------------------------------------------+# DER reader+# ---------------------------------------------------------------------------++def test_der_reader_matches_the_fixture_certificate() -> None:+ cert = tc.parse_der_certificate(FIXTURE_DER)+ assert cert["subject"] == {"common_name": "fixture.example.test", "organization": "Fixture Org"}+ assert cert["issuer"] == cert["subject"]+ assert tc._iso(cert["not_before"]) == "2020-01-01T00:00:00Z"+ assert tc._iso(cert["not_after"]) == "2021-01-01T00:00:00Z"+ assert cert["san"] == ["fixture.example.test", "www.fixture.example.test",+ "*.wild.example.test", "192.0.2.7", "2001:db8::7"]+++def test_der_reader_only_ever_raises_valueerror_on_hostile_bytes() -> None:+ for junk in (b"", b"\x30", b"\x30\x84\xff\xff\xff\xff", b"\x00" * 64, b"\x30\x80\x00\x00",+ b"\xff" * 300_000):+ with pytest.raises(ValueError):+ tc.parse_der_certificate(junk)+ for cut in range(0, len(FIXTURE_DER) - 1, 7):+ with pytest.raises(ValueError):+ tc.parse_der_certificate(FIXTURE_DER[:cut])+ # Corrupt every byte in turn: a result or a ValueError, never another exception.+ for index in range(len(FIXTURE_DER)):+ for value in (0x00, 0x30, 0x80, 0x84, 0xFF):+ mutated = FIXTURE_DER[:index] + bytes([value]) + FIXTURE_DER[index + 1:]+ try:+ tc.parse_der_certificate(mutated)+ except ValueError:+ pass+++def test_san_matching_follows_browser_wildcard_rules() -> None:+ assert tc._name_matches("*.example.com", "www.example.com")+ assert tc._name_matches("EXAMPLE.com.", "example.com")+ assert not tc._name_matches("*.example.com", "example.com")+ assert not tc._name_matches("*.example.com", "a.b.example.com")+ assert tc._name_matches("2001:DB8:0:0:0:0:0:7", "2001:db8::7")+ assert not tc._name_matches("192.0.2.7", "192.0.2.8")+++# ---------------------------------------------------------------------------+# Output contract+# ---------------------------------------------------------------------------++def test_findings_shape_order_and_summary(net, public, web) -> None:+ net.verified = verify_error(10, "certificate has expired")+ net.unverified = FakeTLS(der=FIXTURE_DER)+ routes = site("fixture.example.test", headers={}, cookies=["sid=1"])+ routes["http://fixture.example.test/"] = FakeResponse("http://fixture.example.test/", 200, {})+ web(routes)+ report = tc.run("https://fixture.example.test/", now=NOW)++ assert list(report) == ["url", "host", "tls", "headers", "redirects", "findings", "summary"]+ assert report["findings"], "expected findings"+ order = [tc.SEVERITIES.index(f["severity"]) for f in report["findings"]]+ assert order == sorted(order)+ for finding in report["findings"]:+ assert list(finding) == ["id", "severity", "message", "evidence"]+ assert re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", finding["id"])+ assert finding["severity"] in tc.SEVERITIES+ assert finding["message"].endswith(".") and finding["message"].count(". ") == 0+ assert isinstance(finding["evidence"], dict)+ assert len(set(ids(report))) == len(report["findings"])+ assert sum(report["summary"].values()) == len(report["findings"])+ assert report["summary"]["critical"] == 1+ found = by_id(report)+ assert found["tls-cert-expired"]["severity"] == "Critical"+ assert found["http-no-https-redirect"]["severity"] == "High"+ assert found["hsts-missing"]["severity"] == "Medium"+ json.dumps(report) # serializable as is+++def test_scheme_is_optional_on_the_command_line(net, public, web, capsys) -> None:+ good_tls(net)+ web(site())+ assert tc.main(["example.com", "--timeout", "500", "--json"]) == 0+ report = json.loads(capsys.readouterr().out)+ assert report["url"] == "https://example.com"+ assert net.connects == [((PUBLIC_IP, 443), 60.0)] # timeout is capped+++def test_docstring_does_not_overclaim_ranking_impact() -> None:+ doc = " ".join(tc.__doc__.split())+ assert "not a confirmed Google ranking signal" in doc+ assert "lightweight ranking signal" in doc