From da4f4fb417e50a844cc753d0c74d0dd3ba6951ce Mon Sep 17 00:00:00 2001 From: Daniel Alley Date: Mon, 14 Sep 2026 14:10:46 -0400 Subject: [PATCH 1/6] Stream proxied artifacts with bounded storage reads Serve proxied artifacts without buffering the remote files. django-storages buffers files to provide a seekable interface, but this is unnecessary for the streaming use case. Keep synchronous storage I/O off the content application event loop. closes #7806 Assisted By: Codex (GPT-5) Terra 5.6 --- CHANGES/7806.bugfix | 1 + .../functional/api/test_download_policies.py | 75 +++++++- pulpcore/app/storage_backends.py | 13 +- pulpcore/responses.py | 48 +++-- pulpcore/tests/unit/test_storage_streaming.py | 180 ++++++++++++++++++ pyproject.toml | 6 +- 6 files changed, 302 insertions(+), 21 deletions(-) create mode 100644 CHANGES/7806.bugfix create mode 100644 pulpcore/tests/unit/test_storage_streaming.py diff --git a/CHANGES/7806.bugfix b/CHANGES/7806.bugfix new file mode 100644 index 00000000000..357015a17cc --- /dev/null +++ b/CHANGES/7806.bugfix @@ -0,0 +1 @@ +Fixed proxying large S3 and Azure artifacts without buffering their complete contents. diff --git a/pulp_file/tests/functional/api/test_download_policies.py b/pulp_file/tests/functional/api/test_download_policies.py index 5568462d558..5cdc881df5b 100644 --- a/pulp_file/tests/functional/api/test_download_policies.py +++ b/pulp_file/tests/functional/api/test_download_policies.py @@ -7,10 +7,15 @@ from urllib.parse import urljoin import pytest +import requests from aiohttp.client_exceptions import ClientResponseError from bs4 import BeautifulSoup -from pulpcore.client.pulp_file import FileFilePublication, FileRepositorySyncURL +from pulpcore.client.pulp_file import ( + FileFilePublication, + FileRepositorySyncURL, + RepositoryAddRemoveContent, +) from pulpcore.tests.functional.utils import download_file, get_files_in_manifest OBJECT_STORAGES = ( @@ -37,6 +42,74 @@ def _do_range_request_download_and_assert(url, range_header, expected_bytes): ) +@pytest.mark.parametrize( + "storage_class", + ( + pytest.param("storages.backends.s3.S3Storage", id="s3"), + pytest.param("storages.backends.s3boto3.S3Boto3Storage", id="s3boto3"), + pytest.param("storages.backends.azure_storage.AzureStorage", id="azure"), + ), +) +def test_proxied_object_storage_artifact_streaming( + storage_class, + pulp_settings, + domain_factory, + random_artifact_factory, + file_bindings, + file_repository_factory, + file_publication_factory, + file_distribution_factory, + distribution_base_url, + gen_object_with_cleanup, + monitor_task, +): + """Serve full and ranged object-storage content through Pulp without redirects.""" + + if pulp_settings.STORAGES["default"]["BACKEND"] != storage_class: + pytest.skip("The functional environment does not provide this object-storage configuration") + + domain = domain_factory(storage_class=storage_class, redirect_to_object_storage=False) + artifact = random_artifact_factory(pulp_domain=domain.name, size=32) + content = gen_object_with_cleanup( + file_bindings.ContentFilesApi, + artifact=artifact.pulp_href, + relative_path=str(uuid.uuid4()), + pulp_domain=domain.name, + ) + repository = file_repository_factory(pulp_domain=domain.name) + monitor_task( + file_bindings.RepositoriesFileApi.modify( + repository.pulp_href, + RepositoryAddRemoveContent(add_content_units=[content.pulp_href]), + ).task + ) + publication = file_publication_factory( + pulp_domain=domain.name, + repository=repository.pulp_href, + ) + distribution = file_distribution_factory( + pulp_domain=domain.name, + publication=publication.pulp_href, + ) + content_url = urljoin(distribution_base_url(distribution.base_url), content.relative_path) + + full_response = requests.get(content_url, allow_redirects=False) + assert full_response.status_code == requests.codes.ok + assert not full_response.is_redirect + assert hashlib.sha256(full_response.content).hexdigest() == artifact.sha256 + assert full_response.headers["Content-Length"] == str(len(full_response.content)) + assert full_response.headers["Accept-Ranges"] == "bytes" + + range_response = requests.get( + content_url, headers={"Range": "bytes=1-4"}, allow_redirects=False + ) + assert range_response.status_code == requests.codes.partial_content + assert not range_response.is_redirect + assert range_response.content == full_response.content[1:5] + assert range_response.headers["Content-Length"] == "4" + assert range_response.headers["Content-Range"] == f"bytes 1-4/{len(full_response.content)}" + + @pytest.mark.parallel @pytest.mark.parametrize("download_policy", ["immediate", "on_demand", "streamed"]) def test_download_policy( diff --git a/pulpcore/app/storage_backends.py b/pulpcore/app/storage_backends.py index 763881dbda0..b05af58136d 100644 --- a/pulpcore/app/storage_backends.py +++ b/pulpcore/app/storage_backends.py @@ -149,11 +149,14 @@ def read(self, size=-1): @contextmanager def open_stream(storage, name, start=0, length=None): - """Open a bounded read stream and close it on exit, including after errors. - - Backends with native ranged reads should implement `open_stream`. The - Django `open` fallback bounds bytes returned but may still buffer the - entire object internally, depending on the installed implementation. + """Open the bounded stream used when Pulp serves an artifact itself. + + ArtifactResponse calls this for artifact distributions and for content + responses that Pulp serves instead of redirecting to object storage. Use a + backend's native ranged stream when available; otherwise seek on Django's + `open()` result and bound returned bytes. The fallback may buffer the full + object, depending on the backend. The stream is closed on context exit, + including after errors or early termination. """ if start < 0 or (length is not None and length < 0): raise ValueError("Stream start and length must be non-negative") diff --git a/pulpcore/responses.py b/pulpcore/responses.py index a479a7e5414..da082656ff0 100644 --- a/pulpcore/responses.py +++ b/pulpcore/responses.py @@ -1,4 +1,5 @@ import asyncio +from contextlib import asynccontextmanager from aiohttp import hdrs from aiohttp.web import StreamResponse @@ -14,7 +15,11 @@ class ArtifactResponse(StreamResponse): - """A response object can be used to send artifacts.""" + """Stream artifacts through Pulp instead of sending clients to storage. + + Used by artifact distributions and by content responses when Pulp must serve + bytes from a Domain's storage rather than redirecting to the provider. + """ # Heavily borrowed from FileResponse @@ -38,25 +43,23 @@ def __init__( self._storage = storage async def _sendfile(self, request, storage, name, offset, count): - # To keep memory usage low, fobj is transferred in chunks + """Send artifact bytes in bounded chunks from the selected storage.""" + # Keep memory usage low by transferring the response in bounded chunks # controlled by the constructor's chunk_size argument. writer = await super().prepare(request) assert writer is not None - loop = asyncio.get_event_loop() - - context = open_stream(storage, name, start=offset, length=count) - stream = await loop.run_in_executor(None, context.__enter__) - try: - while count > 0: - chunk = await loop.run_in_executor(None, stream.read, min(self._chunk_size, count)) + async with self._storage_stream(storage, name, offset, count) as stream: + remaining = count + while remaining: + chunk = await asyncio.to_thread(stream.read, min(self._chunk_size, remaining)) if not chunk: break + if len(chunk) > remaining: + chunk = chunk[:remaining] await writer.write(chunk) - count -= len(chunk) - finally: - await loop.run_in_executor(None, context.__exit__, None, None, None) + remaining -= len(chunk) await writer.drain() return writer @@ -73,6 +76,27 @@ async def _get_storage(self): await sync_to_async(lambda: self._artifact.pulp_domain)() return self._artifact.pulp_domain.get_storage() + @staticmethod + @asynccontextmanager + async def _storage_stream(storage, name, offset, count): + """Bridge Pulp's synchronous storage stream to the aiohttp response path. + + `_sendfile()` uses this for artifact distributions and for content served + through Pulp when object-storage redirects are disabled. Django storage + streams are synchronous, so open and close run in worker threads; reads + are dispatched there by `_sendfile()`. Preserve cleanup after errors or + early response termination. + """ + context = await asyncio.to_thread(open_stream, storage, name, start=offset, length=count) + stream = await asyncio.to_thread(context.__enter__) + try: + yield stream + except BaseException as exc: + if not await asyncio.to_thread(context.__exit__, type(exc), exc, exc.__traceback__): + raise + else: + await asyncio.to_thread(context.__exit__, None, None, None) + async def prepare(self, request): if self._artifact is None: self._artifact = await Artifact.objects.select_related("pulp_domain").aget( diff --git a/pulpcore/tests/unit/test_storage_streaming.py b/pulpcore/tests/unit/test_storage_streaming.py new file mode 100644 index 00000000000..c3881963590 --- /dev/null +++ b/pulpcore/tests/unit/test_storage_streaming.py @@ -0,0 +1,180 @@ +"""Tests for bounded artifact streaming through Pulp's storage interface.""" + +import asyncio +import io +import threading +from contextlib import contextmanager +from unittest.mock import AsyncMock, Mock, call + +import pytest + + +def _patch_response_prepare(monkeypatch, writer): + from aiohttp.web import StreamResponse + + async def prepare(_self, _request): + return writer + + monkeypatch.setattr(StreamResponse, "prepare", prepare) + + +def test_artifact_response_streams_requested_storage_range(monkeypatch): + """Use the backend's ranged stream and send only the selected bytes.""" + asyncio.run(_test_artifact_response_streams_requested_storage_range(monkeypatch)) + + +async def _test_artifact_response_streams_requested_storage_range(monkeypatch): + from pulpcore.responses import ArtifactResponse + + writer = Mock() + writer.write = AsyncMock() + writer.drain = AsyncMock() + _patch_response_prepare(monkeypatch, writer) + + stream = Mock() + stream.read.side_effect = (b"bcd", b"") + events = [] + + @contextmanager + def backend_stream(name, start=0, length=None): + events.append(("open", name, start, length)) + try: + yield stream + finally: + events.append(("close",)) + + storage = Mock(open_stream=backend_stream) + response = ArtifactResponse(artifact=Mock(), chunk_size=3) + + assert await response._sendfile("request", storage, "artifact/name", 1, 3) is writer + assert writer.write.await_args_list == [call(b"bcd")] + assert stream.read.call_args_list == [call(3)] + assert events == [("open", "artifact/name", 1, 3), ("close",)] + writer.drain.assert_awaited_once_with() + + +def test_artifact_response_bounds_reads_if_backend_returns_too_much(monkeypatch): + """Do not write past the response length if a backend over-returns bytes.""" + asyncio.run(_test_artifact_response_bounds_reads_if_backend_returns_too_much(monkeypatch)) + + +async def _test_artifact_response_bounds_reads_if_backend_returns_too_much(monkeypatch): + from pulpcore.responses import ArtifactResponse + + writer = Mock() + writer.write = AsyncMock() + writer.drain = AsyncMock() + _patch_response_prepare(monkeypatch, writer) + + stream = Mock() + stream.read.return_value = b"beyond-range" + storage = Mock(open_stream=Mock(return_value=_stream_context(stream))) + response = ArtifactResponse(artifact=Mock(), chunk_size=16) + + assert await response._sendfile("request", storage, "artifact/name", 0, 3) is writer + writer.write.assert_awaited_once_with(b"bey") + stream.read.assert_called_once_with(3) + + +def test_artifact_response_closes_storage_stream_after_write_error(monkeypatch): + """Pass write failures through the stream context so it can release resources.""" + asyncio.run(_test_artifact_response_closes_storage_stream_after_write_error(monkeypatch)) + + +async def _test_artifact_response_closes_storage_stream_after_write_error(monkeypatch): + from pulpcore.responses import ArtifactResponse + + writer = Mock() + writer.write = AsyncMock(side_effect=RuntimeError("client disconnected")) + writer.drain = AsyncMock() + _patch_response_prepare(monkeypatch, writer) + + stream = Mock() + stream.read.return_value = b"abc" + observed_exceptions = [] + closed = [] + + @contextmanager + def backend_stream(*_args, **_kwargs): + try: + yield stream + except BaseException as exc: + observed_exceptions.append(exc) + raise + finally: + closed.append(True) + + response = ArtifactResponse(artifact=Mock(), chunk_size=3) + with pytest.raises(RuntimeError, match="client disconnected"): + await response._sendfile("request", Mock(open_stream=backend_stream), "name", 0, 3) + + assert len(observed_exceptions) == 1 + assert str(observed_exceptions[0]) == "client disconnected" + assert closed == [True] + + +def test_artifact_response_uses_storage_open_fallback(monkeypatch): + """Keep the seekable-file fallback for storage backends without native streams.""" + asyncio.run(_test_artifact_response_uses_storage_open_fallback(monkeypatch)) + + +async def _test_artifact_response_uses_storage_open_fallback(monkeypatch): + from pulpcore.responses import ArtifactResponse + + writer = Mock() + writer.write = AsyncMock() + writer.drain = AsyncMock() + _patch_response_prepare(monkeypatch, writer) + + file = io.BytesIO(b"abcdef") + storage = Mock(spec=["open"]) + storage.open.return_value = file + response = ArtifactResponse(artifact=Mock(), chunk_size=2) + + assert await response._sendfile("request", storage, "artifact/name", 2, 3) is writer + assert writer.write.await_args_list == [call(b"cd"), call(b"e")] + storage.open.assert_called_once_with("artifact/name", "rb") + assert file.closed + + +def test_artifact_response_storage_io_runs_off_event_loop(monkeypatch): + """Keep synchronous storage operations off the aiohttp event-loop thread.""" + asyncio.run(_test_artifact_response_storage_io_runs_off_event_loop(monkeypatch)) + + +async def _test_artifact_response_storage_io_runs_off_event_loop(monkeypatch): + from pulpcore.responses import ArtifactResponse + + event_loop_thread = threading.get_ident() + io_threads = [] + + class Stream: + def read(self, _size): + io_threads.append(threading.get_ident()) + return b"data" + + stream = Stream() + + @contextmanager + def backend_stream(*_args, **_kwargs): + io_threads.append(threading.get_ident()) + yield stream + + writer = Mock() + writer.write = AsyncMock() + writer.drain = AsyncMock() + _patch_response_prepare(monkeypatch, writer) + response = ArtifactResponse(artifact=Mock(), chunk_size=4) + + await response._sendfile("request", Mock(open_stream=backend_stream), "name", 0, 4) + + assert io_threads + assert all(thread_id != event_loop_thread for thread_id in io_threads) + + +def _stream_context(stream): + @contextmanager + def context(*_args, **_kwargs): + yield stream + + return context() diff --git a/pyproject.toml b/pyproject.toml index 0ef01cb449f..051c46f03a4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,9 +68,9 @@ dependencies = [ ] [project.optional-dependencies] -s3 = ["django-storages[boto3]==1.14.6"] -google = ["django-storages[google]==1.14.6"] -azure = ["django-storages[azure]==1.14.6"] +s3 = ["django-storages[boto3] @ git+https://github.com/dralley/django-storages.git@open-stream"] +google = ["django-storages[google] @ git+https://github.com/dralley/django-storages.git@open-stream"] +azure = ["django-storages[azure] @ git+https://github.com/dralley/django-storages.git@open-stream"] prometheus = ["django-prometheus"] saml2 = ["djangosaml2>=1.12.0,<1.14"] kafka = [ From 79659b5db057411dbeba0d76631b1f7a8724d73d Mon Sep 17 00:00:00 2001 From: Daniel Alley Date: Wed, 30 Sep 2026 01:51:36 -0400 Subject: [PATCH 2/6] Vendor django-storages backend modules Bundle the backend source in the pulpcore distribution and retain optional provider dependencies for S3, Azure, and GCS deployments. --- MANIFEST.in | 1 + pyproject.toml | 6 +- storages/LICENSE | 29 ++ storages/__init__.py | 1 + storages/backends/__init__.py | 0 storages/backends/_stream.py | 68 +++ storages/backends/apache_libcloud.py | 203 ++++++++ storages/backends/azure_storage.py | 419 +++++++++++++++ storages/backends/dropbox.py | 202 ++++++++ storages/backends/ftp.py | 287 ++++++++++ storages/backends/gcloud.py | 428 +++++++++++++++ storages/backends/s3.py | 749 +++++++++++++++++++++++++++ storages/backends/s3boto3.py | 6 + storages/backends/sftpstorage.py | 245 +++++++++ storages/base.py | 24 + storages/compress.py | 49 ++ storages/utils.py | 182 +++++++ 17 files changed, 2896 insertions(+), 3 deletions(-) create mode 100644 storages/LICENSE create mode 100644 storages/__init__.py create mode 100644 storages/backends/__init__.py create mode 100644 storages/backends/_stream.py create mode 100644 storages/backends/apache_libcloud.py create mode 100644 storages/backends/azure_storage.py create mode 100644 storages/backends/dropbox.py create mode 100644 storages/backends/ftp.py create mode 100644 storages/backends/gcloud.py create mode 100644 storages/backends/s3.py create mode 100644 storages/backends/s3boto3.py create mode 100644 storages/backends/sftpstorage.py create mode 100644 storages/base.py create mode 100644 storages/compress.py create mode 100644 storages/utils.py diff --git a/MANIFEST.in b/MANIFEST.in index fdda5e340fe..20b84d2d9de 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,6 +2,7 @@ graft pulpcore/etc graft pulp_certguard/tests/functional/artifacts exclude .gitleaks.toml include LICENSE +include pulpcore/vendor/storages/LICENSE include pyproject.toml include CHANGES.md include COMMITMENT diff --git a/pyproject.toml b/pyproject.toml index 051c46f03a4..58c115450d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,9 +68,9 @@ dependencies = [ ] [project.optional-dependencies] -s3 = ["django-storages[boto3] @ git+https://github.com/dralley/django-storages.git@open-stream"] -google = ["django-storages[google] @ git+https://github.com/dralley/django-storages.git@open-stream"] -azure = ["django-storages[azure] @ git+https://github.com/dralley/django-storages.git@open-stream"] +azure = ["azure-core>=1.13", "azure-storage-blob>=12"] +google = ["google-cloud-storage>=1.36.1"] +s3 = ["boto3>=1.4.4"] prometheus = ["django-prometheus"] saml2 = ["djangosaml2>=1.12.0,<1.14"] kafka = [ diff --git a/storages/LICENSE b/storages/LICENSE new file mode 100644 index 00000000000..aa217de892d --- /dev/null +++ b/storages/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2008 - 2023, Josh Schneier, David Larlet, et al. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/storages/__init__.py b/storages/__init__.py new file mode 100644 index 00000000000..ee738f98224 --- /dev/null +++ b/storages/__init__.py @@ -0,0 +1 @@ +__version__ = "1.14.6" diff --git a/storages/backends/__init__.py b/storages/backends/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/storages/backends/_stream.py b/storages/backends/_stream.py new file mode 100644 index 00000000000..705bdf411ac --- /dev/null +++ b/storages/backends/_stream.py @@ -0,0 +1,68 @@ +"""Small file-like helpers used by remote-storage streaming reads.""" + + +def validate_byte_range(start, length): + """Validate the half-open byte range accepted by `open_stream()`. + + A zero-length response should be handled by callers without opening an + object. Requiring a positive length also avoids provider-specific behavior + for invalid `Range` headers. + """ + + if start < 0: + raise ValueError("start must be greater than or equal to zero") + if length is not None and length <= 0: + raise ValueError("length must be greater than zero") + + +class ChunkIteratorStream: + """Expose an iterator of provider chunks through `read()`. + + Azure's download API provides an iterator rather than a file object. This + wrapper retains at most one partially consumed provider chunk, so a caller + can choose its own smaller read size without assembling the full object. + """ + + def __init__(self, chunks): + self._chunks = iter(chunks) + self._pending = b"" + + def read(self, size=-1): + """Read at most `size` bytes, or all remaining bytes when omitted.""" + + if size is None: + size = -1 + if size < 0: + result = self._pending + b"".join(self._chunks) + self._pending = b"" + return result + + while len(self._pending) < size: + chunk = next(self._chunks, None) + if chunk is None: + break + self._pending += chunk + + result, self._pending = self._pending[:size], self._pending[size:] + return result + + +class LimitedStream: + """Limit a file-like reader to the requested number of bytes.""" + + def __init__(self, stream, length): + self._stream = stream + self._remaining = length + + def read(self, size=-1): + """Read without crossing the range passed to `open_stream()`.""" + + if self._remaining is None: + return self._stream.read(size) + if self._remaining == 0: + return b"" + if size is None or size < 0 or size > self._remaining: + size = self._remaining + result = self._stream.read(size) + self._remaining -= len(result) + return result diff --git a/storages/backends/apache_libcloud.py b/storages/backends/apache_libcloud.py new file mode 100644 index 00000000000..2c717a28c29 --- /dev/null +++ b/storages/backends/apache_libcloud.py @@ -0,0 +1,203 @@ +# Django storage using libcloud providers +# Aymeric Barantal (mric at chamal.fr) 2011 +# +import io +from urllib.parse import urljoin + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from django.core.files.base import File +from django.core.files.storage import Storage +from django.utils.deconstruct import deconstructible + +from storages.utils import clean_name + +try: + from libcloud.storage.providers import get_driver + from libcloud.storage.types import ObjectDoesNotExistError + from libcloud.storage.types import Provider +except ImportError: + raise ImproperlyConfigured("Could not load libcloud") + + +@deconstructible +class LibCloudStorage(Storage): + """Django storage derived class using apache libcloud to operate + on supported providers""" + + def __init__(self, provider_name=None, option=None): + if provider_name is None: + provider_name = getattr(settings, "DEFAULT_LIBCLOUD_PROVIDER", "default") + + self.provider = settings.LIBCLOUD_PROVIDERS.get(provider_name) + if not self.provider: + raise ImproperlyConfigured( + "LIBCLOUD_PROVIDERS %s not defined or invalid" % provider_name + ) + extra_kwargs = {} + if "region" in self.provider: + extra_kwargs["region"] = self.provider["region"] + # Used by the GoogleStorageDriver + if "project" in self.provider: + extra_kwargs["project"] = self.provider["project"] + try: + provider_type = self.provider["type"] + if isinstance(provider_type, str): + module_path, tag = provider_type.rsplit(".", 1) + if module_path != "libcloud.storage.types.Provider": + raise ValueError("Invalid module path") + provider_type = getattr(Provider, tag) + + Driver = get_driver(provider_type) + self.driver = Driver( + self.provider["user"], self.provider["key"], **extra_kwargs + ) + except Exception as e: + raise ImproperlyConfigured( + "Unable to create libcloud driver type %s: %s" + % (self.provider.get("type"), e) + ) + self.bucket = self.provider["bucket"] # Limit to one container + + def _get_bucket(self): + """Helper to get bucket object (libcloud container)""" + return self.driver.get_container(self.bucket) + + def _get_object(self, name): + """Get object by its name. ObjectDoesNotExistError will be raised if object not + found""" + return self.driver.get_object(self.bucket, clean_name(name)) + + def delete(self, name): + """Delete object on remote""" + try: + obj = self._get_object(name) + return self.driver.delete_object(obj) + except ObjectDoesNotExistError: + pass + + def exists(self, name): + try: + _ = self._get_object(name) + except ObjectDoesNotExistError: + return False + return True + + def listdir(self, path="/"): + """Lists the contents of the specified path, + returning a 2-tuple of lists; the first item being + directories, the second item being files. + """ + container = self._get_bucket() + objects = self.driver.list_container_objects(container) + path = clean_name(path) + if not path.endswith("/"): + path = "%s/" % path + files = [] + dirs = [] + # TOFIX: better algorithm to filter correctly + # (and not depend on google-storage empty folder naming) + for o in objects: + if path == "/": + if o.name.count("/") == 0: + files.append(o.name) + elif o.name.count("/") == 1: + dir_name = o.name[: o.name.index("/")] + if dir_name not in dirs: + dirs.append(dir_name) + elif o.name.startswith(path): + if o.name.count("/") <= path.count("/"): + # TOFIX : special case for google storage with empty dir + if o.name.endswith("_$folder$"): + name = o.name[:-9] + name = name[len(path) :] + dirs.append(name) + else: + name = o.name[len(path) :] + files.append(name) + return (dirs, files) + + def size(self, name): + obj = self._get_object(name) + return obj.size if obj else -1 + + def url(self, name): + provider_type = self.provider["type"].lower() + obj = self._get_object(name) + if not obj: + return None + try: + url = self.driver.get_object_cdn_url(obj) + except NotImplementedError as e: + object_path = "{}/{}".format(self.bucket, obj.name) + if "s3" in provider_type: + base_url = "https://%s" % self.driver.connection.host + url = urljoin(base_url, object_path) + elif "google" in provider_type: + url = urljoin("https://storage.googleapis.com", object_path) + elif "azure" in provider_type: + base_url = "https://%s.blob.core.windows.net" % self.provider["user"] + url = urljoin(base_url, object_path) + elif "backblaze" in provider_type: + url = urljoin("api.backblaze.com/b2api/v1/", object_path) + else: + raise e + return url + + def _open(self, name, mode="rb"): + remote_file = LibCloudFile(name, self, mode=mode) + return remote_file + + def _read(self, name): + try: + obj = self._get_object(name) + except ObjectDoesNotExistError as e: + raise FileNotFoundError(str(e)) + # TOFIX : we should be able to read chunk by chunk + return next(self.driver.download_object_as_stream(obj, obj.size)) + + def _save(self, name, file): + self.driver.upload_object_via_stream(iter(file), self._get_bucket(), name) + return name + + +class LibCloudFile(File): + """File inherited class for libcloud storage objects read and write""" + + def __init__(self, name, storage, mode): + self.name = name + self._storage = storage + self._mode = mode + self._is_dirty = False + self._file = None + + def _get_file(self): + if self._file is None: + data = self._storage._read(self.name) + self._file = io.BytesIO(data) + return self._file + + def _set_file(self, value): + self._file = value + + file = property(_get_file, _set_file) + + @property + def size(self): + if not hasattr(self, "_size"): + self._size = self._storage.size(self.name) + return self._size + + def read(self, num_bytes=None): + return self.file.read(num_bytes) + + def write(self, content): + if "w" not in self._mode: + raise AttributeError("File was opened for read-only access.") + self.file = io.BytesIO(content) + self._is_dirty = True + + def close(self): + if self._is_dirty: + self._storage._save(self.name, self.file) + self.file.close() diff --git a/storages/backends/azure_storage.py b/storages/backends/azure_storage.py new file mode 100644 index 00000000000..aa53252adc4 --- /dev/null +++ b/storages/backends/azure_storage.py @@ -0,0 +1,419 @@ +import mimetypes +import warnings +from contextlib import contextmanager +from datetime import datetime +from datetime import timedelta +from tempfile import SpooledTemporaryFile +from urllib.parse import urlparse +from urllib.parse import urlunparse + +from azure.core.exceptions import ResourceNotFoundError +from azure.core.utils import parse_connection_string +from azure.storage.blob import BlobClient +from azure.storage.blob import BlobSasPermissions +from azure.storage.blob import BlobServiceClient +from azure.storage.blob import ContentSettings +from azure.storage.blob import generate_blob_sas +from django.core.exceptions import SuspiciousOperation +from django.core.files.base import File +from django.utils import timezone +from django.utils.deconstruct import deconstructible + +from storages.backends._stream import ChunkIteratorStream +from storages.backends._stream import LimitedStream +from storages.backends._stream import validate_byte_range +from storages.base import BaseStorage +from storages.utils import clean_name +from storages.utils import get_available_overwrite_name +from storages.utils import safe_join +from storages.utils import setting +from storages.utils import to_bytes + + +@deconstructible +class AzureStorageFile(File): + def __init__(self, name, mode, storage): + self.name = name + self._mode = mode + self._storage = storage + self._is_dirty = False + self._file = None + self._path = storage._get_valid_path(name) + + def _get_file(self): + if self._file is not None: + return self._file + + file = SpooledTemporaryFile( + max_size=self._storage.max_memory_size, + suffix=".AzureStorageFile", + dir=setting("FILE_UPLOAD_TEMP_DIR", None), + ) + + if "r" in self._mode or "a" in self._mode: + download_stream = self._storage.client.download_blob( + self._path, timeout=self._storage.timeout + ) + download_stream.readinto(file) + if "r" in self._mode: + file.seek(0) + + self._file = file + return self._file + + def _set_file(self, value): + self._file = value + + file = property(_get_file, _set_file) + + def read(self, *args, **kwargs): + if "r" not in self._mode and "a" not in self._mode: + raise AttributeError("File was not opened in read mode.") + return super().read(*args, **kwargs) + + def write(self, content): + if "w" not in self._mode and "+" not in self._mode and "a" not in self._mode: + raise AttributeError("File was not opened in write mode.") + self._is_dirty = True + return super().write(to_bytes(content)) + + def close(self): + if self._file is None: + return + if self._is_dirty: + self._file.seek(0) + self._storage._save(self.name, self._file) + self._is_dirty = False + self._file.close() + self._file = None + + +def _content_type(content): + try: + return content.file.content_type + except AttributeError: + pass + try: + return content.content_type + except AttributeError: + pass + return None + + +def _get_valid_path(s): + # A blob name: + # * must not end with dot or slash + # * can contain any character + # * must escape URL reserved characters + # (not needed here since the azure client will do that) + s = s.strip("./") + if len(s) > _AZURE_NAME_MAX_LEN: + raise ValueError("File name max len is %d" % _AZURE_NAME_MAX_LEN) + if not len(s): + raise ValueError("File name must contain one or more printable characters") + if s.count("/") > 256: + raise ValueError("File name must not contain more than 256 slashes") + return s + + +# Max len according to azure's docs +_AZURE_NAME_MAX_LEN = 1024 + + +@deconstructible +class AzureStorage(BaseStorage): + def __init__(self, **settings): + super().__init__(**settings) + self._service_client = None + self._client = None + self._user_delegation_key = None + self._user_delegation_key_expiry = datetime.utcnow() + if self.connection_string and (not self.account_name or not self.account_key): + parsed = parse_connection_string( + self.connection_string, case_sensitive_keys=True + ) + if not self.account_name and "AccountName" in parsed: + self.account_name = parsed["AccountName"] + if not self.account_key and "AccountKey" in parsed: + self.account_key = parsed["AccountKey"] + + def get_default_settings(self): + return { + "account_name": setting("AZURE_ACCOUNT_NAME"), + "account_key": setting("AZURE_ACCOUNT_KEY"), + "object_parameters": setting("AZURE_OBJECT_PARAMETERS", {}), + "azure_container": setting("AZURE_CONTAINER"), + "azure_ssl": setting("AZURE_SSL", True), + "upload_max_conn": setting("AZURE_UPLOAD_MAX_CONN", 2), + "timeout": setting("AZURE_CONNECTION_TIMEOUT_SECS", 20), + "max_memory_size": setting("AZURE_BLOB_MAX_MEMORY_SIZE", 2 * 1024 * 1024), + "expiration_secs": setting("AZURE_URL_EXPIRATION_SECS"), + "overwrite_files": setting("AZURE_OVERWRITE_FILES", False), + "location": setting("AZURE_LOCATION", ""), + "default_content_type": "application/octet-stream", + "cache_control": setting("AZURE_CACHE_CONTROL"), + "sas_token": setting("AZURE_SAS_TOKEN"), + "endpoint_suffix": setting("AZURE_ENDPOINT_SUFFIX", "core.windows.net"), + "custom_domain": setting("AZURE_CUSTOM_DOMAIN"), + "connection_string": setting("AZURE_CONNECTION_STRING"), + "token_credential": setting("AZURE_TOKEN_CREDENTIAL"), + "api_version": setting("AZURE_API_VERSION", None), + "client_options": setting("AZURE_CLIENT_OPTIONS", {}), + } + + def _get_service_client(self): + if self.connection_string is not None: + return BlobServiceClient.from_connection_string(self.connection_string) + + account_domain = "{}.blob.{}".format(self.account_name, self.endpoint_suffix) + account_url = "{}://{}".format(self.azure_protocol, account_domain) + + credential = None + if self.account_key: + credential = { + "account_name": self.account_name, + "account_key": self.account_key, + } + elif self.sas_token: + credential = self.sas_token + elif self.token_credential: + credential = self.token_credential + + options = self.client_options + if self.api_version: + warnings.warn( + "The AZURE_API_VERSION/api_version setting is deprecated " + "and will be removed in a future version. Use AZURE_CLIENT_OPTIONS " + "to customize any of the BlobServiceClient kwargs.", + DeprecationWarning, + ) + options["api_version"] = self.api_version + return BlobServiceClient(account_url, credential=credential, **options) + + @property + def service_client(self): + if self._service_client is None: + self._service_client = self._get_service_client() + return self._service_client + + @property + def client(self): + if self._client is None: + self._client = self.service_client.get_container_client( + self.azure_container + ) + return self._client + + def get_user_delegation_key(self, expiry): + # We'll only be able to get a user delegation key if we've authenticated with a + # token credential. + if self.token_credential is None: + return None + + # Get a new key if we don't already have one, or if the one we have expires too + # soon. + if ( + self._user_delegation_key is None + or expiry > self._user_delegation_key_expiry + ): + now = datetime.utcnow() + key_expiry_time = now + timedelta(days=7) + self._user_delegation_key = self.service_client.get_user_delegation_key( + key_start_time=now, key_expiry_time=key_expiry_time + ) + self._user_delegation_key_expiry = key_expiry_time + + return self._user_delegation_key + + @property + def azure_protocol(self): + if self.azure_ssl: + return "https" + else: + return "http" + + def _normalize_name(self, name): + try: + return safe_join(self.location, name) + except ValueError: + raise SuspiciousOperation("Attempted access to '%s' denied." % name) + + def _get_valid_path(self, name): + # Must be idempotent + return _get_valid_path(self._normalize_name(clean_name(name))) + + def _open(self, name, mode="rb"): + return AzureStorageFile(name, mode, self) + + @contextmanager + def open_stream(self, name, start=0, length=None): + """Open a forward-only byte-range stream from an Azure blob. + + Unlike :meth:`open`, this method does not create a seekable Django file + or materialize the complete blob in a temporary file. ``name`` is the + logical storage name and is normalized using this storage's configured + location; ``start`` and ``length`` select a half-open byte interval. + Read in bounded sizes; Azure buffers a provider chunk before yielding + it, rather than retaining a provider response between reads. + """ + + validate_byte_range(start, length) + downloader = self.client.download_blob( + self._get_valid_path(name), + offset=start, + length=length, + timeout=self.timeout, + ) + yield LimitedStream(ChunkIteratorStream(downloader.chunks()), length) + + def get_available_name(self, name, max_length=_AZURE_NAME_MAX_LEN): + """ + Returns a filename that's free on the target storage system, and + available for new content to be written to. + """ + name = clean_name(name) + if self.overwrite_files: + return get_available_overwrite_name(name, max_length) + return super().get_available_name(name, max_length) + + def exists(self, name): + if not name: + return True + + blob_client = self.client.get_blob_client(self._get_valid_path(name)) + return blob_client.exists() + + def delete(self, name): + try: + self.client.delete_blob(self._get_valid_path(name), timeout=self.timeout) + except ResourceNotFoundError: + pass + + def size(self, name): + blob_client = self.client.get_blob_client(self._get_valid_path(name)) + properties = blob_client.get_blob_properties(timeout=self.timeout) + return properties.size + + def _save(self, name, content): + cleaned_name = clean_name(name) + name = self._get_valid_path(name) + params = self._get_content_settings_parameters(name, content) + + # Unwrap django file (wrapped by parent's save call) + if isinstance(content, File): + content = content.file + + content.seek(0) + self.client.upload_blob( + name, + content, + content_settings=ContentSettings(**params), + max_concurrency=self.upload_max_conn, + timeout=self.timeout, + overwrite=self.overwrite_files, + ) + return cleaned_name + + def _expire_at(self, expire): + # azure expects time in UTC + return datetime.utcnow() + timedelta(seconds=expire) + + def url(self, name, expire=None, parameters=None, mode="r"): + name = self._get_valid_path(name) + params = parameters or {} + permission = BlobSasPermissions.from_string(mode) + + if expire is None: + expire = self.expiration_secs + + credential = None + if expire: + expiry = self._expire_at(expire) + user_delegation_key = self.get_user_delegation_key(expiry) + sas_token = generate_blob_sas( + self.account_name, + self.azure_container, + name, + account_key=self.account_key, + user_delegation_key=user_delegation_key, + permission=permission, + expiry=expiry, + **params, + ) + credential = sas_token + + container_blob_url = self.client.get_blob_client(name).url + + if self.custom_domain: + # Replace the account name with the custom domain + parsed_url = urlparse(container_blob_url) + container_blob_url = urlunparse( + parsed_url._replace(netloc=self.custom_domain) + ) + + return BlobClient.from_blob_url(container_blob_url, credential=credential).url + + def _get_content_settings_parameters(self, name, content=None): + params = {} + + guessed_type, content_encoding = mimetypes.guess_type(name) + content_type = ( + _content_type(content) or guessed_type or self.default_content_type + ) + + params["cache_control"] = self.cache_control + params["content_type"] = content_type + params["content_encoding"] = content_encoding + + params.update(self.get_object_parameters(name)) + return params + + def get_object_parameters(self, name): + """ + Returns a dictionary that is passed to content settings. Override this + method to adjust this on a per-object basis to set e.g ContentDisposition. + + By default, returns the value of AZURE_OBJECT_PARAMETERS. + """ + return self.object_parameters.copy() + + def get_modified_time(self, name): + """ + Returns an (aware) datetime object containing the last modified time if + USE_TZ is True, otherwise returns a naive datetime in the local timezone. + """ + blob_client = self.client.get_blob_client(self._get_valid_path(name)) + properties = blob_client.get_blob_properties(timeout=self.timeout) + if not setting("USE_TZ", False): + return timezone.make_naive(properties.last_modified) + + tz = timezone.get_current_timezone() + if timezone.is_naive(properties.last_modified): + return timezone.make_aware(properties.last_modified, tz) + + # `last_modified` is in UTC time_zone, we + # must convert it to settings time_zone + return properties.last_modified.astimezone(tz) + + def list_all(self, path=""): + """Return all files for a given path""" + if path: + path = self._get_valid_path(path) + if path and not path.endswith("/"): + path += "/" + # XXX make generator, add start, end + return [ + blob.name + for blob in self.client.list_blobs( + name_starts_with=path, timeout=self.timeout + ) + ] + + def listdir(self, path=""): + """ + Return all files for a given path. + Given that Azure can't return paths it only returns files. + Works great for our little adventure. + """ + + return [], self.list_all(path) diff --git a/storages/backends/dropbox.py b/storages/backends/dropbox.py new file mode 100644 index 00000000000..ef16999f41c --- /dev/null +++ b/storages/backends/dropbox.py @@ -0,0 +1,202 @@ +# Dropbox storage class for Django pluggable storage system. +# Author: Anthony Monthe +# License: BSD + +import warnings +from io import BytesIO +from shutil import copyfileobj +from tempfile import SpooledTemporaryFile + +from django.core.exceptions import ImproperlyConfigured +from django.core.files.base import File +from django.utils._os import safe_join +from django.utils.deconstruct import deconstructible +from dropbox import Dropbox +from dropbox.exceptions import ApiError +from dropbox.files import CommitInfo +from dropbox.files import FolderMetadata +from dropbox.files import UploadSessionCursor +from dropbox.files import WriteMode + +from storages.base import BaseStorage +from storages.utils import get_available_overwrite_name +from storages.utils import setting + +_DEFAULT_TIMEOUT = 100 +_DEFAULT_MODE = "add" + + +class DropboxStorageException(Exception): + pass + + +DropBoxStorageException = DropboxStorageException + + +class DropboxFile(File): + def __init__(self, name, storage): + self.name = name + self._storage = storage + self._file = None + + def _get_file(self): + if self._file is None: + self._file = SpooledTemporaryFile() + # As dropbox==9.3.0, the client returns a tuple + # (dropbox.files.FileMetadata, requests.models.Response) + _file_metadata, response = self._storage.client.files_download(self.name) + if response.status_code == 200: + with BytesIO(response.content) as file_content: + copyfileobj(file_content, self._file) + else: + # JIC the exception isn't caught by the dropbox client + raise DropboxStorageException( + "Dropbox server returned a {} response when accessing {}".format( + response.status_code, self.name + ) + ) + self._file.seek(0) + return self._file + + def _set_file(self, value): + self._file = value + + file = property(_get_file, _set_file) + + +DropBoxFile = DropboxFile + + +@deconstructible +class DropboxStorage(BaseStorage): + """Dropbox Storage class for Django pluggable storage system.""" + + CHUNK_SIZE = 4 * 1024 * 1024 + + def __init__(self, oauth2_access_token=None, **settings): + if oauth2_access_token is not None: + settings["oauth2_access_token"] = oauth2_access_token + super().__init__(**settings) + + if self.oauth2_access_token is None and not all( + [self.app_key, self.app_secret, self.oauth2_refresh_token] + ): + raise ImproperlyConfigured( + "You must configure an auth token at" + "'settings.DROPBOX_OAUTH2_TOKEN' or " + "'setting.DROPBOX_APP_KEY', " + "'setting.DROPBOX_APP_SECRET' " + "and 'setting.DROPBOX_OAUTH2_REFRESH_TOKEN'." + ) + self.client = Dropbox( + self.oauth2_access_token, + app_key=self.app_key, + app_secret=self.app_secret, + oauth2_refresh_token=self.oauth2_refresh_token, + timeout=self.timeout, + ) + + # Backwards compat + if hasattr(self, "location"): + warnings.warn( + "Setting `root_path` with name `location` is deprecated and will be " + "removed in a future version of django-storages. Please update the " + "name from `location` to `root_path`", + DeprecationWarning, + ) + self.root_path = self.location + + def get_default_settings(self): + return { + "root_path": setting("DROPBOX_ROOT_PATH", "/"), + "oauth2_access_token": setting("DROPBOX_OAUTH2_TOKEN"), + "app_key": setting("DROPBOX_APP_KEY"), + "app_secret": setting("DROPBOX_APP_SECRET"), + "oauth2_refresh_token": setting("DROPBOX_OAUTH2_REFRESH_TOKEN"), + "timeout": setting("DROPBOX_TIMEOUT", _DEFAULT_TIMEOUT), + "write_mode": setting("DROPBOX_WRITE_MODE", _DEFAULT_MODE), + } + + def _full_path(self, name): + if name == "/": + name = "" + return safe_join(self.root_path, name).replace("\\", "/") + + def delete(self, name): + self.client.files_delete(self._full_path(name)) + + def exists(self, name): + try: + return bool(self.client.files_get_metadata(self._full_path(name))) + except ApiError: + return False + + def listdir(self, path): + directories, files = [], [] + full_path = self._full_path(path) + + if full_path == "/": + full_path = "" + + metadata = self.client.files_list_folder(full_path) + for entry in metadata.entries: + if isinstance(entry, FolderMetadata): + directories.append(entry.name) + else: + files.append(entry.name) + return directories, files + + def size(self, name): + metadata = self.client.files_get_metadata(self._full_path(name)) + return metadata.size + + def url(self, name): + try: + media = self.client.files_get_temporary_link(self._full_path(name)) + return media.link + except ApiError: + return None + + def _open(self, name, mode="rb"): + remote_file = DropboxFile(self._full_path(name), self) + return remote_file + + def _save(self, name, content): + content.open() + if content.size <= self.CHUNK_SIZE: + self.client.files_upload( + content.read(), self._full_path(name), mode=WriteMode(self.write_mode) + ) + else: + self._chunked_upload(content, self._full_path(name)) + content.close() + return name + + def _chunked_upload(self, content, dest_path): + upload_session = self.client.files_upload_session_start( + content.read(self.CHUNK_SIZE) + ) + cursor = UploadSessionCursor( + session_id=upload_session.session_id, offset=content.tell() + ) + commit = CommitInfo(path=dest_path, mode=WriteMode(self.write_mode)) + + while content.tell() < content.size: + if (content.size - content.tell()) <= self.CHUNK_SIZE: + self.client.files_upload_session_finish( + content.read(self.CHUNK_SIZE), cursor, commit + ) + else: + self.client.files_upload_session_append_v2( + content.read(self.CHUNK_SIZE), cursor + ) + cursor.offset = content.tell() + + def get_available_name(self, name, max_length=None): + """Overwrite existing file with the same name.""" + if self.write_mode == "overwrite": + return get_available_overwrite_name(name, max_length) + return super().get_available_name(name, max_length) + + +DropBoxStorage = DropboxStorage diff --git a/storages/backends/ftp.py b/storages/backends/ftp.py new file mode 100644 index 00000000000..ed53748b47f --- /dev/null +++ b/storages/backends/ftp.py @@ -0,0 +1,287 @@ +# FTP storage class for Django pluggable storage system. +# Author: Rafal Jonca +# License: MIT +# Comes from http://www.djangosnippets.org/snippets/1269/ +# +# Usage: +# +# Add below to settings.py: +# FTP_STORAGE_LOCATION = '[a]ftp[s]://:@:/[path]' +# +# In models.py you can write: +# from FTPStorage import FTPStorage +# fs = FTPStorage() +# For a TLS configuration, you must use 'ftps' protocol +# class FTPTest(models.Model): +# file = models.FileField(upload_to='a/b/c/', storage=fs) + +import ftplib +import io +import os +import re +import urllib.parse + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from django.core.files.base import File +from django.utils.deconstruct import deconstructible + +from storages.base import BaseStorage +from storages.utils import setting + + +class FTPStorageException(Exception): + pass + + +@deconstructible +class FTPStorage(BaseStorage): + """FTP Storage class for Django pluggable storage system.""" + + def __init__(self, **settings): + super().__init__(**settings) + if self.location is None: + raise ImproperlyConfigured( + "You must set a location at instantiation " + "or at settings.FTP_STORAGE_LOCATION." + ) + self._config = self._decode_location(self.location) + self._connection = None + + def get_default_settings(self): + return { + "location": setting("FTP_STORAGE_LOCATION"), + "encoding": setting("FTP_STORAGE_ENCODING", "latin-1"), + "base_url": setting("BASE_URL", settings.MEDIA_URL), + "allow_overwrite": setting("FTP_ALLOW_OVERWRITE", False), + } + + def _decode_location(self, location): + """Return splitted configuration data from location.""" + splitted_url = re.search( + r"^(?P.+)://(?P.+):(?P.+)@" + r"(?P.+):(?P\d+)/(?P.*)$", + location, + ) + + if splitted_url is None: + raise ImproperlyConfigured("Improperly formatted location URL") + if splitted_url["scheme"] not in ("ftp", "aftp", "ftps"): + raise ImproperlyConfigured("Only ftp, aftp, ftps schemes supported") + if splitted_url["host"] == "": + raise ImproperlyConfigured("You must at least provide host!") + + config = {} + config["active"] = splitted_url["scheme"] == "aftp" + config["secure"] = splitted_url["scheme"] == "ftps" + + config["path"] = splitted_url["path"] or "/" + config["host"] = splitted_url["host"] + config["user"] = splitted_url["user"] + config["passwd"] = splitted_url["passwd"] + config["port"] = int(splitted_url["port"]) + + return config + + def _start_connection(self): + # Check if connection is still alive and if not, drop it. + if self._connection is not None: + try: + self._connection.pwd() + except ftplib.all_errors: + self._connection = None + + # Real reconnect + if self._connection is None: + ftp = ftplib.FTP_TLS() if self._config["secure"] else ftplib.FTP() + ftp.encoding = self.encoding + try: + ftp.connect(self._config["host"], self._config["port"]) + ftp.login(self._config["user"], self._config["passwd"]) + if self._config["secure"]: + ftp.prot_p() + if self._config["active"]: + ftp.set_pasv(False) + if self._config["path"] != "": + ftp.cwd(self._config["path"]) + self._connection = ftp + return + except ftplib.all_errors: + raise FTPStorageException( + "Connection or login error using data %s" % repr(self._config) + ) + + def disconnect(self): + self._connection.quit() + self._connection = None + + def _mkremdirs(self, path): + pwd = self._connection.pwd() + path_splitted = path.split(os.path.sep) + for path_part in path_splitted: + try: + self._connection.cwd(path_part) + except ftplib.all_errors: + try: + self._connection.mkd(path_part) + self._connection.cwd(path_part) + except ftplib.all_errors: + raise FTPStorageException("Cannot create directory chain %s" % path) + self._connection.cwd(pwd) + + def _put_file(self, name, content): + # Connection must be open! + try: + self._mkremdirs(os.path.dirname(name)) + pwd = self._connection.pwd() + self._connection.cwd(os.path.dirname(name)) + self._connection.storbinary( + "STOR " + os.path.basename(name), + content.file, + content.DEFAULT_CHUNK_SIZE, + ) + self._connection.cwd(pwd) + except ftplib.all_errors: + raise FTPStorageException("Error writing file %s" % name) + + def _open(self, name, mode="rb"): + remote_file = FTPStorageFile(name, self, mode=mode) + return remote_file + + def _read(self, name): + memory_file = io.BytesIO() + try: + pwd = self._connection.pwd() + self._connection.cwd(os.path.dirname(name)) + self._connection.retrbinary( + "RETR " + os.path.basename(name), memory_file.write + ) + self._connection.cwd(pwd) + memory_file.seek(0) + return memory_file + except ftplib.all_errors: + raise FTPStorageException("Error reading file %s" % name) + + def _save(self, name, content): + content.open() + self._start_connection() + self._put_file(name, content) + content.close() + return name + + def _get_dir_details(self, path): + # Connection must be open! + try: + lines = [] + self._connection.retrlines("LIST " + path, lines.append) + dirs = {} + files = {} + for line in lines: + words = line.split() + if len(words) < 6: + continue + if words[-2] == "->": + continue + if words[0][0] == "d": + dirs[words[-1]] = 0 + elif words[0][0] == "-": + files[words[-1]] = int(words[-5]) + return dirs, files + except ftplib.all_errors: + raise FTPStorageException("Error getting listing for %s" % path) + + def listdir(self, path): + self._start_connection() + try: + dirs, files = self._get_dir_details(path) + return list(dirs.keys()), list(files.keys()) + except FTPStorageException: + raise + + def delete(self, name): + if not self.exists(name): + return + self._start_connection() + try: + self._connection.delete(name) + except ftplib.all_errors: + raise FTPStorageException("Error when removing %s" % name) + + def exists(self, name): + if self.allow_overwrite: + return False + + self._start_connection() + try: + nlst = self._connection.nlst(os.path.dirname(name)) + if name in nlst or os.path.basename(name) in nlst: + return True + else: + return False + except ftplib.error_temp: + return False + except ftplib.error_perm: + # error_perm: 550 Can't find file + return False + except ftplib.all_errors: + raise FTPStorageException("Error when testing existence of %s" % name) + + def size(self, name): + self._start_connection() + try: + _dirs, files = self._get_dir_details(os.path.dirname(name)) + if os.path.basename(name) in files: + return files[os.path.basename(name)] + else: + return 0 + except FTPStorageException: + return 0 + + def url(self, name): + if self.base_url is None: + raise ValueError("This file is not accessible via a URL.") + return urllib.parse.urljoin(self.base_url, name).replace("\\", "/") + + +class FTPStorageFile(File): + def __init__(self, name, storage, mode): + self.name = name + self._storage = storage + self._mode = mode + self._is_dirty = False + self.file = io.BytesIO() + self._is_read = False + + @property + def size(self): + if not hasattr(self, "_size"): + self._size = self._storage.size(self.name) + return self._size + + def readlines(self): + if not self._is_read: + self._storage._start_connection() + self.file = self._storage._read(self.name) + self._is_read = True + return self.file.readlines() + + def read(self, num_bytes=None): + if not self._is_read: + self._storage._start_connection() + self.file = self._storage._read(self.name) + self._is_read = True + return self.file.read(num_bytes) + + def write(self, content): + if "w" not in self._mode: + raise AttributeError("File was opened for read-only access.") + self.file = io.BytesIO(content) + self._is_dirty = True + self._is_read = True + + def close(self): + if self._is_dirty: + self._storage._start_connection() + self._storage._put_file(self.name, self) + self._storage.disconnect() + self.file.close() diff --git a/storages/backends/gcloud.py b/storages/backends/gcloud.py new file mode 100644 index 00000000000..75c4fff0a86 --- /dev/null +++ b/storages/backends/gcloud.py @@ -0,0 +1,428 @@ +import gzip +import io +import mimetypes +from contextlib import contextmanager +from datetime import timedelta +from tempfile import SpooledTemporaryFile + +from django.core.exceptions import ImproperlyConfigured +from django.core.exceptions import SuspiciousOperation +from django.core.files.base import File +from django.utils import timezone +from django.utils.deconstruct import deconstructible + +from storages.backends._stream import LimitedStream +from storages.backends._stream import validate_byte_range +from storages.base import BaseStorage +from storages.compress import CompressedFileMixin +from storages.utils import check_location +from storages.utils import clean_name +from storages.utils import get_available_overwrite_name +from storages.utils import safe_join +from storages.utils import setting +from storages.utils import to_bytes + +try: + from google import auth + from google.auth.credentials import TokenState + from google.auth.transport import requests + from google.cloud.exceptions import NotFound + from google.cloud.storage import Blob + from google.cloud.storage import Client + from google.cloud.storage.blob import _quote + from google.cloud.storage.retry import DEFAULT_RETRY +except ImportError: + raise ImproperlyConfigured( + "Could not load Google Cloud Storage bindings.\n" + "See https://github.com/GoogleCloudPlatform/gcloud-python" + ) + + +CONTENT_ENCODING = "content_encoding" +CONTENT_TYPE = "content_type" + + +class GoogleCloudFile(CompressedFileMixin, File): + def __init__(self, name, mode, storage): + self.name = name + self.mime_type, self.mime_encoding = mimetypes.guess_type(name) + self._mode = mode + self._storage = storage + self.blob = storage.bucket.get_blob(name, chunk_size=storage.blob_chunk_size) + if not self.blob and "w" in mode: + self.blob = Blob( + self.name, storage.bucket, chunk_size=storage.blob_chunk_size + ) + self._file = None + self._is_dirty = False + + @property + def size(self): + return self.blob.size + + def _get_file(self): + if self._file is None: + self._file = SpooledTemporaryFile( + max_size=self._storage.max_memory_size, + suffix=".GSStorageFile", + dir=setting("FILE_UPLOAD_TEMP_DIR"), + ) + if "r" in self._mode: + self._is_dirty = False + # This automatically decompresses the file + self.blob.download_to_file(self._file, checksum="crc32c") + self._file.seek(0) + return self._file + + def _set_file(self, value): + self._file = value + + file = property(_get_file, _set_file) + + def read(self, num_bytes=None): + if "r" not in self._mode: + raise AttributeError("File was not opened in read mode.") + + if num_bytes is None: + num_bytes = -1 + + return super().read(num_bytes) + + def write(self, content): + if "w" not in self._mode: + raise AttributeError("File was not opened in write mode.") + self._is_dirty = True + return super().write(to_bytes(content)) + + def close(self): + if self._file is not None: + if self._is_dirty: + blob_params = self._storage.get_object_parameters(self.name) + self.blob.upload_from_file( + self.file, + rewind=True, + content_type=self.mime_type, + retry=DEFAULT_RETRY, + predefined_acl=blob_params.get("acl", self._storage.default_acl), + ) + self._file.close() + self._file = None + + +class _GoogleCloudStream: + """Read a GCS blob with one bounded HTTP range request per ``read()``.""" + + def __init__(self, blob, start, length): + self.blob = blob + self.position = start + self.length = length + self.remaining = length + + def read(self, size=-1): + if self.remaining == 0: + return b"" + if size is None or size < 0 or size > self.remaining: + size = self.remaining + end = self.position + size - 1 + result = self.blob.download_as_bytes( + start=self.position, + end=end, + retry=DEFAULT_RETRY, + ) + self.position += len(result) + self.remaining -= len(result) + return result + + +@deconstructible +class GoogleCloudStorage(BaseStorage): + def __init__(self, **settings): + super().__init__(**settings) + + check_location(self) + + self._bucket = None + self._client = None + + def get_default_settings(self): + return { + "project_id": setting("GS_PROJECT_ID"), + "credentials": setting("GS_CREDENTIALS"), + "bucket_name": setting("GS_BUCKET_NAME"), + "custom_endpoint": setting("GS_CUSTOM_ENDPOINT", None), + "location": setting("GS_LOCATION", ""), + "default_acl": setting("GS_DEFAULT_ACL"), + "querystring_auth": setting("GS_QUERYSTRING_AUTH", True), + "expiration": setting("GS_EXPIRATION", timedelta(seconds=86400)), + "gzip": setting("GS_IS_GZIPPED", False), + "gzip_content_types": setting( + "GZIP_CONTENT_TYPES", + ( + "text/css", + "text/javascript", + "application/javascript", + "application/x-javascript", + "image/svg+xml", + ), + ), + "file_overwrite": setting("GS_FILE_OVERWRITE", True), + "object_parameters": setting("GS_OBJECT_PARAMETERS", {}), + # The max amount of memory a returned file can take up before being + # rolled over into a temporary file on disk. Default is 0: Do not + # roll over. + "max_memory_size": setting("GS_MAX_MEMORY_SIZE", 0), + "blob_chunk_size": setting("GS_BLOB_CHUNK_SIZE"), + # use in cases where service account key isn't available in env + # in such cases, sign blob api is REQUIRED for signing data + "iam_sign_blob": setting("GS_IAM_SIGN_BLOB", False), + "sa_email": setting("GS_SA_EMAIL"), + } + + @property + def client(self): + if self._client is None: + if self.iam_sign_blob and not self.credentials: + self.credentials, self.project_id = auth.default( + scopes=["https://www.googleapis.com/auth/cloud-platform"] + ) + self._client = Client(project=self.project_id, credentials=self.credentials) + return self._client + + @property + def bucket(self): + if self._bucket is None: + self._bucket = self.client.bucket(self.bucket_name) + return self._bucket + + def _normalize_name(self, name): + """ + Normalizes the name so that paths like /path/to/ignored/../something.txt + and ./file.txt work. Note that clean_name adds ./ to some paths so + they need to be fixed here. We check to make sure that the path pointed + to is not outside the directory specified by the LOCATION setting. + """ + try: + return safe_join(self.location, name) + except ValueError: + raise SuspiciousOperation("Attempted access to '%s' denied." % name) + + def _open(self, name, mode="rb"): + name = self._normalize_name(clean_name(name)) + file_object = GoogleCloudFile(name, mode, self) + if not file_object.blob: + raise FileNotFoundError("File does not exist: %s" % name) + return file_object + + @contextmanager + def open_stream(self, name, start=0, length=None): + """Open a forward-only byte-range stream from a Google Cloud Storage blob. + + Unlike :meth:`open`, this method does not create a seekable Django file + or materialize the complete blob in a temporary file. ``name`` is the + logical storage name; ``start`` and ``length`` select a half-open byte + interval. Each positive-sized ``read()`` issues a bounded ranged + download request, so callers should read in bounded sizes. + """ + + validate_byte_range(start, length) + name = self._normalize_name(clean_name(name)) + blob = self.bucket.get_blob(name, chunk_size=self.blob_chunk_size) + if not blob: + raise FileNotFoundError("File does not exist: %s" % name) + + available = max(blob.size - start, 0) + stream = _GoogleCloudStream( + blob, start, min(length, available) if length else available + ) + yield LimitedStream(stream, stream.length) + + def _compress_content(self, content): + content.seek(0) + zbuf = io.BytesIO() + with gzip.GzipFile(mode="wb", fileobj=zbuf, mtime=0.0) as zfile: + zfile.write(to_bytes(content.read())) + zbuf.seek(0) + return zbuf + + def _save(self, name, content): + cleaned_name = clean_name(name) + name = self._normalize_name(cleaned_name) + + content.name = cleaned_name + file_object = GoogleCloudFile(name, "rw", self) + + blob_params = self.get_object_parameters(name) + if file_object.mime_encoding and CONTENT_ENCODING not in blob_params: + blob_params[CONTENT_ENCODING] = file_object.mime_encoding + + upload_params = {} + upload_params["predefined_acl"] = blob_params.pop("acl", self.default_acl) + upload_params[CONTENT_TYPE] = blob_params.pop( + CONTENT_TYPE, file_object.mime_type + ) + + if ( + self.gzip + and upload_params[CONTENT_TYPE] in self.gzip_content_types + and CONTENT_ENCODING not in blob_params + ): + content = self._compress_content(content) + blob_params[CONTENT_ENCODING] = "gzip" + + for prop, val in blob_params.items(): + setattr(file_object.blob, prop, val) + + file_object.blob.upload_from_file( + content, + rewind=True, + retry=DEFAULT_RETRY, + size=getattr(content, "size", None), + **upload_params, + ) + return cleaned_name + + def get_object_parameters(self, name): + """Override this to return a dictionary of overwritable blob-property to value. + + Returns GS_OBJECT_PARAMETERS by default. See the docs for all possible options. + """ + object_parameters = self.object_parameters.copy() + return object_parameters + + def delete(self, name): + name = self._normalize_name(clean_name(name)) + try: + self.bucket.delete_blob(name, retry=DEFAULT_RETRY) + except NotFound: + pass + + def exists(self, name): + if not name: # root element aka the bucket + try: + self.client.get_bucket(self.bucket) + return True + except NotFound: + return False + + name = self._normalize_name(clean_name(name)) + return bool(self.bucket.get_blob(name)) + + def listdir(self, name): + name = self._normalize_name(clean_name(name)) + # For bucket.list_blobs and logic below name needs to end in / + # but for the root path "" we leave it as an empty string + if name and not name.endswith("/"): + name += "/" + + iterator = self.bucket.list_blobs(prefix=name, delimiter="/") + blobs = list(iterator) + prefixes = iterator.prefixes + + files = [] + dirs = [] + + for blob in blobs: + parts = blob.name.split("/") + files.append(parts[-1]) + for folder_path in prefixes: + parts = folder_path.split("/") + dirs.append(parts[-2]) + + return list(dirs), files + + def _get_blob(self, name): + # Wrap google.cloud.storage's blob to raise if the file doesn't exist + blob = self.bucket.get_blob(name) + + if blob is None: + raise NotFound("File does not exist: {}".format(name)) + + return blob + + def size(self, name): + name = self._normalize_name(clean_name(name)) + blob = self._get_blob(name) + return blob.size + + def get_modified_time(self, name): + name = self._normalize_name(clean_name(name)) + blob = self._get_blob(name) + updated = blob.updated + return updated if setting("USE_TZ") else timezone.make_naive(updated) + + def get_created_time(self, name): + """ + Return the creation time (as a datetime) of the file specified by name. + The datetime will be timezone-aware if USE_TZ=True. + """ + name = self._normalize_name(clean_name(name)) + blob = self._get_blob(name) + created = blob.time_created + return created if setting("USE_TZ") else timezone.make_naive(created) + + def url(self, name, parameters=None): + """ + Return public URL or a signed URL for the Blob. + + To keep things snappy, the existence of blobs for public URLs is not checked. + """ + name = self._normalize_name(clean_name(name)) + blob = self.bucket.blob(name) + blob_params = self.get_object_parameters(name) + no_signed_url = ( + blob_params.get("acl", self.default_acl) == "publicRead" + or not self.querystring_auth + ) + + if not self.custom_endpoint and no_signed_url: + return blob.public_url + elif no_signed_url: + return "{storage_base_url}/{quoted_name}".format( + storage_base_url=self.custom_endpoint, + quoted_name=_quote(name, safe=b"/~"), + ) + else: + default_params = { + "bucket_bound_hostname": self.custom_endpoint, + "expiration": self.expiration, + "version": "v4", + } + params = parameters or {} + + if self.iam_sign_blob: + service_account_email, access_token = self._get_iam_sign_blob_params() + default_params["service_account_email"] = service_account_email + default_params["access_token"] = access_token + + for key, value in default_params.items(): + if value and key not in params: + params[key] = value + + return blob.generate_signed_url(**params) + + def get_available_name(self, name, max_length=None): + name = clean_name(name) + if self.file_overwrite: + return get_available_overwrite_name(name, max_length) + return super().get_available_name(name, max_length) + + def _get_iam_sign_blob_params(self): + if self.credentials.token_state != TokenState.FRESH: + self.credentials.refresh(requests.Request()) + + try: + service_account_email = self.credentials.service_account_email + except AttributeError: + service_account_email = None + + # sa_email has final say of service_account used to sign url if provided + if self.sa_email: + service_account_email = self.sa_email + + if not service_account_email: + raise AttributeError( + "Sign Blob API requires service_account_email to be available " + "through ADC or setting `sa_email`" + ) + + return service_account_email, self.credentials.token diff --git a/storages/backends/s3.py b/storages/backends/s3.py new file mode 100644 index 00000000000..875f34367fe --- /dev/null +++ b/storages/backends/s3.py @@ -0,0 +1,749 @@ +import io +import mimetypes +import os +import posixpath +import tempfile +import threading +import warnings +from contextlib import contextmanager +from datetime import datetime +from datetime import timedelta +from urllib.parse import urlencode + +from django.contrib.staticfiles.storage import ManifestFilesMixin +from django.core.exceptions import ImproperlyConfigured +from django.core.exceptions import SuspiciousOperation +from django.core.files.base import File +from django.utils.deconstruct import deconstructible +from django.utils.encoding import filepath_to_uri +from django.utils.timezone import make_naive + +from storages.backends._stream import validate_byte_range +from storages.base import BaseStorage +from storages.compress import CompressedFileMixin +from storages.compress import CompressStorageMixin +from storages.utils import ReadBytesWrapper +from storages.utils import check_location +from storages.utils import clean_name +from storages.utils import get_available_overwrite_name +from storages.utils import is_seekable +from storages.utils import lookup_env +from storages.utils import safe_join +from storages.utils import setting +from storages.utils import to_bytes + +try: + import boto3.session + import botocore + import s3transfer.constants + from boto3.s3.transfer import TransferConfig + from botocore.config import Config + from botocore.exceptions import ClientError + from botocore.signers import CloudFrontSigner +except ImportError as e: + raise ImproperlyConfigured("Could not load Boto3's S3 bindings. %s" % e) + + +# NOTE: these are defined as functions so both can be tested +def _use_cryptography_signer(): + # https://cryptography.io as an RSA backend + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.asymmetric import padding + from cryptography.hazmat.primitives.serialization import load_pem_private_key + + def _cloud_front_signer_from_pem(key_id, pem): + if isinstance(pem, str): + pem = pem.encode("ascii") + key = load_pem_private_key(pem, password=None, backend=default_backend()) + + return CloudFrontSigner( + key_id, lambda x: key.sign(x, padding.PKCS1v15(), hashes.SHA1()) + ) + + return _cloud_front_signer_from_pem + + +def _use_rsa_signer(): + # https://stuvel.eu/rsa as an RSA backend + import rsa + + def _cloud_front_signer_from_pem(key_id, pem): + if isinstance(pem, str): + pem = pem.encode("ascii") + key = rsa.PrivateKey.load_pkcs1(pem) + return CloudFrontSigner(key_id, lambda x: rsa.sign(x, key, "SHA-1")) + + return _cloud_front_signer_from_pem + + +for _signer_factory in (_use_cryptography_signer, _use_rsa_signer): + try: + _cloud_front_signer_from_pem = _signer_factory() + break + except ImportError: + pass +else: + + def _cloud_front_signer_from_pem(key_id, pem): + raise ImproperlyConfigured( + "An RSA backend is required for signing cloudfront URLs.\n" + "Supported backends are packages: cryptography and rsa." + ) + + +def _filter_download_params(params): + return { + key: value + for (key, value) in params.items() + if key in s3transfer.constants.ALLOWED_DOWNLOAD_ARGS + } + + +@deconstructible +class S3File(CompressedFileMixin, File): + """ + The default file object used by the S3Storage backend. + + This file implements file streaming using boto's multipart + uploading functionality. The file can be opened in read or + write mode. + + This class extends Django's File class. However, the contained + data is only the data contained in the current buffer. So you + should not access the contained file object directly. You should + access the data via this class. + + Warning: This file *must* be closed using the close() method in + order to properly write the file to S3. Be sure to close the file + in your application. + """ + + def __init__(self, name, mode, storage, buffer_size=None): + if "r" in mode and "w" in mode: + raise ValueError("Can't combine 'r' and 'w' in mode.") + self._storage = storage + self.name = name[len(self._storage.location) :].lstrip("/") + self._mode = mode + self.obj = storage.bucket.Object(name) + if "w" not in mode: + # Force early RAII-style exception if object does not exist + params = _filter_download_params( + self._storage.get_object_parameters(self.name) + ) + self.obj.load(**params) + self._closed = False + self._file = None + self._parts = None + # 5 MB is the minimum part size (if there is more than one part). + # Amazon allows up to 10,000 parts. The default supports uploads + # up to roughly 50 GB. Increase the part size to accommodate + # for files larger than this. + self.buffer_size = buffer_size or setting("AWS_S3_FILE_BUFFER_SIZE", 5242880) + self._reset_file_properties() + + def _reset_file_properties(self): + self._multipart = None + self._raw_bytes_written = 0 + self._write_counter = 0 + self._is_dirty = False + + def open(self, mode=None): + if self._file is not None and not self.closed: + self.seek(0) # Mirror Django's behavior + elif mode and mode != self._mode: + raise ValueError("Cannot reopen file with a new mode.") + + # Accessing the file will functionally re-open it + self.file # noqa: B018 + + return self + + @property + def size(self): + return self.obj.content_length + + @property + def closed(self): + return self._closed + + def _get_file(self): + if self._file is None: + self._file = tempfile.SpooledTemporaryFile( + max_size=self._storage.max_memory_size, + suffix=".S3File", + dir=setting("FILE_UPLOAD_TEMP_DIR"), + ) + if "r" in self._mode: + self._is_dirty = False + params = _filter_download_params( + self._storage.get_object_parameters(self.name) + ) + self.obj.download_fileobj( + self._file, ExtraArgs=params, Config=self._storage.transfer_config + ) + self._file.seek(0) + if self._storage.gzip and self.obj.content_encoding == "gzip": + self._file = self._decompress_file(mode=self._mode, file=self._file) + elif "b" not in self._mode: + if hasattr(self._file, "readable"): + # For versions > Python 3.10 compatibility + # See SpooledTemporaryFile changes in 3.11 (https://docs.python.org/3/library/tempfile.html) # noqa: E501 + # Now fully implements the io.BufferedIOBase and io.TextIOBase abstract base classes allowing the file # noqa: E501 + # to be readable in the mode that it was specified (without accessing the underlying _file object). # noqa: E501 + # In this case, we need to wrap the file in a TextIOWrapper to ensure that the file is read as a text file. # noqa: E501 + self._file = io.TextIOWrapper(self._file, encoding="utf-8") + else: + # For versions <= Python 3.10 compatibility + self._file = io.TextIOWrapper( + self._file._file, encoding="utf-8" + ) + self._closed = False + return self._file + + def _set_file(self, value): + self._file = value + + file = property(_get_file, _set_file) + + def read(self, *args, **kwargs): + if "r" not in self._mode: + raise AttributeError("File was not opened in read mode.") + return super().read(*args, **kwargs) + + def readline(self, *args, **kwargs): + if "r" not in self._mode: + raise AttributeError("File was not opened in read mode.") + return super().readline(*args, **kwargs) + + def readlines(self): + return list(self) + + def write(self, content): + if "w" not in self._mode: + raise AttributeError("File was not opened in write mode.") + self._is_dirty = True + if self._multipart is None: + self._multipart = self.obj.initiate_multipart_upload( + **self._storage._get_write_parameters(self.obj.key) + ) + self._parts = [] + if self.buffer_size <= self._buffer_file_size: + self._flush_write_buffer() + bstr = to_bytes(content) + self._raw_bytes_written += len(bstr) + return super().write(bstr) + + @property + def _buffer_file_size(self): + pos = self.file.tell() + self.file.seek(0, os.SEEK_END) + length = self.file.tell() + self.file.seek(pos) + return length + + def _flush_write_buffer(self): + if self._buffer_file_size: + self._write_counter += 1 + self.file.seek(0) + part = self._multipart.Part(self._write_counter) + response = part.upload(Body=self.file.read()) + self._parts.append( + {"ETag": response["ETag"], "PartNumber": self._write_counter} + ) + self.file.seek(0) + self.file.truncate() + + def _create_empty_on_close(self): + """ + Attempt to create an empty file for this key when this File is closed if no + bytes have been written and no object already exists on S3 for this key. + + This behavior is meant to mimic the behavior of Django's builtin + FileSystemStorage, where files are always created after they are opened in + write mode: + + f = storage.open('file.txt', mode='w') + f.close() + """ + assert "w" in self._mode + assert self._raw_bytes_written == 0 + + try: + # Check if the object exists on the server; if so, don't do anything + self.obj.load() + except ClientError as err: + if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + self.obj.put( + Body=b"", **self._storage._get_write_parameters(self.obj.key) + ) + else: + raise + + def close(self): + if self._is_dirty: + if self._multipart is not None: + self._flush_write_buffer() + self._multipart.complete(MultipartUpload={"Parts": self._parts}) + else: + if self._multipart is not None: + self._multipart.abort() + if "w" in self._mode and self._raw_bytes_written == 0: + self._create_empty_on_close() + if self._file is not None: + self._file.close() + self._file = None + + self._reset_file_properties() + self._closed = True + + +@deconstructible +class S3Storage(CompressStorageMixin, BaseStorage): + """ + Amazon Simple Storage Service using Boto3 + + This storage backend supports opening files in read or write + mode and supports streaming(buffering) data in chunks to S3 + when writing. + """ + + default_content_type = "application/octet-stream" + # If config provided in subclass, signature_version and addressing_style + # settings/args are ignored. + config = None + + _signers = {} # noqa: RUF012 + + def __init__(self, **settings): + omitted = object() + if not hasattr(self, "cloudfront_signer"): + self.cloudfront_signer = settings.pop("cloudfront_signer", omitted) + + super().__init__(**settings) + + check_location(self) + + if (self.access_key or self.secret_key) and self.session_profile: + raise ImproperlyConfigured( + "AWS_S3_SESSION_PROFILE/session_profile should not be provided with " + "AWS_S3_ACCESS_KEY_ID/access_key and " + "AWS_S3_SECRET_ACCESS_KEY/secret_key" + ) + + self._bucket = None + self._connections = threading.local() + self._unsigned_connections = threading.local() + + if self.config is not None: + warnings.warn( + "The 'config' class property is deprecated and will be " + "removed in a future version. Use AWS_S3_CLIENT_CONFIG " + "to customize any of the botocore.config.Config parameters.", + DeprecationWarning, + ) + self.client_config = self.config + + if self.client_config is None: + self.client_config = Config( + s3={"addressing_style": self.addressing_style}, + signature_version=self.signature_version, + proxies=self.proxies, + ) + + if self.use_threads is False: + warnings.warn( + "The AWS_S3_USE_THREADS setting is deprecated. Use " + "AWS_S3_TRANSFER_CONFIG to customize any of the " + "boto.s3.transfer.TransferConfig parameters.", + DeprecationWarning, + ) + + if self.transfer_config is None: + self.transfer_config = TransferConfig(use_threads=self.use_threads) + + if self.cloudfront_signer is omitted: + if self.cloudfront_key_id and self.cloudfront_key: + self.cloudfront_signer = self.get_cloudfront_signer( + self.cloudfront_key_id, self.cloudfront_key + ) + elif bool(self.cloudfront_key_id) ^ bool(self.cloudfront_key): + raise ImproperlyConfigured( + "Both AWS_CLOUDFRONT_KEY_ID/cloudfront_key_id and " + "AWS_CLOUDFRONT_KEY/cloudfront_key must be provided together." + ) + else: + self.cloudfront_signer = None + + def get_cloudfront_signer(self, key_id, key): + cache_key = f"{key_id}:{key}" + if cache_key not in self.__class__._signers: + self.__class__._signers[cache_key] = _cloud_front_signer_from_pem( + key_id, key + ) + return self.__class__._signers[cache_key] + + def get_default_settings(self): + return { + "access_key": setting( + "AWS_S3_ACCESS_KEY_ID", + setting( + "AWS_ACCESS_KEY_ID", + lookup_env(["AWS_S3_ACCESS_KEY_ID", "AWS_ACCESS_KEY_ID"]), + ), + ), + "secret_key": setting( + "AWS_S3_SECRET_ACCESS_KEY", + setting( + "AWS_SECRET_ACCESS_KEY", + lookup_env(["AWS_S3_SECRET_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY"]), + ), + ), + "security_token": setting( + "AWS_SESSION_TOKEN", + setting( + "AWS_SECURITY_TOKEN", + lookup_env(["AWS_SESSION_TOKEN", "AWS_SECURITY_TOKEN"]), + ), + ), + "session_profile": setting( + "AWS_S3_SESSION_PROFILE", lookup_env(["AWS_S3_SESSION_PROFILE"]) + ), + "file_overwrite": setting("AWS_S3_FILE_OVERWRITE", True), + "object_parameters": setting("AWS_S3_OBJECT_PARAMETERS", {}), + "bucket_name": setting("AWS_STORAGE_BUCKET_NAME"), + "querystring_auth": setting("AWS_QUERYSTRING_AUTH", True), + "querystring_expire": setting("AWS_QUERYSTRING_EXPIRE", 3600), + "signature_version": setting("AWS_S3_SIGNATURE_VERSION"), + "location": setting("AWS_LOCATION", ""), + "custom_domain": setting("AWS_S3_CUSTOM_DOMAIN"), + "cloudfront_key_id": setting("AWS_CLOUDFRONT_KEY_ID"), + "cloudfront_key": setting("AWS_CLOUDFRONT_KEY"), + "addressing_style": setting("AWS_S3_ADDRESSING_STYLE"), + "file_name_charset": setting("AWS_S3_FILE_NAME_CHARSET", "utf-8"), + "gzip": setting("AWS_IS_GZIPPED", False), + "gzip_content_types": setting( + "GZIP_CONTENT_TYPES", + ( + "text/css", + "text/javascript", + "application/javascript", + "application/x-javascript", + "image/svg+xml", + ), + ), + "url_protocol": setting("AWS_S3_URL_PROTOCOL") or "https:", + "endpoint_url": setting("AWS_S3_ENDPOINT_URL"), + "proxies": setting("AWS_S3_PROXIES"), + "region_name": setting("AWS_S3_REGION_NAME"), + "use_ssl": setting("AWS_S3_USE_SSL", True), + "verify": setting("AWS_S3_VERIFY", None), + "max_memory_size": setting("AWS_S3_MAX_MEMORY_SIZE", 0), + "default_acl": setting("AWS_DEFAULT_ACL", None), + "use_threads": setting("AWS_S3_USE_THREADS", True), + "transfer_config": setting("AWS_S3_TRANSFER_CONFIG", None), + "client_config": setting("AWS_S3_CLIENT_CONFIG", None), + } + + def __getstate__(self): + state = self.__dict__.copy() + state.pop("_connections", None) + state.pop("_unsigned_connections", None) + state.pop("_bucket", None) + return state + + def __setstate__(self, state): + state["_connections"] = threading.local() + state["_unsigned_connections"] = threading.local() + state["_bucket"] = None + self.__dict__ = state + + @property + def connection(self): + connection = getattr(self._connections, "connection", None) + if connection is None: + session = self._create_session() + self._connections.connection = session.resource( + "s3", + region_name=self.region_name, + use_ssl=self.use_ssl, + endpoint_url=self.endpoint_url, + config=self.client_config, + verify=self.verify, + ) + return self._connections.connection + + @property + def unsigned_connection(self): + unsigned_connection = getattr(self._unsigned_connections, "connection", None) + if unsigned_connection is None: + session = self._create_session() + config = self.client_config.merge( + Config(signature_version=botocore.UNSIGNED) + ) + self._unsigned_connections.connection = session.resource( + "s3", + region_name=self.region_name, + use_ssl=self.use_ssl, + endpoint_url=self.endpoint_url, + config=config, + verify=self.verify, + ) + return self._unsigned_connections.connection + + def _create_session(self): + """ + If a user specifies a profile name and this class obtains access keys + from another source such as environment variables,we want the profile + name to take precedence. + """ + if self.session_profile: + session = boto3.Session(profile_name=self.session_profile) + else: + session = boto3.Session( + aws_access_key_id=self.access_key, + aws_secret_access_key=self.secret_key, + aws_session_token=self.security_token, + ) + return session + + @property + def bucket(self): + """ + Get the current bucket. If there is no current bucket object + create it. + """ + if self._bucket is None: + self._bucket = self.connection.Bucket(self.bucket_name) + return self._bucket + + def _normalize_name(self, name): + """ + Normalizes the name so that paths like /path/to/ignored/../something.txt + work. We check to make sure that the path pointed to is not outside + the directory specified by the LOCATION setting. + """ + try: + return safe_join(self.location, name) + except ValueError: + raise SuspiciousOperation("Attempted access to '%s' denied." % name) + + def _open(self, name, mode="rb"): + name = self._normalize_name(clean_name(name)) + try: + f = S3File(name, mode, self) + except ClientError as err: + if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + raise FileNotFoundError("File does not exist: %s" % name) + raise # Let it bubble up if it was some other error + return f + + @contextmanager + def open_stream(self, name, start=0, length=None): + """Open a forward-only byte-range stream from an S3 object. + + Unlike :meth:`open`, this method does not create a seekable Django file + or materialize the complete object in a temporary file. ``name`` is the + logical storage name; ``start`` and ``length`` select a half-open byte + interval. Read in bounded sizes and use the context manager so its HTTP + response body is released when reading ends early. + + This deliberately does not apply :class:`S3File` compatibility + transformations, including transparent gzip decompression. + """ + + validate_byte_range(start, length) + logical_name = clean_name(name) + key = self._normalize_name(logical_name) + params = _filter_download_params(self.get_object_parameters(logical_name)) + params.update(Bucket=self.bucket_name, Key=key) + if start or length is not None: + end = "" if length is None else start + length - 1 + params["Range"] = f"bytes={start}-{end}" + + response = self.connection.meta.client.get_object(**params) + body = response["Body"] + try: + yield body + finally: + body.close() + + def _save(self, name, content): + cleaned_name = clean_name(name) + name = self._normalize_name(cleaned_name) + params = self._get_write_parameters(name, content) + + if is_seekable(content): + content.seek(0, os.SEEK_SET) + + # wrap content so read() always returns bytes. This is required for passing it + # to obj.upload_fileobj() or self._compress_content() + content = ReadBytesWrapper(content) + + if ( + self.gzip + and params["ContentType"] in self.gzip_content_types + and "ContentEncoding" not in params + ): + content = self._compress_content(content) + params["ContentEncoding"] = "gzip" + + obj = self.bucket.Object(name) + + # Workaround file being closed errantly see: https://github.com/boto/s3transfer/issues/80 + original_close = content.close + content.close = lambda: None + try: + obj.upload_fileobj(content, ExtraArgs=params, Config=self.transfer_config) + finally: + content.close = original_close + return cleaned_name + + def delete(self, name): + try: + name = self._normalize_name(clean_name(name)) + self.bucket.Object(name).delete() + except ClientError as err: + if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + # Not an error to delete something that does not exist + return + + # Some other error was encountered. Re-raise it + raise + + def exists(self, name): + name = self._normalize_name(clean_name(name)) + params = _filter_download_params(self.get_object_parameters(name)) + try: + self.connection.meta.client.head_object( + Bucket=self.bucket_name, Key=name, **params + ) + return True + except ClientError as err: + if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + return False + + # Some other error was encountered. Re-raise it. + raise + + def listdir(self, name): + path = self._normalize_name(clean_name(name)) + # The path needs to end with a slash, but if the root is empty, leave it. + if path and not path.endswith("/"): + path += "/" + + directories = [] + files = [] + paginator = self.connection.meta.client.get_paginator("list_objects") + pages = paginator.paginate(Bucket=self.bucket_name, Delimiter="/", Prefix=path) + for page in pages: + directories += [ + posixpath.relpath(entry["Prefix"], path) + for entry in page.get("CommonPrefixes", ()) + ] + for entry in page.get("Contents", ()): + key = entry["Key"] + if key != path: + files.append(posixpath.relpath(key, path)) + return directories, files + + def size(self, name): + name = self._normalize_name(clean_name(name)) + try: + return self.bucket.Object(name).content_length + except ClientError as err: + if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + raise FileNotFoundError("File does not exist: %s" % name) + raise # Let it bubble up if it was some other error + + def _get_write_parameters(self, name, content=None): + params = self.get_object_parameters(name) + + if "ContentType" not in params: + _type, encoding = mimetypes.guess_type(name) + content_type = getattr(content, "content_type", None) + content_type = content_type or _type or self.default_content_type + + params["ContentType"] = content_type + if encoding: + params["ContentEncoding"] = encoding + + if "ACL" not in params and self.default_acl: + params["ACL"] = self.default_acl + + return params + + def get_object_parameters(self, name): + """ + Returns a dictionary that is passed to file upload. Override this + method to adjust this on a per-object basis to set e.g ContentDisposition. + + By default, returns the value of AWS_S3_OBJECT_PARAMETERS. + + Setting ContentEncoding will prevent objects from being automatically gzipped. + """ + return self.object_parameters.copy() + + def get_modified_time(self, name): + """ + Returns an (aware) datetime object containing the last modified time if + USE_TZ is True, otherwise returns a naive datetime in the local timezone. + """ + name = self._normalize_name(clean_name(name)) + entry = self.bucket.Object(name) + if setting("USE_TZ"): + # boto3 returns TZ aware timestamps + return entry.last_modified + else: + return make_naive(entry.last_modified) + + def url(self, name, parameters=None, expire=None, http_method=None): + # Preserve the trailing slash after normalizing the path. + name = self._normalize_name(clean_name(name)) + params = parameters.copy() if parameters else {} + if expire is None: + expire = self.querystring_expire + + if self.custom_domain: + url = "{}//{}/{}{}".format( + self.url_protocol, + self.custom_domain, + filepath_to_uri(name), + "?{}".format(urlencode(params)) if params else "", + ) + + if self.querystring_auth and self.cloudfront_signer: + expiration = datetime.utcnow() + timedelta(seconds=expire) + return self.cloudfront_signer.generate_presigned_url( + url, date_less_than=expiration + ) + + return url + + params["Bucket"] = self.bucket.name + params["Key"] = name + + connection = ( + self.connection if self.querystring_auth else self.unsigned_connection + ) + url = connection.meta.client.generate_presigned_url( + "get_object", Params=params, ExpiresIn=expire, HttpMethod=http_method + ) + return url + + def get_available_name(self, name, max_length=None): + """Overwrite existing file with the same name.""" + name = clean_name(name) + if self.file_overwrite: + return get_available_overwrite_name(name, max_length) + return super().get_available_name(name, max_length) + + +class S3StaticStorage(S3Storage): + """Querystring auth must be disabled so that url() returns a consistent output.""" + + querystring_auth = False + + +class S3ManifestStaticStorage(ManifestFilesMixin, S3StaticStorage): + """Add ManifestFilesMixin with S3StaticStorage.""" diff --git a/storages/backends/s3boto3.py b/storages/backends/s3boto3.py new file mode 100644 index 00000000000..d3a69aa2a30 --- /dev/null +++ b/storages/backends/s3boto3.py @@ -0,0 +1,6 @@ +"""Backwards compat shim.""" + +from storages.backends.s3 import S3File as S3Boto3StorageFile # noqa +from storages.backends.s3 import S3ManifestStaticStorage # noqa +from storages.backends.s3 import S3StaticStorage # noqa +from storages.backends.s3 import S3Storage as S3Boto3Storage # noqa diff --git a/storages/backends/sftpstorage.py b/storages/backends/sftpstorage.py new file mode 100644 index 00000000000..bac6e4ae2a5 --- /dev/null +++ b/storages/backends/sftpstorage.py @@ -0,0 +1,245 @@ +# SFTP storage backend for Django. +# Author: Brent Tubbs +# License: MIT +# +# Modeled on the FTP storage by Rafal Jonca + +import datetime +import getpass +import io +import os +import posixpath +import stat +from urllib.parse import urljoin + +import paramiko +from django.core.files.base import File +from django.utils.deconstruct import deconstructible +from paramiko.util import ClosingContextManager + +from storages.base import BaseStorage +from storages.utils import is_seekable +from storages.utils import setting + + +@deconstructible +class SFTPStorage(ClosingContextManager, BaseStorage): + def __init__(self, **settings): + super().__init__(**settings) + self._ssh = None + self._sftp = None + + def get_default_settings(self): + return { + "host": setting("SFTP_STORAGE_HOST"), + "params": setting("SFTP_STORAGE_PARAMS", {}), + "interactive": setting("SFTP_STORAGE_INTERACTIVE", False), + "file_mode": setting("SFTP_STORAGE_FILE_MODE"), + "dir_mode": setting("SFTP_STORAGE_DIR_MODE"), + "uid": setting("SFTP_STORAGE_UID"), + "gid": setting("SFTP_STORAGE_GID"), + "known_host_file": setting("SFTP_KNOWN_HOST_FILE"), + "root_path": setting("SFTP_STORAGE_ROOT", ""), + "base_url": setting("SFTP_BASE_URL") or setting("MEDIA_URL"), + } + + def _connect(self): + self._ssh = paramiko.SSHClient() + + known_host_file = self.known_host_file or os.path.expanduser( + os.path.join("~", ".ssh", "known_hosts") + ) + + if os.path.exists(known_host_file): + self._ssh.load_host_keys(known_host_file) + + # and automatically add new host keys for hosts we haven't seen before. + self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + try: + self._ssh.connect(self.host, **self.params) + except paramiko.AuthenticationException as e: + if self.interactive and "password" not in self.params: + # If authentication has failed, and we haven't already tried + # username/password, and configuration allows it, then try + # again with username/password. + if "username" not in self.params: + self.params["username"] = getpass.getuser() + self.params["password"] = getpass.getpass() + self._connect() + else: + raise paramiko.AuthenticationException(e) + + if self._ssh.get_transport(): + self._sftp = self._ssh.open_sftp() + + def close(self): + if self._ssh is None: + return + self._ssh.close() + + @property + def sftp(self): + """Lazy SFTP connection""" + if not self._sftp or not self._ssh.get_transport().is_active(): + self._connect() + return self._sftp + + def _remote_path(self, name): + return posixpath.join(self.root_path, name) + + def _open(self, name, mode="rb"): + return SFTPStorageFile(name, self, mode) + + def _read(self, name): + remote_path = self._remote_path(name) + return self.sftp.open(remote_path, "rb") + + def _chown(self, path, uid=None, gid=None): + """Set uid and/or gid for file at path.""" + # Paramiko's chown requires both uid and gid, so look them up first if + # we're only supposed to set one. + if uid is None or gid is None: + attr = self.sftp.stat(path) + uid = uid or attr.st_uid + gid = gid or attr.st_gid + self.sftp.chown(path, uid, gid) + + def _mkdir(self, path): + """Create directory, recursing up to create parent dirs if + necessary.""" + parent = posixpath.dirname(path) + if not self._path_exists(parent): + self._mkdir(parent) + self.sftp.mkdir(path) + + if self.dir_mode is not None: + self.sftp.chmod(path, self.dir_mode) + + if self.uid or self.gid: + self._chown(path, uid=self.uid, gid=self.gid) + + def _save(self, name, content): + """Save file via SFTP.""" + if is_seekable(content): + content.seek(0, os.SEEK_SET) + path = self._remote_path(name) + dirname = posixpath.dirname(path) + if not self._path_exists(dirname): + self._mkdir(dirname) + + self.sftp.putfo(content, path) + + # set file permissions if configured + if self.file_mode is not None: + self.sftp.chmod(path, self.file_mode) + if self.uid or self.gid: + self._chown(path, uid=self.uid, gid=self.gid) + return name + + def delete(self, name): + try: + self.sftp.remove(self._remote_path(name)) + except OSError: + pass + + def _path_exists(self, path): + """Determines whether a file existis in the sftp storage given its + absolute path.""" + try: + self.sftp.stat(path) + return True + except FileNotFoundError: + return False + + def exists(self, name): + """Determines whether a file exists within the root folder of the SFTP storage + (as set by `SFTP_STORAGE_ROOT`). This method differs from `._path_exists()` + in that the provided `name` is assumed to be the relative path of the file + within the root folder. + """ + return self._path_exists(self._remote_path(name)) + + def _isdir_attr(self, item): + # Return whether an item in sftp.listdir_attr results is a directory + if item.st_mode is not None: + return stat.S_IFMT(item.st_mode) == stat.S_IFDIR + else: + return False + + def listdir(self, path): + remote_path = self._remote_path(path) + dirs, files = [], [] + for item in self.sftp.listdir_attr(remote_path): + if self._isdir_attr(item): + dirs.append(item.filename) + else: + files.append(item.filename) + return dirs, files + + def size(self, name): + remote_path = self._remote_path(name) + return self.sftp.stat(remote_path).st_size + + # From Django + def _datetime_from_timestamp(self, ts): + tz = datetime.timezone.utc if setting("USE_TZ") else None + return datetime.datetime.fromtimestamp(ts, tz=tz) + + def get_accessed_time(self, name): + remote_path = self._remote_path(name) + utime = self.sftp.stat(remote_path).st_atime + return self._datetime_from_timestamp(utime) + + def get_modified_time(self, name): + remote_path = self._remote_path(name) + utime = self.sftp.stat(remote_path).st_mtime + return self._datetime_from_timestamp(utime) + + def url(self, name): + if self.base_url is None: + raise ValueError("This file is not accessible via a URL.") + return urljoin(self.base_url, name).replace("\\", "/") + + +class SFTPStorageFile(File): + def __init__(self, name, storage, mode): + self.name = name + self.mode = mode + self.file = io.BytesIO() + self._storage = storage + self._is_read = False + self._is_dirty = False + + @property + def size(self): + if not hasattr(self, "_size"): + self._size = self._storage.size(self.name) + return self._size + + def read(self, num_bytes=None): + if not self._is_read: + self.file = self._storage._read(self.name) + self._is_read = True + + return self.file.read(num_bytes) + + def write(self, content): + if "w" not in self.mode: + raise AttributeError("File was opened for read-only access.") + self.file = io.BytesIO(content) + self._is_dirty = True + self._is_read = True + + def open(self, mode=None): + if not self.closed: + self.seek(0) + elif self.name and self._storage.exists(self.name): + self.file = self._storage._open(self.name, mode or self.mode) + else: + raise ValueError("The file cannot be reopened.") + + def close(self): + if self._is_dirty: + self._storage._save(self.name, self) + self.file.close() diff --git a/storages/base.py b/storages/base.py new file mode 100644 index 00000000000..f919b78f136 --- /dev/null +++ b/storages/base.py @@ -0,0 +1,24 @@ +from django.core.exceptions import ImproperlyConfigured +from django.core.files.storage import Storage + + +class BaseStorage(Storage): + def __init__(self, **settings): + default_settings = self.get_default_settings() + + for name, value in default_settings.items(): + if not hasattr(self, name): + setattr(self, name, value) + + for name, value in settings.items(): + if name not in default_settings: + raise ImproperlyConfigured( + "Invalid setting '{}' for {}".format( + name, + self.__class__.__name__, + ) + ) + setattr(self, name, value) + + def get_default_settings(self): + return {} diff --git a/storages/compress.py b/storages/compress.py new file mode 100644 index 00000000000..0c24255fe5a --- /dev/null +++ b/storages/compress.py @@ -0,0 +1,49 @@ +import io +import zlib +from gzip import GzipFile +from typing import Optional + +from storages.utils import to_bytes + + +class GzipCompressionWrapper(io.RawIOBase): + """Wrapper for compressing file contents on the fly.""" + + def __init__(self, raw, level=zlib.Z_BEST_COMPRESSION): + super().__init__() + self.raw = raw + self.compress = zlib.compressobj(level=level, wbits=31) + self.leftover = bytearray() + + @staticmethod + def readable(): + return True + + def readinto(self, buf: bytearray) -> Optional[int]: + size = len(buf) + while len(self.leftover) < size: + chunk = to_bytes(self.raw.read(size)) + if not chunk: + if self.compress: + self.leftover += self.compress.flush(zlib.Z_FINISH) + self.compress = None + break + self.leftover += self.compress.compress(chunk) + if len(self.leftover) == 0: + return 0 + output = self.leftover[:size] + size = len(output) + buf[:size] = output + self.leftover = self.leftover[size:] + return size + + +class CompressStorageMixin: + def _compress_content(self, content): + """Gzip a given string content.""" + return GzipCompressionWrapper(content) + + +class CompressedFileMixin: + def _decompress_file(self, mode, file, mtime=0.0): + return GzipFile(mode=mode, fileobj=file, mtime=mtime) diff --git a/storages/utils.py b/storages/utils.py new file mode 100644 index 00000000000..9235f5cd879 --- /dev/null +++ b/storages/utils.py @@ -0,0 +1,182 @@ +import os +import pathlib +import posixpath + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from django.core.exceptions import SuspiciousFileOperation +from django.core.files.utils import FileProxyMixin +from django.core.files.utils import validate_file_name +from django.utils.encoding import force_bytes + + +def to_bytes(content): + """Wrap Django's force_bytes to pass through bytearrays.""" + if isinstance(content, bytearray): + return content + + return force_bytes(content) + + +def setting(name, default=None): + """ + Helper function to get a Django setting by name. If setting doesn't exists + it will return a default. + + :param name: Name of setting + :type name: str + :param default: Value if setting is unfound + :returns: Setting's value + """ + return getattr(settings, name, default) + + +def clean_name(name): + """ + Normalize the name. + + Includes cleaning up Windows style paths, ensuring an ending trailing slash, + and coercing from pathlib.PurePath. + """ + if isinstance(name, pathlib.PurePath): + name = str(name) + + # Normalize Windows style paths + clean_name = posixpath.normpath(name).replace("\\", "/") + + # os.path.normpath() can strip trailing slashes so we implement + # a workaround here. + if name.endswith("/") and not clean_name.endswith("/"): + # Add a trailing slash as it was stripped. + clean_name += "/" + + # Given an empty string, os.path.normpath() will return ., which we don't want + if clean_name == ".": + clean_name = "" + + return clean_name + + +def safe_join(base, *paths): + """ + A version of django.utils._os.safe_join for S3 paths. + + Joins one or more path components to the base path component + intelligently. Returns a normalized version of the final path. + + The final path must be located inside of the base path component + (otherwise a ValueError is raised). + + Paths outside the base path indicate a possible security + sensitive operation. + """ + base_path = base + base_path = base_path.rstrip("/") + paths = list(paths) + + final_path = base_path + "/" + for path in paths: + _final_path = posixpath.normpath(posixpath.join(final_path, path)) + # posixpath.normpath() strips the trailing /. Add it back. + if path.endswith("/") or _final_path + "/" == final_path: + _final_path += "/" + final_path = _final_path + if final_path == base_path: + final_path += "/" + + # Ensure final_path starts with base_path and that the next character after + # the base path is /. + base_path_len = len(base_path) + if not final_path.startswith(base_path) or final_path[base_path_len] != "/": + raise ValueError( + "the joined path is located outside of the base path component" + ) + + return final_path.lstrip("/") + + +def check_location(storage): + if storage.location.startswith("/"): + correct = storage.location.lstrip("/") + raise ImproperlyConfigured( + ( + "{}.location cannot begin with a leading slash. Found '{}'. Use '{}' " + "instead." + ).format( + storage.__class__.__name__, + storage.location, + correct, + ) + ) + + +def lookup_env(names): + """ + Look up for names in environment. Returns the first element + found. + """ + for name in names: + value = os.environ.get(name) + if value: + return value + + +def get_available_overwrite_name(name, max_length): + # This is adapted from Django, and will be removed once + # Django 5.1 is the lowest supported version + dir_name, file_name = os.path.split(name) + if ".." in pathlib.PurePath(dir_name).parts: + raise SuspiciousFileOperation( + "Detected path traversal attempt in '%s'" % dir_name + ) + validate_file_name(file_name, allow_relative_path=True) + + if max_length is None or len(name) <= max_length: + return name + + file_root, file_ext = os.path.splitext(file_name) + truncation = len(name) - max_length + + file_root = file_root[:-truncation] + if not file_root: + raise SuspiciousFileOperation( + 'Storage tried to truncate away entire filename "%s". ' + "Please make sure that the corresponding file field " + 'allows sufficient "max_length".' % name + ) + name = os.path.join(dir_name, "{}{}".format(file_root, file_ext)) + validate_file_name(name, allow_relative_path=True) + return name + + +def is_seekable(file_object): + return not hasattr(file_object, "seekable") or file_object.seekable() + + +class ReadBytesWrapper(FileProxyMixin): + """ + A wrapper for a file-like object, that makes read() always returns bytes. + """ + + def __init__(self, file, encoding=None): + """ + :param file: The file-like object to wrap. + :param encoding: Specify the encoding to use when file.read() returns strings. + If not provided will default to file.encoding, of if that's not available, + to utf-8. + """ + self.file = file + self._encoding = encoding or getattr(file, "encoding", None) or "utf-8" + + def read(self, *args, **kwargs): + content = self.file.read(*args, **kwargs) + + if not isinstance(content, bytes): + content = content.encode(self._encoding) + return content + + def close(self): + self.file.close() + + def readable(self): + return True From d6661a024f9ac6515c53b4de6540e6e6cb78da0c Mon Sep 17 00:00:00 2001 From: Daniel Alley Date: Mon, 23 Nov 2026 23:13:32 -0500 Subject: [PATCH 3/6] ruff format --- storages/backends/apache_libcloud.py | 7 ++--- storages/backends/azure_storage.py | 25 ++++----------- storages/backends/dropbox.py | 12 ++----- storages/backends/ftp.py | 7 ++--- storages/backends/gcloud.py | 15 +++------ storages/backends/s3.py | 47 +++++++--------------------- storages/utils.py | 13 ++------ 7 files changed, 32 insertions(+), 94 deletions(-) diff --git a/storages/backends/apache_libcloud.py b/storages/backends/apache_libcloud.py index 2c717a28c29..84fa155cbe2 100644 --- a/storages/backends/apache_libcloud.py +++ b/storages/backends/apache_libcloud.py @@ -49,13 +49,10 @@ def __init__(self, provider_name=None, option=None): provider_type = getattr(Provider, tag) Driver = get_driver(provider_type) - self.driver = Driver( - self.provider["user"], self.provider["key"], **extra_kwargs - ) + self.driver = Driver(self.provider["user"], self.provider["key"], **extra_kwargs) except Exception as e: raise ImproperlyConfigured( - "Unable to create libcloud driver type %s: %s" - % (self.provider.get("type"), e) + "Unable to create libcloud driver type %s: %s" % (self.provider.get("type"), e) ) self.bucket = self.provider["bucket"] # Limit to one container diff --git a/storages/backends/azure_storage.py b/storages/backends/azure_storage.py index aa53252adc4..4c12e7198fd 100644 --- a/storages/backends/azure_storage.py +++ b/storages/backends/azure_storage.py @@ -129,9 +129,7 @@ def __init__(self, **settings): self._user_delegation_key = None self._user_delegation_key_expiry = datetime.utcnow() if self.connection_string and (not self.account_name or not self.account_key): - parsed = parse_connection_string( - self.connection_string, case_sensitive_keys=True - ) + parsed = parse_connection_string(self.connection_string, case_sensitive_keys=True) if not self.account_name and "AccountName" in parsed: self.account_name = parsed["AccountName"] if not self.account_key and "AccountKey" in parsed: @@ -199,9 +197,7 @@ def service_client(self): @property def client(self): if self._client is None: - self._client = self.service_client.get_container_client( - self.azure_container - ) + self._client = self.service_client.get_container_client(self.azure_container) return self._client def get_user_delegation_key(self, expiry): @@ -212,10 +208,7 @@ def get_user_delegation_key(self, expiry): # Get a new key if we don't already have one, or if the one we have expires too # soon. - if ( - self._user_delegation_key is None - or expiry > self._user_delegation_key_expiry - ): + if self._user_delegation_key is None or expiry > self._user_delegation_key_expiry: now = datetime.utcnow() key_expiry_time = now + timedelta(days=7) self._user_delegation_key = self.service_client.get_user_delegation_key( @@ -347,9 +340,7 @@ def url(self, name, expire=None, parameters=None, mode="r"): if self.custom_domain: # Replace the account name with the custom domain parsed_url = urlparse(container_blob_url) - container_blob_url = urlunparse( - parsed_url._replace(netloc=self.custom_domain) - ) + container_blob_url = urlunparse(parsed_url._replace(netloc=self.custom_domain)) return BlobClient.from_blob_url(container_blob_url, credential=credential).url @@ -357,9 +348,7 @@ def _get_content_settings_parameters(self, name, content=None): params = {} guessed_type, content_encoding = mimetypes.guess_type(name) - content_type = ( - _content_type(content) or guessed_type or self.default_content_type - ) + content_type = _content_type(content) or guessed_type or self.default_content_type params["cache_control"] = self.cache_control params["content_type"] = content_type @@ -404,9 +393,7 @@ def list_all(self, path=""): # XXX make generator, add start, end return [ blob.name - for blob in self.client.list_blobs( - name_starts_with=path, timeout=self.timeout - ) + for blob in self.client.list_blobs(name_starts_with=path, timeout=self.timeout) ] def listdir(self, path=""): diff --git a/storages/backends/dropbox.py b/storages/backends/dropbox.py index ef16999f41c..af76aa6206b 100644 --- a/storages/backends/dropbox.py +++ b/storages/backends/dropbox.py @@ -173,12 +173,8 @@ def _save(self, name, content): return name def _chunked_upload(self, content, dest_path): - upload_session = self.client.files_upload_session_start( - content.read(self.CHUNK_SIZE) - ) - cursor = UploadSessionCursor( - session_id=upload_session.session_id, offset=content.tell() - ) + upload_session = self.client.files_upload_session_start(content.read(self.CHUNK_SIZE)) + cursor = UploadSessionCursor(session_id=upload_session.session_id, offset=content.tell()) commit = CommitInfo(path=dest_path, mode=WriteMode(self.write_mode)) while content.tell() < content.size: @@ -187,9 +183,7 @@ def _chunked_upload(self, content, dest_path): content.read(self.CHUNK_SIZE), cursor, commit ) else: - self.client.files_upload_session_append_v2( - content.read(self.CHUNK_SIZE), cursor - ) + self.client.files_upload_session_append_v2(content.read(self.CHUNK_SIZE), cursor) cursor.offset = content.tell() def get_available_name(self, name, max_length=None): diff --git a/storages/backends/ftp.py b/storages/backends/ftp.py index ed53748b47f..157f8c632e2 100644 --- a/storages/backends/ftp.py +++ b/storages/backends/ftp.py @@ -42,8 +42,7 @@ def __init__(self, **settings): super().__init__(**settings) if self.location is None: raise ImproperlyConfigured( - "You must set a location at instantiation " - "or at settings.FTP_STORAGE_LOCATION." + "You must set a location at instantiation or at settings.FTP_STORAGE_LOCATION." ) self._config = self._decode_location(self.location) self._connection = None @@ -153,9 +152,7 @@ def _read(self, name): try: pwd = self._connection.pwd() self._connection.cwd(os.path.dirname(name)) - self._connection.retrbinary( - "RETR " + os.path.basename(name), memory_file.write - ) + self._connection.retrbinary("RETR " + os.path.basename(name), memory_file.write) self._connection.cwd(pwd) memory_file.seek(0) return memory_file diff --git a/storages/backends/gcloud.py b/storages/backends/gcloud.py index 75c4fff0a86..783206afa4b 100644 --- a/storages/backends/gcloud.py +++ b/storages/backends/gcloud.py @@ -50,9 +50,7 @@ def __init__(self, name, mode, storage): self._storage = storage self.blob = storage.bucket.get_blob(name, chunk_size=storage.blob_chunk_size) if not self.blob and "w" in mode: - self.blob = Blob( - self.name, storage.bucket, chunk_size=storage.blob_chunk_size - ) + self.blob = Blob(self.name, storage.bucket, chunk_size=storage.blob_chunk_size) self._file = None self._is_dirty = False @@ -231,9 +229,7 @@ def open_stream(self, name, start=0, length=None): raise FileNotFoundError("File does not exist: %s" % name) available = max(blob.size - start, 0) - stream = _GoogleCloudStream( - blob, start, min(length, available) if length else available - ) + stream = _GoogleCloudStream(blob, start, min(length, available) if length else available) yield LimitedStream(stream, stream.length) def _compress_content(self, content): @@ -257,9 +253,7 @@ def _save(self, name, content): upload_params = {} upload_params["predefined_acl"] = blob_params.pop("acl", self.default_acl) - upload_params[CONTENT_TYPE] = blob_params.pop( - CONTENT_TYPE, file_object.mime_type - ) + upload_params[CONTENT_TYPE] = blob_params.pop(CONTENT_TYPE, file_object.mime_type) if ( self.gzip @@ -370,8 +364,7 @@ def url(self, name, parameters=None): blob = self.bucket.blob(name) blob_params = self.get_object_parameters(name) no_signed_url = ( - blob_params.get("acl", self.default_acl) == "publicRead" - or not self.querystring_auth + blob_params.get("acl", self.default_acl) == "publicRead" or not self.querystring_auth ) if not self.custom_endpoint and no_signed_url: diff --git a/storages/backends/s3.py b/storages/backends/s3.py index 875f34367fe..d0c6cfb8183 100644 --- a/storages/backends/s3.py +++ b/storages/backends/s3.py @@ -57,9 +57,7 @@ def _cloud_front_signer_from_pem(key_id, pem): pem = pem.encode("ascii") key = load_pem_private_key(pem, password=None, backend=default_backend()) - return CloudFrontSigner( - key_id, lambda x: key.sign(x, padding.PKCS1v15(), hashes.SHA1()) - ) + return CloudFrontSigner(key_id, lambda x: key.sign(x, padding.PKCS1v15(), hashes.SHA1())) return _cloud_front_signer_from_pem @@ -128,9 +126,7 @@ def __init__(self, name, mode, storage, buffer_size=None): self.obj = storage.bucket.Object(name) if "w" not in mode: # Force early RAII-style exception if object does not exist - params = _filter_download_params( - self._storage.get_object_parameters(self.name) - ) + params = _filter_download_params(self._storage.get_object_parameters(self.name)) self.obj.load(**params) self._closed = False self._file = None @@ -176,9 +172,7 @@ def _get_file(self): ) if "r" in self._mode: self._is_dirty = False - params = _filter_download_params( - self._storage.get_object_parameters(self.name) - ) + params = _filter_download_params(self._storage.get_object_parameters(self.name)) self.obj.download_fileobj( self._file, ExtraArgs=params, Config=self._storage.transfer_config ) @@ -195,9 +189,7 @@ def _get_file(self): self._file = io.TextIOWrapper(self._file, encoding="utf-8") else: # For versions <= Python 3.10 compatibility - self._file = io.TextIOWrapper( - self._file._file, encoding="utf-8" - ) + self._file = io.TextIOWrapper(self._file._file, encoding="utf-8") self._closed = False return self._file @@ -248,9 +240,7 @@ def _flush_write_buffer(self): self.file.seek(0) part = self._multipart.Part(self._write_counter) response = part.upload(Body=self.file.read()) - self._parts.append( - {"ETag": response["ETag"], "PartNumber": self._write_counter} - ) + self._parts.append({"ETag": response["ETag"], "PartNumber": self._write_counter}) self.file.seek(0) self.file.truncate() @@ -274,9 +264,7 @@ def _create_empty_on_close(self): self.obj.load() except ClientError as err: if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: - self.obj.put( - Body=b"", **self._storage._get_write_parameters(self.obj.key) - ) + self.obj.put(Body=b"", **self._storage._get_write_parameters(self.obj.key)) else: raise @@ -378,9 +366,7 @@ def __init__(self, **settings): def get_cloudfront_signer(self, key_id, key): cache_key = f"{key_id}:{key}" if cache_key not in self.__class__._signers: - self.__class__._signers[cache_key] = _cloud_front_signer_from_pem( - key_id, key - ) + self.__class__._signers[cache_key] = _cloud_front_signer_from_pem(key_id, key) return self.__class__._signers[cache_key] def get_default_settings(self): @@ -478,9 +464,7 @@ def unsigned_connection(self): unsigned_connection = getattr(self._unsigned_connections, "connection", None) if unsigned_connection is None: session = self._create_session() - config = self.client_config.merge( - Config(signature_version=botocore.UNSIGNED) - ) + config = self.client_config.merge(Config(signature_version=botocore.UNSIGNED)) self._unsigned_connections.connection = session.resource( "s3", region_name=self.region_name, @@ -615,9 +599,7 @@ def exists(self, name): name = self._normalize_name(clean_name(name)) params = _filter_download_params(self.get_object_parameters(name)) try: - self.connection.meta.client.head_object( - Bucket=self.bucket_name, Key=name, **params - ) + self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name, **params) return True except ClientError as err: if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: @@ -638,8 +620,7 @@ def listdir(self, name): pages = paginator.paginate(Bucket=self.bucket_name, Delimiter="/", Prefix=path) for page in pages: directories += [ - posixpath.relpath(entry["Prefix"], path) - for entry in page.get("CommonPrefixes", ()) + posixpath.relpath(entry["Prefix"], path) for entry in page.get("CommonPrefixes", ()) ] for entry in page.get("Contents", ()): key = entry["Key"] @@ -714,18 +695,14 @@ def url(self, name, parameters=None, expire=None, http_method=None): if self.querystring_auth and self.cloudfront_signer: expiration = datetime.utcnow() + timedelta(seconds=expire) - return self.cloudfront_signer.generate_presigned_url( - url, date_less_than=expiration - ) + return self.cloudfront_signer.generate_presigned_url(url, date_less_than=expiration) return url params["Bucket"] = self.bucket.name params["Key"] = name - connection = ( - self.connection if self.querystring_auth else self.unsigned_connection - ) + connection = self.connection if self.querystring_auth else self.unsigned_connection url = connection.meta.client.generate_presigned_url( "get_object", Params=params, ExpiresIn=expire, HttpMethod=http_method ) diff --git a/storages/utils.py b/storages/utils.py index 9235f5cd879..685962ceddc 100644 --- a/storages/utils.py +++ b/storages/utils.py @@ -88,9 +88,7 @@ def safe_join(base, *paths): # the base path is /. base_path_len = len(base_path) if not final_path.startswith(base_path) or final_path[base_path_len] != "/": - raise ValueError( - "the joined path is located outside of the base path component" - ) + raise ValueError("the joined path is located outside of the base path component") return final_path.lstrip("/") @@ -99,10 +97,7 @@ def check_location(storage): if storage.location.startswith("/"): correct = storage.location.lstrip("/") raise ImproperlyConfigured( - ( - "{}.location cannot begin with a leading slash. Found '{}'. Use '{}' " - "instead." - ).format( + ("{}.location cannot begin with a leading slash. Found '{}'. Use '{}' instead.").format( storage.__class__.__name__, storage.location, correct, @@ -126,9 +121,7 @@ def get_available_overwrite_name(name, max_length): # Django 5.1 is the lowest supported version dir_name, file_name = os.path.split(name) if ".." in pathlib.PurePath(dir_name).parts: - raise SuspiciousFileOperation( - "Detected path traversal attempt in '%s'" % dir_name - ) + raise SuspiciousFileOperation("Detected path traversal attempt in '%s'" % dir_name) validate_file_name(file_name, allow_relative_path=True) if max_length is None or len(name) <= max_length: From b231f7f50a528763d11794fea8a85a41672070b0 Mon Sep 17 00:00:00 2001 From: Daniel Alley Date: Mon, 23 Nov 2026 23:37:05 -0500 Subject: [PATCH 4/6] Move vendored storage backends under pulpcore Move the vendored backends under Pulp's package namespace so they cannot collide with an independently installed django-storages package. Update built-in backend mappings, test settings, and operator guidance to use the new import paths while preserving legacy Domain storage_class values. Assisted By: Codex (GPT-6) --- .github/workflows/scripts/before_install.sh | 4 +- .../configure-pulp/configure-storages.md | 16 ++++++-- docs/admin/reference/settings.md | 14 ++++--- .../storage_backend_implementations.md | 4 +- .../functional/api/test_download_policies.py | 6 +-- pulpcore/app/settings.py | 9 +++-- pulpcore/pytest_plugin.py | 14 ++++++- pulpcore/tests/unit/test_storage_backends.py | 14 +++++++ pulpcore/vendor/__init__.py | 1 + .../vendor/storages}/LICENSE | 0 .../vendor/storages}/__init__.py | 0 .../vendor/storages}/backends/__init__.py | 0 .../vendor/storages}/backends/_stream.py | 0 .../storages}/backends/apache_libcloud.py | 5 +-- .../storages}/backends/azure_storage.py | 40 ++++++++++--------- .../vendor/storages}/backends/dropbox.py | 12 ++---- .../vendor/storages}/backends/ftp.py | 4 +- .../vendor/storages}/backends/gcloud.py | 27 ++++++------- .../vendor/storages}/backends/s3.py | 33 ++++++++------- pulpcore/vendor/storages/backends/s3boto3.py | 6 +++ .../vendor/storages}/backends/sftpstorage.py | 5 +-- .../vendor/storages}/base.py | 0 .../vendor/storages}/compress.py | 2 +- .../vendor/storages}/utils.py | 6 +-- storages/backends/s3boto3.py | 6 --- template_config.yml | 4 +- 26 files changed, 133 insertions(+), 99 deletions(-) create mode 100644 pulpcore/vendor/__init__.py rename {storages => pulpcore/vendor/storages}/LICENSE (100%) rename {storages => pulpcore/vendor/storages}/__init__.py (100%) rename {storages => pulpcore/vendor/storages}/backends/__init__.py (100%) rename {storages => pulpcore/vendor/storages}/backends/_stream.py (100%) rename {storages => pulpcore/vendor/storages}/backends/apache_libcloud.py (97%) rename {storages => pulpcore/vendor/storages}/backends/azure_storage.py (94%) rename {storages => pulpcore/vendor/storages}/backends/dropbox.py (95%) rename {storages => pulpcore/vendor/storages}/backends/ftp.py (98%) rename {storages => pulpcore/vendor/storages}/backends/gcloud.py (95%) rename {storages => pulpcore/vendor/storages}/backends/s3.py (97%) create mode 100644 pulpcore/vendor/storages/backends/s3boto3.py rename {storages => pulpcore/vendor/storages}/backends/sftpstorage.py (98%) rename {storages => pulpcore/vendor/storages}/base.py (100%) rename {storages => pulpcore/vendor/storages}/compress.py (96%) rename {storages => pulpcore/vendor/storages}/utils.py (95%) delete mode 100644 storages/backends/s3boto3.py diff --git a/.github/workflows/scripts/before_install.sh b/.github/workflows/scripts/before_install.sh index 93fb5e6167d..42c2156fd32 100755 --- a/.github/workflows/scripts/before_install.sh +++ b/.github/workflows/scripts/before_install.sh @@ -95,7 +95,7 @@ if [ "$TEST" = "s3" ]; then s3_test: true rustfs_access_key: "${RUSTFS_ACCESS_KEY}" rustfs_secret_key: "${RUSTFS_SECRET_KEY}" -pulp_scenario_settings: {"DISABLED_authentication_backends": "@merge django.contrib.auth.backends.RemoteUserBackend", "DISABLED_authentication_json_header": "HTTP_X_RH_IDENTITY", "DISABLED_authentication_json_header_jq_filter": ".identity.user.username", "DISABLED_authentication_json_header_openapi_security_scheme": {"description": "External OAuth integration", "flows": {"clientCredentials": {"scopes": {"api.console": "grant_access_to_pulp"}, "tokenUrl": "https://your-identity-provider/token/issuer"}}, "type": "oauth2"}, "DISABLED_rest_framework__default_authentication_classes": "@merge pulpcore.app.authentication.JSONHeaderRemoteAuthentication", "ENABLE_V4_API": true, "MEDIA_ROOT": "", "STORAGES": {"default": {"BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": {"access_key": "AKIAIT2Z5TDYPX3ARJBA", "addressing_style": "path", "bucket_name": "pulp3", "default_acl": "@none", "endpoint_url": "http://rustfs:9000", "region_name": "eu-central-1", "secret_key": "fqRvjWaPU5o0fCqQuUWbj9Fainj2pVZtBCiDiieS", "signature_version": "s3v4"}}, "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}, "api_root": "/rerouted/djnd/", "domain_enabled": true, "hide_guarded_distributions": true, "rest_framework__default_permission_classes": ["pulpcore.plugin.access_policy.AccessPolicyFromSettings"], "spectacular_settings__oas_version": "3.0.3"} +pulp_scenario_settings: {"DISABLED_authentication_backends": "@merge django.contrib.auth.backends.RemoteUserBackend", "DISABLED_authentication_json_header": "HTTP_X_RH_IDENTITY", "DISABLED_authentication_json_header_jq_filter": ".identity.user.username", "DISABLED_authentication_json_header_openapi_security_scheme": {"description": "External OAuth integration", "flows": {"clientCredentials": {"scopes": {"api.console": "grant_access_to_pulp"}, "tokenUrl": "https://your-identity-provider/token/issuer"}}, "type": "oauth2"}, "DISABLED_rest_framework__default_authentication_classes": "@merge pulpcore.app.authentication.JSONHeaderRemoteAuthentication", "ENABLE_V4_API": true, "MEDIA_ROOT": "", "STORAGES": {"default": {"BACKEND": "pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": {"access_key": "AKIAIT2Z5TDYPX3ARJBA", "addressing_style": "path", "bucket_name": "pulp3", "default_acl": "@none", "endpoint_url": "http://rustfs:9000", "region_name": "eu-central-1", "secret_key": "fqRvjWaPU5o0fCqQuUWbj9Fainj2pVZtBCiDiieS", "signature_version": "s3v4"}}, "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}, "api_root": "/rerouted/djnd/", "domain_enabled": true, "hide_guarded_distributions": true, "rest_framework__default_permission_classes": ["pulpcore.plugin.access_policy.AccessPolicyFromSettings"], "spectacular_settings__oas_version": "3.0.3"} # MinIO omits 100-continue on 0-byte PUTs; stock botocore hangs without this (boto/botocore#3123). pulp_scenario_env: {"BOTO_EXPERIMENTAL__NO_EMPTY_CONTINUE": "true"} VARSYAML @@ -107,7 +107,7 @@ if [ "$TEST" = "azure" ]; then image: "mcr.microsoft.com/azure-storage/azurite" command: "azurite-blob --skipApiVersionCheck --blobHost 0.0.0.0" azure_test: true -pulp_scenario_settings: {"MEDIA_ROOT": "", "STORAGES": {"default": {"BACKEND": "storages.backends.azure_storage.AzureStorage", "OPTIONS": {"account_key": "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==", "account_name": "devstoreaccount1", "azure_container": "pulp-test", "connection_string": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://ci-azurite:10000/devstoreaccount1;", "expiration_secs": 120, "location": "pulp3", "overwrite_files": true}}, "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}, "api_root_rewrite_header": "X-API-Root", "content_origin": null, "domain_enabled": true, "rest_framework__default_authentication_classes": "@merge pulpcore.app.authentication.PulpRemoteUserAuthentication", "rest_framework__default_permission_classes": ["pulpcore.plugin.access_policy.DefaultAccessPolicy"], "task_diagnostics": ["memory"], "worker_type": "redis"} +pulp_scenario_settings: {"MEDIA_ROOT": "", "STORAGES": {"default": {"BACKEND": "pulpcore.vendor.storages.backends.azure_storage.AzureStorage", "OPTIONS": {"account_key": "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==", "account_name": "devstoreaccount1", "azure_container": "pulp-test", "connection_string": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://ci-azurite:10000/devstoreaccount1;", "expiration_secs": 120, "location": "pulp3", "overwrite_files": true}}, "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}, "api_root_rewrite_header": "X-API-Root", "content_origin": null, "domain_enabled": true, "rest_framework__default_authentication_classes": "@merge pulpcore.app.authentication.PulpRemoteUserAuthentication", "rest_framework__default_permission_classes": ["pulpcore.plugin.access_policy.DefaultAccessPolicy"], "task_diagnostics": ["memory"], "worker_type": "redis"} pulp_scenario_env: {} VARSYAML fi diff --git a/docs/admin/guides/configure-pulp/configure-storages.md b/docs/admin/guides/configure-pulp/configure-storages.md index 1c58aa948fd..77a25ffc223 100644 --- a/docs/admin/guides/configure-pulp/configure-storages.md +++ b/docs/admin/guides/configure-pulp/configure-storages.md @@ -1,6 +1,7 @@ # Configure Storage Backend -Pulp uses [django-storages](https://django-storages.readthedocs.io) to support multiple storage backends. +Pulp bundles supported object-storage backends based on [django-storages](https://django-storages.readthedocs.io). +Use the `pulpcore.vendor.storages` import paths when selecting a backend in Django's `STORAGES` setting. See the reference for the [`STORAGES` settings](site:pulpcore/docs/admin/reference/settings/#storages). ## Modifying the settings @@ -9,6 +10,10 @@ The settings can be updated via the `settings.py` file or through environment va and have support to dynaconf merge features. The means to modify them will depend on your deployment option. +When upgrading a deployment that overrides `STORAGES` or `DOMAIN_STORAGE_BACKENDS`, change +Pulp backend implementation paths from `storages.backends.*` to `pulpcore.vendor.storages.backends.*`. +Domain API `storage_class` values remain the historical `storages.backends.*` identifiers. + Learn more on the [Settings Introduction](site:pulpcore/docs/admin/guides/configure-pulp/). ## Local Filesystem (default) @@ -63,7 +68,7 @@ In this example, the storage uses a bucket called `pulp3` that is hosted in regi MEDIA_ROOT = "" STORAGES = { "default": { - "BACKEND": "storages.backends.s3.S3Storage", + "BACKEND": "pulpcore.vendor.storages.backends.s3.S3Storage", "OPTIONS": { "access_key": 'AKIAIT2Z5TDYPX3ARJBA', "secret_key": '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', @@ -102,6 +107,9 @@ You'll need: When creating a `Domain` you can use the following payload: +The `storage_class` value is a historical API identifier. Keep using the `storages.backends.*` +value there; use the `pulpcore.vendor.storages.backends.*` path only in `STORAGES` settings. + ```json { "name": "cloudfront_storage", @@ -150,7 +158,7 @@ Comprehensive options for Amazon S3 can be found in ## S3 Compatible -The same `storages.backends.s3.S3Storage` backend can be used for S3 Compatible API services, such as [rustfs](https://rustfs.com/), [Ceph/RADOS](https://docs.ceph.com/en/reef/man/8/rados/) and [Backblaze B2](https://www.backblaze.com/cloud-storage). +The same S3 `storage_class` identifier can be used for S3 Compatible API services, such as [rustfs](https://rustfs.com/), [Ceph/RADOS](https://docs.ceph.com/en/reef/man/8/rados/) and [Backblaze B2](https://www.backblaze.com/cloud-storage). The [django-storages](https://django-storages.readthedocs.io/en/latest/backends/s3_compatible/index.html) documentation provides a reference for setting up some of these services. @@ -175,7 +183,7 @@ In this example, the storage uses a container called `pulp3` with the `pulp-acco MEDIA_ROOT = "" STORAGES = { "default": { - "BACKEND": "storages.backends.azure_storage.AzureStorage", + "BACKEND": "pulpcore.vendor.storages.backends.azure_storage.AzureStorage", "OPTIONS": { "account_name": 'pulp-account', "azure_container": 'pulp3', diff --git a/docs/admin/reference/settings.md b/docs/admin/reference/settings.md index c7c974d83b8..9ccc76e5b89 100644 --- a/docs/admin/reference/settings.md +++ b/docs/admin/reference/settings.md @@ -99,7 +99,13 @@ print(''.join(secrets.choice(chars) for i in range(50))) !!! note "Added in `3.70`" Starting in `3.70`, this should be used in the place of [`DEFAULT_FILE_STORAGE`](#default_file_storage). -Pulp uses [django-storages] to support multiple storage backends. +Pulp bundles its supported object-storage backends under `pulpcore.vendor.storages`. +Use those import paths in `STORAGES` to select Pulp's bundled implementations. Existing +Domain API `storage_class` values such as `storages.backends.s3.S3Storage` remain supported +as compatibility identifiers. +If your deployment overrides `DOMAIN_STORAGE_BACKENDS` or configures object storage in +`STORAGES`, update implementation paths from `storages.backends.*` to +`pulpcore.vendor.storages.backends.*` to select the bundled code. If no backend is configured, Pulp will by default use the local filesystem (`pulpcore.app.models.storage.FileSystem`). The storage setting has the form: @@ -119,8 +125,7 @@ STORAGES = { To use another backend storage, you'll need to: 1. Set up your storage and gather required credentials and specific configs. -1. Ensure the `django-storage[s3|google|azure]` python package is installed. -This depends on the installation method. +1. Install Pulp with the provider extra required by your backend, such as `s3`, `google`, or `azure`. 1. Configure the default `BACKEND` storage class. 1. Configure available `OPTIONS` for that backend. @@ -130,7 +135,7 @@ Learn more on the Overview of the integration with Pulp: - **Supported**: We support (test) Amazon S3 and Azure. -- **Untested**: Other backends provided by `django-storages` may work as well, but we provide no guarantee. +- **Untested**: Other vendored backends may work, but we provide no guarantee. ## Pulp Settings @@ -647,7 +652,6 @@ Defaults to `pulpcore.tasking.status`. [djangosaml2]: https://djangosaml2.readthedocs.io [Django secret key]: https://docs.djangoproject.com/en/4.2/ref/settings/#secret-key [Django setting]: https://docs.djangoproject.com/en/4.2/ref/settings/ -[django-storages]: https://django-storages.readthedocs.io/en/latest/index.html [Django warning at the end of this section in their docs]: https://docs.djangoproject.com/en/4.2/howto/auth-remote-user/#configuration [Enabling Debug Logging]: site:pulpcore/docs/admin/guides/troubleshooting/#enabling-debug-logging [librdkafka configuration documentation]: https://github.com/confluentinc/librdkafka/blob/master/CONFIGURATION.md diff --git a/docs/dev/learn/domains/storage_backend_implementations.md b/docs/dev/learn/domains/storage_backend_implementations.md index 9670734e1bc..6c84637acbd 100644 --- a/docs/dev/learn/domains/storage_backend_implementations.md +++ b/docs/dev/learn/domains/storage_backend_implementations.md @@ -19,8 +19,8 @@ Set the class path for each non-default Domain storage type you are replacing: DOMAIN_STORAGE_BACKENDS = { "filesystem": "pulpcore.app.models.storage.FileSystem", "s3": "my_storage.backends.s3.S3Storage", - "azure": "storages.backends.azure_storage.AzureStorage", - "gcs": "storages.backends.gcloud.GoogleCloudStorage", + "azure": "pulpcore.vendor.storages.backends.azure_storage.AzureStorage", + "gcs": "pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage", } ``` diff --git a/pulp_file/tests/functional/api/test_download_policies.py b/pulp_file/tests/functional/api/test_download_policies.py index 5cdc881df5b..b06ef76597e 100644 --- a/pulp_file/tests/functional/api/test_download_policies.py +++ b/pulp_file/tests/functional/api/test_download_policies.py @@ -45,9 +45,9 @@ def _do_range_request_download_and_assert(url, range_header, expected_bytes): @pytest.mark.parametrize( "storage_class", ( - pytest.param("storages.backends.s3.S3Storage", id="s3"), - pytest.param("storages.backends.s3boto3.S3Boto3Storage", id="s3boto3"), - pytest.param("storages.backends.azure_storage.AzureStorage", id="azure"), + pytest.param("pulpcore.vendor.storages.backends.s3.S3Storage", id="s3"), + pytest.param("pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage", id="s3boto3"), + pytest.param("pulpcore.vendor.storages.backends.azure_storage.AzureStorage", id="azure"), ), ) def test_proxied_object_storage_artifact_streaming( diff --git a/pulpcore/app/settings.py b/pulpcore/app/settings.py index 478235ec540..b624decdf2d 100644 --- a/pulpcore/app/settings.py +++ b/pulpcore/app/settings.py @@ -81,9 +81,11 @@ # here to change the implementation without rewriting stored Domain rows. DOMAIN_STORAGE_BACKENDS = { constants.STORAGE_BACKENDS.FILESYSTEM: "pulpcore.app.models.storage.FileSystem", - constants.STORAGE_BACKENDS.S3: "storages.backends.s3.S3Storage", - constants.STORAGE_BACKENDS.AZURE: "storages.backends.azure_storage.AzureStorage", - constants.STORAGE_BACKENDS.GCS: "storages.backends.gcloud.GoogleCloudStorage", + constants.STORAGE_BACKENDS.S3: "pulpcore.vendor.storages.backends.s3.S3Storage", + constants.STORAGE_BACKENDS.AZURE: ( + "pulpcore.vendor.storages.backends.azure_storage.AzureStorage" + ), + constants.STORAGE_BACKENDS.GCS: "pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage", } REDIRECT_TO_OBJECT_STORAGE = True @@ -127,7 +129,6 @@ OPTIONAL_APPS = [ "crispy_forms", "django_extensions", - "storages", ] for app in OPTIONAL_APPS: diff --git a/pulpcore/pytest_plugin.py b/pulpcore/pytest_plugin.py index 2257b2990d1..8a7afadc38a 100644 --- a/pulpcore/pytest_plugin.py +++ b/pulpcore/pytest_plugin.py @@ -19,6 +19,7 @@ from packaging.version import parse as parse_version from yarl import URL +from pulpcore.app.storage_backends import legacy_backend_path from pulpcore.plugin.find_url import find_api_root from pulpcore.tests.functional.utils import ( SLEEP_TIME, @@ -809,7 +810,13 @@ def _settings_factory(storage_class=None, storage_settings=None): "region_name", "bucket_name", ] + keys["pulpcore.vendor.storages.backends.s3.S3Storage"] = keys[ + "storages.backends.s3.S3Storage" + ] keys["storages.backends.s3boto3.S3Boto3Storage"] = keys["storages.backends.s3.S3Storage"] + keys["pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage"] = keys[ + "storages.backends.s3.S3Storage" + ] keys["storages.backends.azure_storage.AzureStorage"] = [ "account_name", "azure_container", @@ -819,6 +826,9 @@ def _settings_factory(storage_class=None, storage_settings=None): "location", "connection_string", ] + keys["pulpcore.vendor.storages.backends.azure_storage.AzureStorage"] = keys[ + "storages.backends.azure_storage.AzureStorage" + ] def get_installation_storage_option(key, backend): value = pulp_settings.STORAGES["default"].get("OPTIONS", {}).get(key) @@ -832,7 +842,9 @@ def get_installation_storage_option(key, backend): unset_storage_settings = (k for k in keys[storage_backend] if k not in storage_settings) for key in unset_storage_settings: storage_settings[key] = get_installation_storage_option(key, storage_backend) - return storage_backend, storage_settings + # Domain API storage_class values remain legacy identifiers; the configured path above + # is only used to identify backend-specific installation options. + return legacy_backend_path(storage_backend), storage_settings return _settings_factory diff --git a/pulpcore/tests/unit/test_storage_backends.py b/pulpcore/tests/unit/test_storage_backends.py index 0406d0a64db..92d9dce8c81 100644 --- a/pulpcore/tests/unit/test_storage_backends.py +++ b/pulpcore/tests/unit/test_storage_backends.py @@ -60,8 +60,11 @@ def pulp_url(self, name, headers=None, method=None): [ ("pulpcore.app.models.storage.FileSystem", []), ("storages.backends.s3.S3Storage", []), + ("pulpcore.vendor.storages.backends.s3.S3Storage", []), ("storages.backends.azure_storage.AzureStorage", []), + ("pulpcore.vendor.storages.backends.azure_storage.AzureStorage", []), ("storages.backends.gcloud.GoogleCloudStorage", []), + ("pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage", []), ("pulpcore.tests.unit.test_storage_backends.CustomRedirectStorage", []), ("pulpcore.tests.unit.test_storage_backends.FirstStorage", ["pulpcore.E003"]), ("missing.storage.Backend", ["pulpcore.E003"]), @@ -121,6 +124,17 @@ def test_implementation_mapping_does_not_change_backend_id(): assert legacy_backend_path("example.adapters.S3Storage") == "storages.backends.s3.S3Storage" +def test_built_in_backends_use_vendored_implementations(): + """Resolve stable backend IDs to Pulp's isolated vendored package.""" + assert backend_path("s3") == "pulpcore.vendor.storages.backends.s3.S3Storage" + assert backend_path("azure") == "pulpcore.vendor.storages.backends.azure_storage.AzureStorage" + assert backend_path("gcs") == "pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage" + assert ( + legacy_backend_path("pulpcore.vendor.storages.backends.s3.S3Storage") + == "storages.backends.s3.S3Storage" + ) + + def test_local_storage_path_uses_backend_capability(): """A plugin can serve a local file without identifying its storage class.""" file = SimpleNamespace(name="artifact/abc") diff --git a/pulpcore/vendor/__init__.py b/pulpcore/vendor/__init__.py new file mode 100644 index 00000000000..6b84aede685 --- /dev/null +++ b/pulpcore/vendor/__init__.py @@ -0,0 +1 @@ +"""Third-party code vendored for Pulp's internal use.""" diff --git a/storages/LICENSE b/pulpcore/vendor/storages/LICENSE similarity index 100% rename from storages/LICENSE rename to pulpcore/vendor/storages/LICENSE diff --git a/storages/__init__.py b/pulpcore/vendor/storages/__init__.py similarity index 100% rename from storages/__init__.py rename to pulpcore/vendor/storages/__init__.py diff --git a/storages/backends/__init__.py b/pulpcore/vendor/storages/backends/__init__.py similarity index 100% rename from storages/backends/__init__.py rename to pulpcore/vendor/storages/backends/__init__.py diff --git a/storages/backends/_stream.py b/pulpcore/vendor/storages/backends/_stream.py similarity index 100% rename from storages/backends/_stream.py rename to pulpcore/vendor/storages/backends/_stream.py diff --git a/storages/backends/apache_libcloud.py b/pulpcore/vendor/storages/backends/apache_libcloud.py similarity index 97% rename from storages/backends/apache_libcloud.py rename to pulpcore/vendor/storages/backends/apache_libcloud.py index 84fa155cbe2..174f447ffe8 100644 --- a/storages/backends/apache_libcloud.py +++ b/pulpcore/vendor/storages/backends/apache_libcloud.py @@ -10,12 +10,11 @@ from django.core.files.storage import Storage from django.utils.deconstruct import deconstructible -from storages.utils import clean_name +from pulpcore.vendor.storages.utils import clean_name try: from libcloud.storage.providers import get_driver - from libcloud.storage.types import ObjectDoesNotExistError - from libcloud.storage.types import Provider + from libcloud.storage.types import ObjectDoesNotExistError, Provider except ImportError: raise ImproperlyConfigured("Could not load libcloud") diff --git a/storages/backends/azure_storage.py b/pulpcore/vendor/storages/backends/azure_storage.py similarity index 94% rename from storages/backends/azure_storage.py rename to pulpcore/vendor/storages/backends/azure_storage.py index 4c12e7198fd..374107a7d22 100644 --- a/storages/backends/azure_storage.py +++ b/pulpcore/vendor/storages/backends/azure_storage.py @@ -1,33 +1,37 @@ import mimetypes import warnings from contextlib import contextmanager -from datetime import datetime -from datetime import timedelta +from datetime import datetime, timedelta from tempfile import SpooledTemporaryFile -from urllib.parse import urlparse -from urllib.parse import urlunparse +from urllib.parse import urlparse, urlunparse from azure.core.exceptions import ResourceNotFoundError from azure.core.utils import parse_connection_string -from azure.storage.blob import BlobClient -from azure.storage.blob import BlobSasPermissions -from azure.storage.blob import BlobServiceClient -from azure.storage.blob import ContentSettings -from azure.storage.blob import generate_blob_sas +from azure.storage.blob import ( + BlobClient, + BlobSasPermissions, + BlobServiceClient, + ContentSettings, + generate_blob_sas, +) from django.core.exceptions import SuspiciousOperation from django.core.files.base import File from django.utils import timezone from django.utils.deconstruct import deconstructible -from storages.backends._stream import ChunkIteratorStream -from storages.backends._stream import LimitedStream -from storages.backends._stream import validate_byte_range -from storages.base import BaseStorage -from storages.utils import clean_name -from storages.utils import get_available_overwrite_name -from storages.utils import safe_join -from storages.utils import setting -from storages.utils import to_bytes +from pulpcore.vendor.storages.backends._stream import ( + ChunkIteratorStream, + LimitedStream, + validate_byte_range, +) +from pulpcore.vendor.storages.base import BaseStorage +from pulpcore.vendor.storages.utils import ( + clean_name, + get_available_overwrite_name, + safe_join, + setting, + to_bytes, +) @deconstructible diff --git a/storages/backends/dropbox.py b/pulpcore/vendor/storages/backends/dropbox.py similarity index 95% rename from storages/backends/dropbox.py rename to pulpcore/vendor/storages/backends/dropbox.py index af76aa6206b..c901e7e9bd6 100644 --- a/storages/backends/dropbox.py +++ b/pulpcore/vendor/storages/backends/dropbox.py @@ -13,14 +13,10 @@ from django.utils.deconstruct import deconstructible from dropbox import Dropbox from dropbox.exceptions import ApiError -from dropbox.files import CommitInfo -from dropbox.files import FolderMetadata -from dropbox.files import UploadSessionCursor -from dropbox.files import WriteMode - -from storages.base import BaseStorage -from storages.utils import get_available_overwrite_name -from storages.utils import setting +from dropbox.files import CommitInfo, FolderMetadata, UploadSessionCursor, WriteMode + +from pulpcore.vendor.storages.base import BaseStorage +from pulpcore.vendor.storages.utils import get_available_overwrite_name, setting _DEFAULT_TIMEOUT = 100 _DEFAULT_MODE = "add" diff --git a/storages/backends/ftp.py b/pulpcore/vendor/storages/backends/ftp.py similarity index 98% rename from storages/backends/ftp.py rename to pulpcore/vendor/storages/backends/ftp.py index 157f8c632e2..e889d8b81a5 100644 --- a/storages/backends/ftp.py +++ b/pulpcore/vendor/storages/backends/ftp.py @@ -26,8 +26,8 @@ from django.core.files.base import File from django.utils.deconstruct import deconstructible -from storages.base import BaseStorage -from storages.utils import setting +from pulpcore.vendor.storages.base import BaseStorage +from pulpcore.vendor.storages.utils import setting class FTPStorageException(Exception): diff --git a/storages/backends/gcloud.py b/pulpcore/vendor/storages/backends/gcloud.py similarity index 95% rename from storages/backends/gcloud.py rename to pulpcore/vendor/storages/backends/gcloud.py index 783206afa4b..1dc298dc8db 100644 --- a/storages/backends/gcloud.py +++ b/pulpcore/vendor/storages/backends/gcloud.py @@ -5,30 +5,29 @@ from datetime import timedelta from tempfile import SpooledTemporaryFile -from django.core.exceptions import ImproperlyConfigured -from django.core.exceptions import SuspiciousOperation +from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation from django.core.files.base import File from django.utils import timezone from django.utils.deconstruct import deconstructible -from storages.backends._stream import LimitedStream -from storages.backends._stream import validate_byte_range -from storages.base import BaseStorage -from storages.compress import CompressedFileMixin -from storages.utils import check_location -from storages.utils import clean_name -from storages.utils import get_available_overwrite_name -from storages.utils import safe_join -from storages.utils import setting -from storages.utils import to_bytes +from pulpcore.vendor.storages.backends._stream import LimitedStream, validate_byte_range +from pulpcore.vendor.storages.base import BaseStorage +from pulpcore.vendor.storages.compress import CompressedFileMixin +from pulpcore.vendor.storages.utils import ( + check_location, + clean_name, + get_available_overwrite_name, + safe_join, + setting, + to_bytes, +) try: from google import auth from google.auth.credentials import TokenState from google.auth.transport import requests from google.cloud.exceptions import NotFound - from google.cloud.storage import Blob - from google.cloud.storage import Client + from google.cloud.storage import Blob, Client from google.cloud.storage.blob import _quote from google.cloud.storage.retry import DEFAULT_RETRY except ImportError: diff --git a/storages/backends/s3.py b/pulpcore/vendor/storages/backends/s3.py similarity index 97% rename from storages/backends/s3.py rename to pulpcore/vendor/storages/backends/s3.py index d0c6cfb8183..e0e769b23bb 100644 --- a/storages/backends/s3.py +++ b/pulpcore/vendor/storages/backends/s3.py @@ -6,31 +6,30 @@ import threading import warnings from contextlib import contextmanager -from datetime import datetime -from datetime import timedelta +from datetime import datetime, timedelta from urllib.parse import urlencode from django.contrib.staticfiles.storage import ManifestFilesMixin -from django.core.exceptions import ImproperlyConfigured -from django.core.exceptions import SuspiciousOperation +from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation from django.core.files.base import File from django.utils.deconstruct import deconstructible from django.utils.encoding import filepath_to_uri from django.utils.timezone import make_naive -from storages.backends._stream import validate_byte_range -from storages.base import BaseStorage -from storages.compress import CompressedFileMixin -from storages.compress import CompressStorageMixin -from storages.utils import ReadBytesWrapper -from storages.utils import check_location -from storages.utils import clean_name -from storages.utils import get_available_overwrite_name -from storages.utils import is_seekable -from storages.utils import lookup_env -from storages.utils import safe_join -from storages.utils import setting -from storages.utils import to_bytes +from pulpcore.vendor.storages.backends._stream import validate_byte_range +from pulpcore.vendor.storages.base import BaseStorage +from pulpcore.vendor.storages.compress import CompressedFileMixin, CompressStorageMixin +from pulpcore.vendor.storages.utils import ( + ReadBytesWrapper, + check_location, + clean_name, + get_available_overwrite_name, + is_seekable, + lookup_env, + safe_join, + setting, + to_bytes, +) try: import boto3.session diff --git a/pulpcore/vendor/storages/backends/s3boto3.py b/pulpcore/vendor/storages/backends/s3boto3.py new file mode 100644 index 00000000000..2393a55e68d --- /dev/null +++ b/pulpcore/vendor/storages/backends/s3boto3.py @@ -0,0 +1,6 @@ +"""Backwards compat shim.""" + +from pulpcore.vendor.storages.backends.s3 import S3File as S3Boto3StorageFile # noqa +from pulpcore.vendor.storages.backends.s3 import S3ManifestStaticStorage # noqa +from pulpcore.vendor.storages.backends.s3 import S3StaticStorage # noqa +from pulpcore.vendor.storages.backends.s3 import S3Storage as S3Boto3Storage # noqa diff --git a/storages/backends/sftpstorage.py b/pulpcore/vendor/storages/backends/sftpstorage.py similarity index 98% rename from storages/backends/sftpstorage.py rename to pulpcore/vendor/storages/backends/sftpstorage.py index bac6e4ae2a5..1bc61bf521d 100644 --- a/storages/backends/sftpstorage.py +++ b/pulpcore/vendor/storages/backends/sftpstorage.py @@ -17,9 +17,8 @@ from django.utils.deconstruct import deconstructible from paramiko.util import ClosingContextManager -from storages.base import BaseStorage -from storages.utils import is_seekable -from storages.utils import setting +from pulpcore.vendor.storages.base import BaseStorage +from pulpcore.vendor.storages.utils import is_seekable, setting @deconstructible diff --git a/storages/base.py b/pulpcore/vendor/storages/base.py similarity index 100% rename from storages/base.py rename to pulpcore/vendor/storages/base.py diff --git a/storages/compress.py b/pulpcore/vendor/storages/compress.py similarity index 96% rename from storages/compress.py rename to pulpcore/vendor/storages/compress.py index 0c24255fe5a..152ce43ddac 100644 --- a/storages/compress.py +++ b/pulpcore/vendor/storages/compress.py @@ -3,7 +3,7 @@ from gzip import GzipFile from typing import Optional -from storages.utils import to_bytes +from pulpcore.vendor.storages.utils import to_bytes class GzipCompressionWrapper(io.RawIOBase): diff --git a/storages/utils.py b/pulpcore/vendor/storages/utils.py similarity index 95% rename from storages/utils.py rename to pulpcore/vendor/storages/utils.py index 685962ceddc..39c02c959f6 100644 --- a/storages/utils.py +++ b/pulpcore/vendor/storages/utils.py @@ -3,10 +3,8 @@ import posixpath from django.conf import settings -from django.core.exceptions import ImproperlyConfigured -from django.core.exceptions import SuspiciousFileOperation -from django.core.files.utils import FileProxyMixin -from django.core.files.utils import validate_file_name +from django.core.exceptions import ImproperlyConfigured, SuspiciousFileOperation +from django.core.files.utils import FileProxyMixin, validate_file_name from django.utils.encoding import force_bytes diff --git a/storages/backends/s3boto3.py b/storages/backends/s3boto3.py deleted file mode 100644 index d3a69aa2a30..00000000000 --- a/storages/backends/s3boto3.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Backwards compat shim.""" - -from storages.backends.s3 import S3File as S3Boto3StorageFile # noqa -from storages.backends.s3 import S3ManifestStaticStorage # noqa -from storages.backends.s3 import S3StaticStorage # noqa -from storages.backends.s3 import S3Storage as S3Boto3Storage # noqa diff --git a/template_config.yml b/template_config.yml index 181b8cd98eb..8bc6feb480d 100644 --- a/template_config.yml +++ b/template_config.yml @@ -69,7 +69,7 @@ pulp_settings_azure: MEDIA_ROOT: "" STORAGES: default: - BACKEND: "storages.backends.azure_storage.AzureStorage" + BACKEND: "pulpcore.vendor.storages.backends.azure_storage.AzureStorage" OPTIONS: account_key: "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" account_name: "devstoreaccount1" @@ -107,7 +107,7 @@ pulp_settings_s3: MEDIA_ROOT: "" STORAGES: default: - BACKEND: "storages.backends.s3boto3.S3Boto3Storage" + BACKEND: "pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage" OPTIONS: access_key: "AKIAIT2Z5TDYPX3ARJBA" addressing_style: "path" From 0c5bace6c3837c021308245c4e287203c9ee69a4 Mon Sep 17 00:00:00 2001 From: Daniel Alley Date: Tue, 24 Nov 2026 11:01:12 -0500 Subject: [PATCH 5/6] Recognize vendored S3Boto3 backend alias Map the vendored compatibility path to Pulp's S3 backend so the S3 runner's configured storage passes the redirect backend check. Add regression coverage for backend identification and validation. Assisted By: Codex (GPT-6) --- pulpcore/app/storage_backends.py | 11 +++++++++++ pulpcore/tests/unit/test_storage_backends.py | 6 ++++++ 2 files changed, 17 insertions(+) diff --git a/pulpcore/app/storage_backends.py b/pulpcore/app/storage_backends.py index b05af58136d..a3b05efacab 100644 --- a/pulpcore/app/storage_backends.py +++ b/pulpcore/app/storage_backends.py @@ -20,6 +20,12 @@ GCS="storages.backends.gcloud.GoogleCloudStorage", ) +# Vendored settings paths that are valid aliases but aren't the canonical paths in +# DOMAIN_STORAGE_BACKENDS. +VENDORED_STORAGE_ALIASES = SimpleNamespace( + S3BOTO3="pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage", +) + LEGACY_BACKENDS = { LEGACY_STORAGE_CLASSES.FILESYSTEM: STORAGE_BACKENDS.FILESYSTEM, LEGACY_STORAGE_CLASSES.S3BOTO3: STORAGE_BACKENDS.S3, @@ -28,6 +34,9 @@ LEGACY_STORAGE_CLASSES.GCS: STORAGE_BACKENDS.GCS, } +# Resolve those import aliases to their stable storage service IDs. +VENDORED_BACKEND_ALIASES = {VENDORED_STORAGE_ALIASES.S3BOTO3: STORAGE_BACKENDS.S3} + LEGACY_BACKEND_PATHS = { STORAGE_BACKENDS.FILESYSTEM: LEGACY_STORAGE_CLASSES.FILESYSTEM, STORAGE_BACKENDS.S3: LEGACY_STORAGE_CLASSES.S3, @@ -51,6 +60,8 @@ def backend_id(value): return value if value in LEGACY_BACKENDS: return LEGACY_BACKENDS[value] + if value in VENDORED_BACKEND_ALIASES: + return VENDORED_BACKEND_ALIASES[value] for kind, path in settings.DOMAIN_STORAGE_BACKENDS.items(): if value == path and kind in BACKEND_IDS: return kind diff --git a/pulpcore/tests/unit/test_storage_backends.py b/pulpcore/tests/unit/test_storage_backends.py index 92d9dce8c81..f6ad40cfdf3 100644 --- a/pulpcore/tests/unit/test_storage_backends.py +++ b/pulpcore/tests/unit/test_storage_backends.py @@ -61,6 +61,7 @@ def pulp_url(self, name, headers=None, method=None): ("pulpcore.app.models.storage.FileSystem", []), ("storages.backends.s3.S3Storage", []), ("pulpcore.vendor.storages.backends.s3.S3Storage", []), + ("pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage", []), ("storages.backends.azure_storage.AzureStorage", []), ("pulpcore.vendor.storages.backends.azure_storage.AzureStorage", []), ("storages.backends.gcloud.GoogleCloudStorage", []), @@ -129,6 +130,11 @@ def test_built_in_backends_use_vendored_implementations(): assert backend_path("s3") == "pulpcore.vendor.storages.backends.s3.S3Storage" assert backend_path("azure") == "pulpcore.vendor.storages.backends.azure_storage.AzureStorage" assert backend_path("gcs") == "pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage" + assert backend_id("pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage") == "s3" + assert ( + legacy_backend_path("pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage") + == "storages.backends.s3.S3Storage" + ) assert ( legacy_backend_path("pulpcore.vendor.storages.backends.s3.S3Storage") == "storages.backends.s3.S3Storage" From e889eb341b21c9cb3e1462ea82fee0ab3b48a63f Mon Sep 17 00:00:00 2001 From: Daniel Alley Date: Thu, 3 Dec 2026 21:47:54 -0500 Subject: [PATCH 6/6] Keep Domain storage backend mapping internal Move the implementation map out of Django settings so deployments use STORAGES for the default backend while Pulp selects implementations for other Domain storage IDs internally. Update resolution, tests, and admin documentation to reflect the internal mapping. Assisted By: Codex (GPT-6) --- .../configure-pulp/configure-storages.md | 8 ++- docs/admin/reference/settings.md | 11 +-- .../storage_backend_implementations.md | 68 ------------------- pulpcore/app/settings.py | 11 --- pulpcore/app/storage_backends.py | 47 ++++++++++--- pulpcore/tests/unit/test_storage_backends.py | 32 +++++---- 6 files changed, 60 insertions(+), 117 deletions(-) delete mode 100644 docs/dev/learn/domains/storage_backend_implementations.md diff --git a/docs/admin/guides/configure-pulp/configure-storages.md b/docs/admin/guides/configure-pulp/configure-storages.md index 77a25ffc223..0de96e19a5a 100644 --- a/docs/admin/guides/configure-pulp/configure-storages.md +++ b/docs/admin/guides/configure-pulp/configure-storages.md @@ -10,9 +10,11 @@ The settings can be updated via the `settings.py` file or through environment va and have support to dynaconf merge features. The means to modify them will depend on your deployment option. -When upgrading a deployment that overrides `STORAGES` or `DOMAIN_STORAGE_BACKENDS`, change -Pulp backend implementation paths from `storages.backends.*` to `pulpcore.vendor.storages.backends.*`. -Domain API `storage_class` values remain the historical `storages.backends.*` identifiers. +When upgrading a deployment with a custom `STORAGES` setting, change Pulp backend implementation +paths from `storages.backends.*` to `pulpcore.vendor.storages.backends.*`. Pulp selects the +implementation for each Domain storage type internally; `DOMAIN_STORAGE_BACKENDS` is not a +supported deployment setting. Domain API `storage_class` values remain the historical +`storages.backends.*` identifiers. Learn more on the [Settings Introduction](site:pulpcore/docs/admin/guides/configure-pulp/). diff --git a/docs/admin/reference/settings.md b/docs/admin/reference/settings.md index 9ccc76e5b89..fb7dfd2064a 100644 --- a/docs/admin/reference/settings.md +++ b/docs/admin/reference/settings.md @@ -99,14 +99,7 @@ print(''.join(secrets.choice(chars) for i in range(50))) !!! note "Added in `3.70`" Starting in `3.70`, this should be used in the place of [`DEFAULT_FILE_STORAGE`](#default_file_storage). -Pulp bundles its supported object-storage backends under `pulpcore.vendor.storages`. -Use those import paths in `STORAGES` to select Pulp's bundled implementations. Existing -Domain API `storage_class` values such as `storages.backends.s3.S3Storage` remain supported -as compatibility identifiers. -If your deployment overrides `DOMAIN_STORAGE_BACKENDS` or configures object storage in -`STORAGES`, update implementation paths from `storages.backends.*` to -`pulpcore.vendor.storages.backends.*` to select the bundled code. -If no backend is configured, Pulp will by default use the local filesystem (`pulpcore.app.models.storage.FileSystem`). +Pulp supports multiple storage backends using a vendored fork of [django-storages]. The storage setting has the form: @@ -135,7 +128,7 @@ Learn more on the Overview of the integration with Pulp: - **Supported**: We support (test) Amazon S3 and Azure. -- **Untested**: Other vendored backends may work, but we provide no guarantee. +- **Untested**: Other backends may work, but we provide no guarantee. ## Pulp Settings diff --git a/docs/dev/learn/domains/storage_backend_implementations.md b/docs/dev/learn/domains/storage_backend_implementations.md deleted file mode 100644 index 6c84637acbd..00000000000 --- a/docs/dev/learn/domains/storage_backend_implementations.md +++ /dev/null @@ -1,68 +0,0 @@ -# Replacing a Domain storage implementation - -Domain records retain historical storage class paths so older Pulp processes can read them during -a rolling upgrade. Pulp resolves those paths to stable backend IDs (`filesystem`, `s3`, `azure`, and -`gcs`), then selects the installed class through `DOMAIN_STORAGE_BACKENDS`. The API still advertises -the historical class paths and returns them on reads. It also accepts stable IDs in raw requests, -but generated clients may reject those IDs because the schema still lists the historical paths. -Existing `S3Boto3Storage` paths are preserved rather than rewritten to the newer S3 path. - -This boundary replaces the code for an existing storage type; it does not register a new type. -Only filesystem, S3, and Azure are currently offered for new Domains. GCS is recognized for -existing configurations, and SFTP is not supported. - -## Select an implementation - -Set the class path for each non-default Domain storage type you are replacing: - -```python -DOMAIN_STORAGE_BACKENDS = { - "filesystem": "pulpcore.app.models.storage.FileSystem", - "s3": "my_storage.backends.s3.S3Storage", - "azure": "pulpcore.vendor.storages.backends.azure_storage.AzureStorage", - "gcs": "pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage", -} -``` - -The default Domain instead uses Django's `STORAGES["default"]`. When replacing that class, set -both its `BACKEND` and the corresponding `DOMAIN_STORAGE_BACKENDS` entry. The mapping lets Pulp -identify its storage type without requiring the replacement's Python path in a Domain record. -An unrecognized default class can serve redirects only if it implements `pulp_url`. - -For direct content redirects, a replacement may implement -`pulp_url(name, headers=None, method=None)` to sign URLs with Pulp's response-header overrides. -Without that hook, Pulp calls the django-storages-style `url()` method for recognized object storage -types. For ranged content reads, a replacement may expose a synchronous -`open_stream(name, start=0, length=None)` context manager. Pulp falls back to Django's `open()` and -`seek()` if the hook is absent; that fallback bounds the returned bytes but may buffer a whole -remote object. The stream must release its resources when the context exits. - -## Use storage from a plugin - -Plugin code should use `pulpcore.plugin.util.get_local_storage_path(file, domain=None)` when it -needs an actual filesystem path. It returns `None` when the backend does not provide one; other -storage errors are propagated. Use `get_direct_storage_url(file, headers=None, http_method=None, -domain=None)` when a consumer needs a URL directly to object storage. It returns `None` when the -Domain uses filesystem storage or has redirects disabled, and raises `NotImplementedError` when -redirects are requested from an unsupported backend. Both functions accept a Pulp-managed file -such as `Artifact.file` or `PulpTemporaryFile.file`. If the file belongs to another Domain, pass -that Domain explicitly; otherwise they use the current Domain. - -The URL function accepts generic `Content-Type` and `Content-Disposition` response headers and -translates them into the selected provider's signed URL parameters. Plugins should not inspect -`storage_class` or pass provider-specific parameters to `storage.url()`. The existing -`get_artifact_url(artifact, ...)` differs: it always returns a URL, falling back to the content -app when a direct URL is unavailable. - -## Roll out a replacement - -Keep the Domain's storage type, bucket or container, prefix, object names, credentials, and URL -behavior compatible. Install the replacement and its dependencies on every API, content, and worker -process, and test reads, writes, range requests, and signed redirects against existing objects. -Then change the deployment settings. A code-only change needs no Domain data migration. Moving -objects to a different location still requires a storage migration. - -During a rolling upgrade, new processes continue to store and return historical class paths so -older processes can read the same Domain rows. Keep the old implementation installed until those -processes and the rollback window are gone. Do not switch persisted `storage_class` values to IDs -while any process still requires the historical paths. diff --git a/pulpcore/app/settings.py b/pulpcore/app/settings.py index b624decdf2d..5044344a393 100644 --- a/pulpcore/app/settings.py +++ b/pulpcore/app/settings.py @@ -77,17 +77,6 @@ }, } -# Domain class paths are treated as legacy backend identifiers. Override a path -# here to change the implementation without rewriting stored Domain rows. -DOMAIN_STORAGE_BACKENDS = { - constants.STORAGE_BACKENDS.FILESYSTEM: "pulpcore.app.models.storage.FileSystem", - constants.STORAGE_BACKENDS.S3: "pulpcore.vendor.storages.backends.s3.S3Storage", - constants.STORAGE_BACKENDS.AZURE: ( - "pulpcore.vendor.storages.backends.azure_storage.AzureStorage" - ), - constants.STORAGE_BACKENDS.GCS: "pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage", -} - REDIRECT_TO_OBJECT_STORAGE = True WORKING_DIRECTORY = DEPLOY_ROOT / "tmp" diff --git a/pulpcore/app/storage_backends.py b/pulpcore/app/storage_backends.py index a3b05efacab..7f3dc4fb0cf 100644 --- a/pulpcore/app/storage_backends.py +++ b/pulpcore/app/storage_backends.py @@ -1,7 +1,17 @@ -"""Pulp's stable identifiers and operations for domain storage backends. +"""Resolve Pulp Domain storage identifiers and adapt storage operations. -The identifiers in this module describe the storage service, not the Python class -used to access it. Changing an implementation must not change a Domain record. +Domain records retain historical class paths for API and rolling-upgrade compatibility. This +module maps those paths and supported aliases to stable backend IDs, selects implementations for +non-default Domains, and serializes IDs back to legacy paths. The default Domain uses Django's +`STORAGES["default"]`. The mapping replaces implementations of existing storage types; it does not +register new types. + +Artifact-delivery helpers: + +- `signed_url()` adapts generic response headers and methods to the selected provider. +- `get_direct_storage_url()` requests a direct provider URL when the Domain supports it. +- `get_artifact_url()` returns a usable URL, falling back to Pulp's content app when needed. +- `open_stream()` provides bounded reads when Pulp serves stored content itself. """ from contextlib import contextmanager @@ -12,6 +22,7 @@ from pulpcore.constants import STORAGE_BACKENDS, STORAGE_RESPONSE_MAP +# Class paths historically stored on Domain rows or accepted by the API. LEGACY_STORAGE_CLASSES = SimpleNamespace( FILESYSTEM="pulpcore.app.models.storage.FileSystem", S3BOTO3="storages.backends.s3boto3.S3Boto3Storage", @@ -20,12 +31,12 @@ GCS="storages.backends.gcloud.GoogleCloudStorage", ) -# Vendored settings paths that are valid aliases but aren't the canonical paths in -# DOMAIN_STORAGE_BACKENDS. +# Vendored import paths retained as aliases, though they are not the canonical implementation paths. VENDORED_STORAGE_ALIASES = SimpleNamespace( S3BOTO3="pulpcore.vendor.storages.backends.s3boto3.S3Boto3Storage", ) +# Translate historical class paths to stable backend IDs for internal dispatch. LEGACY_BACKENDS = { LEGACY_STORAGE_CLASSES.FILESYSTEM: STORAGE_BACKENDS.FILESYSTEM, LEGACY_STORAGE_CLASSES.S3BOTO3: STORAGE_BACKENDS.S3, @@ -37,6 +48,8 @@ # Resolve those import aliases to their stable storage service IDs. VENDORED_BACKEND_ALIASES = {VENDORED_STORAGE_ALIASES.S3BOTO3: STORAGE_BACKENDS.S3} +# Keep new or stable backend IDs serialized as historical class paths so older Pulp processes can +# still read Domain rows during a rolling upgrade. LEGACY_BACKEND_PATHS = { STORAGE_BACKENDS.FILESYSTEM: LEGACY_STORAGE_CLASSES.FILESYSTEM, STORAGE_BACKENDS.S3: LEGACY_STORAGE_CLASSES.S3, @@ -44,12 +57,24 @@ STORAGE_BACKENDS.GCS: LEGACY_STORAGE_CLASSES.GCS, } +# Internal mapping from stable Domain storage IDs to Django storage implementations. Changing an +# implementation here changes which implementation is used for that backend. +DOMAIN_STORAGE_BACKENDS = { + STORAGE_BACKENDS.FILESYSTEM: "pulpcore.app.models.storage.FileSystem", + STORAGE_BACKENDS.S3: "pulpcore.vendor.storages.backends.s3.S3Storage", + STORAGE_BACKENDS.AZURE: ("pulpcore.vendor.storages.backends.azure_storage.AzureStorage"), + STORAGE_BACKENDS.GCS: "pulpcore.vendor.storages.backends.gcloud.GoogleCloudStorage", +} + +# Stable backend IDs recognized by Pulp's storage helpers. BACKEND_IDS = frozenset(vars(STORAGE_BACKENDS).values()) + +# Generic response headers that Pulp can translate to provider-specific URL parameters. URL_RESPONSE_HEADERS = frozenset().union(*(mapping for mapping in STORAGE_RESPONSE_MAP.values())) def backend_id(value): - """Return a stable ID for a built-in or configured implementation path. + """Return a stable ID for a built-in or mapped implementation path. Unknown paths return `None`; they are not treated as importable Domain backends merely because they happen to be present on `sys.path`. @@ -62,7 +87,7 @@ def backend_id(value): return LEGACY_BACKENDS[value] if value in VENDORED_BACKEND_ALIASES: return VENDORED_BACKEND_ALIASES[value] - for kind, path in settings.DOMAIN_STORAGE_BACKENDS.items(): + for kind, path in DOMAIN_STORAGE_BACKENDS.items(): if value == path and kind in BACKEND_IDS: return kind return None @@ -82,7 +107,7 @@ def legacy_backend_path(value): """Return a class-path identifier understood by older Pulp processes. Existing legacy paths, including the deprecated S3 alias, are preserved. - Stable IDs and configured implementation paths use a canonical legacy path. + Stable IDs and mapped implementation paths use a canonical legacy path. """ if not isinstance(value, str): return value @@ -93,15 +118,15 @@ def legacy_backend_path(value): def backend_path(kind): - """Return the deployment-selected class path for a stable backend ID.""" + """Return the internally selected class path for a stable backend ID.""" kind = backend_id(kind) if kind is None: raise ValueError("Unknown storage backend") - return settings.DOMAIN_STORAGE_BACKENDS[kind] + return DOMAIN_STORAGE_BACKENDS[kind] def backend_class(kind): - """Import the deployment-selected Django storage implementation.""" + """Import the implementation selected for a built-in storage backend ID.""" return import_string(backend_path(kind)) diff --git a/pulpcore/tests/unit/test_storage_backends.py b/pulpcore/tests/unit/test_storage_backends.py index f6ad40cfdf3..3eb73068184 100644 --- a/pulpcore/tests/unit/test_storage_backends.py +++ b/pulpcore/tests/unit/test_storage_backends.py @@ -13,6 +13,7 @@ BackendChoiceField, ) from pulpcore.app.storage_backends import ( + DOMAIN_STORAGE_BACKENDS, backend_id, backend_path, legacy_backend_path, @@ -89,7 +90,7 @@ def test_storage_redirect_backend_check_is_skipped_without_redirects(): @pytest.mark.django_db -def test_domain_implementation_can_change_without_updating_record(): +def test_domain_implementation_can_change_without_updating_record(monkeypatch): """Changing the backend mapping replaces its implementation without changing the row.""" domain = Domain.objects.create( name="other", @@ -102,24 +103,25 @@ def test_domain_implementation_can_change_without_updating_record(): first_path = "pulpcore.tests.unit.test_storage_backends.FirstStorage" second_path = "pulpcore.tests.unit.test_storage_backends.SecondStorage" try: - with override_settings(DOMAIN_STORAGE_BACKENDS={"filesystem": first_path}): - first = domain.get_storage() - assert isinstance(first, FirstStorage) - assert first.settings["location"] == "/tmp/media" - with override_settings(DOMAIN_STORAGE_BACKENDS={"filesystem": second_path}): - second = domain.get_storage() - assert isinstance(second, SecondStorage) - domain.refresh_from_db() - assert domain.storage_class == original_storage_class - assert domain.storage_settings == original_storage_settings - assert domain.pulp_last_updated == original_last_updated + monkeypatch.setitem(DOMAIN_STORAGE_BACKENDS, STORAGE_BACKENDS.FILESYSTEM, first_path) + first = domain.get_storage() + assert isinstance(first, FirstStorage) + assert first.settings["location"] == "/tmp/media" + + monkeypatch.setitem(DOMAIN_STORAGE_BACKENDS, STORAGE_BACKENDS.FILESYSTEM, second_path) + second = domain.get_storage() + assert isinstance(second, SecondStorage) + domain.refresh_from_db() + assert domain.storage_class == original_storage_class + assert domain.storage_settings == original_storage_settings + assert domain.pulp_last_updated == original_last_updated finally: storages.pop(domain.pulp_id, None) -@override_settings(DOMAIN_STORAGE_BACKENDS={"s3": "example.adapters.S3Storage"}) -def test_implementation_mapping_does_not_change_backend_id(): - """A deployment can replace code without updating a Domain row.""" +def test_implementation_mapping_does_not_change_backend_id(monkeypatch): + """A code change can replace the implementation without updating Domain rows.""" + monkeypatch.setitem(DOMAIN_STORAGE_BACKENDS, STORAGE_BACKENDS.S3, "example.adapters.S3Storage") assert backend_id("example.adapters.S3Storage") == "s3" assert backend_path("s3") == "example.adapters.S3Storage" assert legacy_backend_path("example.adapters.S3Storage") == "storages.backends.s3.S3Storage"