flask-squeeze 3.3.1__tar.gz → 3.3.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/PKG-INFO +1 -1
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze/compress.py +7 -8
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze/debug.py +10 -7
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze/flask_squeeze.py +15 -39
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze/log.py +6 -4
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze/minify.py +8 -10
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze/models.py +2 -2
- flask_squeeze-3.3.2/flask_squeeze/utils.py +41 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze.egg-info/PKG-INFO +1 -1
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/pyproject.toml +39 -15
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/tests/test_flask_squeeze.py +63 -19
- flask_squeeze-3.3.1/flask_squeeze/utils.py +0 -12
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/LICENSE +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/README.md +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze/__init__.py +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze.egg-info/SOURCES.txt +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze.egg-info/dependency_links.txt +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze.egg-info/requires.txt +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/flask_squeeze.egg-info/top_level.txt +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.2}/setup.cfg +0 -0
|
@@ -25,14 +25,13 @@ def compress(
|
|
|
25
25
|
) -> CompressionResult:
|
|
26
26
|
t0 = time.perf_counter()
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
raise ValueError(f"Invalid encoding choice {encode_choice}")
|
|
28
|
+
compressors = {
|
|
29
|
+
Encoding.br: lambda d, q: brotli.compress(d, quality=q),
|
|
30
|
+
Encoding.deflate: lambda d, q: zlib.compress(d, level=q),
|
|
31
|
+
Encoding.gzip: lambda d, q: gzip.compress(d, compresslevel=q),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
compressed_data = compressors[encode_choice](data, quality)
|
|
36
35
|
|
|
37
36
|
return CompressionResult(
|
|
38
37
|
data=compressed_data,
|
|
@@ -1,10 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import functools
|
|
2
4
|
import time
|
|
3
|
-
from
|
|
4
|
-
from typing import Any, Dict, Tuple
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
5
6
|
|
|
6
7
|
from flask import Response, current_app
|
|
7
8
|
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
8
12
|
|
|
9
13
|
def _write_benchmark_debug_header(response: Response, header_name: str, t1: float, t2: float) -> None:
|
|
10
14
|
if current_app.config["SQUEEZE_ADD_DEBUG_HEADERS"]:
|
|
@@ -16,20 +20,19 @@ class add_debug_header: # noqa: N801
|
|
|
16
20
|
def __init__(self, header_name: str) -> None:
|
|
17
21
|
self.header_name = header_name
|
|
18
22
|
|
|
19
|
-
def get_response(self, args:
|
|
23
|
+
def get_response(self, args: tuple, kwargs: dict) -> Response:
|
|
20
24
|
for arg in args:
|
|
21
25
|
if isinstance(arg, Response):
|
|
22
26
|
return arg
|
|
23
27
|
for kwarg in kwargs.values():
|
|
24
28
|
if isinstance(kwarg, Response):
|
|
25
29
|
return kwarg
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
)
|
|
30
|
+
msg = "You can only deocrate a function with 'add_debug_header' that has a Response as an argument or kwarg."
|
|
31
|
+
raise ValueError(msg)
|
|
29
32
|
|
|
30
33
|
def __call__(self, method: Callable) -> Callable:
|
|
31
34
|
@functools.wraps(method)
|
|
32
|
-
def wrapper(*args: tuple, **kwargs:
|
|
35
|
+
def wrapper(*args: tuple, **kwargs: dict[str, Any]):
|
|
33
36
|
if not current_app.config["SQUEEZE_ADD_DEBUG_HEADERS"]:
|
|
34
37
|
return method(*args, **kwargs)
|
|
35
38
|
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import hashlib
|
|
2
|
-
from typing import Dict, Tuple, Union
|
|
3
4
|
|
|
4
5
|
from flask import Flask, Response, request
|
|
5
6
|
|
|
6
|
-
from flask_squeeze.utils import add_breach_exploit_protection_header
|
|
7
|
+
from flask_squeeze.utils import add_breach_exploit_protection_header, update_response_headers
|
|
7
8
|
|
|
8
9
|
from .compress import compress, update_response_with_compressed_data
|
|
9
10
|
from .debug import add_debug_header
|
|
@@ -22,10 +23,10 @@ class Squeeze:
|
|
|
22
23
|
__slots__ = "app", "cache_static"
|
|
23
24
|
app: Flask
|
|
24
25
|
|
|
25
|
-
cache_static:
|
|
26
|
+
cache_static: dict[tuple[str, str], tuple[str, bytes]]
|
|
26
27
|
""" (request.path, encoding) -> (original file sha256 hash, compressed bytes) """
|
|
27
28
|
|
|
28
|
-
def __init__(self, app:
|
|
29
|
+
def __init__(self, app: Flask | None = None) -> None:
|
|
29
30
|
"""Initialize Flask-Squeeze with or without app."""
|
|
30
31
|
self.cache_static = {}
|
|
31
32
|
if app is None:
|
|
@@ -75,47 +76,20 @@ class Squeeze:
|
|
|
75
76
|
(Encoding.gzip, ResourceType.dynamic): "SQUEEZE_LEVEL_GZIP_DYNAMIC",
|
|
76
77
|
}
|
|
77
78
|
|
|
78
|
-
|
|
79
|
-
msg = f"Invalid encoding choice {encode_choice} for {resource_type} resource at {request.path}"
|
|
80
|
-
raise ValueError(msg)
|
|
79
|
+
option = options[(encode_choice, resource_type)]
|
|
81
80
|
|
|
82
81
|
return self.app.config[option]
|
|
83
82
|
|
|
84
|
-
def recompute_headers(
|
|
85
|
-
self,
|
|
86
|
-
response: Response,
|
|
87
|
-
original_content_length: int,
|
|
88
|
-
encode_choice: Union[Encoding, None],
|
|
89
|
-
) -> None:
|
|
90
|
-
"""
|
|
91
|
-
Set the Content-Length header if it has changed.
|
|
92
|
-
Set the Content-Encoding header if compressed data is served.
|
|
93
|
-
"""
|
|
94
|
-
if response.direct_passthrough:
|
|
95
|
-
return
|
|
96
|
-
|
|
97
|
-
if encode_choice is not None:
|
|
98
|
-
response.headers["Content-Encoding"] = encode_choice.value
|
|
99
|
-
vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
|
|
100
|
-
vary.add("Accept-Encoding")
|
|
101
|
-
vary.discard("")
|
|
102
|
-
response.headers["Vary"] = ",".join(vary)
|
|
103
|
-
|
|
104
|
-
if original_content_length != response.content_length:
|
|
105
|
-
response.headers["Content-Length"] = response.content_length
|
|
106
|
-
response.headers["X-Uncompressed-Content-Length"] = original_content_length
|
|
107
|
-
|
|
108
83
|
####################################################################################
|
|
109
84
|
#### MARK: Dynamic
|
|
110
85
|
|
|
111
86
|
def run_dynamic(
|
|
112
87
|
self,
|
|
113
88
|
response: Response,
|
|
114
|
-
encode_choice:
|
|
115
|
-
minify_choice:
|
|
89
|
+
encode_choice: Encoding | None,
|
|
90
|
+
minify_choice: Minification | None,
|
|
116
91
|
) -> None:
|
|
117
|
-
|
|
118
|
-
return # Early exit if no compression or minification is requested
|
|
92
|
+
assert encode_choice or minify_choice
|
|
119
93
|
|
|
120
94
|
response.direct_passthrough = False
|
|
121
95
|
|
|
@@ -142,8 +116,8 @@ class Squeeze:
|
|
|
142
116
|
def run_static(
|
|
143
117
|
self,
|
|
144
118
|
response: Response,
|
|
145
|
-
encode_choice:
|
|
146
|
-
minify_choice:
|
|
119
|
+
encode_choice: Encoding | None,
|
|
120
|
+
minify_choice: Minification | None,
|
|
147
121
|
) -> None:
|
|
148
122
|
response.direct_passthrough = False # Ensure we can read the data
|
|
149
123
|
|
|
@@ -221,7 +195,7 @@ class Squeeze:
|
|
|
221
195
|
log(1, "Response status code or content length is None. RETURN")
|
|
222
196
|
return response
|
|
223
197
|
|
|
224
|
-
if response.status_code
|
|
198
|
+
if response.status_code not in range(200, 300):
|
|
225
199
|
log(1, "Response status code is not ok. RETURN")
|
|
226
200
|
return response
|
|
227
201
|
|
|
@@ -250,6 +224,8 @@ class Squeeze:
|
|
|
250
224
|
log(1, "No compression or minification requested. RETURN")
|
|
251
225
|
return response
|
|
252
226
|
|
|
227
|
+
# At least one of minify or compress is requested
|
|
228
|
+
|
|
253
229
|
original_content_length = response.content_length
|
|
254
230
|
|
|
255
231
|
if request.path.startswith("/static/"):
|
|
@@ -257,6 +233,6 @@ class Squeeze:
|
|
|
257
233
|
else:
|
|
258
234
|
self.run_dynamic(response, encode_choice, minify_choice)
|
|
259
235
|
|
|
260
|
-
|
|
236
|
+
update_response_headers(response, original_content_length, encode_choice)
|
|
261
237
|
log(1, f"Static cache: {self.cache_static.keys()}")
|
|
262
238
|
return response
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import functools
|
|
2
4
|
import time
|
|
3
|
-
from typing import Any, Callable,
|
|
5
|
+
from typing import Any, Callable, Union
|
|
4
6
|
|
|
5
7
|
from flask import Request, current_app, request
|
|
6
8
|
|
|
@@ -35,8 +37,8 @@ class d_log: # noqa: N801
|
|
|
35
37
|
def __init__(
|
|
36
38
|
self,
|
|
37
39
|
level: int = 0,
|
|
38
|
-
with_args: Union[
|
|
39
|
-
with_kwargs: Union[
|
|
40
|
+
with_args: Union[list, None] = None,
|
|
41
|
+
with_kwargs: Union[list, None] = None,
|
|
40
42
|
) -> None:
|
|
41
43
|
self.level = level
|
|
42
44
|
self.with_args = with_args if with_args is not None else []
|
|
@@ -44,7 +46,7 @@ class d_log: # noqa: N801
|
|
|
44
46
|
|
|
45
47
|
def __call__(self, method: Callable) -> Callable:
|
|
46
48
|
@functools.wraps(method)
|
|
47
|
-
def wrapper(*args: tuple, **kwargs:
|
|
49
|
+
def wrapper(*args: tuple, **kwargs: dict[str, Any]):
|
|
48
50
|
if not current_app.config["SQUEEZE_VERBOSE_LOGGING"]:
|
|
49
51
|
return method(*args, **kwargs)
|
|
50
52
|
|
|
@@ -3,7 +3,7 @@ from dataclasses import dataclass
|
|
|
3
3
|
|
|
4
4
|
import rcssmin
|
|
5
5
|
import rjsmin
|
|
6
|
-
from flask import Response
|
|
6
|
+
from flask import Response
|
|
7
7
|
|
|
8
8
|
from flask_squeeze.models import Minification
|
|
9
9
|
|
|
@@ -79,15 +79,13 @@ def minify(data: bytes, minify_choice: Minification) -> MinificationResult:
|
|
|
79
79
|
|
|
80
80
|
t0 = time.perf_counter()
|
|
81
81
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
raise ValueError(f"Invalid minify choice {minify_choice} at {request.path}")
|
|
90
|
-
minified = minified.encode("utf-8")
|
|
82
|
+
minifiers = {
|
|
83
|
+
Minification.html: lambda d: minify_html(d),
|
|
84
|
+
Minification.css: lambda d: minify_css(d),
|
|
85
|
+
Minification.js: lambda d: minify_js(d),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
minified = minifiers[minify_choice](data.decode("utf-8")).encode("utf-8")
|
|
91
89
|
|
|
92
90
|
return MinificationResult(
|
|
93
91
|
data=minified,
|
|
@@ -34,7 +34,7 @@ def choose_encoding_from_headers_and_config(
|
|
|
34
34
|
If the client does not accept any of these encodings, or if the config
|
|
35
35
|
variable SQUEEZE_COMPRESS is False, return None.
|
|
36
36
|
"""
|
|
37
|
-
if not config.get("SQUEEZE_COMPRESS")
|
|
37
|
+
if not config.get("SQUEEZE_COMPRESS"):
|
|
38
38
|
return None
|
|
39
39
|
encoding = headers.get("Accept-Encoding", "").lower()
|
|
40
40
|
if "br" in encoding:
|
|
@@ -59,7 +59,7 @@ def choose_minification_from_mimetype_and_config(
|
|
|
59
59
|
"""
|
|
60
60
|
if mimetype is None:
|
|
61
61
|
return None
|
|
62
|
-
is_js_or_json = mimetype.endswith("javascript"
|
|
62
|
+
is_js_or_json = mimetype.endswith(("javascript", "json"))
|
|
63
63
|
if is_js_or_json and config.get("SQUEEZE_MINIFY_JS"):
|
|
64
64
|
return Minification.js
|
|
65
65
|
if mimetype.endswith("css") and config.get("SQUEEZE_MINIFY_CSS"):
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from flask import Response
|
|
8
|
+
|
|
9
|
+
from flask_squeeze.models import Encoding
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def add_breach_exploit_protection_header(response: Response) -> None:
|
|
13
|
+
"""
|
|
14
|
+
Protect against BREACH attack by adding random padding to the response.
|
|
15
|
+
"""
|
|
16
|
+
padding_length = secrets.randbelow(128) + 1
|
|
17
|
+
rand_str = secrets.token_urlsafe(padding_length)
|
|
18
|
+
response.headers["X-Breach-Exploit-Protection-Padding"] = rand_str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def update_response_headers(
|
|
22
|
+
response: Response,
|
|
23
|
+
original_content_length: int,
|
|
24
|
+
encode_choice: Encoding | None,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Set the Content-Length header if it has changed.
|
|
28
|
+
Set the Content-Encoding header if compressed data is served.
|
|
29
|
+
"""
|
|
30
|
+
assert not response.direct_passthrough # At least one of minify or compress was run
|
|
31
|
+
|
|
32
|
+
if encode_choice is not None:
|
|
33
|
+
response.headers["Content-Encoding"] = encode_choice.value
|
|
34
|
+
vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
|
|
35
|
+
vary.add("Accept-Encoding")
|
|
36
|
+
vary.discard("")
|
|
37
|
+
response.headers["Vary"] = ",".join(vary)
|
|
38
|
+
|
|
39
|
+
if original_content_length != response.content_length:
|
|
40
|
+
response.headers["Content-Length"] = response.content_length
|
|
41
|
+
response.headers["X-Uncompressed-Content-Length"] = original_content_length
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "flask-squeeze"
|
|
3
|
-
version = "3.3.
|
|
3
|
+
version = "3.3.2"
|
|
4
4
|
description = "Compress and minify Flask responses!"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
authors = [{ name = "Marcel Kröker", email = "kroeker.marcel@gmail.com" }]
|
|
@@ -14,6 +14,12 @@ classifiers=[
|
|
|
14
14
|
"Topic :: Software Development :: Libraries :: Python Modules"
|
|
15
15
|
]
|
|
16
16
|
requires-python = ">=3.8, <3.14"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
########################################################################################
|
|
20
|
+
#### MARK: Dependencies
|
|
21
|
+
|
|
22
|
+
|
|
17
23
|
dependencies = [
|
|
18
24
|
"flask>=1",
|
|
19
25
|
"brotli~=1.1",
|
|
@@ -25,9 +31,14 @@ dependencies = [
|
|
|
25
31
|
[dependency-groups]
|
|
26
32
|
dev = [
|
|
27
33
|
"pytest-cov ~= 4.0.0",
|
|
34
|
+
"ruff>=0.9.3",
|
|
28
35
|
]
|
|
29
36
|
|
|
30
37
|
|
|
38
|
+
########################################################################################
|
|
39
|
+
#### MARK: Packaging
|
|
40
|
+
|
|
41
|
+
|
|
31
42
|
[tool.setuptools]
|
|
32
43
|
packages = ["flask_squeeze"]
|
|
33
44
|
license-files = [] # Workaround for https://github.com/astral-sh/uv/issues/9513
|
|
@@ -37,32 +48,45 @@ license-files = [] # Workaround for https://github.com/astral-sh/uv/issues/9513
|
|
|
37
48
|
package = true
|
|
38
49
|
|
|
39
50
|
|
|
51
|
+
########################################################################################
|
|
52
|
+
#### MARK: Ruff
|
|
53
|
+
|
|
54
|
+
|
|
40
55
|
[tool.ruff]
|
|
41
56
|
show-fixes = true
|
|
42
57
|
line-length = 120
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"E", # style errors
|
|
48
|
-
"F", # flakes
|
|
49
|
-
"I", # import sorting
|
|
50
|
-
"M", # meta
|
|
51
|
-
"N", # naming
|
|
52
|
-
"U", # upgrade
|
|
53
|
-
"W", # style warnings
|
|
54
|
-
"YTT", # sys.version
|
|
55
|
-
]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint]
|
|
61
|
+
select = ["ALL"]
|
|
56
62
|
ignore = [
|
|
57
|
-
"ANN101", # missing type annotation for self
|
|
58
63
|
"ANN202", # Missing return type annotation for private function
|
|
59
64
|
"E501", # line length
|
|
60
65
|
"UP006", # use Dict (not possible in python 3.8)
|
|
61
66
|
"UP007", # use X | Y for union (not possible in python 3.8)
|
|
62
67
|
"UP035", # use typing Dict and List (not possible in python 3.8)
|
|
63
68
|
"W191", # indentation contains tabs
|
|
69
|
+
"S101", # Use of `assert` detected
|
|
70
|
+
"ERA001", # Found commented-out code
|
|
71
|
+
"D", # docstrings
|
|
72
|
+
"T201", # `print` found
|
|
73
|
+
"FBT001", # Boolean-typed positional argument in function definition
|
|
74
|
+
"INP001", # File is part of an implicit namespace package. Add an `__init__.py`.
|
|
75
|
+
"FIX002", # Line contains TODO, consider resolving the issue
|
|
76
|
+
"TD002", # Missing author in TODO; try: `# TODO(<author_name>): ...`
|
|
77
|
+
"TD003", # Missing issue link on the line following this TODO
|
|
64
78
|
]
|
|
65
79
|
|
|
80
|
+
|
|
66
81
|
[tool.ruff.format]
|
|
67
82
|
indent-style = "tab"
|
|
68
83
|
quote-style = "double"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
########################################################################################
|
|
87
|
+
#### MARK: Testing
|
|
88
|
+
|
|
89
|
+
[tool.coverage.report]
|
|
90
|
+
exclude_also = [
|
|
91
|
+
"if TYPE_CHECKING:",
|
|
92
|
+
]
|
|
@@ -1,17 +1,20 @@
|
|
|
1
|
-
import os
|
|
2
1
|
import tempfile
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any, Generator
|
|
3
4
|
|
|
4
5
|
import pytest
|
|
5
6
|
from flask.testing import FlaskClient
|
|
6
7
|
from test_app import create_app
|
|
7
8
|
from werkzeug.wrappers import Response
|
|
8
9
|
|
|
10
|
+
STATUS_CODE_NOT_FOUND_404 = 404
|
|
11
|
+
|
|
9
12
|
########################################################################################
|
|
10
13
|
#### MARK: Fixtures
|
|
11
14
|
|
|
12
15
|
|
|
13
16
|
@pytest.fixture
|
|
14
|
-
def client():
|
|
17
|
+
def client() -> Generator[FlaskClient, Any, None]:
|
|
15
18
|
app = create_app()
|
|
16
19
|
app.testing = True
|
|
17
20
|
with app.test_client() as test_client:
|
|
@@ -19,17 +22,17 @@ def client(): # noqa
|
|
|
19
22
|
|
|
20
23
|
|
|
21
24
|
@pytest.fixture(params=["", "gzip", "br", "deflate"])
|
|
22
|
-
def use_encoding(request):
|
|
25
|
+
def use_encoding(request: pytest.FixtureRequest) -> str:
|
|
23
26
|
return request.param
|
|
24
27
|
|
|
25
28
|
|
|
26
29
|
@pytest.fixture(params=[False, True])
|
|
27
|
-
def use_minify_js(request):
|
|
30
|
+
def use_minify_js(request: pytest.FixtureRequest) -> bool:
|
|
28
31
|
return request.param
|
|
29
32
|
|
|
30
33
|
|
|
31
34
|
@pytest.fixture(params=[False, True])
|
|
32
|
-
def use_minify_css(request):
|
|
35
|
+
def use_minify_css(request: pytest.FixtureRequest) -> bool:
|
|
33
36
|
return request.param
|
|
34
37
|
|
|
35
38
|
|
|
@@ -37,7 +40,7 @@ def use_minify_css(request):
|
|
|
37
40
|
#### MARK: Utilities
|
|
38
41
|
|
|
39
42
|
|
|
40
|
-
def almost_equal(a, b, percent=0.01):
|
|
43
|
+
def almost_equal(a: float, b: float, percent: float = 0.01) -> bool:
|
|
41
44
|
diff = abs(int(a) - int(b))
|
|
42
45
|
return diff < percent * int(a) and diff < percent * int(b)
|
|
43
46
|
|
|
@@ -54,7 +57,7 @@ def test_get_index(client: FlaskClient, use_encoding: str) -> None:
|
|
|
54
57
|
print("test_get_index")
|
|
55
58
|
r = client.get("/", headers={"Accept-Encoding": use_encoding})
|
|
56
59
|
assert content_length_correct(r)
|
|
57
|
-
length = r.headers.get("Content-Length")
|
|
60
|
+
length = int(r.headers.get("Content-Length", "0"))
|
|
58
61
|
encoding = r.headers.get("Content-Encoding", "")
|
|
59
62
|
|
|
60
63
|
assert use_encoding == encoding
|
|
@@ -74,7 +77,7 @@ def test_get_css_file(client: FlaskClient, use_encoding: str, use_minify_css: bo
|
|
|
74
77
|
client.application.config.update({"SQUEEZE_MINIFY_CSS": use_minify_css})
|
|
75
78
|
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": use_encoding})
|
|
76
79
|
assert content_length_correct(r)
|
|
77
|
-
response_length = r.headers.get("Content-Length")
|
|
80
|
+
response_length = int(r.headers.get("Content-Length", "0"))
|
|
78
81
|
encoding = r.headers.get("Content-Encoding", "")
|
|
79
82
|
|
|
80
83
|
assert use_encoding == encoding
|
|
@@ -119,7 +122,7 @@ def test_get_from_cache(client: FlaskClient, use_encoding: str) -> None:
|
|
|
119
122
|
|
|
120
123
|
def test_get_unknown_url(client: FlaskClient) -> None:
|
|
121
124
|
r = client.get("/static/unknown.js", headers={"Accept-Encoding": "gzip"})
|
|
122
|
-
assert r.status_code ==
|
|
125
|
+
assert r.status_code == STATUS_CODE_NOT_FOUND_404
|
|
123
126
|
|
|
124
127
|
|
|
125
128
|
def test_get_same_repeatedly(client: FlaskClient) -> None:
|
|
@@ -163,7 +166,11 @@ def test_disable_compression(client: FlaskClient) -> None:
|
|
|
163
166
|
def test_disable_minification(client: FlaskClient) -> None:
|
|
164
167
|
"""Test that minification can be disabled."""
|
|
165
168
|
client.application.config.update(
|
|
166
|
-
{
|
|
169
|
+
{
|
|
170
|
+
"SQUEEZE_MINIFY_JS": False,
|
|
171
|
+
"SQUEEZE_MINIFY_CSS": False,
|
|
172
|
+
"SQUEEZE_MINIFY_HTML": False,
|
|
173
|
+
},
|
|
167
174
|
)
|
|
168
175
|
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "gzip"})
|
|
169
176
|
assert "X-Flask-Squeeze-Minify-Duration" not in r.headers
|
|
@@ -205,35 +212,72 @@ def test_debug_headers_presence(client: FlaskClient) -> None:
|
|
|
205
212
|
assert "X-Flask-Squeeze-Compress-Duration" in r.headers or "X-Flask-Squeeze-Minify-Duration" in r.headers
|
|
206
213
|
|
|
207
214
|
|
|
208
|
-
def
|
|
215
|
+
def test_no_minify_no_compress(client: FlaskClient) -> None:
|
|
216
|
+
client.application.config.update(
|
|
217
|
+
{
|
|
218
|
+
"SQUEEZE_MINIFY_JS": False,
|
|
219
|
+
"SQUEEZE_MINIFY_CSS": False,
|
|
220
|
+
"SQUEEZE_MINIFY_HTML": False,
|
|
221
|
+
"SQUEEZE_COMPRESS": False,
|
|
222
|
+
},
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
# Static file with no minification or compression
|
|
226
|
+
|
|
227
|
+
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": "gzip"})
|
|
228
|
+
assert "Content-Encoding" not in r.headers
|
|
229
|
+
assert "X-Flask-Squeeze-Minify-Duration" not in r.headers
|
|
230
|
+
assert "X-Flask-Squeeze-Compression-Duration" not in r.headers
|
|
231
|
+
|
|
232
|
+
# Dynamic file with no minification or compression
|
|
233
|
+
|
|
234
|
+
r = client.get("/", headers={"Accept-Encoding": "gzip"})
|
|
235
|
+
assert "Content-Encoding" not in r.headers
|
|
236
|
+
assert "X-Flask-Squeeze-Minify-Duration" not in r.headers
|
|
237
|
+
assert "X-Flask-Squeeze-Compression-Duration" not in r.headers
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def test_static_file_cache_behavior(
|
|
241
|
+
client: FlaskClient,
|
|
242
|
+
use_encoding: str,
|
|
243
|
+
use_minify_css: bool,
|
|
244
|
+
) -> None:
|
|
209
245
|
"""Test cache behavior for a temporary static file."""
|
|
210
246
|
|
|
247
|
+
# Skip if encoding is not set
|
|
248
|
+
if not use_encoding:
|
|
249
|
+
return
|
|
250
|
+
|
|
251
|
+
client.application.config.update({"SQUEEZE_MINIFY_CSS": use_minify_css})
|
|
252
|
+
|
|
211
253
|
# Ensure the static directory is set
|
|
212
254
|
if (static_dir := client.application.static_folder) is None:
|
|
213
|
-
|
|
255
|
+
msg = "Static directory not found"
|
|
256
|
+
raise ValueError(msg)
|
|
214
257
|
|
|
215
258
|
# Use a temporary file within the static directory
|
|
216
|
-
with tempfile.NamedTemporaryFile(dir=static_dir, suffix=".
|
|
259
|
+
with tempfile.NamedTemporaryFile(dir=static_dir, suffix=".css", delete=True) as temp_file:
|
|
217
260
|
file_path = temp_file.name
|
|
218
|
-
|
|
261
|
+
url_path = "/static/" + Path(file_path).name
|
|
262
|
+
temp_file.write(b"body { color: #000; } " * 1000)
|
|
219
263
|
temp_file.flush() # Ensure content is written to disk
|
|
220
264
|
|
|
221
265
|
# First request: MISS
|
|
222
|
-
r = client.get(
|
|
266
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
223
267
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "MISS"
|
|
224
268
|
|
|
225
269
|
# Second request: HIT
|
|
226
|
-
r = client.get(
|
|
270
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
227
271
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "HIT"
|
|
228
272
|
|
|
229
273
|
# Modify the file content
|
|
230
|
-
temp_file.write(b"
|
|
274
|
+
temp_file.write(b"body { color: #123456; } " * 1000)
|
|
231
275
|
temp_file.flush() # Ensure the new content is written
|
|
232
276
|
|
|
233
277
|
# Third request: MISS
|
|
234
|
-
r = client.get(
|
|
278
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
235
279
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "MISS"
|
|
236
280
|
|
|
237
281
|
# Fourth request: HIT
|
|
238
|
-
r = client.get(
|
|
282
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
239
283
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "HIT"
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import secrets
|
|
2
|
-
|
|
3
|
-
from flask import Response
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
def add_breach_exploit_protection_header(response: Response) -> None:
|
|
7
|
-
"""
|
|
8
|
-
Protect against BREACH attack by adding random padding to the response.
|
|
9
|
-
"""
|
|
10
|
-
padding_length = secrets.randbelow(128) + 1
|
|
11
|
-
rand_str = secrets.token_urlsafe(padding_length)
|
|
12
|
-
response.headers["X-Breach-Exploit-Protection-Padding"] = rand_str
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|