Coverage for lode / reader / loader.py: 91%

104 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-22 15:54 +0000

1"""Loading and validation of one RDF document, from a local file or from a URL. 

2 

3Every security check on remote content (SSRF, size, text-only, XXE) runs here, 

4before the RDF parser sees any byte. The functions keep no state: naming the artefact 

5and loading the documents it imports belong to lode.reader.pipeline. 

6""" 

7import os 

8from typing import Optional 

9from urllib.parse import urlparse, urljoin 

10 

11import requests 

12from rdflib import Graph 

13 

14from lode import security 

15from lode.exceptions import (ArtefactLoadError, ArtefactNotFoundError, 

16 ArtefactUnavailableError, ArtefactValidationError) 

17from lode.helpers.rdf import PARSE_FORMATS, parse_any 

18 

19 

20# ========================================================================== 

21# 1. ENTRY POINT 

22# ========================================================================== 

23def load_document(source: str) -> Graph: 

24 """Load one RDF document from a local file or an http(s) URL and return its graph. 

25 

26 A URL goes through content negotiation and every security check. A value carrying 

27 another scheme (file:, ftp:, ...) is refused: it must not be silently treated as a 

28 local path, while bare local paths (no scheme) stay allowed for the CLI. Raises 

29 ArtefactLoadError when the document parses to an empty graph. 

30 """ 

31 if _is_url(source): 

32 graph = _load_from_url_with_content_negotiation(source) 

33 

34 elif os.path.isfile(source): 

35 graph = _load_from_local_file(source) 

36 else: 

37 # A value carrying a URL scheme that is not http(s) (file:, ftp:, ...) 

38 # must not be silently treated as a local path. Bare local paths 

39 # (no scheme) are still allowed here for the CLI. 

40 scheme = urlparse(source).scheme 

41 if scheme: 

42 raise ArtefactValidationError( 

43 "URL scheme not allowed; use http(s)://host", 

44 context={"scheme": scheme}, 

45 ) 

46 graph = _load_from_local_file(source) 

47 

48 if len(graph) == 0: 

49 raise ArtefactLoadError( 

50 "Parsed graph is empty (wrong URL or not an RDF resource)", 

51 context={"source": source} 

52 ) 

53 return graph 

54 

55 

56# ========================================================================== 

57# 2. URL 

58# ========================================================================== 

59def _load_from_url_with_content_negotiation(url: str) -> Graph: 

60 """RDF graph loading with content-negotiation for semantic artefact loaded from URL""" 

61 

62 security.check_url_safe(url) # SECURITY: url validation (anti-SSRF), before downlaod 

63 

64 headers = { 

65 "Accept": ( 

66 "text/turtle, application/rdf+xml, application/ld+json, " 

67 "application/n-triples, application/n-quads, */*;q=0.1" 

68 ), 

69 # Sent on every redirect hop too, since this dict is reused there. 

70 "User-Agent": security.USER_AGENT, 

71 } 

72 

73 response = None 

74 try: 

75 # SECURITY: fetch with per-hop URL validation (anti-SSRF); manual redirects, no auto-follow into unchecked hosts 

76 response = _fetch_following_redirects(url, headers) 

77 

78 # Error: Cannot Load RDF. A 5xx says the host is broken right now, 

79 # not that the artefact is missing: telling the two apart is the 

80 # difference between "check your URL" and "try again later". 

81 if response.status_code != 200: 

82 if response.status_code >= 500: 

83 raise ArtefactUnavailableError( 

84 "The remote server is not responding, please try again later", 

85 context={"url": url, "http_status": response.status_code} 

86 ) 

87 raise ArtefactNotFoundError( 

88 "Cannot load provided Semantic Artefact", 

89 context={"url": url, "http_status": response.status_code} 

90 ) 

91 

92 # Reject HTML/XHTML pages before downloading: servers answer with a 

93 # human-readable page when no RDF serialization is available. 

94 content_type = response.headers.get("Content-Type", "").lower() 

95 mime = content_type.split(";")[0].strip() 

96 if mime in ("text/html", "application/xhtml+xml"): 

97 response.close() 

98 raise ArtefactLoadError( 

99 "Resource is an HTML page, not an RDF serialization", 

100 context={"url": url, "content_type": mime}, 

101 ) 

102 

103 # SECURITY: reject by declared Content-Length before downloading the body 

104 declared = response.headers.get("Content-Length") 

105 if declared and declared.isdigit(): 

106 security.check_size(int(declared)) 

107 

108 # SECURITY: stop if file > 10MB even without Content-Length 

109 # bytearray: `bytes += chunk` copies the whole buffer each time (quadratic) 

110 buffer = bytearray() 

111 for chunk in response.iter_content(8192): # 8kb at the time in iteration 

112 buffer += chunk 

113 if len(buffer) > security.MAX_BYTES: 

114 security.check_size(len(buffer)) 

115 raw = bytes(buffer) 

116 

117 # SECURITY: checks the file is text not binary 

118 security.check_is_text(raw) 

119 

120 # Proceed with encoding 

121 content = raw.decode("utf-8") 

122 

123 # SECURITY: block XXE / entity-expansion on remote artefacts and owl:imports 

124 security.check_safe_xml(content) 

125 

126 # Format guessed from HTTP Content-Type (content negotiation handler) 

127 graph = parse_any(content, preferred=_guess_format_from_content_type(content_type)) 

128 if graph is None: 

129 raise ArtefactLoadError("Could not parse RDF after content negotiation", 

130 context={"url": url, "formats_tried": list(PARSE_FORMATS)}) 

131 return graph 

132 

133 # Error (Fallback): Cannot Load RDF 

134 except requests.RequestException as e: 

135 raise ArtefactNotFoundError( 

136 "Network error fetching artefact", 

137 context={"url": url, "original_error": str(e)} 

138 ) 

139 

140 

141def _fetch_following_redirects(url: str, headers: dict, max_redirects: int = security.MAX_REDIRECTS): 

142 """Follow URLs redirects manually, validating each hop via security.check_url_safe. Returns final response. 

143 

144 The default hop limit comes from security.MAX_REDIRECTS (env LODE_MAX_REDIRECTS).""" 

145 current = url 

146 for _ in range(max_redirects): 

147 security.check_url_safe(current) 

148 response = requests.get(current, headers=headers, timeout=10, 

149 stream=True, allow_redirects=False) 

150 # Validate the IP we ACTUALLY connected to, before reading anything: 

151 # defeats DNS rebinding between check_url_safe above and this connect. 

152 _verify_peer_ip(response) 

153 if response.status_code in (301, 302, 303, 307, 308): 

154 location = response.headers.get("Location") 

155 response.close() 

156 if not location: 

157 raise ArtefactLoadError("Redirect without Location", context={"url": current}) 

158 current = urljoin(current, location) 

159 continue 

160 return response 

161 raise ArtefactLoadError("Too many redirects", context={"url": url}) 

162 

163 

164def _verify_peer_ip(response) -> None: 

165 """Re-check the SSRF policy against the socket's real peer IP. If it 

166 cannot be determined (e.g. mocked in tests) fall back to the per-hop 

167 check_url_safe already done before connecting.""" 

168 ip = _peer_ip(response) 

169 if ip is None: 

170 return 

171 try: 

172 security.check_ip_safe(ip) 

173 except ArtefactValidationError: 

174 response.close() 

175 raise 

176 

177 

178def _peer_ip(response): 

179 """Best-effort extraction of the connected peer IP from a streamed 

180 requests response (reaches into urllib3 internals, hence defensive).""" 

181 try: 

182 return response.raw._connection.sock.getpeername()[0] 

183 except Exception: 

184 return None 

185 

186 

187# ========================================================================== 

188# 3. LOCAL FILE 

189# ========================================================================== 

190def _load_from_local_file(path: str) -> Graph: 

191 """Parse a local file, trying every known RDF format. 

192 

193 Raises ArtefactLoadError if no format can parse it. The caller is expected 

194 to have excluded URLs: this function opens `path` on the local disk. 

195 """ 

196 with open(path, "rb") as f: 

197 raw = f.read() 

198 graph = parse_any(raw) 

199 if graph is None: 

200 raise ArtefactLoadError("Could not parse RDF with any known format", 

201 context={"path": path, "formats_tried": list(PARSE_FORMATS)}) 

202 return graph 

203 

204 

205# ========================================================================== 

206# 4. HELPERS 

207# ========================================================================== 

208def _is_url(s: str) -> bool: 

209 """Return True only for http(s) URLs; other schemes are not treated as URLs.""" 

210 try: 

211 return urlparse(s).scheme in ("http", "https") 

212 except Exception: 

213 return False 

214 

215 

216def _guess_format_from_content_type(content_type: str) -> Optional[str]: 

217 """Map an HTTP Content-Type to an rdflib format name, or None when unknown. 

218 

219 The result is only a hint: parse_any still falls back to the other formats. 

220 """ 

221 if "text/turtle" in content_type or "application/x-turtle" in content_type: 

222 return "turtle" 

223 if "application/rdf+xml" in content_type: 

224 return "xml" 

225 if "application/ld+json" in content_type or "json" in content_type: 

226 return "json-ld" 

227 if "application/n-triples" in content_type: 

228 return "nt" 

229 return None