| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import re |
| 5 |
import warnings |
| 6 |
from posixpath import normpath |
| 7 |
from typing import Callable |
| 8 |
from wsgiref.headers import Headers |
| 9 |
from wsgiref.util import FileWrapper |
| 10 |
|
| 11 |
from whitenoise.media_types import MediaTypes |
| 12 |
from whitenoise.responders import IsDirectoryError |
| 13 |
from whitenoise.responders import MissingFileError |
| 14 |
from whitenoise.responders import Redirect |
| 15 |
from whitenoise.responders import StaticFile |
| 16 |
from whitenoise.string_utils import decode_path_info |
| 17 |
from whitenoise.string_utils import ensure_leading_trailing_slash |
| 18 |
|
| 19 |
|
| 20 |
class WhiteNoise: |
| 21 |
# Ten years is what nginx sets a max age if you use 'expires max;' |
| 22 |
# so we'll follow its lead |
| 23 |
FOREVER = 10 * 365 * 24 * 60 * 60 |
| 24 |
|
| 25 |
def __init__( |
| 26 |
self, |
| 27 |
application, |
| 28 |
root=None, |
| 29 |
prefix=None, |
| 30 |
*, |
| 31 |
# Re-check the filesystem on every request so that any changes are |
| 32 |
# automatically picked up. NOTE: For use in development only, not supported |
| 33 |
# in production |
| 34 |
autorefresh: bool = False, |
| 35 |
max_age: int | None = 60, # seconds |
| 36 |
# Set 'Access-Control-Allow-Origin: *' header on all files. |
| 37 |
# As these are all public static files this is safe (See |
| 38 |
# https://www.w3.org/TR/cors/#security) and ensures that things (e.g |
| 39 |
# webfonts in Firefox) still work as expected when your static files are |
| 40 |
# served from a CDN, rather than your primary domain. |
| 41 |
allow_all_origins: bool = True, |
| 42 |
charset: str = "utf-8", |
| 43 |
mimetypes: dict[str, str] | None = None, |
| 44 |
add_headers_function: Callable[[Headers, str, str], None] | None = None, |
| 45 |
index_file: str | bool | None = None, |
| 46 |
immutable_file_test: Callable | str | None = None, |
| 47 |
): |
| 48 |
self.autorefresh = autorefresh |
| 49 |
self.max_age = max_age |
| 50 |
self.allow_all_origins = allow_all_origins |
| 51 |
self.charset = charset |
| 52 |
self.add_headers_function = add_headers_function |
| 53 |
if index_file is True: |
| 54 |
self.index_file: str | None = "index.html" |
| 55 |
elif isinstance(index_file, str): |
| 56 |
self.index_file = index_file |
| 57 |
else: |
| 58 |
self.index_file = None |
| 59 |
|
| 60 |
if immutable_file_test is not None: |
| 61 |
if not callable(immutable_file_test): |
| 62 |
regex = re.compile(immutable_file_test) |
| 63 |
self.immutable_file_test = lambda path, url: bool(regex.search(url)) |
| 64 |
else: |
| 65 |
self.immutable_file_test = immutable_file_test |
| 66 |
|
| 67 |
self.media_types = MediaTypes(extra_types=mimetypes) |
| 68 |
self.application = application |
| 69 |
self.files = {} |
| 70 |
self.directories = [] |
| 71 |
if root is not None: |
| 72 |
self.add_files(root, prefix) |
| 73 |
|
| 74 |
def __call__(self, environ, start_response): |
| 75 |
path = decode_path_info(environ.get("PATH_INFO", "")) |
| 76 |
if self.autorefresh: |
| 77 |
static_file = self.find_file(path) |
| 78 |
else: |
| 79 |
static_file = self.files.get(path) |
| 80 |
if static_file is None: |
| 81 |
return self.application(environ, start_response) |
| 82 |
else: |
| 83 |
return self.serve(static_file, environ, start_response) |
| 84 |
|
| 85 |
@staticmethod |
| 86 |
def serve(static_file, environ, start_response): |
| 87 |
response = static_file.get_response(environ["REQUEST_METHOD"], environ) |
| 88 |
status_line = f"{response.status} {response.status.phrase}" |
| 89 |
start_response(status_line, list(response.headers)) |
| 90 |
if response.file is not None: |
| 91 |
file_wrapper = environ.get("wsgi.file_wrapper", FileWrapper) |
| 92 |
return file_wrapper(response.file) |
| 93 |
else: |
| 94 |
return [] |
| 95 |
|
| 96 |
def add_files(self, root, prefix=None): |
| 97 |
root = os.path.abspath(root) |
| 98 |
root = root.rstrip(os.path.sep) + os.path.sep |
| 99 |
prefix = ensure_leading_trailing_slash(prefix) |
| 100 |
if self.autorefresh: |
| 101 |
# Later calls to `add_files` overwrite earlier ones, hence we need |
| 102 |
# to store the list of directories in reverse order so later ones |
| 103 |
# match first when they're checked in "autorefresh" mode |
| 104 |
self.directories.insert(0, (root, prefix)) |
| 105 |
else: |
| 106 |
if os.path.isdir(root): |
| 107 |
self.update_files_dictionary(root, prefix) |
| 108 |
else: |
| 109 |
warnings.warn(f"No directory at: {root}", stacklevel=3) |
| 110 |
|
| 111 |
def update_files_dictionary(self, root, prefix): |
| 112 |
# Build a mapping from paths to the results of `os.stat` calls |
| 113 |
# so we only have to touch the filesystem once |
| 114 |
stat_cache = dict(scantree(root)) |
| 115 |
for path in stat_cache.keys(): |
| 116 |
relative_path = path[len(root) :] |
| 117 |
relative_url = relative_path.replace("\\", "/") |
| 118 |
url = prefix + relative_url |
| 119 |
self.add_file_to_dictionary(url, path, stat_cache=stat_cache) |
| 120 |
|
| 121 |
def add_file_to_dictionary(self, url, path, stat_cache=None): |
| 122 |
if self.is_compressed_variant(path, stat_cache=stat_cache): |
| 123 |
return |
| 124 |
if self.index_file is not None and url.endswith("/" + self.index_file): |
| 125 |
index_url = url[: -len(self.index_file)] |
| 126 |
index_no_slash = index_url.rstrip("/") |
| 127 |
self.files[url] = self.redirect(url, index_url) |
| 128 |
self.files[index_no_slash] = self.redirect(index_no_slash, index_url) |
| 129 |
url = index_url |
| 130 |
static_file = self.get_static_file(path, url, stat_cache=stat_cache) |
| 131 |
self.files[url] = static_file |
| 132 |
|
| 133 |
def find_file(self, url): |
| 134 |
# Optimization: bail early if the URL can never match a file |
| 135 |
if self.index_file is None and url.endswith("/"): |
| 136 |
return |
| 137 |
if not self.url_is_canonical(url): |
| 138 |
return |
| 139 |
for path in self.candidate_paths_for_url(url): |
| 140 |
try: |
| 141 |
return self.find_file_at_path(path, url) |
| 142 |
except MissingFileError: |
| 143 |
pass |
| 144 |
|
| 145 |
def candidate_paths_for_url(self, url): |
| 146 |
for root, prefix in self.directories: |
| 147 |
if url.startswith(prefix): |
| 148 |
path = os.path.join(root, url[len(prefix) :]) |
| 149 |
if os.path.commonprefix((root, path)) == root: |
| 150 |
yield path |
| 151 |
|
| 152 |
def find_file_at_path(self, path, url): |
| 153 |
if self.is_compressed_variant(path): |
| 154 |
raise MissingFileError(path) |
| 155 |
|
| 156 |
if self.index_file is not None: |
| 157 |
if url.endswith("/"): |
| 158 |
path = os.path.join(path, self.index_file) |
| 159 |
return self.get_static_file(path, url) |
| 160 |
elif url.endswith("/" + self.index_file): |
| 161 |
if os.path.isfile(path): |
| 162 |
return self.redirect(url, url[: -len(self.index_file)]) |
| 163 |
else: |
| 164 |
try: |
| 165 |
return self.get_static_file(path, url) |
| 166 |
except IsDirectoryError: |
| 167 |
if os.path.isfile(os.path.join(path, self.index_file)): |
| 168 |
return self.redirect(url, url + "/") |
| 169 |
raise MissingFileError(path) |
| 170 |
|
| 171 |
return self.get_static_file(path, url) |
| 172 |
|
| 173 |
@staticmethod |
| 174 |
def url_is_canonical(url): |
| 175 |
""" |
| 176 |
Check that the URL path is in canonical format i.e. has normalised |
| 177 |
slashes and no path traversal elements |
| 178 |
""" |
| 179 |
if "\\" in url: |
| 180 |
return False |
| 181 |
normalised = normpath(url) |
| 182 |
if url.endswith("/") and url != "/": |
| 183 |
normalised += "/" |
| 184 |
return normalised == url |
| 185 |
|
| 186 |
@staticmethod |
| 187 |
def is_compressed_variant(path, stat_cache=None): |
| 188 |
if path[-3:] in (".gz", ".br"): |
| 189 |
uncompressed_path = path[:-3] |
| 190 |
if stat_cache is None: |
| 191 |
return os.path.isfile(uncompressed_path) |
| 192 |
else: |
| 193 |
return uncompressed_path in stat_cache |
| 194 |
return False |
| 195 |
|
| 196 |
def get_static_file(self, path, url, stat_cache=None): |
| 197 |
# Optimization: bail early if file does not exist |
| 198 |
if stat_cache is None and not os.path.exists(path): |
| 199 |
raise MissingFileError(path) |
| 200 |
headers = Headers([]) |
| 201 |
self.add_mime_headers(headers, path, url) |
| 202 |
self.add_cache_headers(headers, path, url) |
| 203 |
if self.allow_all_origins: |
| 204 |
headers["Access-Control-Allow-Origin"] = "*" |
| 205 |
if self.add_headers_function is not None: |
| 206 |
self.add_headers_function(headers, path, url) |
| 207 |
return StaticFile( |
| 208 |
path, |
| 209 |
headers.items(), |
| 210 |
stat_cache=stat_cache, |
| 211 |
encodings={"gzip": path + ".gz", "br": path + ".br"}, |
| 212 |
) |
| 213 |
|
| 214 |
def add_mime_headers(self, headers, path, url): |
| 215 |
media_type = self.media_types.get_type(path) |
| 216 |
if media_type.startswith("text/"): |
| 217 |
params = {"charset": str(self.charset)} |
| 218 |
else: |
| 219 |
params = {} |
| 220 |
headers.add_header("Content-Type", str(media_type), **params) |
| 221 |
|
| 222 |
def add_cache_headers(self, headers, path, url): |
| 223 |
if self.immutable_file_test(path, url): |
| 224 |
headers["Cache-Control"] = "max-age={}, public, immutable".format( |
| 225 |
self.FOREVER |
| 226 |
) |
| 227 |
elif self.max_age is not None: |
| 228 |
headers["Cache-Control"] = f"max-age={self.max_age}, public" |
| 229 |
|
| 230 |
def immutable_file_test(self, path, url): |
| 231 |
""" |
| 232 |
This should be implemented by sub-classes (see e.g. WhiteNoiseMiddleware) |
| 233 |
or by setting the `immutable_file_test` config option |
| 234 |
""" |
| 235 |
return False |
| 236 |
|
| 237 |
def redirect(self, from_url, to_url): |
| 238 |
""" |
| 239 |
Return a relative 302 redirect |
| 240 |
|
| 241 |
We use relative redirects as we don't know the absolute URL the app is |
| 242 |
being hosted under |
| 243 |
""" |
| 244 |
if to_url == from_url + "/": |
| 245 |
relative_url = from_url.split("/")[-1] + "/" |
| 246 |
elif from_url == to_url + self.index_file: |
| 247 |
relative_url = "./" |
| 248 |
else: |
| 249 |
raise ValueError(f"Cannot handle redirect: {from_url} > {to_url}") |
| 250 |
if self.max_age is not None: |
| 251 |
headers = {"Cache-Control": f"max-age={self.max_age}, public"} |
| 252 |
else: |
| 253 |
headers = {} |
| 254 |
return Redirect(relative_url, headers=headers) |
| 255 |
|
| 256 |
|
| 257 |
def scantree(root): |
| 258 |
""" |
| 259 |
Recurse the given directory yielding (pathname, os.stat(pathname)) pairs |
| 260 |
""" |
| 261 |
for entry in os.scandir(root): |
| 262 |
if entry.is_dir(): |
| 263 |
yield from scantree(entry.path) |
| 264 |
else: |
| 265 |
yield entry.path, entry.stat() |