Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_configuration.py: 88%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

118 statements  

1"""Configuration value handling.""" 

2import dataclasses 

3import functools 

4import shutil 

5from collections.abc import Iterator 

6from contextlib import contextmanager 

7from contextvars import ContextVar 

8from typing import Any, Literal 

9 

10 

11@functools.cache 

12def _determine_jbig2dec_binary() -> str | None: 

13 """ 

14 Small utility function to determine the `jbig2dec` binary path only once. 

15 

16 Returns: 

17 The corresponding binary path if available. 

18 """ 

19 return shutil.which("jbig2dec") 

20 

21 

22@dataclasses.dataclass(frozen=True) 

23class Configuration: 

24 """ 

25 Configuration used while processing PDF files. 

26 

27 These limits mostly protect against excessive resource consumption caused by malformed or malicious PDF files. 

28 

29 .. note:: 

30 

31 Avoid relying on specific implementation details of this class. The main public API consists of the values 

32 being considered read-only for each instance with the overwrite method to create a new instance with the 

33 specified values changed. 

34 """ 

35 

36 maximum_declared_stream_length: int = 75_000_000 

37 """The maximum allowed declared ``/Length`` value for streams.""" 

38 array_based_stream_maximum_output_length: int = 75_000_000 

39 """The maximum allowed output length for array-based streams.""" 

40 array_maximum_element_count: int = 100_000 

41 """The maximum allowed number of elements inside an array.""" 

42 dictionary_maximum_element_count: int = 100_000 

43 """The maximum allowed number of key-value pairs inside a dictionary.""" 

44 

45 jbig2_maximum_output_length: int = 75_000_000 

46 """ 

47 The maximum allowed number of uncompressed bytes during decompression when using the ``/JBIG2Decode`` filter 

48 (JBIG2 images). 

49 """ 

50 lzw_maximum_output_length: int = 75_000_000 

51 """ 

52 The maximum allowed number of uncompressed bytes during decompression when using the ``/LZWDecode`` filter 

53 (LZW compression). 

54 """ 

55 run_length_maximum_output_length: int = 75_000_000 

56 """ 

57 The maximum allowed number of uncompressed bytes during decompression when using the ``/RunLengthDecode`` filter 

58 (run-length compression). 

59 """ 

60 zlib_maximum_output_length: int = 75_000_000 

61 """ 

62 The maximum allowed number of uncompressed bytes during decompression when using the ``/FlateDecode`` filter 

63 (zlib compression). 

64 """ 

65 zlib_maximum_recovery_input_length: int = 5_000_000 

66 """ 

67 The maximum allowed number of bytes to attempt the recovery with when using the ``/FlateDecode`` filter 

68 (zlib compression). 

69 """ 

70 brotli_maximum_output_length: int = 75_000_000 

71 """ 

72 The maximum allowed number of uncompressed bytes during decompression when using the ``/BrotliDecode`` filter 

73 (Brotli compression). 

74 """ 

75 

76 flate_maximum_columns: int = 250_000 

77 """The maximum allowed number of columns when using the ``/FlateDecode`` filter.""" 

78 flate_maximum_row_length: int = 4_000_000 

79 """The maximum allowed row length when using the ``/FlateDecode`` filter.""" 

80 

81 image_maximum_buffer_size: int = 75_000_000 

82 """The maximum allowed number of bytes to allocate for images.""" 

83 

84 stream_filters_maximum_length: int = 16 

85 """The maximum allowed number of filters per stream.""" 

86 stream_decoding_work_maximum_length: int = 300_000_000 

87 """The maximum allowed accumulated decoding work in bytes per stream.""" 

88 stream_parsing_work_maximum_count: int = 2_000_000 

89 """ 

90 The maximum parsing budget for a content stream, including operands, operators, and elements in 

91 nested arrays and dictionaries. 

92 """ 

93 

94 xmp_maximum_input_length: int = 5_000_000 

95 """The maximum allowed actual decompressed stream length in bytes for XMP data.""" 

96 xmp_maximum_element_count: int = 100_000 

97 """The maximum allowed number of elements for XMP data.""" 

98 

99 outline_maximum_entries: int = 100_000 

100 """The maximum allowed number of outline entries.""" 

101 outline_maximum_depth: int = 100 

102 """The maximum allowed depth for outline entries.""" 

103 

104 page_tree_maximum_entries: int = 100_000 

105 """The maximum allowed number of entries in the page tree.""" 

106 page_tree_maximum_depth: int = 100 

107 """The maximum allowed depth of the page tree.""" 

108 page_tree_maximum_page_entries: int = 2_000_000 

109 """ 

110 The maximum allowed total number of page dictionary entries copied while flattening the page tree. 

111 A page referenced multiple times is copied once per reference. 

112 """ 

113 

114 form_fields_maximum_entries: int = 100_000 

115 """The maximum allowed number of form fields.""" 

116 form_fields_maximum_depth: int = 100 

117 """The maximum allowed depth for form fields.""" 

118 

119 named_destinations_maximum_entries: int = 100_000 

120 """The maximum allowed number of named destination name tree nodes.""" 

121 named_destinations_maximum_depth: int = 100 

122 """The maximum allowed depth for a named destination name tree.""" 

123 

124 annotations_maximum_per_page: int = 100_000 

125 """ 

126 The maximum allowed number of annotations processed per page when merging 

127 or appending pages. 

128 """ 

129 

130 embedded_files_maximum_count: int = 1000 

131 """The maximum allowed number of embedded files.""" 

132 embedded_files_maximum_output_length: int = 250_000_000 

133 """The maximum allowed number of aggregated content bytes for the dictionary-based attachment API.""" 

134 

135 xform_maximum_invocations_per_extraction: int = 5_000 

136 """The maximum allowed number of ``/XObject`` forms per page during text extraction.""" 

137 

138 xfa_decoding_work_maximum_length: int = 300_000_000 

139 """The maximum allowed accumulated decoding work in bytes for the XFA form.""" 

140 

141 jbig2dec_binary: str | None = dataclasses.field(default_factory=_determine_jbig2dec_binary) 

142 """ 

143 The location of the ``jbig2dec`` binary. 

144 

145 This either is a string holding the path to the binary, or ``None`` if the binary could not be found 

146 or the binary should not be called. 

147 """ 

148 

149 page_merge_box: Literal["cropbox", "trimbox"] = "cropbox" # pypdf <= 3.4.0 used "trimbox" 

150 """The page box to use during merge.""" 

151 

152 disable_legacy_handling: bool = False 

153 """ 

154 Temporary configuration value for applications which do not rely on old overwrites and thus 

155 are able to skip legacy handling. 

156 

157 This disables looking for changes of the old constants during each initialization of the reader 

158 class. Please note that while this reduces the required overhead, it will disable all related 

159 deprecation warnings/errors. Setting this flag while legacy constants are intentionally being 

160 modified is unsupported/incorrect. 

161 

162 After the deprecation period, this configuration value will be removed with its own deprecation 

163 period as well. 

164 """ 

165 

166 def with_overwrites(self, **kwargs: Any) -> "Configuration": 

167 """ 

168 Creates a new configuration with the specified values overwritten. 

169 

170 Args: 

171 **kwargs: Configuration field names and their new values. 

172 

173 Returns: 

174 A new configuration with the specified values overwritten. 

175 """ 

176 return dataclasses.replace(self, **kwargs) 

177 

178 

179# A default configuration without any value changes. 

180DEFAULT_CONFIGURATION = Configuration() 

181 

182# The current configuration. 

183CURRENT_CONFIGURATION: ContextVar[Configuration] = ContextVar( 

184 "pypdf_configuration", 

185 default=DEFAULT_CONFIGURATION, 

186) 

187 

188 

189def get_configuration() -> Configuration: 

190 """ 

191 Get the current configuration. 

192 

193 Returns: 

194 The current configuration. 

195 """ 

196 return CURRENT_CONFIGURATION.get() 

197 

198 

199def _build_configuration( 

200 configuration: Configuration | None, 

201 overwrites: dict[str, Any], 

202) -> Configuration: 

203 """ 

204 Utility function to build a new configuration from the given values. 

205 

206 Args: 

207 configuration: A possible explicit configuration to use instead of the current configuration. 

208 overwrites: Entries to overwrite. 

209 

210 Returns: 

211 The generated configuration. 

212 """ 

213 base = configuration if configuration is not None else get_configuration() 

214 # TODO: Remove when releasing 8.0.0 

215 # if "disable_legacy_handling" in overwrites: 

216 # deprecate_no_replacement("disable_legacy_handling", "9.0.0") 

217 return base.with_overwrites(**overwrites) 

218 

219 

220def overwrite_configuration( 

221 configuration: Configuration | None = None, 

222 **overwrites: Any, 

223) -> Configuration: 

224 """ 

225 Overwrite the configuration for the current execution context. 

226 

227 Args: 

228 configuration: A direct configuration instance to use. 

229 **overwrites: Configuration parameters to overwrite in the current or given configuration. 

230 

231 Returns: 

232 The new configuration. 

233 """ 

234 new_configuration = _build_configuration(configuration, overwrites) 

235 CURRENT_CONFIGURATION.set(new_configuration) 

236 return new_configuration 

237 

238 

239@contextmanager 

240def apply_configuration( 

241 configuration: Configuration | None = None, 

242 **overwrites: Any, 

243) -> Iterator[Configuration]: 

244 """ 

245 Temporarily overwrite the configuration. 

246 

247 Args: 

248 configuration: A direct configuration instance to use. 

249 **overwrites: Configuration parameters to overwrite in the current or given configuration. 

250 

251 Returns: 

252 The new configuration. 

253 """ 

254 new_configuration = _build_configuration(configuration, overwrites) 

255 token = CURRENT_CONFIGURATION.set(new_configuration) 

256 try: 

257 yield new_configuration 

258 finally: 

259 CURRENT_CONFIGURATION.reset(token) 

260 

261 

262# Map the new field names to their legacy names. 

263LEGACY_NAME_MAPPING = { 

264 "maximum_declared_stream_length": "MAX_DECLARED_STREAM_LENGTH", 

265 "array_based_stream_maximum_output_length": "MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH", 

266 "jbig2_maximum_output_length": "JBIG2_MAX_OUTPUT_LENGTH", 

267 "lzw_maximum_output_length": "LZW_MAX_OUTPUT_LENGTH", 

268 "run_length_maximum_output_length": "RUN_LENGTH_MAX_OUTPUT_LENGTH", 

269 "zlib_maximum_output_length": "ZLIB_MAX_OUTPUT_LENGTH", 

270 "zlib_maximum_recovery_input_length": "ZLIB_MAX_RECOVERY_INPUT_LENGTH", 

271 "flate_maximum_columns": "FLATE_MAX_COLUMNS", 

272 "flate_maximum_row_length": "FLATE_MAX_ROW_LENGTH", 

273 "image_maximum_buffer_size": "FLATE_MAX_BUFFER_SIZE", 

274 "xmp_maximum_input_length": "XMP_MAX_INPUT_LENGTH", 

275 "xmp_maximum_element_count": "XMP_MAX_ELEMENT_COUNT", 

276 "jbig2dec_binary": "JBIG2DEC_BINARY", 

277 "page_merge_box": "MERGE_CROP_BOX", 

278} 

279 

280 

281def apply_legacy_configuration() -> Configuration: 

282 """ 

283 Overwrite the current configuration with the legacy configuration if it has been changed. 

284 

285 Returns: 

286 The new configuration which has been applied. 

287 """ 

288 configuration = get_configuration() 

289 if configuration.disable_legacy_handling: 

290 return configuration 

291 

292 from pypdf._page import MERGE_CROP_BOX # noqa: PLC0415 

293 from pypdf.filters import ( # noqa: PLC0415 

294 FLATE_MAX_BUFFER_SIZE, 

295 FLATE_MAX_COLUMNS, 

296 FLATE_MAX_ROW_LENGTH, 

297 JBIG2_MAX_OUTPUT_LENGTH, 

298 JBIG2DEC_BINARY, 

299 LZW_MAX_OUTPUT_LENGTH, 

300 MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH, 

301 MAX_DECLARED_STREAM_LENGTH, 

302 RUN_LENGTH_MAX_OUTPUT_LENGTH, 

303 ZLIB_MAX_OUTPUT_LENGTH, 

304 ZLIB_MAX_RECOVERY_INPUT_LENGTH, 

305 ) 

306 from pypdf.xmp import XMP_MAX_ELEMENT_COUNT, XMP_MAX_INPUT_LENGTH # noqa: PLC0415 

307 

308 legacy_values = { 

309 "MAX_DECLARED_STREAM_LENGTH": MAX_DECLARED_STREAM_LENGTH, 

310 "MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH": MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH, 

311 "JBIG2_MAX_OUTPUT_LENGTH": JBIG2_MAX_OUTPUT_LENGTH, 

312 "LZW_MAX_OUTPUT_LENGTH": LZW_MAX_OUTPUT_LENGTH, 

313 "RUN_LENGTH_MAX_OUTPUT_LENGTH": RUN_LENGTH_MAX_OUTPUT_LENGTH, 

314 "ZLIB_MAX_OUTPUT_LENGTH": ZLIB_MAX_OUTPUT_LENGTH, 

315 "ZLIB_MAX_RECOVERY_INPUT_LENGTH": ZLIB_MAX_RECOVERY_INPUT_LENGTH, 

316 "FLATE_MAX_COLUMNS": FLATE_MAX_COLUMNS, 

317 "FLATE_MAX_ROW_LENGTH": FLATE_MAX_ROW_LENGTH, 

318 "FLATE_MAX_BUFFER_SIZE": FLATE_MAX_BUFFER_SIZE, 

319 "XMP_MAX_INPUT_LENGTH": XMP_MAX_INPUT_LENGTH, 

320 "XMP_MAX_ELEMENT_COUNT": XMP_MAX_ELEMENT_COUNT, 

321 "JBIG2DEC_BINARY": JBIG2DEC_BINARY, 

322 "MERGE_CROP_BOX": MERGE_CROP_BOX, 

323 } 

324 

325 for field_name, legacy_name in LEGACY_NAME_MAPPING.items(): 

326 legacy_value = legacy_values[legacy_name] 

327 

328 if legacy_value != getattr(DEFAULT_CONFIGURATION, field_name): 

329 from pypdf._utils import deprecation_with_replacement # noqa: PLC0415 

330 

331 deprecation_with_replacement( 

332 old_name=legacy_name, 

333 new_name=f"Configuration.{field_name}", 

334 removed_in="7.0.0", 

335 ) 

336 

337 return configuration