Coverage for app / knowledge / favicon.py: 93%

95 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2A site's icon, fetched on the platform's behalf rather than the user's. 

3 

4fe-core used to load citation icons from ``google.com/s2/favicons?domain=…``, 

5which told Google every domain a user looked at a citation for. Icons are now 

6fetched here — once per domain, cached by svc-core — so neither Google nor the 

7cited site learns who is reading what. 

8 

9Everything goes through ``UrlFetcher``: https only, every redirect hop 

10re-resolved to a public address, a byte cap. The icon itself is identified by 

11its **bytes**, not its declared content type, and only raster formats are 

12accepted. SVG is refused outright: it can carry script, and an icon has no 

13need of it. 

14""" 

15 

16from __future__ import annotations 

17 

18import base64 

19import logging 

20import re 

21import urllib.parse 

22from dataclasses import dataclass 

23from html.parser import HTMLParser 

24from typing import Literal 

25 

26from app.common.settings import get_settings 

27from app.tools.web.fetch import FetchError, UnsafeUrlError, UrlFetcher 

28from app.tools.web.policy import DomainPolicy 

29from app.util.document_images import sniff 

30 

31logger = logging.getLogger(__name__) 

32 

33#: An icon larger than this is not an icon. 

34MAX_ICON_BYTES = 100 * 1024 

35#: Enough of a home page to find its ``<link rel="icon">`` in ``<head>``. 

36MAX_HOME_BYTES = 512 * 1024 

37_TIMEOUT_S = 6.0 

38 

39_DOMAIN = re.compile( 

40 r"^(?=.{4,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$" 

41) 

42 

43IconStatus = Literal["ok", "missing", "unsafe", "invalid"] 

44 

45 

46@dataclass 

47class IconResult: 

48 status: IconStatus 

49 content_type: str | None = None 

50 data_b64: str | None = None 

51 source_url: str | None = None 

52 error: str | None = None 

53 

54 

55def valid_domain(domain: str) -> bool: 

56 """A bare public host name: no scheme, port, path, credentials or IP.""" 

57 return bool(_DOMAIN.match(domain or "")) 

58 

59 

60#: The raster type a body is, from its bytes — or None. Shared with the 

61#: images documents carry (``app/util/document_images.py``). 

62sniff_image = sniff 

63 

64 

65class _IconLinks(HTMLParser): 

66 def __init__(self) -> None: 

67 super().__init__() 

68 self.candidates: list[tuple[int, str]] = [] 

69 

70 def handle_starttag(self, tag: str, attrs: list) -> None: # type: ignore[override] 

71 if tag != "link": 

72 return 

73 attributes = {k: (v or "") for k, v in attrs} 

74 rel = attributes.get("rel", "").lower().split() 

75 href = attributes.get("href", "").strip() 

76 if not href or "icon" not in " ".join(rel): 

77 return 

78 kind = attributes.get("type", "").lower() 

79 if "svg" in kind or href.lower().split("?")[0].endswith(".svg"): 

80 return # never used; skip the round trip 

81 sizes = attributes.get("sizes", "").lower() 

82 # Prefer a small PNG; a 180px apple-touch icon is a fine fallback. 

83 score = 0 

84 if "png" in kind or href.lower().split("?")[0].endswith(".png"): 

85 score += 2 

86 if re.search(r"\b(16|32|48|64)x", sizes): 

87 score += 2 

88 if "apple-touch-icon" in rel: 

89 score -= 1 

90 self.candidates.append((score, href)) 

91 

92 

93def icon_candidates(html: str, base_url: str) -> list[str]: 

94 """Icon URLs a home page declares, best first, then ``/favicon.ico``.""" 

95 parser = _IconLinks() 

96 try: 

97 parser.feed(html) 

98 except Exception: # noqa: BLE001 — malformed markup: keep what parsed 

99 pass 

100 ordered = [href for _, href in sorted(parser.candidates, key=lambda c: -c[0])] 

101 urls: list[str] = [] 

102 for href in ordered + ["/favicon.ico"]: 

103 url = urllib.parse.urljoin(base_url, href) 

104 if url.startswith("https://") and url not in urls: 

105 urls.append(url) 

106 return urls[:4] 

107 

108 

109def _fetcher(max_bytes: int) -> UrlFetcher: 

110 settings = get_settings() 

111 policy = DomainPolicy(allowed_domains=[], blocked_domains=[], require_https=True) 

112 return UrlFetcher( 

113 policy, 

114 max_bytes=max_bytes, 

115 user_agent=settings.url_fetch_user_agent, 

116 timeout_s=_TIMEOUT_S, 

117 ) 

118 

119 

120async def fetch_icon( 

121 domain: str, 

122 *, 

123 home_fetcher: UrlFetcher | None = None, 

124 icon_fetcher: UrlFetcher | None = None, 

125) -> IconResult: 

126 """Find and fetch ``domain``'s icon. Never raises.""" 

127 domain = (domain or "").strip().lower() 

128 if not valid_domain(domain): 

129 return IconResult("invalid", error="not a public host name") 

130 home_fetcher = home_fetcher or _fetcher(MAX_HOME_BYTES) 

131 icon_fetcher = icon_fetcher or _fetcher(MAX_ICON_BYTES) 

132 home = f"https://{domain}/" 

133 

134 candidates = [f"{home}favicon.ico"] 

135 try: 

136 page = await home_fetcher.fetch(home) 

137 candidates = icon_candidates( 

138 page.body.decode(page.encoding or "utf-8", errors="replace"), page.url 

139 ) 

140 except UnsafeUrlError as exc: 

141 return IconResult("unsafe", error=str(exc)) 

142 except (FetchError, Exception) as exc: # noqa: BLE001 — try /favicon.ico anyway 

143 logger.debug("[favicon] home page of %s unavailable: %s", domain, exc) 

144 

145 for url in candidates: 

146 try: 

147 res = await icon_fetcher.fetch(url) 

148 except UnsafeUrlError: 

149 continue 

150 except Exception: # noqa: BLE001 — next candidate 

151 continue 

152 content_type = sniff_image(res.body) 

153 if content_type: 

154 return IconResult( 

155 "ok", 

156 content_type=content_type, 

157 data_b64=base64.b64encode(res.body).decode("ascii"), 

158 source_url=res.url, 

159 ) 

160 return IconResult("missing")