././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1701732382.4403527 django_titofisto-1.1.0/CHANGELOG.md0000644000000000000000000000360614533460036013627 0ustar00# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.1.0] - 2023-12-05 ### Changed - Allow Django 5.0 ### Removed - Remove support for Django versions below 4.2 ## [1.0.0] - 2023-07-07 ### Added - Time-constrained upload slot handling ### Changed - Use Django's Signer for token generation and verification ## [0.2.2] - 2022-02-03 ### Fixed - Non-existing files in the public namespace erroneously raised interal server errors. ## [0.2.1] – 2021-12-07 ### Changed - Allow Django 4.0 ## [0.2.0] - 2021-10-24 ### Changed - Provide mechanism to make files in a public namespace accessible without a token. ## [0.1.2.post1] - 2021-05-17 ### Changed - Amend mistakes in changelog ## [0.1.2] - 2021-05-17 ### Changed - Combine timestamp into token parameter - (Dev) Move settings handling into separate module ## [0.1.1] - 2021-05-16 ### Fixed - Fall back to current time if file does not exist to get mtime ## [0.1.0] - 2021-05-16 ### Added - Initial release, as described in readme [Unreleased]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tree/master [0.1.0]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.0 [0.1.1]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.1 [0.1.2]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.2 [0.1.2.post1]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.2.post1 [0.2.0]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.2.0 [0.2.1]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.2.1 [0.2.2]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.2.2 [1.0.0]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/1.0.0 [1.1.0]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/1.1.0 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1634983075.6969686 django_titofisto-1.1.0/LICENSE0000644000000000000000000002615514134756244013035 0ustar00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2021 Dominik George Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732201.189965 django_titofisto-1.1.0/README.rst0000644000000000000000000001064714533457551013520 0ustar00Django Time-Token File Storage ============================== This is a simple extension to Django's `FileSystemStorage` that adds a URL parameter carrying a shared token, which is only valid for a defined period of time. Additionally, a like-wise time-constrained file upload slot mechanism is available. Functionality ------------- File storage with token-secured URLs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is a drop-in replacement for the Django `FileSystemStorage`, usable if media files are served by Django itself. It does currently not work if media files are served from an independent web server. The storage and its accompanying view do the following: * When a URL to a storage file is generated, a HMAC-based token is generated * The token and the timestamp when it was generated are appended as request parameters to the URL * Upon retrieval of the file through the accompanying view, the requested file name and the passed timestamp are used to recalculate the HMAC-based token * Only if the tokens match, and a configured timeout has not passed, is the file served The signature-based token ensures that the token is invalidated when: * The filename changes * The timestamp changes * The mtime of the file changes * The `SECRET_KEY` changes Time-constrained uplaod slot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The upload slot mechanism can be used to generically handle file uploads by clients that can not upload files with a regular request. One example for this is a client using GraphQL to talk to Django, because GraphQL does not support file uploads and rather suggests to do uplaods out-of-band. With Titofisto's upload slot mechanism, calling code can request a secure URL which it can hand out to a client. When the client POSTs its file to the endpoint, a previously provided callback is called to handle the uploaded file. Installation ------------ To add `django-titofisto`_ to a project, first add it as dependency to your project, e.g. using `poetry`_:: $ poetry add django-titofisto `django-titofisto` will use the base `FileSystemStorage` for almost everything, including determining the `MEDIA_ROOT`. It merely adds a token as URL parameter to whatever the base `FileSystemStorage.url()` method returns. Add the following to your settings:: DEFAULT_FILE_STORAGE = "titofisto.TitofistoStorage" TITOFISTO_TIMEOUT = 3600 # optional, this is the default TITOFISTO_PARAM = "titofisto_token" # optional, this is the default Add the following to your URL config:: from django.conf import settings from django.urls import include, path urlpatterns += [ path(settings.MEDIA_URL.removeprefix("/"), include("titofisto.urls")), ] Django will start serving media files under the configured `MEDIA_URL`. Provide public media files ~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes, there might be media files, for example favicons, you want to be accessible without any authentication. Per default, `django-titofisto` will serve all files stored in the directory `public` without a token. You can disable or configure this behavior using these settings:: TITOFISTO_USE_PUBLIC_NAMESPACE = True # optional, this is the default TITOFISTO_PUBLIC_NAMESPACE = "public/" # optional, this is the default Use the time-constrained upload slot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To enable the file upload mechanism, a setting must be set, because the default `upload/` prefix could potentially shadow expected media file URLs:: TITOFISTO_ENABLE_UPLOAD = True TITOFISTO_UPLOAD_NAMESPACE = "titofisto/upload/" A simplified example for using the upload slot mechanism is:: from titofisto.views import TitofistoUploadView def handle_file(request, pk): instance = MyModel.objects.get(pk=pk) instance.photo = request.FILES["photo"] instance.save() # This gets an uplaod URL to pass on to the client # On upload, the handler above will be called, with 15 as positional argument upload_url = TitofistoUploadView.get_upload_slot( "mymodule.handle_file", (15,) ) Credits ------- `django-titofisto` was developed for the `AlekSIS`_ school information system by its team:: Copyright © 2021, 2023 Dominik George Copyright © 2021 Jonathan Weth .. _django-titofisto: https://edugit.org/AlekSIS/libs/django-titofisto .. _poetry: https://python-poetry.org/ .. _Django's cache framework: https://docs.djangoproject.com/en/3.2/topics/cache/ .. _AlekSIS: https://aleksis.org/ ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732289.836967 django_titofisto-1.1.0/pyproject.toml0000644000000000000000000000153714533457702014741 0ustar00[tool.poetry] name = "django-titofisto" version = "1.1.0" description = "Django Time-Token File Storage" authors = ["Dominik George ", "Jonathan Weth "] license = "Apache-2.0" readme = "README.rst" repository = "https://edugit.org/AlekSIS/libs/django-titofisto" keywords = ["django", "storage", "media", "secure"] classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", ] packages = [ { include = "titofisto" }, ] include = ["LICENSE", "CHANGELOG.md"] [tool.poetry.dependencies] python = "^3.9" Django = ">4.2,<6.0" shortuuid = "^1.0.11" [tool.poetry.group.dev.dependencies] pytest = "^7.4.0" freezegun = "^1.1.0" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1634983075.6969686 django_titofisto-1.1.0/titofisto/__init__.py0000644000000000000000000000004614134756244016154 0ustar00from .storage import TitofistoStorage ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732201.189965 django_titofisto-1.1.0/titofisto/settings.py0000644000000000000000000000073014533457551016257 0ustar00from django.conf import settings PARAM = getattr(settings, "TITOFISTO_PARAM", "titofisto_token") TIMEOUT = getattr(settings, "TITOFISTO_TIMEOUT", 60 * 60) USE_PUBLIC_NAMESPACE = getattr(settings, "TITOFISTO_USE_PUBLIC_NAMESPACE", True) PUBLIC_NAMESPACE = getattr(settings, "TITOFISTO_PUBLIC_NAMESPACE", "public/") ENABLE_UPLOAD = getattr(settings, "TITOFISTO_ENABLE_UPLOAD", False) UPLOAD_NAMESPACE = getattr(settings, "TITOFISTO_UPLOAD_NAMESPACE", "titofisto/upload/") ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732201.189965 django_titofisto-1.1.0/titofisto/storage.py0000644000000000000000000000321014533457551016057 0ustar00from datetime import datetime from django.core.files.storage import FileSystemStorage from django.core.signing import TimestampSigner from .settings import PARAM, TIMEOUT, USE_PUBLIC_NAMESPACE, PUBLIC_NAMESPACE class TitofistoStorage(FileSystemStorage): """Time-token secured variant of the base filesystem storage.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._signer = TimestampSigner() def url(self, name: str) -> str: """Compute URL for requested storage file.""" # Get regular URL from base FileSystemStorage raw_url = super().url(name) if USE_PUBLIC_NAMESPACE: # Public files are accessible without a token if name.startswith(PUBLIC_NAMESPACE): return raw_url # Get token and timestamp token = self.get_token(name) # Generate full, token-secured URL full_url = f"{raw_url}?{PARAM}={token}" return full_url def get_token_message(self, name: str) -> str: """Determine parts of the MAC from the file.""" if self.exists(name): mtime = self.get_modified_time(name).isoformat() else: mtime = datetime.now().isoformat() return f"{name}//{mtime}" def get_token(self, name: str) -> str: """Get a token for a filename.""" return ":".join(self._signer.sign(self.get_token_message(name)).split(":")[-2:]) def verify_token(self, name: str, token: str): """Verify a token for validity and timeout.""" return self._signer.unsign(":".join((self.get_token_message(name), token)), max_age=TIMEOUT) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732201.189965 django_titofisto-1.1.0/titofisto/test_settings.py0000644000000000000000000000133514533457551017320 0ustar00from tempfile import mkdtemp # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "yiv&ahwdi^^_(m63-%uok#9k6vp#6*p=@d+a=hk4vj62=me5&2" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "titofisto.test_urls" WSGI_APPLICATION = "titofisto_example.wsgi.application" USE_TZ = True MEDIA_ROOT = mkdtemp() MEDIA_URL = "/media/" TITOFISTO_ENABLE_UPLOAD = True ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1634983075.6969686 django_titofisto-1.1.0/titofisto/test_urls.py0000644000000000000000000000024514134756244016442 0ustar00from django.conf import settings from django.urls import include, path urlpatterns = [ path(settings.MEDIA_URL.removeprefix("/"), include("titofisto.urls")), ] ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732201.189965 django_titofisto-1.1.0/titofisto/tests.py0000644000000000000000000001727614533457551015576 0ustar00from datetime import datetime, timedelta from io import BytesIO from pathlib import Path from unittest import TestCase from freezegun import freeze_time from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile from django.http import HttpRequest, HttpResponse from django.test import Client from .storage import TitofistoStorage from .views import TitofistoUploadView test_file_1 = b"The quick brown fox jumps over the lazy dog" test_file_1_name = "quickfox.dat" class TitofistoMediaTestCase(TestCase): def setUp(self): self.storage = TitofistoStorage() self.test_file_1 = b"The quick brown fox jumps over the lazy dog" self.test_file_1_name = "quickfox.dat" self.storage.save(self.test_file_1_name, BytesIO(self.test_file_1)) self.test_file_2 = b"Franz jagt im komplett verwahrlosten Taxi quer durch Bayern" self.test_file_2_name = "franztaxi.dat" self.storage.save(self.test_file_2_name, BytesIO(self.test_file_2)) self.test_file_3 = b"Franz jagt im komplett verwahrlosten Taxi quer durch Bayern" self.test_file_3_name = "public/franztaxi.dat" self.storage.save(self.test_file_3_name, BytesIO(self.test_file_3)) self.param = "titofisto_token" self.timeout = 60 * 60 self.client = Client() def tearDown(self): self.storage.delete(self.test_file_1_name) self.storage.delete(self.test_file_2_name) def test_token_deterministic(self): """The generated token is deterministic for a single, unchanged file""" with freeze_time(): token_1 = self.storage.get_token(self.test_file_1_name) token_2 = self.storage.get_token(self.test_file_1_name) self.assertEqual(token_1, token_2) def test_token_file_dependent(self): """The generated token is different for different files""" with freeze_time(): token_1 = self.storage.get_token(self.test_file_1_name) token_2 = self.storage.get_token(self.test_file_2_name) self.assertNotEqual(token_1, token_2) def test_token_ts_dependent(self): """The generated token is different for different timestamps""" with freeze_time(): token_1 = self.storage.get_token(self.test_file_1_name) with freeze_time(): token_2 = self.storage.get_token(self.test_file_2_name) self.assertNotEqual(token_1, token_2) def test_get_valid_token(self): """A file can be retrieved with a valid token""" token = self.storage.get_token(self.test_file_1_name) url = f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.streaming_content)[0], self.test_file_1) def test_get_invalid_token(self): """A file can not be retrieved with an invalid token""" token = self.storage.get_token(self.test_file_1_name) url = f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}=a{token}" res = self.client.get(url) self.assertEqual(res.status_code, 404) def test_get_close_to_timeout(self): """A file can still be retrieved close to the timeout""" now = datetime.now() with freeze_time(now + timedelta(seconds=self.timeout - 1)): token = self.storage.get_token(self.test_file_1_name) url = f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.streaming_content)[0], self.test_file_1) def test_get_after_timeout(self): """A file can not be retrieved after the timeout""" now = datetime.now() with freeze_time(now): token = self.storage.get_token(self.test_file_1_name) url = f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" with freeze_time(now + timedelta(seconds=self.timeout + 1)): res = self.client.get(url) self.assertEqual(res.status_code, 404) def test_get_after_mtime_change(self): """A file can not be retrieved with the same token after its mtime changes""" now = datetime.now() with freeze_time(now + timedelta(seconds=10)): token = self.storage.get_token(self.test_file_1_name) url = f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" Path(self.storage.path(self.test_file_1_name)).touch() res = self.client.get(url) self.assertEqual(res.status_code, 404) def test_url(self): """The URL for a file should contain a token.""" url1 = self.storage.url(self.test_file_1_name) url2 = self.storage.url(self.test_file_2_name) self.assertIn(self.param, url1) self.assertIn(self.param, url2) def test_public_files_url(self): """The URL for a file in the public namespace doesn't contain a token.""" url = self.storage.url(self.test_file_3_name) self.assertNotIn(self.param, url) def test_public_files_view(self): """A file in the public namespace can be acessed without a token.""" self.storage.url(self.test_file_3_name) url = f"{settings.MEDIA_URL}{self.test_file_3_name}" res = self.client.get(url) self.assertEqual(res.status_code, 200) def test_404_not_found(self): """A 404 is returned for non-existent files.""" url = f"{settings.MEDIA_URL}public/some_not_existing_file.txt" res = self.client.get(url) self.assertEqual(res.status_code, 404) def _upload_cb_test_1(request) -> HttpResponse: file = request.FILES["file"] assert file.name == test_file_1_name assert file.read() == test_file_1 return HttpResponse(status=418) def _upload_cb_test_2(request, p1, p2, foo) -> HttpResponse: assert p1 == "pos1" assert p2 == "pos2" assert foo == "bar" file = request.FILES["file"] assert file.name == test_file_1_name assert file.read() == test_file_1 return HttpResponse(status=420) class TitofistoUploadTestCase(TestCase): def setUp(self): self.client = Client() def test_upload_valid_slot_no_args(self): upload_url = TitofistoUploadView.get_upload_slot("titofisto.tests._upload_cb_test_1") res = self.client.post( upload_url, data={"file": SimpleUploadedFile(test_file_1_name, test_file_1)} ) assert res.status_code == 418 def test_upload_valid_slot_with_args(self): upload_url = TitofistoUploadView.get_upload_slot( "titofisto.tests._upload_cb_test_2", ("pos1", "pos2"), {"foo": "bar"} ) res = self.client.post( upload_url, data={"file": SimpleUploadedFile(test_file_1_name, test_file_1)} ) assert res.status_code == 420 def test_upload_invalid_slot(self): upload_url = TitofistoUploadView.get_upload_slot("titofisto.tests._upload_cb_test_1") upload_url_mangled = upload_url[:-1] + "a/" res = self.client.post( upload_url_mangled, data={"file": SimpleUploadedFile(test_file_1_name, test_file_1)} ) assert res.status_code == 404 def test_upload_valid_slot_twice(self): upload_url = TitofistoUploadView.get_upload_slot("titofisto.tests._upload_cb_test_1") res1 = self.client.post( upload_url, data={"file": SimpleUploadedFile(test_file_1_name, test_file_1)} ) res2 = self.client.post( upload_url, data={"file": SimpleUploadedFile(test_file_1_name, test_file_1)} ) assert res1.status_code == 418 assert res2.status_code == 404 ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732201.189965 django_titofisto-1.1.0/titofisto/urls.py0000644000000000000000000000071414533457551015406 0ustar00from django.urls import path from .views import TitofistoMediaView, TitofistoUploadView from .settings import ENABLE_UPLOAD, UPLOAD_NAMESPACE app_name = "titofisto" urlpatterns = [ path("", TitofistoMediaView.as_view()), ] if ENABLE_UPLOAD: urlpatterns.insert( 0, path( f"{UPLOAD_NAMESPACE}///", TitofistoUploadView.as_view(), name="upload", ), ) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1701732201.189965 django_titofisto-1.1.0/titofisto/views.py0000644000000000000000000000755414533457551015567 0ustar00from typing import Any, Optional from django.core.cache import cache from django.core.signing import BadSignature, SignatureExpired, TimestampSigner from django.http import FileResponse, Http404, HttpRequest, HttpResponse from django.urls import reverse from django.utils.module_loading import import_string from django.views import View import shortuuid from .settings import PARAM, USE_PUBLIC_NAMESPACE, PUBLIC_NAMESPACE, TIMEOUT from .storage import TitofistoStorage class TitofistoMediaView(View): def get(self, request: HttpRequest, name: str) -> FileResponse: # Get storage storage = TitofistoStorage() if USE_PUBLIC_NAMESPACE: # Public files are directly served without needing a token if name.startswith(PUBLIC_NAMESPACE): if storage.exists(name): return FileResponse(storage._open(name)) else: raise Http404() # Inspect URL parameter token = request.GET.get(PARAM, None) if token is None: raise Http404() # Verify token for filename try: storage.verify_token(name, token) except FileNotFoundError: raise Http404() except (BadSignature, SignatureExpired): raise Http404() # Finally, serve file from disk if all checks passed return FileResponse(storage._open(name)) class TitofistoUploadView(View): """Handles time-constrained upload slots for files. This view can be used to dynamically handle file uploads that are protected with a generic upload slot. The mechanism works by some code requesting an upload slot URL, to which a client can then POST a file. On successful upload, a callback function is called, where the requesting code receives the actual file to handle. .. code-block:: python from titofisto.views import TitofistoUploadView def handle_file(request, pk): instance = MyModel.objects.get(pk=pk) instance.photo = request.FILES["photo"] instance.save() # This gets an uplaod URL to pass on to the client # On upload, the handler above will be called, with 15 as positional argument upload_url = TitofistoUploadView.get_upload_slot( "mymodule.handle_file", (15,) ) """ @classmethod def get_upload_slot( cls, cb: str, args: Optional[tuple[Any]] = None, kwargs: Optional[dict[str, Any]] = None, ) -> str: """Gets an upload slot URL to pass on to a client. :param cb: dotted path to a callable accepting an HttpRequest as first argument, and returning an HttpResponse (or None for 200) :param args: a tuple of positional arguments to pass to the callback :param kwargs: a dictionary of keyword arguments to pass to the callback """ slot_name = shortuuid.uuid() token = ":".join(TimestampSigner().sign(slot_name).split(":")[-2:]) slot_info = { "cb": cb, "args": args or tuple(), "kwargs": kwargs or {}, } cache.set(f"titofisto.slot:{slot_name}", slot_info, TIMEOUT) return reverse("titofisto:upload", kwargs={"slot_name": slot_name, "token": token}) def post(self, request: HttpRequest, slot_name: str, token: str) -> HttpResponse: try: TimestampSigner().unsign(":".join((slot_name, token)), max_age=TIMEOUT) except (BadSignature, SignatureExpired): raise Http404() slot_info = cache.get(f"titofisto.slot:{slot_name}") if slot_info is None: raise Http404() cache.delete(f"titofisto.slot:{slot_name}") cb = import_string(slot_info["cb"]) res = cb(request, *(slot_info["args"]), **(slot_info["kwargs"])) return res or HttpResponse() django_titofisto-1.1.0/PKG-INFO0000644000000000000000000001250400000000000013045 0ustar00Metadata-Version: 2.1 Name: django-titofisto Version: 1.1.0 Summary: Django Time-Token File Storage Home-page: https://edugit.org/AlekSIS/libs/django-titofisto License: Apache-2.0 Keywords: django,storage,media,secure Author: Dominik George Author-email: dominik.george@teckids.org Requires-Python: >=3.9,<4.0 Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Framework :: Django Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Requires-Dist: Django (>4.2,<6.0) Requires-Dist: shortuuid (>=1.0.11,<2.0.0) Project-URL: Repository, https://edugit.org/AlekSIS/libs/django-titofisto Description-Content-Type: text/x-rst Django Time-Token File Storage ============================== This is a simple extension to Django's `FileSystemStorage` that adds a URL parameter carrying a shared token, which is only valid for a defined period of time. Additionally, a like-wise time-constrained file upload slot mechanism is available. Functionality ------------- File storage with token-secured URLs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is a drop-in replacement for the Django `FileSystemStorage`, usable if media files are served by Django itself. It does currently not work if media files are served from an independent web server. The storage and its accompanying view do the following: * When a URL to a storage file is generated, a HMAC-based token is generated * The token and the timestamp when it was generated are appended as request parameters to the URL * Upon retrieval of the file through the accompanying view, the requested file name and the passed timestamp are used to recalculate the HMAC-based token * Only if the tokens match, and a configured timeout has not passed, is the file served The signature-based token ensures that the token is invalidated when: * The filename changes * The timestamp changes * The mtime of the file changes * The `SECRET_KEY` changes Time-constrained uplaod slot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The upload slot mechanism can be used to generically handle file uploads by clients that can not upload files with a regular request. One example for this is a client using GraphQL to talk to Django, because GraphQL does not support file uploads and rather suggests to do uplaods out-of-band. With Titofisto's upload slot mechanism, calling code can request a secure URL which it can hand out to a client. When the client POSTs its file to the endpoint, a previously provided callback is called to handle the uploaded file. Installation ------------ To add `django-titofisto`_ to a project, first add it as dependency to your project, e.g. using `poetry`_:: $ poetry add django-titofisto `django-titofisto` will use the base `FileSystemStorage` for almost everything, including determining the `MEDIA_ROOT`. It merely adds a token as URL parameter to whatever the base `FileSystemStorage.url()` method returns. Add the following to your settings:: DEFAULT_FILE_STORAGE = "titofisto.TitofistoStorage" TITOFISTO_TIMEOUT = 3600 # optional, this is the default TITOFISTO_PARAM = "titofisto_token" # optional, this is the default Add the following to your URL config:: from django.conf import settings from django.urls import include, path urlpatterns += [ path(settings.MEDIA_URL.removeprefix("/"), include("titofisto.urls")), ] Django will start serving media files under the configured `MEDIA_URL`. Provide public media files ~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes, there might be media files, for example favicons, you want to be accessible without any authentication. Per default, `django-titofisto` will serve all files stored in the directory `public` without a token. You can disable or configure this behavior using these settings:: TITOFISTO_USE_PUBLIC_NAMESPACE = True # optional, this is the default TITOFISTO_PUBLIC_NAMESPACE = "public/" # optional, this is the default Use the time-constrained upload slot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To enable the file upload mechanism, a setting must be set, because the default `upload/` prefix could potentially shadow expected media file URLs:: TITOFISTO_ENABLE_UPLOAD = True TITOFISTO_UPLOAD_NAMESPACE = "titofisto/upload/" A simplified example for using the upload slot mechanism is:: from titofisto.views import TitofistoUploadView def handle_file(request, pk): instance = MyModel.objects.get(pk=pk) instance.photo = request.FILES["photo"] instance.save() # This gets an uplaod URL to pass on to the client # On upload, the handler above will be called, with 15 as positional argument upload_url = TitofistoUploadView.get_upload_slot( "mymodule.handle_file", (15,) ) Credits ------- `django-titofisto` was developed for the `AlekSIS`_ school information system by its team:: Copyright © 2021, 2023 Dominik George Copyright © 2021 Jonathan Weth .. _django-titofisto: https://edugit.org/AlekSIS/libs/django-titofisto .. _poetry: https://python-poetry.org/ .. _Django's cache framework: https://docs.djangoproject.com/en/3.2/topics/cache/ .. _AlekSIS: https://aleksis.org/