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

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

106 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 xform_maximum_invocations_per_extraction: int = 5_000 

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

121 

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

123 """ 

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

125 

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

127 or the binary should not be called. 

128 """ 

129 

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

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

132 

133 disable_legacy_handling: bool = False 

134 """ 

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

136 are able to skip legacy handling. 

137 

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

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

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

141 modified is unsupported/incorrect. 

142 

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

144 period as well. 

145 """ 

146 

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

148 """ 

149 Creates a new configuration with the specified values overwritten. 

150 

151 Args: 

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

153 

154 Returns: 

155 A new configuration with the specified values overwritten. 

156 """ 

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

158 

159 

160# A default configuration without any value changes. 

161DEFAULT_CONFIGURATION = Configuration() 

162 

163# The current configuration. 

164CURRENT_CONFIGURATION: ContextVar[Configuration] = ContextVar( 

165 "pypdf_configuration", 

166 default=DEFAULT_CONFIGURATION, 

167) 

168 

169 

170def get_configuration() -> Configuration: 

171 """ 

172 Get the current configuration. 

173 

174 Returns: 

175 The current configuration. 

176 """ 

177 return CURRENT_CONFIGURATION.get() 

178 

179 

180def _build_configuration( 

181 configuration: Configuration | None, 

182 overwrites: dict[str, Any], 

183) -> Configuration: 

184 """ 

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

186 

187 Args: 

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

189 overwrites: Entries to overwrite. 

190 

191 Returns: 

192 The generated configuration. 

193 """ 

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

195 # TODO: Remove when releasing 8.0.0 

196 # if "disable_legacy_handling" in overwrites: 

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

198 return base.with_overwrites(**overwrites) 

199 

200 

201def overwrite_configuration( 

202 configuration: Configuration | None = None, 

203 **overwrites: Any, 

204) -> Configuration: 

205 """ 

206 Overwrite the configuration for the current execution context. 

207 

208 Args: 

209 configuration: A direct configuration instance to use. 

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

211 

212 Returns: 

213 The new configuration. 

214 """ 

215 new_configuration = _build_configuration(configuration, overwrites) 

216 CURRENT_CONFIGURATION.set(new_configuration) 

217 return new_configuration 

218 

219 

220@contextmanager 

221def apply_configuration( 

222 configuration: Configuration | None = None, 

223 **overwrites: Any, 

224) -> Iterator[Configuration]: 

225 """ 

226 Temporarily overwrite the configuration. 

227 

228 Args: 

229 configuration: A direct configuration instance to use. 

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

231 

232 Returns: 

233 The new configuration. 

234 """ 

235 new_configuration = _build_configuration(configuration, overwrites) 

236 token = CURRENT_CONFIGURATION.set(new_configuration) 

237 try: 

238 yield new_configuration 

239 finally: 

240 CURRENT_CONFIGURATION.reset(token) 

241 

242 

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

244LEGACY_NAME_MAPPING = { 

245 "maximum_declared_stream_length": "MAX_DECLARED_STREAM_LENGTH", 

246 "array_based_stream_maximum_output_length": "MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH", 

247 "jbig2_maximum_output_length": "JBIG2_MAX_OUTPUT_LENGTH", 

248 "lzw_maximum_output_length": "LZW_MAX_OUTPUT_LENGTH", 

249 "run_length_maximum_output_length": "RUN_LENGTH_MAX_OUTPUT_LENGTH", 

250 "zlib_maximum_output_length": "ZLIB_MAX_OUTPUT_LENGTH", 

251 "zlib_maximum_recovery_input_length": "ZLIB_MAX_RECOVERY_INPUT_LENGTH", 

252 "flate_maximum_columns": "FLATE_MAX_COLUMNS", 

253 "flate_maximum_row_length": "FLATE_MAX_ROW_LENGTH", 

254 "image_maximum_buffer_size": "FLATE_MAX_BUFFER_SIZE", 

255 "xmp_maximum_input_length": "XMP_MAX_INPUT_LENGTH", 

256 "xmp_maximum_element_count": "XMP_MAX_ELEMENT_COUNT", 

257 "jbig2dec_binary": "JBIG2DEC_BINARY", 

258 "page_merge_box": "MERGE_CROP_BOX", 

259} 

260 

261 

262def apply_legacy_configuration() -> Configuration: 

263 """ 

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

265 

266 Returns: 

267 The new configuration which has been applied. 

268 """ 

269 configuration = get_configuration() 

270 if configuration.disable_legacy_handling: 

271 return configuration 

272 

273 from pypdf._page import MERGE_CROP_BOX # noqa: PLC0415 

274 from pypdf.filters import ( # noqa: PLC0415 

275 FLATE_MAX_BUFFER_SIZE, 

276 FLATE_MAX_COLUMNS, 

277 FLATE_MAX_ROW_LENGTH, 

278 JBIG2_MAX_OUTPUT_LENGTH, 

279 JBIG2DEC_BINARY, 

280 LZW_MAX_OUTPUT_LENGTH, 

281 MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH, 

282 MAX_DECLARED_STREAM_LENGTH, 

283 RUN_LENGTH_MAX_OUTPUT_LENGTH, 

284 ZLIB_MAX_OUTPUT_LENGTH, 

285 ZLIB_MAX_RECOVERY_INPUT_LENGTH, 

286 ) 

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

288 

289 legacy_values = { 

290 "MAX_DECLARED_STREAM_LENGTH": MAX_DECLARED_STREAM_LENGTH, 

291 "MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH": MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH, 

292 "JBIG2_MAX_OUTPUT_LENGTH": JBIG2_MAX_OUTPUT_LENGTH, 

293 "LZW_MAX_OUTPUT_LENGTH": LZW_MAX_OUTPUT_LENGTH, 

294 "RUN_LENGTH_MAX_OUTPUT_LENGTH": RUN_LENGTH_MAX_OUTPUT_LENGTH, 

295 "ZLIB_MAX_OUTPUT_LENGTH": ZLIB_MAX_OUTPUT_LENGTH, 

296 "ZLIB_MAX_RECOVERY_INPUT_LENGTH": ZLIB_MAX_RECOVERY_INPUT_LENGTH, 

297 "FLATE_MAX_COLUMNS": FLATE_MAX_COLUMNS, 

298 "FLATE_MAX_ROW_LENGTH": FLATE_MAX_ROW_LENGTH, 

299 "FLATE_MAX_BUFFER_SIZE": FLATE_MAX_BUFFER_SIZE, 

300 "XMP_MAX_INPUT_LENGTH": XMP_MAX_INPUT_LENGTH, 

301 "XMP_MAX_ELEMENT_COUNT": XMP_MAX_ELEMENT_COUNT, 

302 "JBIG2DEC_BINARY": JBIG2DEC_BINARY, 

303 "MERGE_CROP_BOX": MERGE_CROP_BOX, 

304 } 

305 

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

307 legacy_value = legacy_values[legacy_name] 

308 

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

310 from pypdf._utils import deprecation_with_replacement # noqa: PLC0415 

311 

312 deprecation_with_replacement( 

313 old_name=legacy_name, 

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

315 removed_in="7.0.0", 

316 ) 

317 

318 return configuration