From 7937352159dc176af29b0b4ecffc8b7f9def1a94 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Wed, 25 Nov 2026 14:32:16 +0330 Subject: [PATCH 1/8] ci: run tests on pull requests to main only, via shared ci-workflows Tests-only gate (python-test.yml) on pull requests into main; nothing runs on any other branch or event. Publishing uses the shared python-publish.yml. --- .github/workflows/ci.yml | 147 ++++++++++------------------------ .github/workflows/release.yml | 36 ++++----- 2 files changed, 56 insertions(+), 127 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b2555e3..eaa5d99 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,116 +1,51 @@ +# Runs the tests on a pull request into main — and on nothing else. +# The job lives once in CtrlAltDevelop/ci-workflows (python-test.yml). + name: CI on: pull_request: + branches: [main] + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true -permissions: - contents: read +permissions: {} jobs: - # Every pull request runs the suite, and a pull request into `main` runs this - # and nothing else: the branch has already been through the whole pipeline on - # its way into `develop`, and repeating the packaging, the wheel smoke test - # and the example tour to merge a reviewed branch buys minutes, not safety. test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-python@v6 - with: - python-version: "3.12" - cache: pip - - run: python -m pip install -e '.[dev]' - - run: make test + name: Test + uses: CtrlAltDevelop/ci-workflows/.github/workflows/python-test.yml@v1.2.0 + permissions: + contents: read + with: + python-version: "3.12" + install: uv venv && uv pip install -e '.[dev]' + test-command: uv run --no-sync make test - # The wallet's safety rests on `select_for_update`, and SQLite compiles that - # away -- so on the default backend the race tests skip and the whole "no - # double withdrawal" claim is untested. This job is the one place it is - # actually exercised: a real Postgres, and the wallet suite run against it. - # Scoped to the wallet rather than the whole suite because row locking is the - # only thing this proves that the job above does not. + # The wallet's row-lock tests need a real PostgreSQL; on SQLite they skip. locks: - runs-on: ubuntu-latest - services: - postgres: - image: postgres:17 - env: - POSTGRES_USER: wallet - POSTGRES_PASSWORD: wallet - POSTGRES_DB: wallet - ports: - - 5432:5432 - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - env: - DJANGO_DB_ENGINE: django.db.backends.postgresql - DJANGO_DB_NAME: wallet - DJANGO_DB_USER: wallet - DJANGO_DB_PASSWORD: wallet - DJANGO_DB_HOST: localhost - DJANGO_DB_PORT: "5432" - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-python@v6 - with: - python-version: "3.12" - cache: pip - - run: python -m pip install -e '.[dev]' 'psycopg[binary]' - # `-p no:randomly` because the race tests run real threads against real - # rows: an ordering that leaves a wallet behind from another test is a - # flake nobody can reproduce. - - run: pytest src/apps/wallet -p no:randomly --no-cov - # Fails the job if the race tests were skipped after all -- a silent skip - # here would put this workflow back exactly where it started. - - name: The row-lock tests must actually have run - run: | - # pipefail, or `tee` succeeding would hide pytest failing. - set -o pipefail - pytest src/apps/wallet/tests/test_concurrency.py -p no:randomly --no-cov -q \ - | tee /tmp/locks.txt - if grep -qi "skipped" /tmp/locks.txt; then - echo "::error::the row-lock tests skipped, so nothing proved the locks work" - exit 1 - fi - - # Everything else a merge could break: the linters and the type checker, the - # wheel, and the published generator building and touring a real project. - # Skipped for a pull request into `main`. - verify: - if: github.base_ref != 'main' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-python@v6 - with: - python-version: "3.12" - cache: pip - - run: python -m pip install -e '.[dev]' - - run: make check - - run: make package - - name: Smoke-test the built wheel - run: | - python -m venv /tmp/django-ninja-starter-wheel - /tmp/django-ninja-starter-wheel/bin/pip install dist/*.whl - cd /tmp - /tmp/django-ninja-starter-wheel/bin/django-ninja-starter example-api - /tmp/django-ninja-starter-wheel/bin/pip install -e 'example-api[dev]' - cd example-api - /tmp/django-ninja-starter-wheel/bin/python manage.py startapi example --api-version v2 - # `startapi` scaffolds a gRPC service and says so; its stubs do not - # exist until this runs, and `make check` type-checks the import of - # them. Doing it here is the workflow the command itself prints. - /tmp/django-ninja-starter-wheel/bin/python manage.py protos - PATH="/tmp/django-ninja-starter-wheel/bin:$PATH" make check - PATH="/tmp/django-ninja-starter-wheel/bin:$PATH" make test - - name: Build and tour the example project from that wheel - # The wheel's own django-ninja-starter is first on the path here, so - # this is the published generator building the example, not the - # checkout's copy of it. - run: | - /tmp/django-ninja-starter-wheel/bin/python examples/build.py \ - --into /tmp/example-tour --rebuild - /tmp/django-ninja-starter-wheel/bin/python examples/walkthrough.py \ - --project /tmp/example-tour + name: Row locks (PostgreSQL) + uses: CtrlAltDevelop/ci-workflows/.github/workflows/python-test.yml@v1.2.0 + permissions: + contents: read + with: + python-version: "3.12" + postgres: true + install: uv venv && uv pip install -e '.[dev]' 'psycopg[binary]' + env: | + DJANGO_DB_ENGINE=django.db.backends.postgresql + DJANGO_DB_NAME=test_db + DJANGO_DB_USER=test_user + DJANGO_DB_PASSWORD=test_pass + DJANGO_DB_HOST=localhost + DJANGO_DB_PORT=5432 + test-command: | + set -o pipefail + uv run --no-sync pytest src/apps/wallet -p no:randomly --no-cov + uv run --no-sync pytest src/apps/wallet/tests/test_concurrency.py -p no:randomly --no-cov -q | tee /tmp/locks.txt + if grep -qi "skipped" /tmp/locks.txt; then + echo "::error::the row-lock tests skipped, so nothing proved the locks work" + exit 1 + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3d07609..3939d1e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,30 +1,24 @@ -name: Publish to PyPI +# Publishes the package to PyPI when a GitHub release is published. +# +# `v` publishes that version. The tag check and the one-off PyPI +# setup live in CtrlAltDevelop/ci-workflows (python-publish.yml). PyPI trusts +# this file's name and the `pypi` environment, so keep both. + +name: Release on: release: types: [published] -permissions: - contents: read +permissions: {} jobs: - publish: - runs-on: ubuntu-latest - environment: - name: pypi - url: https://pypi.org/p/django-ninja-starter + release: + name: Release + uses: CtrlAltDevelop/ci-workflows/.github/workflows/python-publish.yml@v1.2.0 permissions: + contents: read id-token: write - steps: - - uses: actions/checkout@v6 - with: - persist-credentials: false - - uses: actions/setup-python@v6 - with: - python-version: "3.12" - - name: Build distributions - run: | - python -m pip install build - python -m build - - name: Publish distributions - uses: pypa/gh-action-pypi-publish@release/v1 + with: + package-name: django-ninja-starter + python-version: "3.12" From 624e563a3fb2395b2da8e54145694dae9eccec0f Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Thu, 26 Nov 2026 17:50:43 +0330 Subject: [PATCH 2/8] =?UTF-8?q?=F0=9F=93=84=20document(license):=20relicen?= =?UTF-8?q?se=20from=20MIT=20to=20AGPL-3.0-only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE | 683 +++++++++++++++++++++++++++++++++++++++++++++++-- pyproject.toml | 2 +- 2 files changed, 663 insertions(+), 22 deletions(-) diff --git a/LICENSE b/LICENSE index c451562..fe6b903 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,662 @@ -MIT License - -Copyright (c) 2026 django-ninja-starter contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/pyproject.toml b/pyproject.toml index 4f8e78e..4bf2c18 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ dynamic = ["version"] description = "A production-oriented Django Ninja API template and project generator" readme = "README.md" requires-python = ">=3.12" -license = "MIT" +license = "AGPL-3.0-only" keywords = [ "django", "django-ninja", From 3b83ee0646acd69bbb7898590937c83627473699 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Thu, 26 Nov 2026 17:50:43 +0330 Subject: [PATCH 3/8] =?UTF-8?q?=F0=9F=93=84=20document(readme):=20add=20ba?= =?UTF-8?q?dges=20and=20contributing/security=20section?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ef6654a..9a1b035 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,13 @@ # Django Ninja Starter [![PyPI](https://img.shields.io/pypi/v/django-ninja-starter.svg)](https://pypi.org/project/django-ninja-starter/) +[![CI](https://github.com/CtrlAltDevelop/django-ninja-starter/actions/workflows/ci.yml/badge.svg)](https://github.com/CtrlAltDevelop/django-ninja-starter/actions/workflows/ci.yml) +[![license: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](https://github.com/CtrlAltDevelop/django-ninja-starter/blob/main/LICENSE) +[![Python](https://img.shields.io/badge/Python-3.12%2B-3776AB.svg?logo=python&logoColor=white)](https://www.python.org) +[![Django](https://img.shields.io/badge/Django-5.2%2B-092E20.svg?logo=django)](https://www.djangoproject.com) +[![Django Ninja](https://img.shields.io/badge/Django%20Ninja-1.4%2B-0f766e.svg)](https://django-ninja.dev) +[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-supported-4169E1.svg?logo=postgresql&logoColor=white)](https://www.postgresql.org) +[![last commit](https://img.shields.io/github/last-commit/CtrlAltDevelop/django-ninja-starter.svg)](https://github.com/CtrlAltDevelop/django-ninja-starter/commits) A production-oriented Django and Django Ninja starter, available as both a GitHub Template and an installable Python project generator. @@ -570,6 +577,10 @@ To publish a release: 4. Create and publish a GitHub Release. The release workflow builds and uploads the wheel and source distribution without a long-lived PyPI token. +## Contributing and security + +See [CONTRIBUTING.md](CONTRIBUTING.md) for how to propose changes and [SECURITY.md](SECURITY.md) for reporting vulnerabilities. Release notes are in the [CHANGELOG](CHANGELOG.md). + ## License -MIT. See [LICENSE](LICENSE). +AGPL-3.0-only. See [LICENSE](LICENSE). From 206cf76437bdce0839b8b20eab71fb841570384c Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Thu, 26 Nov 2026 18:13:55 +0330 Subject: [PATCH 4/8] =?UTF-8?q?=E2=9A=99=EF=B8=8F=20ci(release):=20publish?= =?UTF-8?q?=20from=20this=20workflow,=20not=20the=20shared=20one?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PyPI trusted publishing rejects the shared reusable publish workflow with invalid-publisher, so build and publish live in release.yml and run on a v* tag, as in mdp-outbox. --- .github/workflows/release.yml | 70 ++++++++++++++++++++++++++++------- README.md | 9 +++-- 2 files changed, 62 insertions(+), 17 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3939d1e..9e4d3b6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,24 +1,68 @@ -# Publishes the package to PyPI when a GitHub release is published. +# ============================================================================= +# Release: build once, publish to PyPI with trusted publishing. +# ============================================================================= +# Runs on a version tag. No API token exists anywhere: PyPI trusts this +# workflow's OIDC identity, configured once under the project's "Publishing" +# settings (owner CtrlAltDevelop, repo django-ninja-starter, workflow +# release.yml, environment pypi). # -# `v` publishes that version. The tag check and the one-off PyPI -# setup live in CtrlAltDevelop/ci-workflows (python-publish.yml). PyPI trusts -# this file's name and the `pypi` environment, so keep both. +# The publish job lives in this file on purpose: PyPI's trusted publishing +# does not accept the same job run from the shared reusable workflow +# (CtrlAltDevelop/ci-workflows python-publish.yml); it fails with +# `invalid-publisher`, as it did for mdp-outbox v0.2.0. name: Release on: - release: - types: [published] + push: + tags: ["v*"] permissions: {} jobs: - release: - name: Release - uses: CtrlAltDevelop/ci-workflows/.github/workflows/python-publish.yml@v1.2.0 + build: + name: Build + runs-on: ubuntu-latest + timeout-minutes: 10 permissions: contents: read - id-token: write - with: - package-name: django-ninja-starter - python-version: "3.12" + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@v7 + with: + python-version: "3.12" + - name: Tag matches the package version + run: | + version=$(sed -n 's/^__version__ = "\(.*\)"$/\1/p' src/django_ninja_starter/__init__.py) + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "::error::Tag $GITHUB_REF_NAME does not match __version__ $version" + exit 1 + fi + - run: uv build + - uses: actions/upload-artifact@v7 + with: + name: dist + path: dist/ + if-no-files-found: error + + publish: + name: Publish to PyPI + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: + name: pypi + url: https://pypi.org/project/django-ninja-starter/ + permissions: + id-token: write # the OIDC token PyPI exchanges for a short-lived upload credential + steps: + - uses: actions/download-artifact@v8 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + # Don't fail on a re-run: files PyPI already has are skipped. + skip-existing: true diff --git a/README.md b/README.md index 9a1b035..af469c5 100644 --- a/README.md +++ b/README.md @@ -569,13 +569,14 @@ scaffold together when changing project behavior. To publish a release: -1. Update `version` in `pyproject.toml` and `__version__` in - `src/django_ninja_starter/__init__.py`. +1. Update `__version__` in `src/django_ninja_starter/__init__.py` and add the + release to `CHANGELOG.md`. 2. Run `make check`, `make test`, and `make package`. 3. Configure a PyPI Trusted Publisher for `.github/workflows/release.yml` with the `pypi` GitHub environment and require approval on that environment. -4. Create and publish a GitHub Release. The release workflow builds and uploads the wheel - and source distribution without a long-lived PyPI token. +4. Push a `v` tag matching `__version__`. The release workflow builds and uploads + the wheel and source distribution without a long-lived PyPI token. Then create the + GitHub Release from that tag. ## Contributing and security From 7b8c7f3eaaa79f48e174821b48701b49e302b803 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Thu, 26 Nov 2026 18:13:55 +0330 Subject: [PATCH 5/8] =?UTF-8?q?=F0=9F=9A=80=20release:=202.2.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 10 ++++++++++ src/django_ninja_starter/__init__.py | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e858309..0e43186 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.2.0] - 2026-11-26 + +### Changed + +- **Relicensed from MIT to AGPL-3.0-only.** Releases from 2.2.0 on are under the + GNU Affero General Public License v3; earlier releases keep their MIT license. +- **Releases publish from this repository's own workflow on a `v*` tag.** PyPI's + trusted publishing rejects the shared reusable publish workflow with + `invalid-publisher`, so the build and publish jobs live in `release.yml`. + ## [2.1.1] - 2026-10-15 ### Changed diff --git a/src/django_ninja_starter/__init__.py b/src/django_ninja_starter/__init__.py index e7205d3..3e9d0ca 100644 --- a/src/django_ninja_starter/__init__.py +++ b/src/django_ninja_starter/__init__.py @@ -1,3 +1,3 @@ """Django Ninja Starter project generator.""" -__version__ = "2.1.1" +__version__ = "2.2.0" From c86f08605ba231296a5f340a0c1950d041f829d6 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Thu, 26 Nov 2026 18:22:14 +0330 Subject: [PATCH 6/8] =?UTF-8?q?=E2=9A=99=EF=B8=8F=20ci(release):=20publish?= =?UTF-8?q?=20on=20a=20published=20GitHub=20Release?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keeps the trigger the last successful publish (2.1.1) used, so creating the release is the single step that ships it. --- .github/workflows/release.yml | 7 ++++--- CHANGELOG.md | 5 +++-- README.md | 6 +++--- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9e4d3b6..062aa9d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,8 @@ # ============================================================================= # Release: build once, publish to PyPI with trusted publishing. # ============================================================================= -# Runs on a version tag. No API token exists anywhere: PyPI trusts this +# Runs when a GitHub Release is published; its tag must be v<__version__>. +# No API token exists anywhere: PyPI trusts this # workflow's OIDC identity, configured once under the project's "Publishing" # settings (owner CtrlAltDevelop, repo django-ninja-starter, workflow # release.yml, environment pypi). @@ -14,8 +15,8 @@ name: Release on: - push: - tags: ["v*"] + release: + types: [published] permissions: {} diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e43186..aa0d78f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,9 +10,10 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - **Relicensed from MIT to AGPL-3.0-only.** Releases from 2.2.0 on are under the GNU Affero General Public License v3; earlier releases keep their MIT license. -- **Releases publish from this repository's own workflow on a `v*` tag.** PyPI's +- **Releases publish from this repository's own workflow.** PyPI's trusted publishing rejects the shared reusable publish workflow with - `invalid-publisher`, so the build and publish jobs live in `release.yml`. + `invalid-publisher`, so the build and publish jobs live in `release.yml`, still run by + publishing a GitHub Release. ## [2.1.1] - 2026-10-15 diff --git a/README.md b/README.md index af469c5..7da1500 100644 --- a/README.md +++ b/README.md @@ -574,9 +574,9 @@ To publish a release: 2. Run `make check`, `make test`, and `make package`. 3. Configure a PyPI Trusted Publisher for `.github/workflows/release.yml` with the `pypi` GitHub environment and require approval on that environment. -4. Push a `v` tag matching `__version__`. The release workflow builds and uploads - the wheel and source distribution without a long-lived PyPI token. Then create the - GitHub Release from that tag. +4. Create and publish a GitHub Release tagged `v`, matching `__version__`. The + release workflow builds and uploads the wheel and source distribution without a + long-lived PyPI token. ## Contributing and security From 5b0621099f1c2b50eb43c730709cfe4821b67e5e Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Thu, 26 Nov 2026 18:06:27 +0330 Subject: [PATCH 7/8] =?UTF-8?q?=F0=9F=93=A6=20add(webhooks):=20signed=20ou?= =?UTF-8?q?tgoing=20webhooks=20with=20retries=20and=20SSRF=20guard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New optional feature app (DJANGO_WEBHOOKS_ENABLED). Accounts register https endpoints with subscribed event types and a per-endpoint secret. Deliveries are signed with HMAC-SHA256 over timestamp and body (X-Webhook-Signature), sent by the cron-run `manage.py webhooks_deliver` with exponential backoff, and every attempt is recorded. Private, loopback, link-local and reserved targets are refused at registration and again before every send; redirects are not followed. Published over REST, GraphQL and gRPC, and mirrored into the template. --- .env.example | 8 + Makefile | 2 +- docs/README.md | 3 +- docs/webhooks.md | 114 ++++++++ examples/env.example | 8 + src/apps/webhooks/__init__.py | 1 + src/apps/webhooks/admin.py | 42 +++ src/apps/webhooks/apps.py | 41 +++ src/apps/webhooks/graph/__init__.py | 5 + src/apps/webhooks/graph/schema.py | 90 ++++++ src/apps/webhooks/grpc/__init__.py | 0 src/apps/webhooks/grpc/serializers.py | 30 ++ src/apps/webhooks/grpc/services.py | 101 +++++++ src/apps/webhooks/grpc/webhooks.proto | 71 +++++ src/apps/webhooks/grpc/webhooks_pb2.py | 57 ++++ src/apps/webhooks/grpc/webhooks_pb2.pyi | 265 +++++++++++++++++ src/apps/webhooks/grpc/webhooks_pb2_grpc.py | 270 ++++++++++++++++++ src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi | 86 ++++++ src/apps/webhooks/management/__init__.py | 0 .../webhooks/management/commands/__init__.py | 0 .../management/commands/webhooks_deliver.py | 18 ++ src/apps/webhooks/migrations/0001_initial.py | 123 ++++++++ src/apps/webhooks/migrations/__init__.py | 0 src/apps/webhooks/models.py | 73 +++++ src/apps/webhooks/rest/__init__.py | 5 + src/apps/webhooks/rest/schemas.py | 37 +++ src/apps/webhooks/rest/v1.py | 51 ++++ src/apps/webhooks/services.py | 261 +++++++++++++++++ src/apps/webhooks/tests/__init__.py | 0 src/apps/webhooks/tests/conftest.py | 45 +++ src/apps/webhooks/tests/test_api.py | 90 ++++++ src/apps/webhooks/tests/test_services.py | 133 +++++++++ src/config/api.py | 1 + src/config/settings/base.py | 31 ++ src/config/settings/test.py | 1 + src/django_ninja_starter/template/Makefile | 2 +- .../template/_env.example | 8 + .../template/docs/README.md | 3 +- .../template/docs/webhooks.md | 114 ++++++++ .../template/src/apps/webhooks/__init__.py | 1 + .../template/src/apps/webhooks/admin.py | 42 +++ .../template/src/apps/webhooks/apps.py | 41 +++ .../src/apps/webhooks/graph/__init__.py | 5 + .../src/apps/webhooks/graph/schema.py | 90 ++++++ .../src/apps/webhooks/grpc/__init__.py | 0 .../src/apps/webhooks/grpc/serializers.py | 30 ++ .../src/apps/webhooks/grpc/services.py | 101 +++++++ .../src/apps/webhooks/grpc/webhooks.proto | 71 +++++ .../src/apps/webhooks/grpc/webhooks_pb2.py | 57 ++++ .../src/apps/webhooks/grpc/webhooks_pb2.pyi | 265 +++++++++++++++++ .../apps/webhooks/grpc/webhooks_pb2_grpc.py | 270 ++++++++++++++++++ .../apps/webhooks/grpc/webhooks_pb2_grpc.pyi | 86 ++++++ .../src/apps/webhooks/management/__init__.py | 0 .../webhooks/management/commands/__init__.py | 0 .../management/commands/webhooks_deliver.py | 18 ++ .../apps/webhooks/migrations/0001_initial.py | 123 ++++++++ .../src/apps/webhooks/migrations/__init__.py | 0 .../template/src/apps/webhooks/models.py | 73 +++++ .../src/apps/webhooks/rest/__init__.py | 5 + .../src/apps/webhooks/rest/schemas.py | 37 +++ .../template/src/apps/webhooks/rest/v1.py | 51 ++++ .../template/src/apps/webhooks/services.py | 261 +++++++++++++++++ .../src/apps/webhooks/tests/__init__.py | 0 .../src/apps/webhooks/tests/conftest.py | 45 +++ .../src/apps/webhooks/tests/test_api.py | 90 ++++++ .../src/apps/webhooks/tests/test_services.py | 133 +++++++++ .../template/src/config/api.py | 1 + .../template/src/config/settings/base.py | 31 ++ .../template/src/config/settings/test.py | 1 + .../common/management/commands/authdocs.py | 2 +- .../common/management/commands/authdocs.py | 2 +- tests/test_env_samples.py | 2 +- 72 files changed, 4117 insertions(+), 7 deletions(-) create mode 100644 docs/webhooks.md create mode 100644 src/apps/webhooks/__init__.py create mode 100644 src/apps/webhooks/admin.py create mode 100644 src/apps/webhooks/apps.py create mode 100644 src/apps/webhooks/graph/__init__.py create mode 100644 src/apps/webhooks/graph/schema.py create mode 100644 src/apps/webhooks/grpc/__init__.py create mode 100644 src/apps/webhooks/grpc/serializers.py create mode 100644 src/apps/webhooks/grpc/services.py create mode 100644 src/apps/webhooks/grpc/webhooks.proto create mode 100644 src/apps/webhooks/grpc/webhooks_pb2.py create mode 100644 src/apps/webhooks/grpc/webhooks_pb2.pyi create mode 100644 src/apps/webhooks/grpc/webhooks_pb2_grpc.py create mode 100644 src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi create mode 100644 src/apps/webhooks/management/__init__.py create mode 100644 src/apps/webhooks/management/commands/__init__.py create mode 100644 src/apps/webhooks/management/commands/webhooks_deliver.py create mode 100644 src/apps/webhooks/migrations/0001_initial.py create mode 100644 src/apps/webhooks/migrations/__init__.py create mode 100644 src/apps/webhooks/models.py create mode 100644 src/apps/webhooks/rest/__init__.py create mode 100644 src/apps/webhooks/rest/schemas.py create mode 100644 src/apps/webhooks/rest/v1.py create mode 100644 src/apps/webhooks/services.py create mode 100644 src/apps/webhooks/tests/__init__.py create mode 100644 src/apps/webhooks/tests/conftest.py create mode 100644 src/apps/webhooks/tests/test_api.py create mode 100644 src/apps/webhooks/tests/test_services.py create mode 100644 src/django_ninja_starter/template/docs/webhooks.md create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/admin.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/apps.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/graph/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/graph/schema.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/serializers.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/services.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks.proto create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.pyi create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/management/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/management/commands/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/management/commands/webhooks_deliver.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/migrations/0001_initial.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/migrations/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/models.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/rest/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/rest/schemas.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/rest/v1.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/services.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/tests/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/tests/conftest.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/tests/test_api.py create mode 100644 src/django_ninja_starter/template/src/apps/webhooks/tests/test_services.py diff --git a/.env.example b/.env.example index 70645ca..4202642 100644 --- a/.env.example +++ b/.env.example @@ -268,3 +268,11 @@ DJANGO_WEBSOCKET_ALLOWED_ORIGINS= DJANGO_SECURE_SSL_REDIRECT=true DJANGO_SECURE_HSTS_SECONDS=31536000 DJANGO_SECURE_HSTS_PRELOAD=true + +# Outgoing webhooks. Deliveries are sent by `manage.py webhooks_deliver`; schedule +# it (every minute, say). See docs/webhooks.md. +DJANGO_WEBHOOKS_ENABLED=true +# DJANGO_WEBHOOKS_TRANSPORTS=rest,graph,grpc +DJANGO_WEBHOOKS_MAX_ATTEMPTS=6 +DJANGO_WEBHOOKS_BACKOFF_SECONDS=30 +DJANGO_WEBHOOKS_TIMEOUT_SECONDS=10 diff --git a/Makefile b/Makefile index 6ff442d..200dd2e 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ install: # Every optional app turned on, so the checks below see the whole project # rather than whatever this developer happens to have in their `.env`. An app # left off is an app whose models, admin, migrations and protos nobody checked. -ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true +ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true DJANGO_WEBHOOKS_ENABLED=true check: ruff check --no-cache . diff --git a/docs/README.md b/docs/README.md index 11d1e04..cfdd651 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,7 +15,7 @@ themselves — see [keeping these pages honest](#keeping-these-pages-honest). | Social providers | [`oauth_google`](oauth/google.md), [`oauth_apple`](oauth/apple.md), [`oauth_microsoft`](oauth/microsoft.md), [`oauth_github`](oauth/github.md) | | Token modes | [`oauth_sliding`](oauth/sliding.md), [`oauth_session`](oauth/session.md), [`oauth_rotation`](oauth/rotation.md) | | Shared by those | [`auth_core`](auth/core.md), [`oauth_core`](oauth/core.md) | -| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md), [`notes`](notes.md) | +| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md), [`webhooks`](webhooks.md), [`notes`](notes.md) | | Cross-cutting | [The response envelope](responses.md), [Signing in](signing-in.md), [Credentials](credentials.md), [The admin](admin.md) | ## Start here @@ -107,6 +107,7 @@ features a project chooses rather than the plumbing under them. | [`shop`](shop.md) | `DJANGO_SHOP_ENABLED=true` | A catalogue whose categories declare what their products are, several sellers per product, timed campaigns, search and merchandising lists, reviews and likes, a basket per account, and an order cycle that reserves stock and issues an invoice | | [`wallet`](wallet.md) | `DJANGO_WALLET_ENABLED=true` | A wallet per account with the balance derived from its movements rather than stored, payment methods an administrator configures rather than code declares, fees and taxes priced by the same function that quotes them, crypto with its chains, currency conversion at a published rate, and deposits that stay requests until an operator applies them | | [`club`](club.md) | `DJANGO_CLUB_ENABLED=true` | Clubs with a levelled ladder, an account in one club at a time, XP derived from an immutable award ledger rather than stored, and missions that complete themselves from events the other apps emit -- including events an app of your own registers, which is what lets a mission be built out of code this starter has never seen | +| [`webhooks`](webhooks.md) | `DJANGO_WEBHOOKS_ENABLED=true` | Outgoing webhooks: https endpoints per account with their own secret and event types, HMAC-SHA256-signed deliveries retried with exponential backoff by `manage.py webhooks_deliver`, every attempt recorded, and private, loopback and link-local targets refused at send time | | [`notes`](notes.md) | `manage.py startapi` | Not shipped installed: the worked example of a feature app, one model served at two API versions, built into the example project | All five ship **off** in a generated project, which is why a fresh `/api/docs` diff --git a/docs/webhooks.md b/docs/webhooks.md new file mode 100644 index 0000000..ca992f8 --- /dev/null +++ b/docs/webhooks.md @@ -0,0 +1,114 @@ +# Webhooks + +`DJANGO_WEBHOOKS_ENABLED=true` installs outgoing webhooks: an account registers +https endpoints, each with the event types it wants and a secret of its own, and +the project POSTs each matching event to it -- signed, retried and recorded. + +## Sending an event + +Code with something to say queues it; nothing is sent inside the request: + +```python +from apps.webhooks.services import emit + +emit(order.customer, "shop.order.paid", {"order": str(order.id)}) +``` + +`manage.py webhooks_deliver` sends whatever is due. Schedule it (every minute +from cron or a systemd timer is plenty). A delivery that fails is retried after +`DJANGO_WEBHOOKS_BACKOFF_SECONDS`, then twice that, four times that, and so on, +until `DJANGO_WEBHOOKS_MAX_ATTEMPTS` is reached and it is marked `failed`. Every +try is kept as a `DeliveryAttempt`, readable at +`GET /api/v1/webhooks/{id}/deliveries`. + +## Verifying a delivery + +Each request carries `X-Webhook-Event` and +`X-Webhook-Signature: t=,v1=`, where `v1` is +HMAC-SHA256 with the endpoint's secret over `"." + raw body`. Recompute it, +compare in constant time, and reject a `t` that is too old. + +## SSRF + +Only `https` URLs are accepted, and the host's every resolved address must be +public: private, loopback, link-local and reserved ranges are refused when the +endpoint is registered **and again before each send**. Redirects are not followed. + +## Routes + + +| Method | Path | Auth | Purpose | +| --- | --- | --- | --- | +| `GET` | `/api/v1/webhooks` | Bearer | List this account's webhook endpoints | +| `POST` | `/api/v1/webhooks` | Bearer | Register a webhook endpoint | +| `DELETE` | `/api/v1/webhooks/{endpoint_id}` | Bearer | Delete a webhook endpoint | +| `GET` | `/api/v1/webhooks/{endpoint_id}/deliveries` | Bearer | Recent deliveries to an endpoint, with every attempt | +| `POST` | `/api/v1/webhooks/{endpoint_id}/rotate-secret` | Bearer | Replace the signing secret | + + +## Settings + + +| Environment variable | Required | Purpose | +| --- | --- | --- | +| `DJANGO_WEBHOOKS_ENABLED` | **Yes** | whether this deployment carries outgoing webhooks at all. | +| `DJANGO_WEBHOOKS_MAX_ATTEMPTS` | Optional | how many times a delivery is tried before it is marked failed. 1 or more. | +| `DJANGO_WEBHOOKS_BACKOFF_SECONDS` | Optional | the wait after the first failure; it doubles after each one. 1 or more. | +| `DJANGO_WEBHOOKS_TIMEOUT_SECONDS` | Optional | how long one delivery waits for the receiver to answer. 1 or more. | + + +## Models + + +#### `Delivery` + +One event bound for one endpoint, retried until it lands or gives up. + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | UUID | primary key, not editable | +| `endpoint` | ForeignKey | → `webhooks.Endpoint` | +| `event` | Char | | +| `payload` | JSON | | +| `status` | Char | | +| `attempts` | PositiveInteger | | +| `next_attempt_at` | DateTime | nullable | +| `created_at` | DateTime | not editable | + +#### `DeliveryAttempt` + +What happened the one time a delivery was tried. A record, never edited. + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | BigAuto | primary key | +| `delivery` | ForeignKey | → `webhooks.Delivery` | +| `number` | PositiveInteger | | +| `status_code` | PositiveInteger | nullable | +| `error` | Text | | +| `duration_ms` | PositiveInteger | | +| `created_at` | DateTime | not editable | + +#### `Endpoint` + +An https URL an account wants told about some of its events. + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | UUID | primary key, not editable | +| `owner` | ForeignKey | → `accounts.User` | +| `url` | Char | | +| `events` | JSON | | +| `secret` | Char | | +| `is_active` | Boolean | | +| `created_at` | DateTime | not editable | + + +## Admin + + +| Model | Editable | Actions | Columns | +| --- | --- | --- | --- | +| `Delivery` | Yes | — | `event`, `endpoint`, `status`, `attempts`, `next_attempt_at`, `created_at` | +| `Endpoint` | Yes | — | `url`, `owner`, `is_active`, `created_at` | + diff --git a/examples/env.example b/examples/env.example index 3683ba7..e291d17 100644 --- a/examples/env.example +++ b/examples/env.example @@ -347,3 +347,11 @@ DJANGO_API_THROTTLE_AUTH= DJANGO_API_THROTTLE_LOGIN= DJANGO_API_THROTTLE_UPLOAD= DJANGO_NOTIFICATIONS_SOCKET_COMMANDS_PER_MINUTE=0 + +# Outgoing webhooks. Deliveries are sent by `manage.py webhooks_deliver`; schedule +# it (every minute, say). See docs/webhooks.md. +DJANGO_WEBHOOKS_ENABLED=true +# DJANGO_WEBHOOKS_TRANSPORTS=rest,graph,grpc +DJANGO_WEBHOOKS_MAX_ATTEMPTS=6 +DJANGO_WEBHOOKS_BACKOFF_SECONDS=30 +DJANGO_WEBHOOKS_TIMEOUT_SECONDS=10 diff --git a/src/apps/webhooks/__init__.py b/src/apps/webhooks/__init__.py new file mode 100644 index 0000000..563a672 --- /dev/null +++ b/src/apps/webhooks/__init__.py @@ -0,0 +1 @@ +"""Outgoing webhooks: signed, retried, recorded deliveries to endpoints an account registers.""" diff --git a/src/apps/webhooks/admin.py b/src/apps/webhooks/admin.py new file mode 100644 index 0000000..6256004 --- /dev/null +++ b/src/apps/webhooks/admin.py @@ -0,0 +1,42 @@ +"""The admin: endpoints, and the delivery record (read-only, because it is a record).""" + +from typing import Any + +from django.contrib import admin +from django.http import HttpRequest + +from apps.webhooks.models import Delivery, DeliveryAttempt, Endpoint + +try: # pragma: no cover - exercised by whichever branch the project installs + from unfold.admin import ModelAdmin, TabularInline +except ImportError: # pragma: no cover - only in a project without Unfold + from django.contrib.admin import ModelAdmin, TabularInline + + +@admin.register(Endpoint) +class EndpointAdmin(ModelAdmin): + list_display = ("url", "owner", "is_active", "created_at") + list_filter = ("is_active",) + search_fields = ("url",) + exclude = ("secret",) + + +class AttemptInline(TabularInline): + model = DeliveryAttempt + extra = 0 + can_delete = False + readonly_fields = ("number", "status_code", "error", "duration_ms", "created_at") + + def has_add_permission(self, request: HttpRequest, obj: Any = None) -> bool: + return False + + +@admin.register(Delivery) +class DeliveryAdmin(ModelAdmin): + list_display = ("event", "endpoint", "status", "attempts", "next_attempt_at", "created_at") + list_filter = ("status",) + readonly_fields = ("endpoint", "event", "payload", "status", "attempts", "next_attempt_at") + inlines = (AttemptInline,) + + def has_add_permission(self, request: HttpRequest) -> bool: + return False diff --git a/src/apps/webhooks/apps.py b/src/apps/webhooks/apps.py new file mode 100644 index 0000000..632d7b4 --- /dev/null +++ b/src/apps/webhooks/apps.py @@ -0,0 +1,41 @@ +from django.apps import AppConfig + +from infrastructure.common.appsettings import AppSettings, Requirement + + +class WebhooksConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.webhooks" + label = "webhooks" + verbose_name = "Webhooks" + + settings_spec = AppSettings( + title="Webhooks", + summary="Signed outgoing webhooks, retried with backoff by `manage.py webhooks_deliver`.", + requirements=( + Requirement( + "WEBHOOKS_ENABLED", + env="DJANGO_WEBHOOKS_ENABLED", + purpose="whether this deployment carries outgoing webhooks at all", + required=True, + ), + Requirement( + "WEBHOOKS_MAX_ATTEMPTS", + env="DJANGO_WEBHOOKS_MAX_ATTEMPTS", + purpose="how many times a delivery is tried before it is marked failed", + minimum=1, + ), + Requirement( + "WEBHOOKS_BACKOFF_SECONDS", + env="DJANGO_WEBHOOKS_BACKOFF_SECONDS", + purpose="the wait after the first failure; it doubles after each one", + minimum=1, + ), + Requirement( + "WEBHOOKS_TIMEOUT_SECONDS", + env="DJANGO_WEBHOOKS_TIMEOUT_SECONDS", + purpose="how long one delivery waits for the receiver to answer", + minimum=1, + ), + ), + ) diff --git a/src/apps/webhooks/graph/__init__.py b/src/apps/webhooks/graph/__init__.py new file mode 100644 index 0000000..e695ffd --- /dev/null +++ b/src/apps/webhooks/graph/__init__.py @@ -0,0 +1,5 @@ +"""The GraphQL transport for the webhooks app.""" + +from apps.webhooks.graph.schema import Mutation, Query + +__all__ = ["Mutation", "Query"] diff --git a/src/apps/webhooks/graph/schema.py b/src/apps/webhooks/graph/schema.py new file mode 100644 index 0000000..29dbbf6 --- /dev/null +++ b/src/apps/webhooks/graph/schema.py @@ -0,0 +1,90 @@ +"""The webhooks app's GraphQL fields, mirroring the REST endpoints one for one.""" + +from typing import Any + +import strawberry +from strawberry.types import Info + +from apps.webhooks import services +from infrastructure.common.graph.errors import require_caller, resolver +from infrastructure.common.identity import caller + + +@strawberry.type +class WebhookEndpointType: + id: str + url: str + events: list[str] + is_active: bool + created_at: str + secret: str + + +@strawberry.type +class WebhookAttemptType: + number: int + status_code: int + error: str + duration_ms: int + created_at: str + + +@strawberry.type +class WebhookDeliveryType: + id: str + event: str + status: str + attempts: int + next_attempt_at: str + created_at: str + attempt_log: list[WebhookAttemptType] + + +def _caller(info: Info[Any, Any]) -> Any: + return require_caller(caller(info.context.request)) + + +def _endpoint(row: dict[str, Any]) -> WebhookEndpointType: + return WebhookEndpointType(**row) + + +def _delivery(row: dict[str, Any]) -> WebhookDeliveryType: + attempts = [WebhookAttemptType(**attempt) for attempt in row["attempt_log"]] + return WebhookDeliveryType(**{**row, "attempt_log": attempts}) + + +@strawberry.type +class Query: + @strawberry.field(description="This account's webhook endpoints.") + @resolver + def webhook_endpoints(self, info: Info[Any, Any]) -> list[WebhookEndpointType]: + return [_endpoint(row) for row in services.list_endpoints(_caller(info))] + + @strawberry.field(description="Recent deliveries to one endpoint, with every attempt.") + @resolver + def webhook_deliveries( + self, info: Info[Any, Any], endpoint_id: str, limit: int = 50 + ) -> list[WebhookDeliveryType]: + rows = services.list_deliveries(_caller(info), endpoint_id, limit) + return [_delivery(row) for row in rows] + + +@strawberry.type +class Mutation: + @strawberry.mutation(description="Register an endpoint. The answer carries its secret.") + @resolver + def create_webhook_endpoint( + self, info: Info[Any, Any], url: str, events: list[str] + ) -> WebhookEndpointType: + return _endpoint(services.create_endpoint(_caller(info), url, events)) + + @strawberry.mutation(description="Delete an endpoint and its delivery record.") + @resolver + def delete_webhook_endpoint(self, info: Info[Any, Any], endpoint_id: str) -> bool: + services.delete_endpoint(_caller(info), endpoint_id) + return True + + @strawberry.mutation(description="Replace an endpoint's signing secret.") + @resolver + def rotate_webhook_secret(self, info: Info[Any, Any], endpoint_id: str) -> WebhookEndpointType: + return _endpoint(services.rotate_secret(_caller(info), endpoint_id)) diff --git a/src/apps/webhooks/grpc/__init__.py b/src/apps/webhooks/grpc/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/webhooks/grpc/serializers.py b/src/apps/webhooks/grpc/serializers.py new file mode 100644 index 0000000..1d76803 --- /dev/null +++ b/src/apps/webhooks/grpc/serializers.py @@ -0,0 +1,30 @@ +"""The nested messages the webhook service answers with.""" + +from rest_framework import serializers + + +class WebhookEndpoint(serializers.Serializer[dict[str, object]]): + id = serializers.CharField() + url = serializers.CharField() + events = serializers.ListField(child=serializers.CharField()) + is_active = serializers.BooleanField() + created_at = serializers.CharField() + secret = serializers.CharField() + + +class WebhookAttempt(serializers.Serializer[dict[str, object]]): + number = serializers.IntegerField() + status_code = serializers.IntegerField() + error = serializers.CharField() + duration_ms = serializers.IntegerField() + created_at = serializers.CharField() + + +class WebhookDelivery(serializers.Serializer[dict[str, object]]): + id = serializers.CharField() + event = serializers.CharField() + status = serializers.CharField() + attempts = serializers.IntegerField() + next_attempt_at = serializers.CharField() + created_at = serializers.CharField() + attempt_log = WebhookAttempt(many=True) diff --git a/src/apps/webhooks/grpc/services.py b/src/apps/webhooks/grpc/services.py new file mode 100644 index 0000000..8ff1741 --- /dev/null +++ b/src/apps/webhooks/grpc/services.py @@ -0,0 +1,101 @@ +"""Managing webhook endpoints over gRPC, mirroring the REST endpoints one for one.""" + +from typing import Any + +from asgiref.sync import sync_to_async +from django_socio_grpc import generics +from django_socio_grpc.decorators import grpc_action + +from apps.webhooks import services +from apps.webhooks.grpc.serializers import WebhookDelivery, WebhookEndpoint +from infrastructure.common.grpc.errors import action, require_caller +from infrastructure.common.identity import grpc_caller + + +def _pb2() -> Any: + from apps.webhooks.grpc import webhooks_pb2 + + return webhooks_pb2 + + +def _endpoint(row: dict[str, Any]) -> Any: + return _pb2().WebhookEndpoint(**row) + + +def _delivery(row: dict[str, Any]) -> Any: + pb2 = _pb2() + attempts = [pb2.WebhookAttempt(**attempt) for attempt in row["attempt_log"]] + return pb2.WebhookDelivery(**{**row, "attempt_log": attempts}) + + +class WebhookService(generics.GenericService): + """The same calls the REST router publishes under `/webhooks`.""" + + @grpc_action( + request=[], + response=[{"name": "endpoints", "cardinality": "repeated", "type": WebhookEndpoint}], + response_name="EndpointList", + ) + @action + async def List(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + rows = await sync_to_async(services.list_endpoints)(user) + return _pb2().EndpointList(endpoints=[_endpoint(row) for row in rows]) + + @grpc_action( + request=[ + {"name": "url", "type": "string"}, + {"name": "events", "cardinality": "repeated", "type": "string"}, + ], + request_name="CreateRequest", + response=WebhookEndpoint, + response_name="WebhookEndpoint", + ) + @action + async def Create(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + row = await sync_to_async(services.create_endpoint)(user, request.url, list(request.events)) + return _endpoint(row) + + @grpc_action( + request=[{"name": "endpoint_id", "type": "string"}], + request_name="DeleteRequest", + response=[{"name": "deleted", "type": "bool"}], + response_name="DeleteResult", + ) + @action + async def Delete(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + await sync_to_async(services.delete_endpoint)(user, request.endpoint_id) + return _pb2().DeleteResult(deleted=True) + + @grpc_action( + request=[{"name": "endpoint_id", "type": "string"}], + request_name="RotateSecretRequest", + response=WebhookEndpoint, + response_name="WebhookEndpoint", + ) + @action + async def RotateSecret(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + return _endpoint(await sync_to_async(services.rotate_secret)(user, request.endpoint_id)) + + @grpc_action( + request=[ + {"name": "endpoint_id", "type": "string"}, + {"name": "limit", "type": "int32"}, + ], + request_name="ListDeliveriesRequest", + response=[{"name": "deliveries", "cardinality": "repeated", "type": WebhookDelivery}], + response_name="DeliveryList", + ) + @action + async def ListDeliveries(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + rows = await sync_to_async(services.list_deliveries)( + user, request.endpoint_id, request.limit or 50 + ) + return _pb2().DeliveryList(deliveries=[_delivery(row) for row in rows]) + + +GRPC_SERVICES = [WebhookService] diff --git a/src/apps/webhooks/grpc/webhooks.proto b/src/apps/webhooks/grpc/webhooks.proto new file mode 100644 index 0000000..fe8efd5 --- /dev/null +++ b/src/apps/webhooks/grpc/webhooks.proto @@ -0,0 +1,71 @@ +syntax = "proto3"; + +package config.webhooks; + +import "google/protobuf/empty.proto"; + +service WebhookController { + rpc Create(CreateRequest) returns (WebhookEndpoint) {} + rpc Delete(DeleteRequest) returns (DeleteResult) {} + rpc List(google.protobuf.Empty) returns (EndpointList) {} + rpc ListDeliveries(ListDeliveriesRequest) returns (DeliveryList) {} + rpc RotateSecret(RotateSecretRequest) returns (WebhookEndpoint) {} +} + +message CreateRequest { + string url = 1; + repeated string events = 2; +} + +message DeleteRequest { + string endpoint_id = 1; +} + +message DeleteResult { + bool deleted = 1; +} + +message DeliveryList { + repeated WebhookDelivery deliveries = 1; +} + +message EndpointList { + repeated WebhookEndpoint endpoints = 1; +} + +message ListDeliveriesRequest { + string endpoint_id = 1; + int32 limit = 2; +} + +message RotateSecretRequest { + string endpoint_id = 1; +} + +message WebhookAttempt { + int32 number = 1; + int32 status_code = 2; + string error = 3; + int32 duration_ms = 4; + string created_at = 5; +} + +message WebhookDelivery { + string id = 1; + string event = 2; + string status = 3; + int32 attempts = 4; + string next_attempt_at = 5; + string created_at = 6; + repeated WebhookAttempt attempt_log = 7; +} + +message WebhookEndpoint { + string id = 1; + string url = 2; + repeated string events = 3; + bool is_active = 4; + string created_at = 5; + string secret = 6; +} + diff --git a/src/apps/webhooks/grpc/webhooks_pb2.py b/src/apps/webhooks/grpc/webhooks_pb2.py new file mode 100644 index 0000000..ea9cb71 --- /dev/null +++ b/src/apps/webhooks/grpc/webhooks_pb2.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: apps/webhooks/grpc/webhooks.proto +# Protobuf Python Version: 7.35.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 7, + 35, + 1, + '', + 'apps/webhooks/grpc/webhooks.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!apps/webhooks/grpc/webhooks.proto\x12\x0f\x63onfig.webhooks\x1a\x1bgoogle/protobuf/empty.proto\",\n\rCreateRequest\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\x0e\n\x06\x65vents\x18\x02 \x03(\t\"$\n\rDeleteRequest\x12\x13\n\x0b\x65ndpoint_id\x18\x01 \x01(\t\"\x1f\n\x0c\x44\x65leteResult\x12\x0f\n\x07\x64\x65leted\x18\x01 \x01(\x08\"D\n\x0c\x44\x65liveryList\x12\x34\n\ndeliveries\x18\x01 \x03(\x0b\x32 .config.webhooks.WebhookDelivery\"C\n\x0c\x45ndpointList\x12\x33\n\tendpoints\x18\x01 \x03(\x0b\x32 .config.webhooks.WebhookEndpoint\";\n\x15ListDeliveriesRequest\x12\x13\n\x0b\x65ndpoint_id\x18\x01 \x01(\t\x12\r\n\x05limit\x18\x02 \x01(\x05\"*\n\x13RotateSecretRequest\x12\x13\n\x0b\x65ndpoint_id\x18\x01 \x01(\t\"m\n\x0eWebhookAttempt\x12\x0e\n\x06number\x18\x01 \x01(\x05\x12\x13\n\x0bstatus_code\x18\x02 \x01(\x05\x12\r\n\x05\x65rror\x18\x03 \x01(\t\x12\x13\n\x0b\x64uration_ms\x18\x04 \x01(\x05\x12\x12\n\ncreated_at\x18\x05 \x01(\t\"\xb1\x01\n\x0fWebhookDelivery\x12\n\n\x02id\x18\x01 \x01(\t\x12\r\n\x05\x65vent\x18\x02 \x01(\t\x12\x0e\n\x06status\x18\x03 \x01(\t\x12\x10\n\x08\x61ttempts\x18\x04 \x01(\x05\x12\x17\n\x0fnext_attempt_at\x18\x05 \x01(\t\x12\x12\n\ncreated_at\x18\x06 \x01(\t\x12\x34\n\x0b\x61ttempt_log\x18\x07 \x03(\x0b\x32\x1f.config.webhooks.WebhookAttempt\"q\n\x0fWebhookEndpoint\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0b\n\x03url\x18\x02 \x01(\t\x12\x0e\n\x06\x65vents\x18\x03 \x03(\t\x12\x11\n\tis_active\x18\x04 \x01(\x08\x12\x12\n\ncreated_at\x18\x05 \x01(\t\x12\x0e\n\x06secret\x18\x06 \x01(\t2\xa2\x03\n\x11WebhookController\x12L\n\x06\x43reate\x12\x1e.config.webhooks.CreateRequest\x1a .config.webhooks.WebhookEndpoint\"\x00\x12I\n\x06\x44\x65lete\x12\x1e.config.webhooks.DeleteRequest\x1a\x1d.config.webhooks.DeleteResult\"\x00\x12?\n\x04List\x12\x16.google.protobuf.Empty\x1a\x1d.config.webhooks.EndpointList\"\x00\x12Y\n\x0eListDeliveries\x12&.config.webhooks.ListDeliveriesRequest\x1a\x1d.config.webhooks.DeliveryList\"\x00\x12X\n\x0cRotateSecret\x12$.config.webhooks.RotateSecretRequest\x1a .config.webhooks.WebhookEndpoint\"\x00\x62\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.webhooks.grpc.webhooks_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR._loaded_options = None + _globals['_CREATEREQUEST']._serialized_start=83 + _globals['_CREATEREQUEST']._serialized_end=127 + _globals['_DELETEREQUEST']._serialized_start=129 + _globals['_DELETEREQUEST']._serialized_end=165 + _globals['_DELETERESULT']._serialized_start=167 + _globals['_DELETERESULT']._serialized_end=198 + _globals['_DELIVERYLIST']._serialized_start=200 + _globals['_DELIVERYLIST']._serialized_end=268 + _globals['_ENDPOINTLIST']._serialized_start=270 + _globals['_ENDPOINTLIST']._serialized_end=337 + _globals['_LISTDELIVERIESREQUEST']._serialized_start=339 + _globals['_LISTDELIVERIESREQUEST']._serialized_end=398 + _globals['_ROTATESECRETREQUEST']._serialized_start=400 + _globals['_ROTATESECRETREQUEST']._serialized_end=442 + _globals['_WEBHOOKATTEMPT']._serialized_start=444 + _globals['_WEBHOOKATTEMPT']._serialized_end=553 + _globals['_WEBHOOKDELIVERY']._serialized_start=556 + _globals['_WEBHOOKDELIVERY']._serialized_end=733 + _globals['_WEBHOOKENDPOINT']._serialized_start=735 + _globals['_WEBHOOKENDPOINT']._serialized_end=848 + _globals['_WEBHOOKCONTROLLER']._serialized_start=851 + _globals['_WEBHOOKCONTROLLER']._serialized_end=1269 +# @@protoc_insertion_point(module_scope) diff --git a/src/apps/webhooks/grpc/webhooks_pb2.pyi b/src/apps/webhooks/grpc/webhooks_pb2.pyi new file mode 100644 index 0000000..4ca3c4f --- /dev/null +++ b/src/apps/webhooks/grpc/webhooks_pb2.pyi @@ -0,0 +1,265 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from collections import abc as _abc +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers +import builtins as _builtins +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import TypeAlias as _TypeAlias, Never as _Never +else: + from typing_extensions import TypeAlias as _TypeAlias, Never as _Never + +DESCRIPTOR: _descriptor.FileDescriptor + +@_typing.final +class CreateRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + URL_FIELD_NUMBER: _builtins.int + EVENTS_FIELD_NUMBER: _builtins.int + url: _builtins.str + @_builtins.property + def events(self) -> _containers.RepeatedScalarFieldContainer[_builtins.str]: ... + def __init__( + self, + *, + url: _builtins.str = ..., + events: _abc.Iterable[_builtins.str] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["events", b"events", "url", b"url"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___CreateRequest: _TypeAlias = CreateRequest # noqa: Y015 + +@_typing.final +class DeleteRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINT_ID_FIELD_NUMBER: _builtins.int + endpoint_id: _builtins.str + def __init__( + self, + *, + endpoint_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoint_id", b"endpoint_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteRequest: _TypeAlias = DeleteRequest # noqa: Y015 + +@_typing.final +class DeleteResult(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + DELETED_FIELD_NUMBER: _builtins.int + deleted: _builtins.bool + def __init__( + self, + *, + deleted: _builtins.bool = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["deleted", b"deleted"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteResult: _TypeAlias = DeleteResult # noqa: Y015 + +@_typing.final +class DeliveryList(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + DELIVERIES_FIELD_NUMBER: _builtins.int + @_builtins.property + def deliveries(self) -> _containers.RepeatedCompositeFieldContainer[Global___WebhookDelivery]: ... + def __init__( + self, + *, + deliveries: _abc.Iterable[Global___WebhookDelivery] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["deliveries", b"deliveries"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeliveryList: _TypeAlias = DeliveryList # noqa: Y015 + +@_typing.final +class EndpointList(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINTS_FIELD_NUMBER: _builtins.int + @_builtins.property + def endpoints(self) -> _containers.RepeatedCompositeFieldContainer[Global___WebhookEndpoint]: ... + def __init__( + self, + *, + endpoints: _abc.Iterable[Global___WebhookEndpoint] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoints", b"endpoints"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___EndpointList: _TypeAlias = EndpointList # noqa: Y015 + +@_typing.final +class ListDeliveriesRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINT_ID_FIELD_NUMBER: _builtins.int + LIMIT_FIELD_NUMBER: _builtins.int + endpoint_id: _builtins.str + limit: _builtins.int + def __init__( + self, + *, + endpoint_id: _builtins.str = ..., + limit: _builtins.int = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoint_id", b"endpoint_id", "limit", b"limit"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___ListDeliveriesRequest: _TypeAlias = ListDeliveriesRequest # noqa: Y015 + +@_typing.final +class RotateSecretRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINT_ID_FIELD_NUMBER: _builtins.int + endpoint_id: _builtins.str + def __init__( + self, + *, + endpoint_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoint_id", b"endpoint_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___RotateSecretRequest: _TypeAlias = RotateSecretRequest # noqa: Y015 + +@_typing.final +class WebhookAttempt(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + NUMBER_FIELD_NUMBER: _builtins.int + STATUS_CODE_FIELD_NUMBER: _builtins.int + ERROR_FIELD_NUMBER: _builtins.int + DURATION_MS_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + number: _builtins.int + status_code: _builtins.int + error: _builtins.str + duration_ms: _builtins.int + created_at: _builtins.str + def __init__( + self, + *, + number: _builtins.int = ..., + status_code: _builtins.int = ..., + error: _builtins.str = ..., + duration_ms: _builtins.int = ..., + created_at: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["created_at", b"created_at", "duration_ms", b"duration_ms", "error", b"error", "number", b"number", "status_code", b"status_code"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___WebhookAttempt: _TypeAlias = WebhookAttempt # noqa: Y015 + +@_typing.final +class WebhookDelivery(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + EVENT_FIELD_NUMBER: _builtins.int + STATUS_FIELD_NUMBER: _builtins.int + ATTEMPTS_FIELD_NUMBER: _builtins.int + NEXT_ATTEMPT_AT_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + ATTEMPT_LOG_FIELD_NUMBER: _builtins.int + id: _builtins.str + event: _builtins.str + status: _builtins.str + attempts: _builtins.int + next_attempt_at: _builtins.str + created_at: _builtins.str + @_builtins.property + def attempt_log(self) -> _containers.RepeatedCompositeFieldContainer[Global___WebhookAttempt]: ... + def __init__( + self, + *, + id: _builtins.str = ..., + event: _builtins.str = ..., + status: _builtins.str = ..., + attempts: _builtins.int = ..., + next_attempt_at: _builtins.str = ..., + created_at: _builtins.str = ..., + attempt_log: _abc.Iterable[Global___WebhookAttempt] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["attempt_log", b"attempt_log", "attempts", b"attempts", "created_at", b"created_at", "event", b"event", "id", b"id", "next_attempt_at", b"next_attempt_at", "status", b"status"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___WebhookDelivery: _TypeAlias = WebhookDelivery # noqa: Y015 + +@_typing.final +class WebhookEndpoint(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + URL_FIELD_NUMBER: _builtins.int + EVENTS_FIELD_NUMBER: _builtins.int + IS_ACTIVE_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + SECRET_FIELD_NUMBER: _builtins.int + id: _builtins.str + url: _builtins.str + is_active: _builtins.bool + created_at: _builtins.str + secret: _builtins.str + @_builtins.property + def events(self) -> _containers.RepeatedScalarFieldContainer[_builtins.str]: ... + def __init__( + self, + *, + id: _builtins.str = ..., + url: _builtins.str = ..., + events: _abc.Iterable[_builtins.str] | None = ..., + is_active: _builtins.bool = ..., + created_at: _builtins.str = ..., + secret: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["created_at", b"created_at", "events", b"events", "id", b"id", "is_active", b"is_active", "secret", b"secret", "url", b"url"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___WebhookEndpoint: _TypeAlias = WebhookEndpoint # noqa: Y015 diff --git a/src/apps/webhooks/grpc/webhooks_pb2_grpc.py b/src/apps/webhooks/grpc/webhooks_pb2_grpc.py new file mode 100644 index 0000000..2a9d193 --- /dev/null +++ b/src/apps/webhooks/grpc/webhooks_pb2_grpc.py @@ -0,0 +1,270 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc +import warnings + +from apps.webhooks.grpc import webhooks_pb2 as apps_dot_webhooks_dot_grpc_dot_webhooks__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + +GRPC_GENERATED_VERSION = '1.84.0' +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) +except ImportError: + _version_not_supported = True + +if _version_not_supported: + raise RuntimeError( + f'The grpc package installed is at version {GRPC_VERSION},' + + ' but the generated code in apps/webhooks/grpc/webhooks_pb2_grpc.py depends on' + + f' grpcio>={GRPC_GENERATED_VERSION}.' + + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' + + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' + ) + + +class WebhookControllerStub: + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Create = channel.unary_unary( + '/config.webhooks.WebhookController/Create', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.CreateRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + _registered_method=True) + self.Delete = channel.unary_unary( + '/config.webhooks.WebhookController/Delete', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteResult.FromString, + _registered_method=True) + self.List = channel.unary_unary( + '/config.webhooks.WebhookController/List', + request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.EndpointList.FromString, + _registered_method=True) + self.ListDeliveries = channel.unary_unary( + '/config.webhooks.WebhookController/ListDeliveries', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.ListDeliveriesRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeliveryList.FromString, + _registered_method=True) + self.RotateSecret = channel.unary_unary( + '/config.webhooks.WebhookController/RotateSecret', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.RotateSecretRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + _registered_method=True) + + +class WebhookControllerServicer: + """Missing associated documentation comment in .proto file.""" + + def Create(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Delete(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def List(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ListDeliveries(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def RotateSecret(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_WebhookControllerServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Create': grpc.unary_unary_rpc_method_handler( + servicer.Create, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.CreateRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.SerializeToString, + ), + 'Delete': grpc.unary_unary_rpc_method_handler( + servicer.Delete, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteResult.SerializeToString, + ), + 'List': grpc.unary_unary_rpc_method_handler( + servicer.List, + request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.EndpointList.SerializeToString, + ), + 'ListDeliveries': grpc.unary_unary_rpc_method_handler( + servicer.ListDeliveries, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.ListDeliveriesRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeliveryList.SerializeToString, + ), + 'RotateSecret': grpc.unary_unary_rpc_method_handler( + servicer.RotateSecret, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.RotateSecretRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'config.webhooks.WebhookController', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + server.add_registered_method_handlers('config.webhooks.WebhookController', rpc_method_handlers) + + + # This class is part of an EXPERIMENTAL API. +class WebhookController: + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def Create(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/Create', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.CreateRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Delete(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/Delete', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteResult.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def List(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/List', + google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.EndpointList.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def ListDeliveries(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/ListDeliveries', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.ListDeliveriesRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeliveryList.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def RotateSecret(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/RotateSecret', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.RotateSecretRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) diff --git a/src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi b/src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi new file mode 100644 index 0000000..bccc80d --- /dev/null +++ b/src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi @@ -0,0 +1,86 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from apps.webhooks.grpc import webhooks_pb2 as _webhooks_pb2 +from collections import abc as _abc +from google.protobuf import empty_pb2 as _empty_pb2 +from grpc import aio as _aio +import abc as _abc_1 +import grpc as _grpc +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import Self as _Self +else: + from typing_extensions import Self as _Self + +_T = _typing.TypeVar("_T") + +class _MaybeAsyncIterator(_abc.AsyncIterator[_T], _abc.Iterator[_T], metaclass=_abc_1.ABCMeta): ... + +class _ServicerContext(_grpc.ServicerContext, _aio.ServicerContext): # type: ignore[misc, type-arg] + ... + +GRPC_GENERATED_VERSION: str +GRPC_VERSION: str + +class WebhookControllerStub: + @_typing.overload + def __new__(cls, channel: _grpc.Channel) -> _Self: ... + @_typing.overload + def __new__(cls, channel: _aio.Channel) -> WebhookControllerAsyncStub: ... + Create: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.CreateRequest, _webhooks_pb2.WebhookEndpoint] + Delete: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.DeleteRequest, _webhooks_pb2.DeleteResult] + List: _grpc.UnaryUnaryMultiCallable[_empty_pb2.Empty, _webhooks_pb2.EndpointList] + ListDeliveries: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.ListDeliveriesRequest, _webhooks_pb2.DeliveryList] + RotateSecret: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.RotateSecretRequest, _webhooks_pb2.WebhookEndpoint] + +@_typing.type_check_only +class WebhookControllerAsyncStub(WebhookControllerStub): + def __init__(self, channel: _aio.Channel) -> None: ... + Create: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.CreateRequest, _webhooks_pb2.WebhookEndpoint] # type: ignore[assignment] + Delete: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.DeleteRequest, _webhooks_pb2.DeleteResult] # type: ignore[assignment] + List: _aio.UnaryUnaryMultiCallable[_empty_pb2.Empty, _webhooks_pb2.EndpointList] # type: ignore[assignment] + ListDeliveries: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.ListDeliveriesRequest, _webhooks_pb2.DeliveryList] # type: ignore[assignment] + RotateSecret: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.RotateSecretRequest, _webhooks_pb2.WebhookEndpoint] # type: ignore[assignment] + +class WebhookControllerServicer(metaclass=_abc_1.ABCMeta): + @_abc_1.abstractmethod + def Create( + self, + request: _webhooks_pb2.CreateRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.WebhookEndpoint, _abc.Awaitable[_webhooks_pb2.WebhookEndpoint]]: ... + + @_abc_1.abstractmethod + def Delete( + self, + request: _webhooks_pb2.DeleteRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.DeleteResult, _abc.Awaitable[_webhooks_pb2.DeleteResult]]: ... + + @_abc_1.abstractmethod + def List( + self, + request: _empty_pb2.Empty, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.EndpointList, _abc.Awaitable[_webhooks_pb2.EndpointList]]: ... + + @_abc_1.abstractmethod + def ListDeliveries( + self, + request: _webhooks_pb2.ListDeliveriesRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.DeliveryList, _abc.Awaitable[_webhooks_pb2.DeliveryList]]: ... + + @_abc_1.abstractmethod + def RotateSecret( + self, + request: _webhooks_pb2.RotateSecretRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.WebhookEndpoint, _abc.Awaitable[_webhooks_pb2.WebhookEndpoint]]: ... + +def add_WebhookControllerServicer_to_server(servicer: WebhookControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ... diff --git a/src/apps/webhooks/management/__init__.py b/src/apps/webhooks/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/webhooks/management/commands/__init__.py b/src/apps/webhooks/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/webhooks/management/commands/webhooks_deliver.py b/src/apps/webhooks/management/commands/webhooks_deliver.py new file mode 100644 index 0000000..f9f6438 --- /dev/null +++ b/src/apps/webhooks/management/commands/webhooks_deliver.py @@ -0,0 +1,18 @@ +"""Send every webhook delivery that is due. Schedule it, e.g. every minute from cron.""" + +from typing import Any + +from django.core.management.base import BaseCommand, CommandParser + +from apps.webhooks.services import deliver_due + + +class Command(BaseCommand): + help = "Attempt every pending webhook delivery whose next attempt is due." + + def add_arguments(self, parser: CommandParser) -> None: + parser.add_argument("--limit", type=int, default=100) + + def handle(self, *args: Any, **options: Any) -> None: + count = deliver_due(limit=options["limit"]) + self.stdout.write(f"Attempted {count} webhook deliveries.") diff --git a/src/apps/webhooks/migrations/0001_initial.py b/src/apps/webhooks/migrations/0001_initial.py new file mode 100644 index 0000000..a9b17cc --- /dev/null +++ b/src/apps/webhooks/migrations/0001_initial.py @@ -0,0 +1,123 @@ +# Generated by Django 6.1.3 on 2026-11-26 14:27 + +import uuid + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="Delivery", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, editable=False, primary_key=True, serialize=False + ), + ), + ("event", models.CharField(max_length=100)), + ("payload", models.JSONField(default=dict)), + ( + "status", + models.CharField( + choices=[ + ("pending", "Pending"), + ("succeeded", "Succeeded"), + ("failed", "Failed"), + ], + default="pending", + max_length=16, + ), + ), + ("attempts", models.PositiveIntegerField(default=0)), + ("next_attempt_at", models.DateTimeField(blank=True, db_index=True, null=True)), + ("created_at", models.DateTimeField(auto_now_add=True)), + ], + options={ + "verbose_name_plural": "deliveries", + "ordering": ("-created_at",), + }, + ), + migrations.CreateModel( + name="DeliveryAttempt", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" + ), + ), + ("number", models.PositiveIntegerField()), + ("status_code", models.PositiveIntegerField(blank=True, null=True)), + ("error", models.TextField(blank=True)), + ("duration_ms", models.PositiveIntegerField(default=0)), + ("created_at", models.DateTimeField(auto_now_add=True)), + ( + "delivery", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="attempt_log", + to="webhooks.delivery", + ), + ), + ], + options={ + "ordering": ("number",), + }, + ), + migrations.CreateModel( + name="Endpoint", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, editable=False, primary_key=True, serialize=False + ), + ), + ("url", models.URLField(max_length=2000)), + ( + "events", + models.JSONField( + default=list, help_text="The event types this endpoint receives." + ), + ), + ( + "secret", + models.CharField( + help_text="The HMAC-SHA256 key deliveries are signed with.", max_length=64 + ), + ), + ("is_active", models.BooleanField(default=True)), + ("created_at", models.DateTimeField(auto_now_add=True)), + ( + "owner", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="webhook_endpoints", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "ordering": ("-created_at",), + }, + ), + migrations.AddField( + model_name="delivery", + name="endpoint", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="deliveries", + to="webhooks.endpoint", + ), + ), + ] diff --git a/src/apps/webhooks/migrations/__init__.py b/src/apps/webhooks/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/webhooks/models.py b/src/apps/webhooks/models.py new file mode 100644 index 0000000..dda6e61 --- /dev/null +++ b/src/apps/webhooks/models.py @@ -0,0 +1,73 @@ +"""Outgoing webhooks: where to send, what was sent, and every try at sending it.""" + +import uuid + +from django.conf import settings +from django.db import models + + +class Endpoint(models.Model): + """An https URL an account wants told about some of its events.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + owner = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="webhook_endpoints" + ) + url = models.URLField(max_length=2000) + events = models.JSONField(default=list, help_text="The event types this endpoint receives.") + secret = models.CharField( + max_length=64, help_text="The HMAC-SHA256 key deliveries are signed with." + ) + is_active = models.BooleanField(default=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("-created_at",) + + def __str__(self) -> str: + return self.url + + +class DeliveryStatus(models.TextChoices): + PENDING = "pending", "Pending" + SUCCEEDED = "succeeded", "Succeeded" + FAILED = "failed", "Failed" + + +class Delivery(models.Model): + """One event bound for one endpoint, retried until it lands or gives up.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + endpoint = models.ForeignKey(Endpoint, on_delete=models.CASCADE, related_name="deliveries") + event = models.CharField(max_length=100) + payload = models.JSONField(default=dict) + status = models.CharField( + max_length=16, choices=DeliveryStatus.choices, default=DeliveryStatus.PENDING + ) + attempts = models.PositiveIntegerField(default=0) + next_attempt_at = models.DateTimeField(null=True, blank=True, db_index=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("-created_at",) + verbose_name_plural = "deliveries" + + def __str__(self) -> str: + return f"{self.event} -> {self.endpoint_id}" + + +class DeliveryAttempt(models.Model): + """What happened the one time a delivery was tried. A record, never edited.""" + + delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE, related_name="attempt_log") + number = models.PositiveIntegerField() + status_code = models.PositiveIntegerField(null=True, blank=True) + error = models.TextField(blank=True) + duration_ms = models.PositiveIntegerField(default=0) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("number",) + + def __str__(self) -> str: + return f"{self.delivery_id} #{self.number}" diff --git a/src/apps/webhooks/rest/__init__.py b/src/apps/webhooks/rest/__init__.py new file mode 100644 index 0000000..e47cefc --- /dev/null +++ b/src/apps/webhooks/rest/__init__.py @@ -0,0 +1,5 @@ +"""The HTTP transport for the webhooks app.""" + +from apps.webhooks.rest.v1 import router + +__all__ = ["router"] diff --git a/src/apps/webhooks/rest/schemas.py b/src/apps/webhooks/rest/schemas.py new file mode 100644 index 0000000..c840f92 --- /dev/null +++ b/src/apps/webhooks/rest/schemas.py @@ -0,0 +1,37 @@ +"""The contract the webhook endpoints publish.""" + +from ninja import Schema + + +class EndpointIn(Schema): + url: str + events: list[str] + + +class EndpointOut(Schema): + """``secret`` is filled only when created or rotated, and empty otherwise.""" + + id: str + url: str + events: list[str] + is_active: bool + created_at: str + secret: str + + +class AttemptOut(Schema): + number: int + status_code: int + error: str + duration_ms: int + created_at: str + + +class DeliveryOut(Schema): + id: str + event: str + status: str + attempts: int + next_attempt_at: str + created_at: str + attempt_log: list[AttemptOut] diff --git a/src/apps/webhooks/rest/v1.py b/src/apps/webhooks/rest/v1.py new file mode 100644 index 0000000..2b6c0f1 --- /dev/null +++ b/src/apps/webhooks/rest/v1.py @@ -0,0 +1,51 @@ +"""Managing webhook endpoints over HTTP. Every decision is in ``services``.""" + +from typing import Any + +from django.http import HttpRequest +from ninja import Router + +from apps.webhooks import services +from apps.webhooks.rest.schemas import DeliveryOut, EndpointIn, EndpointOut + +try: # pragma: no cover - exercised by whichever branch the project installs + from infrastructure.auth.core.sessions import api_auth +except ImportError: # pragma: no cover - only in a project without the auth apps + from ninja.security import django_auth as api_auth # type: ignore[assignment] + +router = Router(auth=api_auth) + + +@router.get("", response=list[EndpointOut], summary="List this account's webhook endpoints") +def list_endpoints(request: HttpRequest) -> list[dict[str, Any]]: + return services.list_endpoints(request.user) + + +@router.post("", response={201: EndpointOut}, summary="Register a webhook endpoint") +def create_endpoint(request: HttpRequest, payload: EndpointIn) -> tuple[int, dict[str, Any]]: + """The answer carries the signing secret; it is not shown again except on rotation.""" + return 201, services.create_endpoint(request.user, payload.url, payload.events) + + +@router.delete("/{endpoint_id}", response={204: None}, summary="Delete a webhook endpoint") +def delete_endpoint(request: HttpRequest, endpoint_id: str) -> tuple[int, None]: + services.delete_endpoint(request.user, endpoint_id) + return 204, None + + +@router.post( + "/{endpoint_id}/rotate-secret", response=EndpointOut, summary="Replace the signing secret" +) +def rotate_secret(request: HttpRequest, endpoint_id: str) -> dict[str, Any]: + return services.rotate_secret(request.user, endpoint_id) + + +@router.get( + "/{endpoint_id}/deliveries", + response=list[DeliveryOut], + summary="Recent deliveries to an endpoint, with every attempt", +) +def list_deliveries( + request: HttpRequest, endpoint_id: str, limit: int = 50 +) -> list[dict[str, Any]]: + return services.list_deliveries(request.user, endpoint_id, limit) diff --git a/src/apps/webhooks/services.py b/src/apps/webhooks/services.py new file mode 100644 index 0000000..26e1e24 --- /dev/null +++ b/src/apps/webhooks/services.py @@ -0,0 +1,261 @@ +"""Every webhook decision, shared by REST, GraphQL, gRPC and the delivery command. + +Code with something to say calls :func:`emit`; that only writes rows. The +sending happens in ``manage.py webhooks_deliver``, which a scheduler runs, the +same way ``support_prune`` and ``notifications_prune`` are run. +""" + +import hashlib +import hmac +import ipaddress +import json +import re +import secrets +import socket +import time +import urllib.error +import urllib.request +from datetime import datetime, timedelta +from typing import Any +from urllib.parse import urlsplit +from uuid import UUID + +from django.conf import settings +from django.db import transaction +from django.utils import timezone + +from apps.webhooks.models import Delivery, DeliveryAttempt, DeliveryStatus, Endpoint +from infrastructure.common.errors import ApiError +from infrastructure.common.responses import ResponseTitle + +SIGNATURE_HEADER = "X-Webhook-Signature" +EVENT_HEADER = "X-Webhook-Event" +EVENT_PATTERN = re.compile(r"^[a-z0-9_]+(\.[a-z0-9_]+)*$") +MAX_EVENTS = 50 +MAX_ERROR_LENGTH = 2000 + + +class UnsafeTarget(ValueError): + """The URL resolves somewhere this server must never be made to call.""" + + +def _is_public(address: str) -> bool: + ip = ipaddress.ip_address(address) + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped: + ip = ip.ipv4_mapped + return ip.is_global and not ip.is_multicast + + +def assert_public_target(url: str) -> None: + """Refuse anything but https to a host whose every address is public. + + Checked at registration and again right before every send, because DNS can + change between the two. + """ + parts = urlsplit(url) + if parts.scheme != "https" or not parts.hostname: + raise UnsafeTarget("Webhook URLs must be https.") + try: + infos = socket.getaddrinfo(parts.hostname, parts.port or 443, proto=socket.IPPROTO_TCP) + except (socket.gaierror, UnicodeError) as error: + raise UnsafeTarget(f"Cannot resolve {parts.hostname}.") from error + addresses = {str(info[4][0]) for info in infos} + if not addresses or not all(_is_public(address) for address in addresses): + raise UnsafeTarget(f"{parts.hostname} resolves to a private or reserved address.") + + +def sign(secret: str, timestamp: int, body: bytes) -> str: + """HMAC-SHA256 over ``"{timestamp}." + body``, as the header value carries it.""" + digest = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256) + return f"t={timestamp},v1={digest.hexdigest()}" + + +def _not_found() -> ApiError: + return ApiError("No such webhook endpoint.", status=404, title=ResponseTitle.NOT_FOUND) + + +def _clean_events(events: list[str]) -> list[str]: + cleaned = sorted({event.strip() for event in events}) + if not cleaned or len(cleaned) > MAX_EVENTS: + raise ApiError(f"Subscribe to between 1 and {MAX_EVENTS} event types.") + bad = [event for event in cleaned if not EVENT_PATTERN.fullmatch(event)] + if bad: + raise ApiError(f"Invalid event types: {', '.join(bad)}.") + return cleaned + + +def endpoint_data(endpoint: Endpoint, *, with_secret: bool = False) -> dict[str, Any]: + return { + "id": str(endpoint.id), + "url": endpoint.url, + "events": list(endpoint.events), + "is_active": endpoint.is_active, + "created_at": endpoint.created_at.isoformat(), + "secret": endpoint.secret if with_secret else "", + } + + +def delivery_data(delivery: Delivery) -> dict[str, Any]: + return { + "id": str(delivery.id), + "event": delivery.event, + "status": str(delivery.status), + "attempts": delivery.attempts, + "next_attempt_at": ( + delivery.next_attempt_at.isoformat() if delivery.next_attempt_at else "" + ), + "created_at": delivery.created_at.isoformat(), + "attempt_log": [ + { + "number": attempt.number, + "status_code": attempt.status_code or 0, + "error": attempt.error, + "duration_ms": attempt.duration_ms, + "created_at": attempt.created_at.isoformat(), + } + for attempt in delivery.attempt_log.all() + ], + } + + +def _owned(user: Any, endpoint_id: str | UUID) -> Endpoint: + try: + return Endpoint.objects.get(id=UUID(str(endpoint_id)), owner=user) + except (Endpoint.DoesNotExist, ValueError): + raise _not_found() from None + + +def list_endpoints(user: Any) -> list[dict[str, Any]]: + return [endpoint_data(endpoint) for endpoint in Endpoint.objects.filter(owner=user)] + + +def create_endpoint(user: Any, url: str, events: list[str]) -> dict[str, Any]: + """Register an endpoint; the secret is shown in this answer and on rotation only.""" + try: + assert_public_target(url) + except UnsafeTarget as error: + raise ApiError(str(error)) from None + endpoint = Endpoint.objects.create( + owner=user, url=url, events=_clean_events(events), secret=secrets.token_hex(32) + ) + return endpoint_data(endpoint, with_secret=True) + + +def delete_endpoint(user: Any, endpoint_id: str | UUID) -> None: + _owned(user, endpoint_id).delete() + + +def rotate_secret(user: Any, endpoint_id: str | UUID) -> dict[str, Any]: + endpoint = _owned(user, endpoint_id) + endpoint.secret = secrets.token_hex(32) + endpoint.save(update_fields=["secret"]) + return endpoint_data(endpoint, with_secret=True) + + +def list_deliveries(user: Any, endpoint_id: str | UUID, limit: int = 50) -> list[dict[str, Any]]: + endpoint = _owned(user, endpoint_id) + rows = endpoint.deliveries.prefetch_related("attempt_log")[: max(1, min(limit, 200))] + return [delivery_data(delivery) for delivery in rows] + + +def emit(user: Any, event: str, payload: dict[str, Any]) -> list[Delivery]: + """Queue ``event`` for every active endpoint of ``user`` subscribed to it.""" + now = timezone.now() + endpoints = Endpoint.objects.filter(owner=user, is_active=True) + return [ + Delivery.objects.create( + endpoint=endpoint, event=event, payload=payload, next_attempt_at=now + ) + for endpoint in endpoints + if event in endpoint.events + ] + + +class _NoRedirects(urllib.request.HTTPRedirectHandler): + """A redirect would be a second, unchecked target, so it is a failure instead.""" + + def redirect_request(self, *args: Any, **kwargs: Any) -> None: + return None + + +_opener = urllib.request.build_opener(_NoRedirects) + + +def _send(endpoint: Endpoint, delivery: Delivery) -> tuple[int | None, str]: + """POST once. Returns the status code (None if none came back) and an error.""" + try: + assert_public_target(endpoint.url) + except UnsafeTarget as error: + return None, str(error) + # ponytail: the address is re-resolved by urllib after the check, so a + # rebinding DNS server could still win the race; pin the IP if that matters. + body = json.dumps( + {"id": str(delivery.id), "event": delivery.event, "data": delivery.payload}, + default=str, + ).encode() + timestamp = int(time.time()) + request = urllib.request.Request( + endpoint.url, + data=body, + method="POST", + headers={ + "Content-Type": "application/json", + "User-Agent": "django-ninja-starter-webhooks", + EVENT_HEADER: delivery.event, + SIGNATURE_HEADER: sign(endpoint.secret, timestamp, body), + }, + ) + try: + with _opener.open(request, timeout=settings.WEBHOOKS_TIMEOUT_SECONDS) as response: + return response.status, "" + except urllib.error.HTTPError as error: + return error.code, f"HTTP {error.code}" + except (urllib.error.URLError, OSError) as error: + return None, str(error) + + +def backoff(attempts: int) -> timedelta: + """Wait after the ``attempts``-th failure: base, 2x base, 4x base, ...""" + return timedelta(seconds=settings.WEBHOOKS_BACKOFF_SECONDS * 2 ** (attempts - 1)) + + +def attempt(delivery: Delivery) -> Delivery: + """Try one delivery once, record the try, and schedule the next or give up.""" + started = time.monotonic() + status_code, error = _send(delivery.endpoint, delivery) + delivery.attempts += 1 + DeliveryAttempt.objects.create( + delivery=delivery, + number=delivery.attempts, + status_code=status_code, + error=error[:MAX_ERROR_LENGTH], + duration_ms=int((time.monotonic() - started) * 1000), + ) + if status_code is not None and 200 <= status_code < 300: + delivery.status, delivery.next_attempt_at = DeliveryStatus.SUCCEEDED, None + elif delivery.attempts >= settings.WEBHOOKS_MAX_ATTEMPTS: + delivery.status, delivery.next_attempt_at = DeliveryStatus.FAILED, None + else: + delivery.next_attempt_at = timezone.now() + backoff(delivery.attempts) + delivery.save(update_fields=["status", "attempts", "next_attempt_at"]) + return delivery + + +def deliver_due(now: datetime | None = None, limit: int = 100) -> int: + """Attempt every pending delivery whose time has come. Returns how many.""" + due = Delivery.objects.filter( + status=DeliveryStatus.PENDING, next_attempt_at__lte=now or timezone.now() + ).order_by("next_attempt_at") + done = 0 + for delivery_id in list(due.values_list("id", flat=True)[:limit]): + with transaction.atomic(): + delivery = ( + Delivery.objects.select_for_update() + .select_related("endpoint") + .filter(id=delivery_id, status=DeliveryStatus.PENDING) + .first() + ) + if delivery is not None: + attempt(delivery) + done += 1 + return done diff --git a/src/apps/webhooks/tests/__init__.py b/src/apps/webhooks/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/webhooks/tests/conftest.py b/src/apps/webhooks/tests/conftest.py new file mode 100644 index 0000000..0271708 --- /dev/null +++ b/src/apps/webhooks/tests/conftest.py @@ -0,0 +1,45 @@ +"""Fixtures for the webhook tests. Collection stops if the app is not installed.""" + +from collections.abc import Iterator +from typing import Any +from unittest import mock + +import pytest +from django.apps import apps as django_apps +from django.contrib.auth import get_user_model +from django.test import RequestFactory + +collect_ignore_glob = [] if django_apps.is_installed("apps.webhooks") else ["*"] + +PUBLIC_IP = "93.184.216.34" + + +def resolving_to(address: str) -> Any: + return mock.patch( + "apps.webhooks.services.socket.getaddrinfo", + return_value=[(2, 1, 6, "", (address, 443))], + ) + + +@pytest.fixture(autouse=True) +def public_dns() -> Iterator[None]: + """No test reaches a real resolver; every host is public unless a test says not.""" + with resolving_to(PUBLIC_IP): + yield + + +def access_token(user: Any) -> str: + from infrastructure.auth.core.sessions import issue_credentials + + token: str = issue_credentials(RequestFactory().post("/"), user, method="password").access_token + return token + + +@pytest.fixture +def alice(db: None) -> Any: + return get_user_model().objects.create_user(username="alice", email="alice@example.test") + + +@pytest.fixture +def bob(db: None) -> Any: + return get_user_model().objects.create_user(username="bob", email="bob@example.test") diff --git a/src/apps/webhooks/tests/test_api.py b/src/apps/webhooks/tests/test_api.py new file mode 100644 index 0000000..b4a501a --- /dev/null +++ b/src/apps/webhooks/tests/test_api.py @@ -0,0 +1,90 @@ +"""The three transports, each against a real credential.""" + +from collections.abc import Callable +from typing import Any + +import grpc +import pytest +from django.contrib.auth import get_user_model +from django.test import Client +from google.protobuf.empty_pb2 import Empty + +from apps.webhooks.grpc import webhooks_pb2, webhooks_pb2_grpc +from apps.webhooks.tests.conftest import access_token, resolving_to + +BASE = "/api/v1/webhooks" +URL = "https://hooks.example.test/in" + + +def _bearer(user: Any) -> dict[str, str]: + return {"HTTP_AUTHORIZATION": f"Bearer {access_token(user)}"} + + +def test_rest_round_trip(alice: Any, bob: Any) -> None: + client = Client() + created = client.post( + BASE, + {"url": URL, "events": ["order.paid"]}, + content_type="application/json", + **_bearer(alice), + ) + assert created.status_code == 201, created.content + endpoint = created.json()["data"] + assert len(endpoint["secret"]) == 64 + + listed = client.get(BASE, **_bearer(alice)).json()["data"] + assert [row["id"] for row in listed] == [endpoint["id"]] + assert listed[0]["secret"] == "" + assert client.get(BASE, **_bearer(bob)).json()["data"] == [] + + rotated = client.post(f"{BASE}/{endpoint['id']}/rotate-secret", **_bearer(alice)).json() + assert rotated["data"]["secret"] != endpoint["secret"] + assert client.get(f"{BASE}/{endpoint['id']}/deliveries", **_bearer(alice)).status_code == 200 + assert client.delete(f"{BASE}/{endpoint['id']}", **_bearer(bob)).status_code == 404 + assert client.delete(f"{BASE}/{endpoint['id']}", **_bearer(alice)).status_code == 204 + + +def test_rest_refuses_a_private_target(alice: Any) -> None: + with resolving_to("169.254.169.254"): + response = Client().post( + BASE, {"url": URL, "events": ["x"]}, content_type="application/json", **_bearer(alice) + ) + assert response.status_code == 400 + + +def test_rest_needs_a_credential(db: None) -> None: + assert Client().get(BASE).status_code == 401 + + +def test_graphql_round_trip(alice: Any) -> None: + client = Client() + create = 'mutation { createWebhookEndpoint(url: "' + URL + '", events: ["a.b"]) { id secret } }' + made = client.post( + "/graphql", {"query": create}, content_type="application/json", **_bearer(alice) + ).json() + endpoint_id = made["data"]["createWebhookEndpoint"]["id"] + + listed = client.post( + "/graphql", + {"query": "{ webhookEndpoints { id events } }"}, + content_type="application/json", + **_bearer(alice), + ).json() + assert listed["data"]["webhookEndpoints"] == [{"id": endpoint_id, "events": ["a.b"]}] + + +@pytest.fixture +def carol(transactional_db: None) -> Any: + return get_user_model().objects.create_user(username="carol", email="carol@example.test") + + +def test_grpc_round_trip(carol: Any, grpc_call: Callable[..., Any]) -> None: + Stub = webhooks_pb2_grpc.WebhookControllerStub + token = access_token(carol) + made = grpc_call(Stub, "Create", webhooks_pb2.CreateRequest(url=URL, events=["a.b"]), token) + listed = grpc_call(Stub, "List", Empty(), token) + + assert [row.id for row in listed.endpoints] == [made.id] + with pytest.raises(grpc.aio.AioRpcError) as refusal: + grpc_call(Stub, "Delete", webhooks_pb2.DeleteRequest(endpoint_id="nope"), token) + assert refusal.value.code() is grpc.StatusCode.NOT_FOUND diff --git a/src/apps/webhooks/tests/test_services.py b/src/apps/webhooks/tests/test_services.py new file mode 100644 index 0000000..cb4f2d7 --- /dev/null +++ b/src/apps/webhooks/tests/test_services.py @@ -0,0 +1,133 @@ +"""Signing, the SSRF guard, and the retry schedule.""" + +import hashlib +import hmac +import urllib.error +from datetime import timedelta +from typing import Any +from unittest import mock + +import pytest +from django.core.management import call_command +from django.utils import timezone + +from apps.webhooks import services +from apps.webhooks.models import Delivery, DeliveryStatus +from apps.webhooks.tests.conftest import resolving_to +from infrastructure.common.errors import ApiError + +URL = "https://hooks.example.test/in" + + +def test_the_signature_is_hmac_sha256_over_timestamp_and_body() -> None: + expected = hmac.new(b"key", b"1700000000.{}", hashlib.sha256).hexdigest() + + assert services.sign("key", 1700000000, b"{}") == f"t=1700000000,v1={expected}" + + +@pytest.mark.parametrize( + "address", + [ + "127.0.0.1", + "10.0.0.5", + "192.168.1.1", + "169.254.169.254", + "::1", + "fe80::1", + "::ffff:10.0.0.1", + ], +) +def test_private_loopback_and_link_local_targets_are_refused(address: str) -> None: + with resolving_to(address), pytest.raises(services.UnsafeTarget): + services.assert_public_target(URL) + + +def test_plain_http_is_refused() -> None: + with pytest.raises(services.UnsafeTarget): + services.assert_public_target("http://hooks.example.test/in") + + +def test_registration_refuses_an_unsafe_url(alice: Any) -> None: + with resolving_to("127.0.0.1"), pytest.raises(ApiError): + services.create_endpoint(alice, URL, ["order.paid"]) + + +def test_registration_refuses_malformed_event_types(alice: Any) -> None: + with pytest.raises(ApiError): + services.create_endpoint(alice, URL, ["Not An Event"]) + + +def _queued(user: Any) -> Delivery: + services.create_endpoint(user, URL, ["order.paid"]) + (delivery,) = services.emit(user, "order.paid", {"order": 1}) + return delivery + + +def test_emit_queues_only_for_subscribed_endpoints(alice: Any, bob: Any) -> None: + services.create_endpoint(alice, URL, ["order.paid"]) + services.create_endpoint(bob, URL, ["order.paid"]) + + assert len(services.emit(alice, "order.paid", {})) == 1 + assert services.emit(alice, "order.refunded", {}) == [] + + +def _response(status: int) -> Any: + response = mock.MagicMock(status=status) + response.__enter__.return_value = response + return response + + +def test_a_delivery_is_signed_and_recorded(alice: Any) -> None: + delivery = _queued(alice) + with mock.patch.object(services._opener, "open", return_value=_response(204)) as sent: + assert services.deliver_due() == 1 + + request = sent.call_args.args[0] + timestamp = request.get_header("X-webhook-signature").split(",")[0][2:] + assert request.get_header("X-webhook-signature") == services.sign( + delivery.endpoint.secret, int(timestamp), request.data + ) + delivery.refresh_from_db() + assert delivery.status == DeliveryStatus.SUCCEEDED + assert delivery.attempt_log.get().status_code == 204 + + +def test_a_failure_backs_off_exponentially_then_gives_up(alice: Any, settings: Any) -> None: + settings.WEBHOOKS_MAX_ATTEMPTS = 3 + settings.WEBHOOKS_BACKOFF_SECONDS = 10 + delivery = _queued(alice) + failure = urllib.error.HTTPError(URL, 500, "boom", {}, None) # type: ignore[arg-type] + waits = [] + with mock.patch.object(services._opener, "open", side_effect=failure): + for _ in range(3): + before = timezone.now() + services.attempt(Delivery.objects.select_related("endpoint").get(id=delivery.id)) + delivery.refresh_from_db() + if delivery.next_attempt_at: + waits.append(round((delivery.next_attempt_at - before).total_seconds())) + + assert waits == [10, 20] + assert delivery.status == DeliveryStatus.FAILED + assert [a.status_code for a in delivery.attempt_log.all()] == [500, 500, 500] + + +def test_the_ssrf_guard_runs_again_at_send_time(alice: Any) -> None: + delivery = _queued(alice) + with resolving_to("10.0.0.7"), mock.patch.object(services._opener, "open") as sent: + services.deliver_due() + + sent.assert_not_called() + delivery.refresh_from_db() + assert "private" in delivery.attempt_log.get().error + assert delivery.status == DeliveryStatus.PENDING + + +def test_deliveries_not_yet_due_wait(alice: Any) -> None: + delivery = _queued(alice) + Delivery.objects.filter(id=delivery.id).update( + next_attempt_at=timezone.now() + timedelta(minutes=5) + ) + with mock.patch.object(services._opener, "open") as sent: + call_command("webhooks_deliver") + + sent.assert_not_called() diff --git a/src/config/api.py b/src/config/api.py index 22a9c9e..0dd3758 100644 --- a/src/config/api.py +++ b/src/config/api.py @@ -47,6 +47,7 @@ def build_apis() -> dict[str, NinjaAPI]: *settings.SHOP_ROUTERS, *settings.SUPPORT_ROUTERS, *settings.WALLET_ROUTERS, + *settings.WEBHOOKS_ROUTERS, ] guarded = {id(route["router"]) for route in credential_routes} api = EnvelopeAPI( diff --git a/src/config/settings/base.py b/src/config/settings/base.py index f2d8258..bbfca73 100644 --- a/src/config/settings/base.py +++ b/src/config/settings/base.py @@ -903,6 +903,35 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: # app was installed to serve REST only. An app absent from this mapping -- every # infrastructure app -- publishes whatever it has, because the transports there # are the project's own and are turned off by the global flags below. +# Outgoing webhooks. Optional like every feature app: naming it installs its +# tables and routes. Deliveries are sent by `manage.py webhooks_deliver`, which +# a scheduler runs; nothing is sent from inside a request. +WEBHOOKS_ENABLED = os.getenv("DJANGO_WEBHOOKS_ENABLED", "false").lower() == "true" +WEBHOOKS_APP = "apps.webhooks.apps.WebhooksConfig" +WEBHOOKS_INSTALLED_APPS = [WEBHOOKS_APP] if WEBHOOKS_ENABLED else [] +WEBHOOKS_TRANSPORTS = ( + app_transports("webhooks", ("rest", "graph", "grpc")) if WEBHOOKS_ENABLED else () +) +WEBHOOKS_ROUTERS = ( + [ + { + "prefix": "/webhooks", + "router": "apps.webhooks.rest.router", + "tag": "Webhooks", + "description": ( + "Register https endpoints to be told about this account's events. " + "Every delivery is signed with HMAC-SHA256 in `X-Webhook-Signature`, " + "retried with exponential backoff, and every attempt is recorded." + ), + } + ] + if "rest" in WEBHOOKS_TRANSPORTS + else [] +) +WEBHOOKS_MAX_ATTEMPTS = int(os.getenv("DJANGO_WEBHOOKS_MAX_ATTEMPTS", "6")) +WEBHOOKS_BACKOFF_SECONDS = int(os.getenv("DJANGO_WEBHOOKS_BACKOFF_SECONDS", "30")) +WEBHOOKS_TIMEOUT_SECONDS = int(os.getenv("DJANGO_WEBHOOKS_TIMEOUT_SECONDS", "10")) + APP_TRANSPORTS = { "apps.cms": CMS_TRANSPORTS, "apps.notifications": NOTIFICATIONS_TRANSPORTS, @@ -910,6 +939,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: "apps.support": SUPPORT_TRANSPORTS, "apps.wallet": WALLET_TRANSPORTS, "apps.club": CLUB_TRANSPORTS, + "apps.webhooks": WEBHOOKS_TRANSPORTS, } # How often one caller may ask, whichever endpoint they are asking. A correct @@ -1022,6 +1052,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: *SUPPORT_INSTALLED_APPS, *WALLET_INSTALLED_APPS, *CLUB_INSTALLED_APPS, + *WEBHOOKS_INSTALLED_APPS, # The transports beside REST. Both are installed whether or not they are # published: `generateproto` and the schema check have to be able to run in a # deployment that serves neither. diff --git a/src/config/settings/test.py b/src/config/settings/test.py index 474cdb6..b52d4ab 100644 --- a/src/config/settings/test.py +++ b/src/config/settings/test.py @@ -6,6 +6,7 @@ os.environ.setdefault("DJANGO_SUPPORT_ENABLED", "true") os.environ.setdefault("DJANGO_WALLET_ENABLED", "true") os.environ.setdefault("DJANGO_CLUB_ENABLED", "true") +os.environ.setdefault("DJANGO_WEBHOOKS_ENABLED", "true") os.environ.setdefault("DJANGO_OAUTH_MODE", "all") os.environ.setdefault("DJANGO_AUTH_TOKEN_MODE", "rotation") os.environ.setdefault("DJANGO_AUTH_METHODS", "password,email_code,sms_code,magic_link") diff --git a/src/django_ninja_starter/template/Makefile b/src/django_ninja_starter/template/Makefile index 642a1a4..615c66b 100644 --- a/src/django_ninja_starter/template/Makefile +++ b/src/django_ninja_starter/template/Makefile @@ -6,7 +6,7 @@ install: # Every optional app turned on, so the checks below see the whole project # rather than whatever this developer happens to have in their `.env`. An app # left off is an app whose models, admin, migrations and protos nobody checked. -ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true +ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true DJANGO_WEBHOOKS_ENABLED=true check: ruff check --no-cache . diff --git a/src/django_ninja_starter/template/_env.example b/src/django_ninja_starter/template/_env.example index bc617ab..a997671 100644 --- a/src/django_ninja_starter/template/_env.example +++ b/src/django_ninja_starter/template/_env.example @@ -267,3 +267,11 @@ DJANGO_WEBSOCKET_ALLOWED_ORIGINS= DJANGO_SECURE_SSL_REDIRECT=true DJANGO_SECURE_HSTS_SECONDS=31536000 DJANGO_SECURE_HSTS_PRELOAD=true + +# Outgoing webhooks. Deliveries are sent by `manage.py webhooks_deliver`; schedule +# it (every minute, say). See docs/webhooks.md. +DJANGO_WEBHOOKS_ENABLED=false +# DJANGO_WEBHOOKS_TRANSPORTS=rest,graph,grpc +DJANGO_WEBHOOKS_MAX_ATTEMPTS=6 +DJANGO_WEBHOOKS_BACKOFF_SECONDS=30 +DJANGO_WEBHOOKS_TIMEOUT_SECONDS=10 diff --git a/src/django_ninja_starter/template/docs/README.md b/src/django_ninja_starter/template/docs/README.md index 209108c..6f2160f 100644 --- a/src/django_ninja_starter/template/docs/README.md +++ b/src/django_ninja_starter/template/docs/README.md @@ -15,7 +15,7 @@ themselves — see [keeping these pages honest](#keeping-these-pages-honest). | Social providers | [`oauth_google`](oauth/google.md), [`oauth_apple`](oauth/apple.md), [`oauth_microsoft`](oauth/microsoft.md), [`oauth_github`](oauth/github.md) | | Token modes | [`oauth_sliding`](oauth/sliding.md), [`oauth_session`](oauth/session.md), [`oauth_rotation`](oauth/rotation.md) | | Shared by those | [`auth_core`](auth/core.md), [`oauth_core`](oauth/core.md) | -| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md) | +| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md), [`webhooks`](webhooks.md) | | Cross-cutting | [The response envelope](responses.md), [Signing in](signing-in.md), [Credentials](credentials.md), [The admin](admin.md) | ## Start here @@ -102,6 +102,7 @@ features a project chooses rather than the plumbing under them. | [`shop`](shop.md) | `DJANGO_SHOP_ENABLED=true` | A catalogue whose categories declare what their products are, several sellers per product, timed campaigns, search and merchandising lists, reviews and likes, a basket per account, and an order cycle that reserves stock and issues an invoice | | [`wallet`](wallet.md) | `DJANGO_WALLET_ENABLED=true` | A wallet per account with the balance derived from its movements rather than stored, payment methods an administrator configures rather than code declares, fees and taxes priced by the same function that quotes them, crypto with its chains, currency conversion at a published rate, and deposits that stay requests until an operator applies them | | [`club`](club.md) | `DJANGO_CLUB_ENABLED=true` | Clubs with a levelled ladder, an account in one club at a time, XP derived from an immutable award ledger rather than stored, and missions that complete themselves from events the other apps emit -- including events an app of your own registers, which is what lets a mission be built out of code this starter has never seen | +| [`webhooks`](webhooks.md) | `DJANGO_WEBHOOKS_ENABLED=true` | Outgoing webhooks: https endpoints per account with their own secret and event types, HMAC-SHA256-signed deliveries retried with exponential backoff by `manage.py webhooks_deliver`, every attempt recorded, and private, loopback and link-local targets refused at send time | All five ship **off**, which is why a fresh `/api/docs` lists none of them: an app nobody named has no tables, no routes and no admin, and never imports its diff --git a/src/django_ninja_starter/template/docs/webhooks.md b/src/django_ninja_starter/template/docs/webhooks.md new file mode 100644 index 0000000..ca992f8 --- /dev/null +++ b/src/django_ninja_starter/template/docs/webhooks.md @@ -0,0 +1,114 @@ +# Webhooks + +`DJANGO_WEBHOOKS_ENABLED=true` installs outgoing webhooks: an account registers +https endpoints, each with the event types it wants and a secret of its own, and +the project POSTs each matching event to it -- signed, retried and recorded. + +## Sending an event + +Code with something to say queues it; nothing is sent inside the request: + +```python +from apps.webhooks.services import emit + +emit(order.customer, "shop.order.paid", {"order": str(order.id)}) +``` + +`manage.py webhooks_deliver` sends whatever is due. Schedule it (every minute +from cron or a systemd timer is plenty). A delivery that fails is retried after +`DJANGO_WEBHOOKS_BACKOFF_SECONDS`, then twice that, four times that, and so on, +until `DJANGO_WEBHOOKS_MAX_ATTEMPTS` is reached and it is marked `failed`. Every +try is kept as a `DeliveryAttempt`, readable at +`GET /api/v1/webhooks/{id}/deliveries`. + +## Verifying a delivery + +Each request carries `X-Webhook-Event` and +`X-Webhook-Signature: t=,v1=`, where `v1` is +HMAC-SHA256 with the endpoint's secret over `"." + raw body`. Recompute it, +compare in constant time, and reject a `t` that is too old. + +## SSRF + +Only `https` URLs are accepted, and the host's every resolved address must be +public: private, loopback, link-local and reserved ranges are refused when the +endpoint is registered **and again before each send**. Redirects are not followed. + +## Routes + + +| Method | Path | Auth | Purpose | +| --- | --- | --- | --- | +| `GET` | `/api/v1/webhooks` | Bearer | List this account's webhook endpoints | +| `POST` | `/api/v1/webhooks` | Bearer | Register a webhook endpoint | +| `DELETE` | `/api/v1/webhooks/{endpoint_id}` | Bearer | Delete a webhook endpoint | +| `GET` | `/api/v1/webhooks/{endpoint_id}/deliveries` | Bearer | Recent deliveries to an endpoint, with every attempt | +| `POST` | `/api/v1/webhooks/{endpoint_id}/rotate-secret` | Bearer | Replace the signing secret | + + +## Settings + + +| Environment variable | Required | Purpose | +| --- | --- | --- | +| `DJANGO_WEBHOOKS_ENABLED` | **Yes** | whether this deployment carries outgoing webhooks at all. | +| `DJANGO_WEBHOOKS_MAX_ATTEMPTS` | Optional | how many times a delivery is tried before it is marked failed. 1 or more. | +| `DJANGO_WEBHOOKS_BACKOFF_SECONDS` | Optional | the wait after the first failure; it doubles after each one. 1 or more. | +| `DJANGO_WEBHOOKS_TIMEOUT_SECONDS` | Optional | how long one delivery waits for the receiver to answer. 1 or more. | + + +## Models + + +#### `Delivery` + +One event bound for one endpoint, retried until it lands or gives up. + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | UUID | primary key, not editable | +| `endpoint` | ForeignKey | → `webhooks.Endpoint` | +| `event` | Char | | +| `payload` | JSON | | +| `status` | Char | | +| `attempts` | PositiveInteger | | +| `next_attempt_at` | DateTime | nullable | +| `created_at` | DateTime | not editable | + +#### `DeliveryAttempt` + +What happened the one time a delivery was tried. A record, never edited. + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | BigAuto | primary key | +| `delivery` | ForeignKey | → `webhooks.Delivery` | +| `number` | PositiveInteger | | +| `status_code` | PositiveInteger | nullable | +| `error` | Text | | +| `duration_ms` | PositiveInteger | | +| `created_at` | DateTime | not editable | + +#### `Endpoint` + +An https URL an account wants told about some of its events. + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | UUID | primary key, not editable | +| `owner` | ForeignKey | → `accounts.User` | +| `url` | Char | | +| `events` | JSON | | +| `secret` | Char | | +| `is_active` | Boolean | | +| `created_at` | DateTime | not editable | + + +## Admin + + +| Model | Editable | Actions | Columns | +| --- | --- | --- | --- | +| `Delivery` | Yes | — | `event`, `endpoint`, `status`, `attempts`, `next_attempt_at`, `created_at` | +| `Endpoint` | Yes | — | `url`, `owner`, `is_active`, `created_at` | + diff --git a/src/django_ninja_starter/template/src/apps/webhooks/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/__init__.py new file mode 100644 index 0000000..563a672 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/__init__.py @@ -0,0 +1 @@ +"""Outgoing webhooks: signed, retried, recorded deliveries to endpoints an account registers.""" diff --git a/src/django_ninja_starter/template/src/apps/webhooks/admin.py b/src/django_ninja_starter/template/src/apps/webhooks/admin.py new file mode 100644 index 0000000..6256004 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/admin.py @@ -0,0 +1,42 @@ +"""The admin: endpoints, and the delivery record (read-only, because it is a record).""" + +from typing import Any + +from django.contrib import admin +from django.http import HttpRequest + +from apps.webhooks.models import Delivery, DeliveryAttempt, Endpoint + +try: # pragma: no cover - exercised by whichever branch the project installs + from unfold.admin import ModelAdmin, TabularInline +except ImportError: # pragma: no cover - only in a project without Unfold + from django.contrib.admin import ModelAdmin, TabularInline + + +@admin.register(Endpoint) +class EndpointAdmin(ModelAdmin): + list_display = ("url", "owner", "is_active", "created_at") + list_filter = ("is_active",) + search_fields = ("url",) + exclude = ("secret",) + + +class AttemptInline(TabularInline): + model = DeliveryAttempt + extra = 0 + can_delete = False + readonly_fields = ("number", "status_code", "error", "duration_ms", "created_at") + + def has_add_permission(self, request: HttpRequest, obj: Any = None) -> bool: + return False + + +@admin.register(Delivery) +class DeliveryAdmin(ModelAdmin): + list_display = ("event", "endpoint", "status", "attempts", "next_attempt_at", "created_at") + list_filter = ("status",) + readonly_fields = ("endpoint", "event", "payload", "status", "attempts", "next_attempt_at") + inlines = (AttemptInline,) + + def has_add_permission(self, request: HttpRequest) -> bool: + return False diff --git a/src/django_ninja_starter/template/src/apps/webhooks/apps.py b/src/django_ninja_starter/template/src/apps/webhooks/apps.py new file mode 100644 index 0000000..632d7b4 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/apps.py @@ -0,0 +1,41 @@ +from django.apps import AppConfig + +from infrastructure.common.appsettings import AppSettings, Requirement + + +class WebhooksConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.webhooks" + label = "webhooks" + verbose_name = "Webhooks" + + settings_spec = AppSettings( + title="Webhooks", + summary="Signed outgoing webhooks, retried with backoff by `manage.py webhooks_deliver`.", + requirements=( + Requirement( + "WEBHOOKS_ENABLED", + env="DJANGO_WEBHOOKS_ENABLED", + purpose="whether this deployment carries outgoing webhooks at all", + required=True, + ), + Requirement( + "WEBHOOKS_MAX_ATTEMPTS", + env="DJANGO_WEBHOOKS_MAX_ATTEMPTS", + purpose="how many times a delivery is tried before it is marked failed", + minimum=1, + ), + Requirement( + "WEBHOOKS_BACKOFF_SECONDS", + env="DJANGO_WEBHOOKS_BACKOFF_SECONDS", + purpose="the wait after the first failure; it doubles after each one", + minimum=1, + ), + Requirement( + "WEBHOOKS_TIMEOUT_SECONDS", + env="DJANGO_WEBHOOKS_TIMEOUT_SECONDS", + purpose="how long one delivery waits for the receiver to answer", + minimum=1, + ), + ), + ) diff --git a/src/django_ninja_starter/template/src/apps/webhooks/graph/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/graph/__init__.py new file mode 100644 index 0000000..e695ffd --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/graph/__init__.py @@ -0,0 +1,5 @@ +"""The GraphQL transport for the webhooks app.""" + +from apps.webhooks.graph.schema import Mutation, Query + +__all__ = ["Mutation", "Query"] diff --git a/src/django_ninja_starter/template/src/apps/webhooks/graph/schema.py b/src/django_ninja_starter/template/src/apps/webhooks/graph/schema.py new file mode 100644 index 0000000..29dbbf6 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/graph/schema.py @@ -0,0 +1,90 @@ +"""The webhooks app's GraphQL fields, mirroring the REST endpoints one for one.""" + +from typing import Any + +import strawberry +from strawberry.types import Info + +from apps.webhooks import services +from infrastructure.common.graph.errors import require_caller, resolver +from infrastructure.common.identity import caller + + +@strawberry.type +class WebhookEndpointType: + id: str + url: str + events: list[str] + is_active: bool + created_at: str + secret: str + + +@strawberry.type +class WebhookAttemptType: + number: int + status_code: int + error: str + duration_ms: int + created_at: str + + +@strawberry.type +class WebhookDeliveryType: + id: str + event: str + status: str + attempts: int + next_attempt_at: str + created_at: str + attempt_log: list[WebhookAttemptType] + + +def _caller(info: Info[Any, Any]) -> Any: + return require_caller(caller(info.context.request)) + + +def _endpoint(row: dict[str, Any]) -> WebhookEndpointType: + return WebhookEndpointType(**row) + + +def _delivery(row: dict[str, Any]) -> WebhookDeliveryType: + attempts = [WebhookAttemptType(**attempt) for attempt in row["attempt_log"]] + return WebhookDeliveryType(**{**row, "attempt_log": attempts}) + + +@strawberry.type +class Query: + @strawberry.field(description="This account's webhook endpoints.") + @resolver + def webhook_endpoints(self, info: Info[Any, Any]) -> list[WebhookEndpointType]: + return [_endpoint(row) for row in services.list_endpoints(_caller(info))] + + @strawberry.field(description="Recent deliveries to one endpoint, with every attempt.") + @resolver + def webhook_deliveries( + self, info: Info[Any, Any], endpoint_id: str, limit: int = 50 + ) -> list[WebhookDeliveryType]: + rows = services.list_deliveries(_caller(info), endpoint_id, limit) + return [_delivery(row) for row in rows] + + +@strawberry.type +class Mutation: + @strawberry.mutation(description="Register an endpoint. The answer carries its secret.") + @resolver + def create_webhook_endpoint( + self, info: Info[Any, Any], url: str, events: list[str] + ) -> WebhookEndpointType: + return _endpoint(services.create_endpoint(_caller(info), url, events)) + + @strawberry.mutation(description="Delete an endpoint and its delivery record.") + @resolver + def delete_webhook_endpoint(self, info: Info[Any, Any], endpoint_id: str) -> bool: + services.delete_endpoint(_caller(info), endpoint_id) + return True + + @strawberry.mutation(description="Replace an endpoint's signing secret.") + @resolver + def rotate_webhook_secret(self, info: Info[Any, Any], endpoint_id: str) -> WebhookEndpointType: + return _endpoint(services.rotate_secret(_caller(info), endpoint_id)) diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/grpc/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/serializers.py b/src/django_ninja_starter/template/src/apps/webhooks/grpc/serializers.py new file mode 100644 index 0000000..1d76803 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/grpc/serializers.py @@ -0,0 +1,30 @@ +"""The nested messages the webhook service answers with.""" + +from rest_framework import serializers + + +class WebhookEndpoint(serializers.Serializer[dict[str, object]]): + id = serializers.CharField() + url = serializers.CharField() + events = serializers.ListField(child=serializers.CharField()) + is_active = serializers.BooleanField() + created_at = serializers.CharField() + secret = serializers.CharField() + + +class WebhookAttempt(serializers.Serializer[dict[str, object]]): + number = serializers.IntegerField() + status_code = serializers.IntegerField() + error = serializers.CharField() + duration_ms = serializers.IntegerField() + created_at = serializers.CharField() + + +class WebhookDelivery(serializers.Serializer[dict[str, object]]): + id = serializers.CharField() + event = serializers.CharField() + status = serializers.CharField() + attempts = serializers.IntegerField() + next_attempt_at = serializers.CharField() + created_at = serializers.CharField() + attempt_log = WebhookAttempt(many=True) diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/services.py b/src/django_ninja_starter/template/src/apps/webhooks/grpc/services.py new file mode 100644 index 0000000..8ff1741 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/grpc/services.py @@ -0,0 +1,101 @@ +"""Managing webhook endpoints over gRPC, mirroring the REST endpoints one for one.""" + +from typing import Any + +from asgiref.sync import sync_to_async +from django_socio_grpc import generics +from django_socio_grpc.decorators import grpc_action + +from apps.webhooks import services +from apps.webhooks.grpc.serializers import WebhookDelivery, WebhookEndpoint +from infrastructure.common.grpc.errors import action, require_caller +from infrastructure.common.identity import grpc_caller + + +def _pb2() -> Any: + from apps.webhooks.grpc import webhooks_pb2 + + return webhooks_pb2 + + +def _endpoint(row: dict[str, Any]) -> Any: + return _pb2().WebhookEndpoint(**row) + + +def _delivery(row: dict[str, Any]) -> Any: + pb2 = _pb2() + attempts = [pb2.WebhookAttempt(**attempt) for attempt in row["attempt_log"]] + return pb2.WebhookDelivery(**{**row, "attempt_log": attempts}) + + +class WebhookService(generics.GenericService): + """The same calls the REST router publishes under `/webhooks`.""" + + @grpc_action( + request=[], + response=[{"name": "endpoints", "cardinality": "repeated", "type": WebhookEndpoint}], + response_name="EndpointList", + ) + @action + async def List(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + rows = await sync_to_async(services.list_endpoints)(user) + return _pb2().EndpointList(endpoints=[_endpoint(row) for row in rows]) + + @grpc_action( + request=[ + {"name": "url", "type": "string"}, + {"name": "events", "cardinality": "repeated", "type": "string"}, + ], + request_name="CreateRequest", + response=WebhookEndpoint, + response_name="WebhookEndpoint", + ) + @action + async def Create(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + row = await sync_to_async(services.create_endpoint)(user, request.url, list(request.events)) + return _endpoint(row) + + @grpc_action( + request=[{"name": "endpoint_id", "type": "string"}], + request_name="DeleteRequest", + response=[{"name": "deleted", "type": "bool"}], + response_name="DeleteResult", + ) + @action + async def Delete(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + await sync_to_async(services.delete_endpoint)(user, request.endpoint_id) + return _pb2().DeleteResult(deleted=True) + + @grpc_action( + request=[{"name": "endpoint_id", "type": "string"}], + request_name="RotateSecretRequest", + response=WebhookEndpoint, + response_name="WebhookEndpoint", + ) + @action + async def RotateSecret(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + return _endpoint(await sync_to_async(services.rotate_secret)(user, request.endpoint_id)) + + @grpc_action( + request=[ + {"name": "endpoint_id", "type": "string"}, + {"name": "limit", "type": "int32"}, + ], + request_name="ListDeliveriesRequest", + response=[{"name": "deliveries", "cardinality": "repeated", "type": WebhookDelivery}], + response_name="DeliveryList", + ) + @action + async def ListDeliveries(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + rows = await sync_to_async(services.list_deliveries)( + user, request.endpoint_id, request.limit or 50 + ) + return _pb2().DeliveryList(deliveries=[_delivery(row) for row in rows]) + + +GRPC_SERVICES = [WebhookService] diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks.proto b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks.proto new file mode 100644 index 0000000..fe8efd5 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks.proto @@ -0,0 +1,71 @@ +syntax = "proto3"; + +package config.webhooks; + +import "google/protobuf/empty.proto"; + +service WebhookController { + rpc Create(CreateRequest) returns (WebhookEndpoint) {} + rpc Delete(DeleteRequest) returns (DeleteResult) {} + rpc List(google.protobuf.Empty) returns (EndpointList) {} + rpc ListDeliveries(ListDeliveriesRequest) returns (DeliveryList) {} + rpc RotateSecret(RotateSecretRequest) returns (WebhookEndpoint) {} +} + +message CreateRequest { + string url = 1; + repeated string events = 2; +} + +message DeleteRequest { + string endpoint_id = 1; +} + +message DeleteResult { + bool deleted = 1; +} + +message DeliveryList { + repeated WebhookDelivery deliveries = 1; +} + +message EndpointList { + repeated WebhookEndpoint endpoints = 1; +} + +message ListDeliveriesRequest { + string endpoint_id = 1; + int32 limit = 2; +} + +message RotateSecretRequest { + string endpoint_id = 1; +} + +message WebhookAttempt { + int32 number = 1; + int32 status_code = 2; + string error = 3; + int32 duration_ms = 4; + string created_at = 5; +} + +message WebhookDelivery { + string id = 1; + string event = 2; + string status = 3; + int32 attempts = 4; + string next_attempt_at = 5; + string created_at = 6; + repeated WebhookAttempt attempt_log = 7; +} + +message WebhookEndpoint { + string id = 1; + string url = 2; + repeated string events = 3; + bool is_active = 4; + string created_at = 5; + string secret = 6; +} + diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.py b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.py new file mode 100644 index 0000000..ea9cb71 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: apps/webhooks/grpc/webhooks.proto +# Protobuf Python Version: 7.35.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 7, + 35, + 1, + '', + 'apps/webhooks/grpc/webhooks.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!apps/webhooks/grpc/webhooks.proto\x12\x0f\x63onfig.webhooks\x1a\x1bgoogle/protobuf/empty.proto\",\n\rCreateRequest\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\x0e\n\x06\x65vents\x18\x02 \x03(\t\"$\n\rDeleteRequest\x12\x13\n\x0b\x65ndpoint_id\x18\x01 \x01(\t\"\x1f\n\x0c\x44\x65leteResult\x12\x0f\n\x07\x64\x65leted\x18\x01 \x01(\x08\"D\n\x0c\x44\x65liveryList\x12\x34\n\ndeliveries\x18\x01 \x03(\x0b\x32 .config.webhooks.WebhookDelivery\"C\n\x0c\x45ndpointList\x12\x33\n\tendpoints\x18\x01 \x03(\x0b\x32 .config.webhooks.WebhookEndpoint\";\n\x15ListDeliveriesRequest\x12\x13\n\x0b\x65ndpoint_id\x18\x01 \x01(\t\x12\r\n\x05limit\x18\x02 \x01(\x05\"*\n\x13RotateSecretRequest\x12\x13\n\x0b\x65ndpoint_id\x18\x01 \x01(\t\"m\n\x0eWebhookAttempt\x12\x0e\n\x06number\x18\x01 \x01(\x05\x12\x13\n\x0bstatus_code\x18\x02 \x01(\x05\x12\r\n\x05\x65rror\x18\x03 \x01(\t\x12\x13\n\x0b\x64uration_ms\x18\x04 \x01(\x05\x12\x12\n\ncreated_at\x18\x05 \x01(\t\"\xb1\x01\n\x0fWebhookDelivery\x12\n\n\x02id\x18\x01 \x01(\t\x12\r\n\x05\x65vent\x18\x02 \x01(\t\x12\x0e\n\x06status\x18\x03 \x01(\t\x12\x10\n\x08\x61ttempts\x18\x04 \x01(\x05\x12\x17\n\x0fnext_attempt_at\x18\x05 \x01(\t\x12\x12\n\ncreated_at\x18\x06 \x01(\t\x12\x34\n\x0b\x61ttempt_log\x18\x07 \x03(\x0b\x32\x1f.config.webhooks.WebhookAttempt\"q\n\x0fWebhookEndpoint\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0b\n\x03url\x18\x02 \x01(\t\x12\x0e\n\x06\x65vents\x18\x03 \x03(\t\x12\x11\n\tis_active\x18\x04 \x01(\x08\x12\x12\n\ncreated_at\x18\x05 \x01(\t\x12\x0e\n\x06secret\x18\x06 \x01(\t2\xa2\x03\n\x11WebhookController\x12L\n\x06\x43reate\x12\x1e.config.webhooks.CreateRequest\x1a .config.webhooks.WebhookEndpoint\"\x00\x12I\n\x06\x44\x65lete\x12\x1e.config.webhooks.DeleteRequest\x1a\x1d.config.webhooks.DeleteResult\"\x00\x12?\n\x04List\x12\x16.google.protobuf.Empty\x1a\x1d.config.webhooks.EndpointList\"\x00\x12Y\n\x0eListDeliveries\x12&.config.webhooks.ListDeliveriesRequest\x1a\x1d.config.webhooks.DeliveryList\"\x00\x12X\n\x0cRotateSecret\x12$.config.webhooks.RotateSecretRequest\x1a .config.webhooks.WebhookEndpoint\"\x00\x62\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.webhooks.grpc.webhooks_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR._loaded_options = None + _globals['_CREATEREQUEST']._serialized_start=83 + _globals['_CREATEREQUEST']._serialized_end=127 + _globals['_DELETEREQUEST']._serialized_start=129 + _globals['_DELETEREQUEST']._serialized_end=165 + _globals['_DELETERESULT']._serialized_start=167 + _globals['_DELETERESULT']._serialized_end=198 + _globals['_DELIVERYLIST']._serialized_start=200 + _globals['_DELIVERYLIST']._serialized_end=268 + _globals['_ENDPOINTLIST']._serialized_start=270 + _globals['_ENDPOINTLIST']._serialized_end=337 + _globals['_LISTDELIVERIESREQUEST']._serialized_start=339 + _globals['_LISTDELIVERIESREQUEST']._serialized_end=398 + _globals['_ROTATESECRETREQUEST']._serialized_start=400 + _globals['_ROTATESECRETREQUEST']._serialized_end=442 + _globals['_WEBHOOKATTEMPT']._serialized_start=444 + _globals['_WEBHOOKATTEMPT']._serialized_end=553 + _globals['_WEBHOOKDELIVERY']._serialized_start=556 + _globals['_WEBHOOKDELIVERY']._serialized_end=733 + _globals['_WEBHOOKENDPOINT']._serialized_start=735 + _globals['_WEBHOOKENDPOINT']._serialized_end=848 + _globals['_WEBHOOKCONTROLLER']._serialized_start=851 + _globals['_WEBHOOKCONTROLLER']._serialized_end=1269 +# @@protoc_insertion_point(module_scope) diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.pyi b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.pyi new file mode 100644 index 0000000..4ca3c4f --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2.pyi @@ -0,0 +1,265 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from collections import abc as _abc +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers +import builtins as _builtins +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import TypeAlias as _TypeAlias, Never as _Never +else: + from typing_extensions import TypeAlias as _TypeAlias, Never as _Never + +DESCRIPTOR: _descriptor.FileDescriptor + +@_typing.final +class CreateRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + URL_FIELD_NUMBER: _builtins.int + EVENTS_FIELD_NUMBER: _builtins.int + url: _builtins.str + @_builtins.property + def events(self) -> _containers.RepeatedScalarFieldContainer[_builtins.str]: ... + def __init__( + self, + *, + url: _builtins.str = ..., + events: _abc.Iterable[_builtins.str] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["events", b"events", "url", b"url"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___CreateRequest: _TypeAlias = CreateRequest # noqa: Y015 + +@_typing.final +class DeleteRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINT_ID_FIELD_NUMBER: _builtins.int + endpoint_id: _builtins.str + def __init__( + self, + *, + endpoint_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoint_id", b"endpoint_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteRequest: _TypeAlias = DeleteRequest # noqa: Y015 + +@_typing.final +class DeleteResult(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + DELETED_FIELD_NUMBER: _builtins.int + deleted: _builtins.bool + def __init__( + self, + *, + deleted: _builtins.bool = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["deleted", b"deleted"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteResult: _TypeAlias = DeleteResult # noqa: Y015 + +@_typing.final +class DeliveryList(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + DELIVERIES_FIELD_NUMBER: _builtins.int + @_builtins.property + def deliveries(self) -> _containers.RepeatedCompositeFieldContainer[Global___WebhookDelivery]: ... + def __init__( + self, + *, + deliveries: _abc.Iterable[Global___WebhookDelivery] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["deliveries", b"deliveries"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeliveryList: _TypeAlias = DeliveryList # noqa: Y015 + +@_typing.final +class EndpointList(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINTS_FIELD_NUMBER: _builtins.int + @_builtins.property + def endpoints(self) -> _containers.RepeatedCompositeFieldContainer[Global___WebhookEndpoint]: ... + def __init__( + self, + *, + endpoints: _abc.Iterable[Global___WebhookEndpoint] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoints", b"endpoints"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___EndpointList: _TypeAlias = EndpointList # noqa: Y015 + +@_typing.final +class ListDeliveriesRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINT_ID_FIELD_NUMBER: _builtins.int + LIMIT_FIELD_NUMBER: _builtins.int + endpoint_id: _builtins.str + limit: _builtins.int + def __init__( + self, + *, + endpoint_id: _builtins.str = ..., + limit: _builtins.int = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoint_id", b"endpoint_id", "limit", b"limit"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___ListDeliveriesRequest: _TypeAlias = ListDeliveriesRequest # noqa: Y015 + +@_typing.final +class RotateSecretRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ENDPOINT_ID_FIELD_NUMBER: _builtins.int + endpoint_id: _builtins.str + def __init__( + self, + *, + endpoint_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoint_id", b"endpoint_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___RotateSecretRequest: _TypeAlias = RotateSecretRequest # noqa: Y015 + +@_typing.final +class WebhookAttempt(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + NUMBER_FIELD_NUMBER: _builtins.int + STATUS_CODE_FIELD_NUMBER: _builtins.int + ERROR_FIELD_NUMBER: _builtins.int + DURATION_MS_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + number: _builtins.int + status_code: _builtins.int + error: _builtins.str + duration_ms: _builtins.int + created_at: _builtins.str + def __init__( + self, + *, + number: _builtins.int = ..., + status_code: _builtins.int = ..., + error: _builtins.str = ..., + duration_ms: _builtins.int = ..., + created_at: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["created_at", b"created_at", "duration_ms", b"duration_ms", "error", b"error", "number", b"number", "status_code", b"status_code"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___WebhookAttempt: _TypeAlias = WebhookAttempt # noqa: Y015 + +@_typing.final +class WebhookDelivery(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + EVENT_FIELD_NUMBER: _builtins.int + STATUS_FIELD_NUMBER: _builtins.int + ATTEMPTS_FIELD_NUMBER: _builtins.int + NEXT_ATTEMPT_AT_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + ATTEMPT_LOG_FIELD_NUMBER: _builtins.int + id: _builtins.str + event: _builtins.str + status: _builtins.str + attempts: _builtins.int + next_attempt_at: _builtins.str + created_at: _builtins.str + @_builtins.property + def attempt_log(self) -> _containers.RepeatedCompositeFieldContainer[Global___WebhookAttempt]: ... + def __init__( + self, + *, + id: _builtins.str = ..., + event: _builtins.str = ..., + status: _builtins.str = ..., + attempts: _builtins.int = ..., + next_attempt_at: _builtins.str = ..., + created_at: _builtins.str = ..., + attempt_log: _abc.Iterable[Global___WebhookAttempt] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["attempt_log", b"attempt_log", "attempts", b"attempts", "created_at", b"created_at", "event", b"event", "id", b"id", "next_attempt_at", b"next_attempt_at", "status", b"status"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___WebhookDelivery: _TypeAlias = WebhookDelivery # noqa: Y015 + +@_typing.final +class WebhookEndpoint(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + URL_FIELD_NUMBER: _builtins.int + EVENTS_FIELD_NUMBER: _builtins.int + IS_ACTIVE_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + SECRET_FIELD_NUMBER: _builtins.int + id: _builtins.str + url: _builtins.str + is_active: _builtins.bool + created_at: _builtins.str + secret: _builtins.str + @_builtins.property + def events(self) -> _containers.RepeatedScalarFieldContainer[_builtins.str]: ... + def __init__( + self, + *, + id: _builtins.str = ..., + url: _builtins.str = ..., + events: _abc.Iterable[_builtins.str] | None = ..., + is_active: _builtins.bool = ..., + created_at: _builtins.str = ..., + secret: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["created_at", b"created_at", "events", b"events", "id", b"id", "is_active", b"is_active", "secret", b"secret", "url", b"url"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___WebhookEndpoint: _TypeAlias = WebhookEndpoint # noqa: Y015 diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.py new file mode 100644 index 0000000..2a9d193 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.py @@ -0,0 +1,270 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc +import warnings + +from apps.webhooks.grpc import webhooks_pb2 as apps_dot_webhooks_dot_grpc_dot_webhooks__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + +GRPC_GENERATED_VERSION = '1.84.0' +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) +except ImportError: + _version_not_supported = True + +if _version_not_supported: + raise RuntimeError( + f'The grpc package installed is at version {GRPC_VERSION},' + + ' but the generated code in apps/webhooks/grpc/webhooks_pb2_grpc.py depends on' + + f' grpcio>={GRPC_GENERATED_VERSION}.' + + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' + + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' + ) + + +class WebhookControllerStub: + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Create = channel.unary_unary( + '/config.webhooks.WebhookController/Create', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.CreateRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + _registered_method=True) + self.Delete = channel.unary_unary( + '/config.webhooks.WebhookController/Delete', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteResult.FromString, + _registered_method=True) + self.List = channel.unary_unary( + '/config.webhooks.WebhookController/List', + request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.EndpointList.FromString, + _registered_method=True) + self.ListDeliveries = channel.unary_unary( + '/config.webhooks.WebhookController/ListDeliveries', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.ListDeliveriesRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeliveryList.FromString, + _registered_method=True) + self.RotateSecret = channel.unary_unary( + '/config.webhooks.WebhookController/RotateSecret', + request_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.RotateSecretRequest.SerializeToString, + response_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + _registered_method=True) + + +class WebhookControllerServicer: + """Missing associated documentation comment in .proto file.""" + + def Create(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Delete(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def List(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ListDeliveries(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def RotateSecret(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_WebhookControllerServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Create': grpc.unary_unary_rpc_method_handler( + servicer.Create, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.CreateRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.SerializeToString, + ), + 'Delete': grpc.unary_unary_rpc_method_handler( + servicer.Delete, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteResult.SerializeToString, + ), + 'List': grpc.unary_unary_rpc_method_handler( + servicer.List, + request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.EndpointList.SerializeToString, + ), + 'ListDeliveries': grpc.unary_unary_rpc_method_handler( + servicer.ListDeliveries, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.ListDeliveriesRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeliveryList.SerializeToString, + ), + 'RotateSecret': grpc.unary_unary_rpc_method_handler( + servicer.RotateSecret, + request_deserializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.RotateSecretRequest.FromString, + response_serializer=apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'config.webhooks.WebhookController', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + server.add_registered_method_handlers('config.webhooks.WebhookController', rpc_method_handlers) + + + # This class is part of an EXPERIMENTAL API. +class WebhookController: + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def Create(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/Create', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.CreateRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Delete(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/Delete', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeleteResult.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def List(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/List', + google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.EndpointList.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def ListDeliveries(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/ListDeliveries', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.ListDeliveriesRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.DeliveryList.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def RotateSecret(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.webhooks.WebhookController/RotateSecret', + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.RotateSecretRequest.SerializeToString, + apps_dot_webhooks_dot_grpc_dot_webhooks__pb2.WebhookEndpoint.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) diff --git a/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi new file mode 100644 index 0000000..bccc80d --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/grpc/webhooks_pb2_grpc.pyi @@ -0,0 +1,86 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from apps.webhooks.grpc import webhooks_pb2 as _webhooks_pb2 +from collections import abc as _abc +from google.protobuf import empty_pb2 as _empty_pb2 +from grpc import aio as _aio +import abc as _abc_1 +import grpc as _grpc +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import Self as _Self +else: + from typing_extensions import Self as _Self + +_T = _typing.TypeVar("_T") + +class _MaybeAsyncIterator(_abc.AsyncIterator[_T], _abc.Iterator[_T], metaclass=_abc_1.ABCMeta): ... + +class _ServicerContext(_grpc.ServicerContext, _aio.ServicerContext): # type: ignore[misc, type-arg] + ... + +GRPC_GENERATED_VERSION: str +GRPC_VERSION: str + +class WebhookControllerStub: + @_typing.overload + def __new__(cls, channel: _grpc.Channel) -> _Self: ... + @_typing.overload + def __new__(cls, channel: _aio.Channel) -> WebhookControllerAsyncStub: ... + Create: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.CreateRequest, _webhooks_pb2.WebhookEndpoint] + Delete: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.DeleteRequest, _webhooks_pb2.DeleteResult] + List: _grpc.UnaryUnaryMultiCallable[_empty_pb2.Empty, _webhooks_pb2.EndpointList] + ListDeliveries: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.ListDeliveriesRequest, _webhooks_pb2.DeliveryList] + RotateSecret: _grpc.UnaryUnaryMultiCallable[_webhooks_pb2.RotateSecretRequest, _webhooks_pb2.WebhookEndpoint] + +@_typing.type_check_only +class WebhookControllerAsyncStub(WebhookControllerStub): + def __init__(self, channel: _aio.Channel) -> None: ... + Create: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.CreateRequest, _webhooks_pb2.WebhookEndpoint] # type: ignore[assignment] + Delete: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.DeleteRequest, _webhooks_pb2.DeleteResult] # type: ignore[assignment] + List: _aio.UnaryUnaryMultiCallable[_empty_pb2.Empty, _webhooks_pb2.EndpointList] # type: ignore[assignment] + ListDeliveries: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.ListDeliveriesRequest, _webhooks_pb2.DeliveryList] # type: ignore[assignment] + RotateSecret: _aio.UnaryUnaryMultiCallable[_webhooks_pb2.RotateSecretRequest, _webhooks_pb2.WebhookEndpoint] # type: ignore[assignment] + +class WebhookControllerServicer(metaclass=_abc_1.ABCMeta): + @_abc_1.abstractmethod + def Create( + self, + request: _webhooks_pb2.CreateRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.WebhookEndpoint, _abc.Awaitable[_webhooks_pb2.WebhookEndpoint]]: ... + + @_abc_1.abstractmethod + def Delete( + self, + request: _webhooks_pb2.DeleteRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.DeleteResult, _abc.Awaitable[_webhooks_pb2.DeleteResult]]: ... + + @_abc_1.abstractmethod + def List( + self, + request: _empty_pb2.Empty, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.EndpointList, _abc.Awaitable[_webhooks_pb2.EndpointList]]: ... + + @_abc_1.abstractmethod + def ListDeliveries( + self, + request: _webhooks_pb2.ListDeliveriesRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.DeliveryList, _abc.Awaitable[_webhooks_pb2.DeliveryList]]: ... + + @_abc_1.abstractmethod + def RotateSecret( + self, + request: _webhooks_pb2.RotateSecretRequest, + context: _ServicerContext, + ) -> _typing.Union[_webhooks_pb2.WebhookEndpoint, _abc.Awaitable[_webhooks_pb2.WebhookEndpoint]]: ... + +def add_WebhookControllerServicer_to_server(servicer: WebhookControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ... diff --git a/src/django_ninja_starter/template/src/apps/webhooks/management/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/webhooks/management/commands/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/webhooks/management/commands/webhooks_deliver.py b/src/django_ninja_starter/template/src/apps/webhooks/management/commands/webhooks_deliver.py new file mode 100644 index 0000000..f9f6438 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/management/commands/webhooks_deliver.py @@ -0,0 +1,18 @@ +"""Send every webhook delivery that is due. Schedule it, e.g. every minute from cron.""" + +from typing import Any + +from django.core.management.base import BaseCommand, CommandParser + +from apps.webhooks.services import deliver_due + + +class Command(BaseCommand): + help = "Attempt every pending webhook delivery whose next attempt is due." + + def add_arguments(self, parser: CommandParser) -> None: + parser.add_argument("--limit", type=int, default=100) + + def handle(self, *args: Any, **options: Any) -> None: + count = deliver_due(limit=options["limit"]) + self.stdout.write(f"Attempted {count} webhook deliveries.") diff --git a/src/django_ninja_starter/template/src/apps/webhooks/migrations/0001_initial.py b/src/django_ninja_starter/template/src/apps/webhooks/migrations/0001_initial.py new file mode 100644 index 0000000..a9b17cc --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/migrations/0001_initial.py @@ -0,0 +1,123 @@ +# Generated by Django 6.1.3 on 2026-11-26 14:27 + +import uuid + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="Delivery", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, editable=False, primary_key=True, serialize=False + ), + ), + ("event", models.CharField(max_length=100)), + ("payload", models.JSONField(default=dict)), + ( + "status", + models.CharField( + choices=[ + ("pending", "Pending"), + ("succeeded", "Succeeded"), + ("failed", "Failed"), + ], + default="pending", + max_length=16, + ), + ), + ("attempts", models.PositiveIntegerField(default=0)), + ("next_attempt_at", models.DateTimeField(blank=True, db_index=True, null=True)), + ("created_at", models.DateTimeField(auto_now_add=True)), + ], + options={ + "verbose_name_plural": "deliveries", + "ordering": ("-created_at",), + }, + ), + migrations.CreateModel( + name="DeliveryAttempt", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" + ), + ), + ("number", models.PositiveIntegerField()), + ("status_code", models.PositiveIntegerField(blank=True, null=True)), + ("error", models.TextField(blank=True)), + ("duration_ms", models.PositiveIntegerField(default=0)), + ("created_at", models.DateTimeField(auto_now_add=True)), + ( + "delivery", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="attempt_log", + to="webhooks.delivery", + ), + ), + ], + options={ + "ordering": ("number",), + }, + ), + migrations.CreateModel( + name="Endpoint", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, editable=False, primary_key=True, serialize=False + ), + ), + ("url", models.URLField(max_length=2000)), + ( + "events", + models.JSONField( + default=list, help_text="The event types this endpoint receives." + ), + ), + ( + "secret", + models.CharField( + help_text="The HMAC-SHA256 key deliveries are signed with.", max_length=64 + ), + ), + ("is_active", models.BooleanField(default=True)), + ("created_at", models.DateTimeField(auto_now_add=True)), + ( + "owner", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="webhook_endpoints", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "ordering": ("-created_at",), + }, + ), + migrations.AddField( + model_name="delivery", + name="endpoint", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="deliveries", + to="webhooks.endpoint", + ), + ), + ] diff --git a/src/django_ninja_starter/template/src/apps/webhooks/migrations/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/webhooks/models.py b/src/django_ninja_starter/template/src/apps/webhooks/models.py new file mode 100644 index 0000000..dda6e61 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/models.py @@ -0,0 +1,73 @@ +"""Outgoing webhooks: where to send, what was sent, and every try at sending it.""" + +import uuid + +from django.conf import settings +from django.db import models + + +class Endpoint(models.Model): + """An https URL an account wants told about some of its events.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + owner = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="webhook_endpoints" + ) + url = models.URLField(max_length=2000) + events = models.JSONField(default=list, help_text="The event types this endpoint receives.") + secret = models.CharField( + max_length=64, help_text="The HMAC-SHA256 key deliveries are signed with." + ) + is_active = models.BooleanField(default=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("-created_at",) + + def __str__(self) -> str: + return self.url + + +class DeliveryStatus(models.TextChoices): + PENDING = "pending", "Pending" + SUCCEEDED = "succeeded", "Succeeded" + FAILED = "failed", "Failed" + + +class Delivery(models.Model): + """One event bound for one endpoint, retried until it lands or gives up.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + endpoint = models.ForeignKey(Endpoint, on_delete=models.CASCADE, related_name="deliveries") + event = models.CharField(max_length=100) + payload = models.JSONField(default=dict) + status = models.CharField( + max_length=16, choices=DeliveryStatus.choices, default=DeliveryStatus.PENDING + ) + attempts = models.PositiveIntegerField(default=0) + next_attempt_at = models.DateTimeField(null=True, blank=True, db_index=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("-created_at",) + verbose_name_plural = "deliveries" + + def __str__(self) -> str: + return f"{self.event} -> {self.endpoint_id}" + + +class DeliveryAttempt(models.Model): + """What happened the one time a delivery was tried. A record, never edited.""" + + delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE, related_name="attempt_log") + number = models.PositiveIntegerField() + status_code = models.PositiveIntegerField(null=True, blank=True) + error = models.TextField(blank=True) + duration_ms = models.PositiveIntegerField(default=0) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("number",) + + def __str__(self) -> str: + return f"{self.delivery_id} #{self.number}" diff --git a/src/django_ninja_starter/template/src/apps/webhooks/rest/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/rest/__init__.py new file mode 100644 index 0000000..e47cefc --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/rest/__init__.py @@ -0,0 +1,5 @@ +"""The HTTP transport for the webhooks app.""" + +from apps.webhooks.rest.v1 import router + +__all__ = ["router"] diff --git a/src/django_ninja_starter/template/src/apps/webhooks/rest/schemas.py b/src/django_ninja_starter/template/src/apps/webhooks/rest/schemas.py new file mode 100644 index 0000000..c840f92 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/rest/schemas.py @@ -0,0 +1,37 @@ +"""The contract the webhook endpoints publish.""" + +from ninja import Schema + + +class EndpointIn(Schema): + url: str + events: list[str] + + +class EndpointOut(Schema): + """``secret`` is filled only when created or rotated, and empty otherwise.""" + + id: str + url: str + events: list[str] + is_active: bool + created_at: str + secret: str + + +class AttemptOut(Schema): + number: int + status_code: int + error: str + duration_ms: int + created_at: str + + +class DeliveryOut(Schema): + id: str + event: str + status: str + attempts: int + next_attempt_at: str + created_at: str + attempt_log: list[AttemptOut] diff --git a/src/django_ninja_starter/template/src/apps/webhooks/rest/v1.py b/src/django_ninja_starter/template/src/apps/webhooks/rest/v1.py new file mode 100644 index 0000000..2b6c0f1 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/rest/v1.py @@ -0,0 +1,51 @@ +"""Managing webhook endpoints over HTTP. Every decision is in ``services``.""" + +from typing import Any + +from django.http import HttpRequest +from ninja import Router + +from apps.webhooks import services +from apps.webhooks.rest.schemas import DeliveryOut, EndpointIn, EndpointOut + +try: # pragma: no cover - exercised by whichever branch the project installs + from infrastructure.auth.core.sessions import api_auth +except ImportError: # pragma: no cover - only in a project without the auth apps + from ninja.security import django_auth as api_auth # type: ignore[assignment] + +router = Router(auth=api_auth) + + +@router.get("", response=list[EndpointOut], summary="List this account's webhook endpoints") +def list_endpoints(request: HttpRequest) -> list[dict[str, Any]]: + return services.list_endpoints(request.user) + + +@router.post("", response={201: EndpointOut}, summary="Register a webhook endpoint") +def create_endpoint(request: HttpRequest, payload: EndpointIn) -> tuple[int, dict[str, Any]]: + """The answer carries the signing secret; it is not shown again except on rotation.""" + return 201, services.create_endpoint(request.user, payload.url, payload.events) + + +@router.delete("/{endpoint_id}", response={204: None}, summary="Delete a webhook endpoint") +def delete_endpoint(request: HttpRequest, endpoint_id: str) -> tuple[int, None]: + services.delete_endpoint(request.user, endpoint_id) + return 204, None + + +@router.post( + "/{endpoint_id}/rotate-secret", response=EndpointOut, summary="Replace the signing secret" +) +def rotate_secret(request: HttpRequest, endpoint_id: str) -> dict[str, Any]: + return services.rotate_secret(request.user, endpoint_id) + + +@router.get( + "/{endpoint_id}/deliveries", + response=list[DeliveryOut], + summary="Recent deliveries to an endpoint, with every attempt", +) +def list_deliveries( + request: HttpRequest, endpoint_id: str, limit: int = 50 +) -> list[dict[str, Any]]: + return services.list_deliveries(request.user, endpoint_id, limit) diff --git a/src/django_ninja_starter/template/src/apps/webhooks/services.py b/src/django_ninja_starter/template/src/apps/webhooks/services.py new file mode 100644 index 0000000..26e1e24 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/services.py @@ -0,0 +1,261 @@ +"""Every webhook decision, shared by REST, GraphQL, gRPC and the delivery command. + +Code with something to say calls :func:`emit`; that only writes rows. The +sending happens in ``manage.py webhooks_deliver``, which a scheduler runs, the +same way ``support_prune`` and ``notifications_prune`` are run. +""" + +import hashlib +import hmac +import ipaddress +import json +import re +import secrets +import socket +import time +import urllib.error +import urllib.request +from datetime import datetime, timedelta +from typing import Any +from urllib.parse import urlsplit +from uuid import UUID + +from django.conf import settings +from django.db import transaction +from django.utils import timezone + +from apps.webhooks.models import Delivery, DeliveryAttempt, DeliveryStatus, Endpoint +from infrastructure.common.errors import ApiError +from infrastructure.common.responses import ResponseTitle + +SIGNATURE_HEADER = "X-Webhook-Signature" +EVENT_HEADER = "X-Webhook-Event" +EVENT_PATTERN = re.compile(r"^[a-z0-9_]+(\.[a-z0-9_]+)*$") +MAX_EVENTS = 50 +MAX_ERROR_LENGTH = 2000 + + +class UnsafeTarget(ValueError): + """The URL resolves somewhere this server must never be made to call.""" + + +def _is_public(address: str) -> bool: + ip = ipaddress.ip_address(address) + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped: + ip = ip.ipv4_mapped + return ip.is_global and not ip.is_multicast + + +def assert_public_target(url: str) -> None: + """Refuse anything but https to a host whose every address is public. + + Checked at registration and again right before every send, because DNS can + change between the two. + """ + parts = urlsplit(url) + if parts.scheme != "https" or not parts.hostname: + raise UnsafeTarget("Webhook URLs must be https.") + try: + infos = socket.getaddrinfo(parts.hostname, parts.port or 443, proto=socket.IPPROTO_TCP) + except (socket.gaierror, UnicodeError) as error: + raise UnsafeTarget(f"Cannot resolve {parts.hostname}.") from error + addresses = {str(info[4][0]) for info in infos} + if not addresses or not all(_is_public(address) for address in addresses): + raise UnsafeTarget(f"{parts.hostname} resolves to a private or reserved address.") + + +def sign(secret: str, timestamp: int, body: bytes) -> str: + """HMAC-SHA256 over ``"{timestamp}." + body``, as the header value carries it.""" + digest = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256) + return f"t={timestamp},v1={digest.hexdigest()}" + + +def _not_found() -> ApiError: + return ApiError("No such webhook endpoint.", status=404, title=ResponseTitle.NOT_FOUND) + + +def _clean_events(events: list[str]) -> list[str]: + cleaned = sorted({event.strip() for event in events}) + if not cleaned or len(cleaned) > MAX_EVENTS: + raise ApiError(f"Subscribe to between 1 and {MAX_EVENTS} event types.") + bad = [event for event in cleaned if not EVENT_PATTERN.fullmatch(event)] + if bad: + raise ApiError(f"Invalid event types: {', '.join(bad)}.") + return cleaned + + +def endpoint_data(endpoint: Endpoint, *, with_secret: bool = False) -> dict[str, Any]: + return { + "id": str(endpoint.id), + "url": endpoint.url, + "events": list(endpoint.events), + "is_active": endpoint.is_active, + "created_at": endpoint.created_at.isoformat(), + "secret": endpoint.secret if with_secret else "", + } + + +def delivery_data(delivery: Delivery) -> dict[str, Any]: + return { + "id": str(delivery.id), + "event": delivery.event, + "status": str(delivery.status), + "attempts": delivery.attempts, + "next_attempt_at": ( + delivery.next_attempt_at.isoformat() if delivery.next_attempt_at else "" + ), + "created_at": delivery.created_at.isoformat(), + "attempt_log": [ + { + "number": attempt.number, + "status_code": attempt.status_code or 0, + "error": attempt.error, + "duration_ms": attempt.duration_ms, + "created_at": attempt.created_at.isoformat(), + } + for attempt in delivery.attempt_log.all() + ], + } + + +def _owned(user: Any, endpoint_id: str | UUID) -> Endpoint: + try: + return Endpoint.objects.get(id=UUID(str(endpoint_id)), owner=user) + except (Endpoint.DoesNotExist, ValueError): + raise _not_found() from None + + +def list_endpoints(user: Any) -> list[dict[str, Any]]: + return [endpoint_data(endpoint) for endpoint in Endpoint.objects.filter(owner=user)] + + +def create_endpoint(user: Any, url: str, events: list[str]) -> dict[str, Any]: + """Register an endpoint; the secret is shown in this answer and on rotation only.""" + try: + assert_public_target(url) + except UnsafeTarget as error: + raise ApiError(str(error)) from None + endpoint = Endpoint.objects.create( + owner=user, url=url, events=_clean_events(events), secret=secrets.token_hex(32) + ) + return endpoint_data(endpoint, with_secret=True) + + +def delete_endpoint(user: Any, endpoint_id: str | UUID) -> None: + _owned(user, endpoint_id).delete() + + +def rotate_secret(user: Any, endpoint_id: str | UUID) -> dict[str, Any]: + endpoint = _owned(user, endpoint_id) + endpoint.secret = secrets.token_hex(32) + endpoint.save(update_fields=["secret"]) + return endpoint_data(endpoint, with_secret=True) + + +def list_deliveries(user: Any, endpoint_id: str | UUID, limit: int = 50) -> list[dict[str, Any]]: + endpoint = _owned(user, endpoint_id) + rows = endpoint.deliveries.prefetch_related("attempt_log")[: max(1, min(limit, 200))] + return [delivery_data(delivery) for delivery in rows] + + +def emit(user: Any, event: str, payload: dict[str, Any]) -> list[Delivery]: + """Queue ``event`` for every active endpoint of ``user`` subscribed to it.""" + now = timezone.now() + endpoints = Endpoint.objects.filter(owner=user, is_active=True) + return [ + Delivery.objects.create( + endpoint=endpoint, event=event, payload=payload, next_attempt_at=now + ) + for endpoint in endpoints + if event in endpoint.events + ] + + +class _NoRedirects(urllib.request.HTTPRedirectHandler): + """A redirect would be a second, unchecked target, so it is a failure instead.""" + + def redirect_request(self, *args: Any, **kwargs: Any) -> None: + return None + + +_opener = urllib.request.build_opener(_NoRedirects) + + +def _send(endpoint: Endpoint, delivery: Delivery) -> tuple[int | None, str]: + """POST once. Returns the status code (None if none came back) and an error.""" + try: + assert_public_target(endpoint.url) + except UnsafeTarget as error: + return None, str(error) + # ponytail: the address is re-resolved by urllib after the check, so a + # rebinding DNS server could still win the race; pin the IP if that matters. + body = json.dumps( + {"id": str(delivery.id), "event": delivery.event, "data": delivery.payload}, + default=str, + ).encode() + timestamp = int(time.time()) + request = urllib.request.Request( + endpoint.url, + data=body, + method="POST", + headers={ + "Content-Type": "application/json", + "User-Agent": "django-ninja-starter-webhooks", + EVENT_HEADER: delivery.event, + SIGNATURE_HEADER: sign(endpoint.secret, timestamp, body), + }, + ) + try: + with _opener.open(request, timeout=settings.WEBHOOKS_TIMEOUT_SECONDS) as response: + return response.status, "" + except urllib.error.HTTPError as error: + return error.code, f"HTTP {error.code}" + except (urllib.error.URLError, OSError) as error: + return None, str(error) + + +def backoff(attempts: int) -> timedelta: + """Wait after the ``attempts``-th failure: base, 2x base, 4x base, ...""" + return timedelta(seconds=settings.WEBHOOKS_BACKOFF_SECONDS * 2 ** (attempts - 1)) + + +def attempt(delivery: Delivery) -> Delivery: + """Try one delivery once, record the try, and schedule the next or give up.""" + started = time.monotonic() + status_code, error = _send(delivery.endpoint, delivery) + delivery.attempts += 1 + DeliveryAttempt.objects.create( + delivery=delivery, + number=delivery.attempts, + status_code=status_code, + error=error[:MAX_ERROR_LENGTH], + duration_ms=int((time.monotonic() - started) * 1000), + ) + if status_code is not None and 200 <= status_code < 300: + delivery.status, delivery.next_attempt_at = DeliveryStatus.SUCCEEDED, None + elif delivery.attempts >= settings.WEBHOOKS_MAX_ATTEMPTS: + delivery.status, delivery.next_attempt_at = DeliveryStatus.FAILED, None + else: + delivery.next_attempt_at = timezone.now() + backoff(delivery.attempts) + delivery.save(update_fields=["status", "attempts", "next_attempt_at"]) + return delivery + + +def deliver_due(now: datetime | None = None, limit: int = 100) -> int: + """Attempt every pending delivery whose time has come. Returns how many.""" + due = Delivery.objects.filter( + status=DeliveryStatus.PENDING, next_attempt_at__lte=now or timezone.now() + ).order_by("next_attempt_at") + done = 0 + for delivery_id in list(due.values_list("id", flat=True)[:limit]): + with transaction.atomic(): + delivery = ( + Delivery.objects.select_for_update() + .select_related("endpoint") + .filter(id=delivery_id, status=DeliveryStatus.PENDING) + .first() + ) + if delivery is not None: + attempt(delivery) + done += 1 + return done diff --git a/src/django_ninja_starter/template/src/apps/webhooks/tests/__init__.py b/src/django_ninja_starter/template/src/apps/webhooks/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/webhooks/tests/conftest.py b/src/django_ninja_starter/template/src/apps/webhooks/tests/conftest.py new file mode 100644 index 0000000..0271708 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/tests/conftest.py @@ -0,0 +1,45 @@ +"""Fixtures for the webhook tests. Collection stops if the app is not installed.""" + +from collections.abc import Iterator +from typing import Any +from unittest import mock + +import pytest +from django.apps import apps as django_apps +from django.contrib.auth import get_user_model +from django.test import RequestFactory + +collect_ignore_glob = [] if django_apps.is_installed("apps.webhooks") else ["*"] + +PUBLIC_IP = "93.184.216.34" + + +def resolving_to(address: str) -> Any: + return mock.patch( + "apps.webhooks.services.socket.getaddrinfo", + return_value=[(2, 1, 6, "", (address, 443))], + ) + + +@pytest.fixture(autouse=True) +def public_dns() -> Iterator[None]: + """No test reaches a real resolver; every host is public unless a test says not.""" + with resolving_to(PUBLIC_IP): + yield + + +def access_token(user: Any) -> str: + from infrastructure.auth.core.sessions import issue_credentials + + token: str = issue_credentials(RequestFactory().post("/"), user, method="password").access_token + return token + + +@pytest.fixture +def alice(db: None) -> Any: + return get_user_model().objects.create_user(username="alice", email="alice@example.test") + + +@pytest.fixture +def bob(db: None) -> Any: + return get_user_model().objects.create_user(username="bob", email="bob@example.test") diff --git a/src/django_ninja_starter/template/src/apps/webhooks/tests/test_api.py b/src/django_ninja_starter/template/src/apps/webhooks/tests/test_api.py new file mode 100644 index 0000000..b4a501a --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/tests/test_api.py @@ -0,0 +1,90 @@ +"""The three transports, each against a real credential.""" + +from collections.abc import Callable +from typing import Any + +import grpc +import pytest +from django.contrib.auth import get_user_model +from django.test import Client +from google.protobuf.empty_pb2 import Empty + +from apps.webhooks.grpc import webhooks_pb2, webhooks_pb2_grpc +from apps.webhooks.tests.conftest import access_token, resolving_to + +BASE = "/api/v1/webhooks" +URL = "https://hooks.example.test/in" + + +def _bearer(user: Any) -> dict[str, str]: + return {"HTTP_AUTHORIZATION": f"Bearer {access_token(user)}"} + + +def test_rest_round_trip(alice: Any, bob: Any) -> None: + client = Client() + created = client.post( + BASE, + {"url": URL, "events": ["order.paid"]}, + content_type="application/json", + **_bearer(alice), + ) + assert created.status_code == 201, created.content + endpoint = created.json()["data"] + assert len(endpoint["secret"]) == 64 + + listed = client.get(BASE, **_bearer(alice)).json()["data"] + assert [row["id"] for row in listed] == [endpoint["id"]] + assert listed[0]["secret"] == "" + assert client.get(BASE, **_bearer(bob)).json()["data"] == [] + + rotated = client.post(f"{BASE}/{endpoint['id']}/rotate-secret", **_bearer(alice)).json() + assert rotated["data"]["secret"] != endpoint["secret"] + assert client.get(f"{BASE}/{endpoint['id']}/deliveries", **_bearer(alice)).status_code == 200 + assert client.delete(f"{BASE}/{endpoint['id']}", **_bearer(bob)).status_code == 404 + assert client.delete(f"{BASE}/{endpoint['id']}", **_bearer(alice)).status_code == 204 + + +def test_rest_refuses_a_private_target(alice: Any) -> None: + with resolving_to("169.254.169.254"): + response = Client().post( + BASE, {"url": URL, "events": ["x"]}, content_type="application/json", **_bearer(alice) + ) + assert response.status_code == 400 + + +def test_rest_needs_a_credential(db: None) -> None: + assert Client().get(BASE).status_code == 401 + + +def test_graphql_round_trip(alice: Any) -> None: + client = Client() + create = 'mutation { createWebhookEndpoint(url: "' + URL + '", events: ["a.b"]) { id secret } }' + made = client.post( + "/graphql", {"query": create}, content_type="application/json", **_bearer(alice) + ).json() + endpoint_id = made["data"]["createWebhookEndpoint"]["id"] + + listed = client.post( + "/graphql", + {"query": "{ webhookEndpoints { id events } }"}, + content_type="application/json", + **_bearer(alice), + ).json() + assert listed["data"]["webhookEndpoints"] == [{"id": endpoint_id, "events": ["a.b"]}] + + +@pytest.fixture +def carol(transactional_db: None) -> Any: + return get_user_model().objects.create_user(username="carol", email="carol@example.test") + + +def test_grpc_round_trip(carol: Any, grpc_call: Callable[..., Any]) -> None: + Stub = webhooks_pb2_grpc.WebhookControllerStub + token = access_token(carol) + made = grpc_call(Stub, "Create", webhooks_pb2.CreateRequest(url=URL, events=["a.b"]), token) + listed = grpc_call(Stub, "List", Empty(), token) + + assert [row.id for row in listed.endpoints] == [made.id] + with pytest.raises(grpc.aio.AioRpcError) as refusal: + grpc_call(Stub, "Delete", webhooks_pb2.DeleteRequest(endpoint_id="nope"), token) + assert refusal.value.code() is grpc.StatusCode.NOT_FOUND diff --git a/src/django_ninja_starter/template/src/apps/webhooks/tests/test_services.py b/src/django_ninja_starter/template/src/apps/webhooks/tests/test_services.py new file mode 100644 index 0000000..cb4f2d7 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/webhooks/tests/test_services.py @@ -0,0 +1,133 @@ +"""Signing, the SSRF guard, and the retry schedule.""" + +import hashlib +import hmac +import urllib.error +from datetime import timedelta +from typing import Any +from unittest import mock + +import pytest +from django.core.management import call_command +from django.utils import timezone + +from apps.webhooks import services +from apps.webhooks.models import Delivery, DeliveryStatus +from apps.webhooks.tests.conftest import resolving_to +from infrastructure.common.errors import ApiError + +URL = "https://hooks.example.test/in" + + +def test_the_signature_is_hmac_sha256_over_timestamp_and_body() -> None: + expected = hmac.new(b"key", b"1700000000.{}", hashlib.sha256).hexdigest() + + assert services.sign("key", 1700000000, b"{}") == f"t=1700000000,v1={expected}" + + +@pytest.mark.parametrize( + "address", + [ + "127.0.0.1", + "10.0.0.5", + "192.168.1.1", + "169.254.169.254", + "::1", + "fe80::1", + "::ffff:10.0.0.1", + ], +) +def test_private_loopback_and_link_local_targets_are_refused(address: str) -> None: + with resolving_to(address), pytest.raises(services.UnsafeTarget): + services.assert_public_target(URL) + + +def test_plain_http_is_refused() -> None: + with pytest.raises(services.UnsafeTarget): + services.assert_public_target("http://hooks.example.test/in") + + +def test_registration_refuses_an_unsafe_url(alice: Any) -> None: + with resolving_to("127.0.0.1"), pytest.raises(ApiError): + services.create_endpoint(alice, URL, ["order.paid"]) + + +def test_registration_refuses_malformed_event_types(alice: Any) -> None: + with pytest.raises(ApiError): + services.create_endpoint(alice, URL, ["Not An Event"]) + + +def _queued(user: Any) -> Delivery: + services.create_endpoint(user, URL, ["order.paid"]) + (delivery,) = services.emit(user, "order.paid", {"order": 1}) + return delivery + + +def test_emit_queues_only_for_subscribed_endpoints(alice: Any, bob: Any) -> None: + services.create_endpoint(alice, URL, ["order.paid"]) + services.create_endpoint(bob, URL, ["order.paid"]) + + assert len(services.emit(alice, "order.paid", {})) == 1 + assert services.emit(alice, "order.refunded", {}) == [] + + +def _response(status: int) -> Any: + response = mock.MagicMock(status=status) + response.__enter__.return_value = response + return response + + +def test_a_delivery_is_signed_and_recorded(alice: Any) -> None: + delivery = _queued(alice) + with mock.patch.object(services._opener, "open", return_value=_response(204)) as sent: + assert services.deliver_due() == 1 + + request = sent.call_args.args[0] + timestamp = request.get_header("X-webhook-signature").split(",")[0][2:] + assert request.get_header("X-webhook-signature") == services.sign( + delivery.endpoint.secret, int(timestamp), request.data + ) + delivery.refresh_from_db() + assert delivery.status == DeliveryStatus.SUCCEEDED + assert delivery.attempt_log.get().status_code == 204 + + +def test_a_failure_backs_off_exponentially_then_gives_up(alice: Any, settings: Any) -> None: + settings.WEBHOOKS_MAX_ATTEMPTS = 3 + settings.WEBHOOKS_BACKOFF_SECONDS = 10 + delivery = _queued(alice) + failure = urllib.error.HTTPError(URL, 500, "boom", {}, None) # type: ignore[arg-type] + waits = [] + with mock.patch.object(services._opener, "open", side_effect=failure): + for _ in range(3): + before = timezone.now() + services.attempt(Delivery.objects.select_related("endpoint").get(id=delivery.id)) + delivery.refresh_from_db() + if delivery.next_attempt_at: + waits.append(round((delivery.next_attempt_at - before).total_seconds())) + + assert waits == [10, 20] + assert delivery.status == DeliveryStatus.FAILED + assert [a.status_code for a in delivery.attempt_log.all()] == [500, 500, 500] + + +def test_the_ssrf_guard_runs_again_at_send_time(alice: Any) -> None: + delivery = _queued(alice) + with resolving_to("10.0.0.7"), mock.patch.object(services._opener, "open") as sent: + services.deliver_due() + + sent.assert_not_called() + delivery.refresh_from_db() + assert "private" in delivery.attempt_log.get().error + assert delivery.status == DeliveryStatus.PENDING + + +def test_deliveries_not_yet_due_wait(alice: Any) -> None: + delivery = _queued(alice) + Delivery.objects.filter(id=delivery.id).update( + next_attempt_at=timezone.now() + timedelta(minutes=5) + ) + with mock.patch.object(services._opener, "open") as sent: + call_command("webhooks_deliver") + + sent.assert_not_called() diff --git a/src/django_ninja_starter/template/src/config/api.py b/src/django_ninja_starter/template/src/config/api.py index 4cf4c85..2ccd527 100644 --- a/src/django_ninja_starter/template/src/config/api.py +++ b/src/django_ninja_starter/template/src/config/api.py @@ -47,6 +47,7 @@ def build_apis() -> dict[str, NinjaAPI]: *settings.SHOP_ROUTERS, *settings.SUPPORT_ROUTERS, *settings.WALLET_ROUTERS, + *settings.WEBHOOKS_ROUTERS, ] guarded = {id(route["router"]) for route in credential_routes} api = EnvelopeAPI( diff --git a/src/django_ninja_starter/template/src/config/settings/base.py b/src/django_ninja_starter/template/src/config/settings/base.py index 156596d..cbcbd3b 100644 --- a/src/django_ninja_starter/template/src/config/settings/base.py +++ b/src/django_ninja_starter/template/src/config/settings/base.py @@ -903,6 +903,35 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: # app was installed to serve REST only. An app absent from this mapping -- every # infrastructure app -- publishes whatever it has, because the transports there # are the project's own and are turned off by the global flags below. +# Outgoing webhooks. Optional like every feature app: naming it installs its +# tables and routes. Deliveries are sent by `manage.py webhooks_deliver`, which +# a scheduler runs; nothing is sent from inside a request. +WEBHOOKS_ENABLED = os.getenv("DJANGO_WEBHOOKS_ENABLED", "false").lower() == "true" +WEBHOOKS_APP = "apps.webhooks.apps.WebhooksConfig" +WEBHOOKS_INSTALLED_APPS = [WEBHOOKS_APP] if WEBHOOKS_ENABLED else [] +WEBHOOKS_TRANSPORTS = ( + app_transports("webhooks", ("rest", "graph", "grpc")) if WEBHOOKS_ENABLED else () +) +WEBHOOKS_ROUTERS = ( + [ + { + "prefix": "/webhooks", + "router": "apps.webhooks.rest.router", + "tag": "Webhooks", + "description": ( + "Register https endpoints to be told about this account's events. " + "Every delivery is signed with HMAC-SHA256 in `X-Webhook-Signature`, " + "retried with exponential backoff, and every attempt is recorded." + ), + } + ] + if "rest" in WEBHOOKS_TRANSPORTS + else [] +) +WEBHOOKS_MAX_ATTEMPTS = int(os.getenv("DJANGO_WEBHOOKS_MAX_ATTEMPTS", "6")) +WEBHOOKS_BACKOFF_SECONDS = int(os.getenv("DJANGO_WEBHOOKS_BACKOFF_SECONDS", "30")) +WEBHOOKS_TIMEOUT_SECONDS = int(os.getenv("DJANGO_WEBHOOKS_TIMEOUT_SECONDS", "10")) + APP_TRANSPORTS = { "apps.cms": CMS_TRANSPORTS, "apps.notifications": NOTIFICATIONS_TRANSPORTS, @@ -910,6 +939,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: "apps.support": SUPPORT_TRANSPORTS, "apps.wallet": WALLET_TRANSPORTS, "apps.club": CLUB_TRANSPORTS, + "apps.webhooks": WEBHOOKS_TRANSPORTS, } # How often one caller may ask, whichever endpoint they are asking. A correct @@ -1022,6 +1052,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: *SUPPORT_INSTALLED_APPS, *WALLET_INSTALLED_APPS, *CLUB_INSTALLED_APPS, + *WEBHOOKS_INSTALLED_APPS, # The transports beside REST. Both are installed whether or not they are # published: `generateproto` and the schema check have to be able to run in a # deployment that serves neither. diff --git a/src/django_ninja_starter/template/src/config/settings/test.py b/src/django_ninja_starter/template/src/config/settings/test.py index 474cdb6..b52d4ab 100644 --- a/src/django_ninja_starter/template/src/config/settings/test.py +++ b/src/django_ninja_starter/template/src/config/settings/test.py @@ -6,6 +6,7 @@ os.environ.setdefault("DJANGO_SUPPORT_ENABLED", "true") os.environ.setdefault("DJANGO_WALLET_ENABLED", "true") os.environ.setdefault("DJANGO_CLUB_ENABLED", "true") +os.environ.setdefault("DJANGO_WEBHOOKS_ENABLED", "true") os.environ.setdefault("DJANGO_OAUTH_MODE", "all") os.environ.setdefault("DJANGO_AUTH_TOKEN_MODE", "rotation") os.environ.setdefault("DJANGO_AUTH_METHODS", "password,email_code,sms_code,magic_link") diff --git a/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py b/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py index b1f0e18..9d54807 100644 --- a/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py +++ b/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py @@ -43,7 +43,7 @@ # and still get a page: the foundation every project carries, the accounts it # resolves to, and the optional feature apps. PROJECT_LABELS = frozenset( - {"accounts", "common", "cms", "club", "notifications", "shop", "support", "wallet"} + {"accounts", "common", "cms", "club", "notifications", "shop", "support", "wallet", "webhooks"} ) NONE = "_None._" diff --git a/src/infrastructure/common/management/commands/authdocs.py b/src/infrastructure/common/management/commands/authdocs.py index b1f0e18..9d54807 100644 --- a/src/infrastructure/common/management/commands/authdocs.py +++ b/src/infrastructure/common/management/commands/authdocs.py @@ -43,7 +43,7 @@ # and still get a page: the foundation every project carries, the accounts it # resolves to, and the optional feature apps. PROJECT_LABELS = frozenset( - {"accounts", "common", "cms", "club", "notifications", "shop", "support", "wallet"} + {"accounts", "common", "cms", "club", "notifications", "shop", "support", "wallet", "webhooks"} ) NONE = "_None._" diff --git a/tests/test_env_samples.py b/tests/test_env_samples.py index 31cfc04..0392250 100644 --- a/tests/test_env_samples.py +++ b/tests/test_env_samples.py @@ -29,7 +29,7 @@ EXAMPLE_SAMPLE = ROOT / "examples" / "env.example" SETTINGS = ROOT / "src" / "config" / "settings" / "base.py" -FEATURE_APPS = ("CMS", "NOTIFICATIONS", "SHOP", "SUPPORT", "WALLET", "CLUB") +FEATURE_APPS = ("CMS", "NOTIFICATIONS", "SHOP", "SUPPORT", "WALLET", "CLUB", "WEBHOOKS") def flag(sample: Path, app: str) -> str | None: From 3e3c1a4cf232cb4ca0e92ebf27cb30b04fa769ac Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Thu, 26 Nov 2026 18:10:58 +0330 Subject: [PATCH 8/8] =?UTF-8?q?=F0=9F=93=A6=20add(files):=20owned=20file?= =?UTF-8?q?=20uploads=20over=20REST,=20GraphQL=20and=20gRPC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New optional app apps.files (DJANGO_FILES_ENABLED): size limit checked before reading, content type sniffed from magic bytes and matched against the extension, random storage keys, owner-or-staff access (others get 404). Storage via Django's storage API; DJANGO_STORAGE_BACKEND=s3 uses django-storages (new [s3] extra). Shared naming/size/sniff helpers extracted from apps/support/uploads.py into infrastructure/common/uploads.py. Mirrored into the template. --- .env.example | 14 + Makefile | 2 +- README.md | 1 + docs/README.md | 3 +- docs/files.md | 72 +++++ examples/env.example | 14 + pyproject.toml | 2 + src/apps/files/__init__.py | 0 src/apps/files/admin.py | 29 ++ src/apps/files/adminui.py | 42 +++ src/apps/files/apps.py | 42 +++ src/apps/files/graph/__init__.py | 5 + src/apps/files/graph/schema.py | 93 ++++++ src/apps/files/graph/types.py | 35 +++ src/apps/files/grpc/__init__.py | 5 + src/apps/files/grpc/files.proto | 60 ++++ src/apps/files/grpc/files_pb2.py | 54 ++++ src/apps/files/grpc/files_pb2.pyi | 228 +++++++++++++++ src/apps/files/grpc/files_pb2_grpc.py | 269 ++++++++++++++++++ src/apps/files/grpc/files_pb2_grpc.pyi | 85 ++++++ src/apps/files/grpc/serializers.py | 14 + src/apps/files/grpc/services.py | 123 ++++++++ src/apps/files/migrations/0001_initial.py | 65 +++++ src/apps/files/migrations/__init__.py | 0 src/apps/files/models.py | 47 +++ src/apps/files/rest/__init__.py | 5 + src/apps/files/rest/schemas.py | 29 ++ src/apps/files/rest/v1.py | 79 +++++ src/apps/files/services.py | 150 ++++++++++ src/apps/files/tests/__init__.py | 0 src/apps/files/tests/conftest.py | 45 +++ src/apps/files/tests/test_api.py | 61 ++++ src/apps/files/tests/test_graph.py | 49 ++++ src/apps/files/tests/test_grpc.py | 41 +++ src/apps/files/tests/test_services.py | 82 ++++++ src/apps/files/tests/test_uploads.py | 40 +++ src/apps/support/uploads.py | 39 +-- src/config/api.py | 1 + src/config/settings/base.py | 55 ++++ src/config/settings/test.py | 1 + src/django_ninja_starter/template/Makefile | 2 +- .../template/_env.example | 14 + .../template/docs/README.md | 3 +- .../template/docs/files.md | 72 +++++ .../template/pyproject.toml | 2 + .../template/src/apps/files/__init__.py | 0 .../template/src/apps/files/admin.py | 29 ++ .../template/src/apps/files/adminui.py | 42 +++ .../template/src/apps/files/apps.py | 42 +++ .../template/src/apps/files/graph/__init__.py | 5 + .../template/src/apps/files/graph/schema.py | 93 ++++++ .../template/src/apps/files/graph/types.py | 35 +++ .../template/src/apps/files/grpc/__init__.py | 5 + .../template/src/apps/files/grpc/files.proto | 60 ++++ .../template/src/apps/files/grpc/files_pb2.py | 54 ++++ .../src/apps/files/grpc/files_pb2.pyi | 228 +++++++++++++++ .../src/apps/files/grpc/files_pb2_grpc.py | 269 ++++++++++++++++++ .../src/apps/files/grpc/files_pb2_grpc.pyi | 85 ++++++ .../src/apps/files/grpc/serializers.py | 14 + .../template/src/apps/files/grpc/services.py | 123 ++++++++ .../src/apps/files/migrations/0001_initial.py | 65 +++++ .../src/apps/files/migrations/__init__.py | 0 .../template/src/apps/files/models.py | 47 +++ .../template/src/apps/files/rest/__init__.py | 5 + .../template/src/apps/files/rest/schemas.py | 29 ++ .../template/src/apps/files/rest/v1.py | 79 +++++ .../template/src/apps/files/services.py | 150 ++++++++++ .../template/src/apps/files/tests/__init__.py | 0 .../template/src/apps/files/tests/conftest.py | 45 +++ .../template/src/apps/files/tests/test_api.py | 61 ++++ .../src/apps/files/tests/test_graph.py | 49 ++++ .../src/apps/files/tests/test_grpc.py | 41 +++ .../src/apps/files/tests/test_services.py | 82 ++++++ .../src/apps/files/tests/test_uploads.py | 40 +++ .../template/src/apps/support/uploads.py | 39 +-- .../template/src/config/api.py | 1 + .../template/src/config/settings/base.py | 55 ++++ .../template/src/config/settings/test.py | 1 + .../common/management/commands/authdocs.py | 13 +- .../src/infrastructure/common/uploads.py | 88 ++++++ .../common/management/commands/authdocs.py | 13 +- src/infrastructure/common/uploads.py | 88 ++++++ tests/test_app_isolation.py | 3 +- tests/test_env_samples.py | 2 +- 84 files changed, 4074 insertions(+), 80 deletions(-) create mode 100644 docs/files.md create mode 100644 src/apps/files/__init__.py create mode 100644 src/apps/files/admin.py create mode 100644 src/apps/files/adminui.py create mode 100644 src/apps/files/apps.py create mode 100644 src/apps/files/graph/__init__.py create mode 100644 src/apps/files/graph/schema.py create mode 100644 src/apps/files/graph/types.py create mode 100644 src/apps/files/grpc/__init__.py create mode 100644 src/apps/files/grpc/files.proto create mode 100644 src/apps/files/grpc/files_pb2.py create mode 100644 src/apps/files/grpc/files_pb2.pyi create mode 100644 src/apps/files/grpc/files_pb2_grpc.py create mode 100644 src/apps/files/grpc/files_pb2_grpc.pyi create mode 100644 src/apps/files/grpc/serializers.py create mode 100644 src/apps/files/grpc/services.py create mode 100644 src/apps/files/migrations/0001_initial.py create mode 100644 src/apps/files/migrations/__init__.py create mode 100644 src/apps/files/models.py create mode 100644 src/apps/files/rest/__init__.py create mode 100644 src/apps/files/rest/schemas.py create mode 100644 src/apps/files/rest/v1.py create mode 100644 src/apps/files/services.py create mode 100644 src/apps/files/tests/__init__.py create mode 100644 src/apps/files/tests/conftest.py create mode 100644 src/apps/files/tests/test_api.py create mode 100644 src/apps/files/tests/test_graph.py create mode 100644 src/apps/files/tests/test_grpc.py create mode 100644 src/apps/files/tests/test_services.py create mode 100644 src/apps/files/tests/test_uploads.py create mode 100644 src/django_ninja_starter/template/docs/files.md create mode 100644 src/django_ninja_starter/template/src/apps/files/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/files/admin.py create mode 100644 src/django_ninja_starter/template/src/apps/files/adminui.py create mode 100644 src/django_ninja_starter/template/src/apps/files/apps.py create mode 100644 src/django_ninja_starter/template/src/apps/files/graph/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/files/graph/schema.py create mode 100644 src/django_ninja_starter/template/src/apps/files/graph/types.py create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/files.proto create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.py create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.pyi create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.py create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.pyi create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/serializers.py create mode 100644 src/django_ninja_starter/template/src/apps/files/grpc/services.py create mode 100644 src/django_ninja_starter/template/src/apps/files/migrations/0001_initial.py create mode 100644 src/django_ninja_starter/template/src/apps/files/migrations/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/files/models.py create mode 100644 src/django_ninja_starter/template/src/apps/files/rest/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/files/rest/schemas.py create mode 100644 src/django_ninja_starter/template/src/apps/files/rest/v1.py create mode 100644 src/django_ninja_starter/template/src/apps/files/services.py create mode 100644 src/django_ninja_starter/template/src/apps/files/tests/__init__.py create mode 100644 src/django_ninja_starter/template/src/apps/files/tests/conftest.py create mode 100644 src/django_ninja_starter/template/src/apps/files/tests/test_api.py create mode 100644 src/django_ninja_starter/template/src/apps/files/tests/test_graph.py create mode 100644 src/django_ninja_starter/template/src/apps/files/tests/test_grpc.py create mode 100644 src/django_ninja_starter/template/src/apps/files/tests/test_services.py create mode 100644 src/django_ninja_starter/template/src/apps/files/tests/test_uploads.py create mode 100644 src/django_ninja_starter/template/src/infrastructure/common/uploads.py create mode 100644 src/infrastructure/common/uploads.py diff --git a/.env.example b/.env.example index 4202642..9b50834 100644 --- a/.env.example +++ b/.env.example @@ -113,6 +113,20 @@ DJANGO_SUPPORT_UPLOAD_EXTENSIONS= # Zero keeps everything. Set a window and schedule `manage.py support_prune`; # nothing deletes a customer's support history until you run it. DJANGO_SUPPORT_RETENTION_DAYS=0 +DJANGO_FILES_ENABLED=true +# DJANGO_FILES_TRANSPORTS=rest,graph,grpc +# A prefix inside STORAGES["default"], not a filesystem path. +DJANGO_FILES_UPLOAD_PATH=files +# The largest file anybody may upload. Zero means no limit. +DJANGO_FILES_MAX_UPLOAD_MB=10 +# Where uploads are stored: `filesystem` (MEDIA_ROOT) or `s3` (needs +# `pip install '.[s3]'` and the bucket settings below). +DJANGO_STORAGE_BACKEND=filesystem +DJANGO_AWS_STORAGE_BUCKET_NAME= +DJANGO_AWS_S3_REGION_NAME= +DJANGO_AWS_S3_ENDPOINT_URL= +DJANGO_AWS_ACCESS_KEY_ID= +DJANGO_AWS_SECRET_ACCESS_KEY= DJANGO_SHOP_ENABLED=true # DJANGO_SHOP_TRANSPORTS=rest,graph,grpc DJANGO_SHOP_CURRENCY=USD diff --git a/Makefile b/Makefile index 200dd2e..de5c19c 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ install: # Every optional app turned on, so the checks below see the whole project # rather than whatever this developer happens to have in their `.env`. An app # left off is an app whose models, admin, migrations and protos nobody checked. -ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true DJANGO_WEBHOOKS_ENABLED=true +ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true DJANGO_WEBHOOKS_ENABLED=true DJANGO_FILES_ENABLED=true check: ruff check --no-cache . diff --git a/README.md b/README.md index 7da1500..ac5cf40 100644 --- a/README.md +++ b/README.md @@ -401,6 +401,7 @@ another Django project or deleted from this one without leaving a hole. | [`cms`](docs/cms.md) | `DJANGO_CMS_ENABLED=true` | Pages made of sections made of typed, translatable fields; a library of shared sections; menus; drafts, schedules and signed preview links; export/import for moving content between environments; and a content-editing admin screen separate from the structural one | | [`notifications`](docs/notifications.md) | `DJANGO_NOTIFICATIONS_ENABLED=true` | A notification table addressed to one account or to everybody; per-account read and dismiss receipts, so a broadcast is read and cleared by each person separately; a scoped read API with the same surface over REST, GraphQL, gRPC and a WebSocket that pushes new ones on save and keeps a second device in step; and a retention command | | [`support`](docs/support.md) | `DJANGO_SUPPORT_ENABLED=true` | Chat and support tickets as one thing, because a ticket is a conversation: live chat and filed tickets with staff-only notes, attachments, SLA-carrying categories, a queue with assignment, priorities and tags — plus open **channels**, private **groups** and one-to-one **direct messages** that staff have no more right to read than anyone else. Read state per participant, and one authenticated WebSocket carrying every conversation an account is in | +| [`files`](docs/files.md) | `DJANGO_FILES_ENABLED=true` | Owned file uploads through Django's storage API -- local disk by default, S3 via django-storages -- with a size limit, content types sniffed rather than trusted, random storage names, and owner-or-staff access over REST, GraphQL and gRPC | | [`shop`](docs/shop.md) | `DJANGO_SHOP_ENABLED=true` | A catalogue whose categories declare the attributes their products answer; products, variants and stock; timed discount campaigns; search, filters and named listings; reviews and likes; a basket per account; a saved address book and delivery options costed against that basket; and an order, coupon and payment cycle that reserves stock when the order is placed | | [`wallet`](docs/wallet.md) | `DJANGO_WALLET_ENABLED=true` | A wallet per account whose balance is derived from its movements rather than stored beside them; deposits, withdrawals and free wallet-to-wallet transfers; payment methods, currencies, limits, commissions and taxes an administrator configures rather than code declares; crypto with per-chain fees, confirmations and address checks; currency conversion at a published rate and spread; and an approval flow that leaves a movement a request until an operator applies it | diff --git a/docs/README.md b/docs/README.md index cfdd651..435c5e4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,7 +15,7 @@ themselves — see [keeping these pages honest](#keeping-these-pages-honest). | Social providers | [`oauth_google`](oauth/google.md), [`oauth_apple`](oauth/apple.md), [`oauth_microsoft`](oauth/microsoft.md), [`oauth_github`](oauth/github.md) | | Token modes | [`oauth_sliding`](oauth/sliding.md), [`oauth_session`](oauth/session.md), [`oauth_rotation`](oauth/rotation.md) | | Shared by those | [`auth_core`](auth/core.md), [`oauth_core`](oauth/core.md) | -| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md), [`webhooks`](webhooks.md), [`notes`](notes.md) | +| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md), [`webhooks`](webhooks.md), [`files`](files.md), [`notes`](notes.md) | | Cross-cutting | [The response envelope](responses.md), [Signing in](signing-in.md), [Credentials](credentials.md), [The admin](admin.md) | ## Start here @@ -108,6 +108,7 @@ features a project chooses rather than the plumbing under them. | [`wallet`](wallet.md) | `DJANGO_WALLET_ENABLED=true` | A wallet per account with the balance derived from its movements rather than stored, payment methods an administrator configures rather than code declares, fees and taxes priced by the same function that quotes them, crypto with its chains, currency conversion at a published rate, and deposits that stay requests until an operator applies them | | [`club`](club.md) | `DJANGO_CLUB_ENABLED=true` | Clubs with a levelled ladder, an account in one club at a time, XP derived from an immutable award ledger rather than stored, and missions that complete themselves from events the other apps emit -- including events an app of your own registers, which is what lets a mission be built out of code this starter has never seen | | [`webhooks`](webhooks.md) | `DJANGO_WEBHOOKS_ENABLED=true` | Outgoing webhooks: https endpoints per account with their own secret and event types, HMAC-SHA256-signed deliveries retried with exponential backoff by `manage.py webhooks_deliver`, every attempt recorded, and private, loopback and link-local targets refused at send time | +| [`files`](files.md) | `DJANGO_FILES_ENABLED=true` | Owned file uploads through Django's storage API (local or S3): sniffed content types, random storage names, and owner-or-staff access over REST, GraphQL and gRPC | | [`notes`](notes.md) | `manage.py startapi` | Not shipped installed: the worked example of a feature app, one model served at two API versions, built into the example project | All five ship **off** in a generated project, which is why a fresh `/api/docs` diff --git a/docs/files.md b/docs/files.md new file mode 100644 index 0000000..10430eb --- /dev/null +++ b/docs/files.md @@ -0,0 +1,72 @@ +# Files + +Owned file uploads over REST, GraphQL and gRPC. Optional: naming it in +`DJANGO_FILES_ENABLED` installs its table, routes and admin; a project that does +not name it never imports the package. It lives in `src/apps/files`. + +- **Storage** is Django's storage API. `DJANGO_STORAGE_BACKEND=filesystem` (the + default) writes under `MEDIA_ROOT`; `DJANGO_STORAGE_BACKEND=s3` writes to a + private bucket through django-storages (`pip install '.[s3]'`), configured by + `DJANGO_AWS_STORAGE_BUCKET_NAME`, `DJANGO_AWS_S3_REGION_NAME`, + `DJANGO_AWS_S3_ENDPOINT_URL`, `DJANGO_AWS_ACCESS_KEY_ID` and + `DJANGO_AWS_SECRET_ACCESS_KEY`. +- **Validation**: a size limit (`DJANGO_FILES_MAX_UPLOAD_MB`) checked before the + content is read, then the content type sniffed from the first bytes. The + extension must be one the sniffed type is known by, so a renamed file is + refused. Accepted: PNG, JPEG, GIF, WebP, PDF, zip (and Office documents), + gzip, and plain text (`.txt .csv .json .md .log`). Nothing a browser executes. +- **Names**: stored under `/YYYY/MM/DD/.`; + the uploader's name is kept on the row and used only as the download filename. +- **Access**: the owner and staff may list, read, download and delete. Anybody + else gets 404, the same as a missing id. Downloads are always attachments. +- Uploads share the `upload` rate-limit scope (`DJANGO_API_THROTTLE_UPLOAD`). + +## Routes + + +| Method | Path | Auth | Purpose | +| --- | --- | --- | --- | +| `GET` | `/api/v1/files` | Bearer | List files this account may see | +| `POST` | `/api/v1/files` | Bearer | Upload a file | +| `DELETE` | `/api/v1/files/{file_id}` | Bearer | Delete one file | +| `GET` | `/api/v1/files/{file_id}` | Bearer | Read one file's metadata | +| `GET` | `/api/v1/files/{file_id}/download` | Bearer | Download one file's bytes | + + +GraphQL: `files`, `file`, `fileContent` (base64), `uploadFile(name, contentBase64)`, +`deleteFile`. gRPC: `FileController` with `List`, `Get`, `Upload`, `Download`, +`Delete`, the bytes as a protobuf `bytes` field. + +## Models + + +#### `StoredFile` + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | UUID | primary key, not editable | +| `owner` | ForeignKey | → `accounts.User` | +| `name` | Char | | +| `storage_key` | Char | unique, not editable | +| `content_type` | Char | | +| `size` | PositiveBigInteger | | +| `created_at` | DateTime | not editable | + + +## Admin + + +| Model | Editable | Actions | Columns | +| --- | --- | --- | --- | +| `StoredFile` | Yes | — | `name`, `owner`, `content_type`, `size`, `created_at` | + + +## Settings + + +| Environment variable | Required | Purpose | +| --- | --- | --- | +| `DJANGO_FILES_ENABLED` | **Yes** | whether this deployment carries file uploads at all. | +| `DJANGO_FILES_UPLOAD_PATH` | **Yes** | the folder or key prefix inside the configured storage files go under. | +| `DJANGO_FILES_MAX_UPLOAD_MB` | Optional | the largest file anybody may upload, in megabytes; zero means no limit. 0 or more. | + diff --git a/examples/env.example b/examples/env.example index e291d17..194f66d 100644 --- a/examples/env.example +++ b/examples/env.example @@ -212,6 +212,20 @@ DJANGO_SUPPORT_UPLOAD_EXTENSIONS= # scheduled. Zero keeps everything, which is the only safe default for a # customer's support history. DJANGO_SUPPORT_RETENTION_DAYS=0 +DJANGO_FILES_ENABLED=true +# DJANGO_FILES_TRANSPORTS=rest,graph,grpc +# A prefix inside STORAGES["default"], not a filesystem path. +DJANGO_FILES_UPLOAD_PATH=files +# The largest file anybody may upload. Zero means no limit. +DJANGO_FILES_MAX_UPLOAD_MB=10 +# Where uploads are stored: `filesystem` (MEDIA_ROOT) or `s3` (needs +# `pip install '.[s3]'` and the bucket settings below). +DJANGO_STORAGE_BACKEND=filesystem +DJANGO_AWS_STORAGE_BUCKET_NAME= +DJANGO_AWS_S3_REGION_NAME= +DJANGO_AWS_S3_ENDPOINT_URL= +DJANGO_AWS_ACCESS_KEY_ID= +DJANGO_AWS_SECRET_ACCESS_KEY= # --------------------------------------------------------------------------- # The wallet. One per account, with the balance derived from the movements diff --git a/pyproject.toml b/pyproject.toml index 4bf2c18..0717aa7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,6 +54,8 @@ Documentation = "https://github.com/CtrlAltDevelop/django-ninja-starter/tree/mai django-ninja-starter = "django_ninja_starter.cli:main" [project.optional-dependencies] +# The S3 backend for DJANGO_STORAGE_BACKEND=s3. +s3 = ["django-storages[s3]>=1.14,<2.0"] dev = [ "Django>=5.2,<7.0", "cryptography>=45,<51", diff --git a/src/apps/files/__init__.py b/src/apps/files/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/files/admin.py b/src/apps/files/admin.py new file mode 100644 index 0000000..3715ec4 --- /dev/null +++ b/src/apps/files/admin.py @@ -0,0 +1,29 @@ +"""The admin: who uploaded what. Read-only, because a file's metadata is a record +of what was sniffed and stored, and editing it by hand would make it a lie. +Deleting a row deletes its bytes (see the model's ``post_delete``).""" + +from typing import Any + +from django.contrib import admin +from django.http import HttpRequest + +from apps.files.models import StoredFile + +try: # pragma: no cover - exercised by whichever branch the project installs + from unfold.admin import ModelAdmin +except ImportError: # pragma: no cover - only in a project without Unfold + from django.contrib.admin import ModelAdmin + + +@admin.register(StoredFile) +class StoredFileAdmin(ModelAdmin): + list_display = ("name", "owner", "content_type", "size", "created_at") + list_filter = ("content_type",) + search_fields = ("name", "owner__username", "owner__email") + readonly_fields = ("id", "owner", "name", "storage_key", "content_type", "size", "created_at") + + def has_add_permission(self, request: HttpRequest) -> bool: + return False + + def has_change_permission(self, request: HttpRequest, obj: Any = None) -> bool: + return False diff --git a/src/apps/files/adminui.py b/src/apps/files/adminui.py new file mode 100644 index 0000000..d5dd65e --- /dev/null +++ b/src/apps/files/adminui.py @@ -0,0 +1,42 @@ +"""This app's sidebar group and dashboard numbers. See :mod:`infrastructure.common.adminui`.""" + +from typing import Any + +from django.db.models import Sum +from django.http import HttpRequest + +from infrastructure.common.adminui import Section, card, changelist, item, may + +NAVIGATION_ORDER = 45 +DASHBOARD_ORDER = 45 + + +def navigation(request: HttpRequest) -> dict[str, Any]: + return { + "title": "Files", + "separator": False, + "collapsible": False, + "items": [ + item("Files", "folder", changelist("files", "storedfile"), "files.view_storedfile"), + ], + } + + +def dashboard(request: HttpRequest) -> Section | None: + if not may(request, "files.view_storedfile"): + return None + from apps.files.models import StoredFile + + totals = StoredFile.objects.aggregate(size=Sum("size")) + return Section( + title="Files", + cards=[ + card( + "Stored files", + StoredFile.objects.count(), + hint=f"{(totals['size'] or 0) // (1024 * 1024)} MB in storage", + icon="folder", + link=changelist("files", "storedfile"), + ), + ], + ) diff --git a/src/apps/files/apps.py b/src/apps/files/apps.py new file mode 100644 index 0000000..b174c16 --- /dev/null +++ b/src/apps/files/apps.py @@ -0,0 +1,42 @@ +from django.apps import AppConfig + +from infrastructure.common.appsettings import AppSettings, Requirement + + +class FilesConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.files" + label = "files" + verbose_name = "Files" + + settings_spec = AppSettings( + title="Files", + summary=( + "Owned file uploads over REST, GraphQL and gRPC, stored through Django's " + "storage API: local disk by default, S3 when configured." + ), + requirements=( + Requirement( + "FILES_ENABLED", + env="DJANGO_FILES_ENABLED", + purpose="whether this deployment carries file uploads at all", + required=True, + hint=( + "The app is installed, so something put it in INSTALLED_APPS while " + "DJANGO_FILES_ENABLED was off. Set it to true, or drop the app." + ), + ), + Requirement( + "FILES_UPLOAD_PATH", + env="DJANGO_FILES_UPLOAD_PATH", + purpose="the folder or key prefix inside the configured storage files go under", + required=True, + ), + Requirement( + "FILES_MAX_UPLOAD_MB", + env="DJANGO_FILES_MAX_UPLOAD_MB", + purpose="the largest file anybody may upload, in megabytes; zero means no limit", + minimum=0, + ), + ), + ) diff --git a/src/apps/files/graph/__init__.py b/src/apps/files/graph/__init__.py new file mode 100644 index 0000000..b97fc52 --- /dev/null +++ b/src/apps/files/graph/__init__.py @@ -0,0 +1,5 @@ +"""The GraphQL transport for the files app.""" + +from apps.files.graph.schema import Mutation, Query + +__all__ = ["Mutation", "Query"] diff --git a/src/apps/files/graph/schema.py b/src/apps/files/graph/schema.py new file mode 100644 index 0000000..14be895 --- /dev/null +++ b/src/apps/files/graph/schema.py @@ -0,0 +1,93 @@ +"""The files app's contribution to the project's GraphQL schema. + +GraphQL has no binary type, so bytes travel base64-encoded both ways. The size +limit is checked against the encoded length before decoding, so an oversized +upload costs a rejection rather than the memory to decode it. +""" + +import base64 +import binascii +from typing import Any + +import strawberry +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.files.base import ContentFile +from strawberry.types import Info + +from apps.files import services +from apps.files.graph.types import FileContentType, FilePageType, FileType, file_type +from infrastructure.common.errors import ApiError +from infrastructure.common.graph.errors import require_caller, resolver +from infrastructure.common.identity import caller +from infrastructure.common.responses import ResponseTitle + + +def _caller(info: Info[Any, Any]) -> Any: + return require_caller(caller(info.context.request)) + + +def _found(method: Any, *args: Any) -> Any: + try: + return method(*args) + except services.FileNotFound as error: + raise ApiError("No such file.", status=404, title=ResponseTitle.NOT_FOUND) from error + + +def decode(content_base64: str) -> bytes: + """Decode an upload, refusing one too large before spending memory on it.""" + limit = int(settings.FILES_MAX_UPLOAD_BYTES) + if limit and len(content_base64) * 3 // 4 > limit + 2: + raise ApiError(f"The limit is {limit // 1024} KB.", status=400) + try: + return base64.b64decode(content_base64, validate=True) + except (binascii.Error, ValueError) as error: + raise ApiError("contentBase64 is not valid base64.", status=400) from error + + +@strawberry.type +class Query: + @strawberry.field(description="Files this account may see, newest first.") + @resolver + def files( + self, info: Info[Any, Any], limit: int = services.DEFAULT_PAGE, offset: int = 0 + ) -> FilePageType: + page = services.list_files(_caller(info), limit=limit, offset=offset) + return FilePageType( + files=[file_type(row) for row in page["files"]], + total=page["total"], + limit=page["limit"], + offset=page["offset"], + ) + + @strawberry.field(description="One file's metadata.") + @resolver + def file(self, info: Info[Any, Any], file_id: str) -> FileType: + return file_type(_found(services.get, _caller(info), file_id)) + + @strawberry.field(description="One file's metadata and its bytes, base64-encoded.") + @resolver + def file_content(self, info: Info[Any, Any], file_id: str) -> FileContentType: + meta, content = _found(services.read, _caller(info), file_id) + return FileContentType( + file=file_type(meta), content_base64=base64.b64encode(content).decode() + ) + + +@strawberry.type +class Mutation: + @strawberry.mutation(description="Upload a file. The content is sniffed, not trusted.") + @resolver + def upload_file(self, info: Info[Any, Any], name: str, content_base64: str) -> FileType: + user = _caller(info) + content = decode(content_base64) + try: + return file_type(services.upload(user, name, ContentFile(content), len(content))) + except ValidationError as refused: + raise ApiError("; ".join(refused.messages), status=400) from refused + + @strawberry.mutation(description="Delete one file.") + @resolver + def delete_file(self, info: Info[Any, Any], file_id: str) -> bool: + _found(services.delete, _caller(info), file_id) + return True diff --git a/src/apps/files/graph/types.py b/src/apps/files/graph/types.py new file mode 100644 index 0000000..7b271f2 --- /dev/null +++ b/src/apps/files/graph/types.py @@ -0,0 +1,35 @@ +"""GraphQL types for stored files.""" + +from typing import Any + +import strawberry + + +@strawberry.type +class FileType: + id: str + owner_id: str + name: str + content_type: str + size: int + created_at: str + + +@strawberry.type +class FilePageType: + files: list[FileType] + total: int + limit: int + offset: int + + +@strawberry.type +class FileContentType: + """A file and its bytes, base64-encoded because GraphQL has no binary scalar.""" + + file: FileType + content_base64: str + + +def file_type(row: dict[str, Any]) -> FileType: + return FileType(**row) diff --git a/src/apps/files/grpc/__init__.py b/src/apps/files/grpc/__init__.py new file mode 100644 index 0000000..889fde6 --- /dev/null +++ b/src/apps/files/grpc/__init__.py @@ -0,0 +1,5 @@ +"""The gRPC transport for the files app. + +The generated stubs live here beside the ``.proto`` that produced them. +Regenerate with ``python manage.py protos``. +""" diff --git a/src/apps/files/grpc/files.proto b/src/apps/files/grpc/files.proto new file mode 100644 index 0000000..3a06cbe --- /dev/null +++ b/src/apps/files/grpc/files.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package config.files; + +service FileController { + rpc Delete(DeleteRequest) returns (DeleteResult) {} + rpc Download(DownloadRequest) returns (FileContent) {} + rpc Get(GetRequest) returns (StoredFile) {} + rpc List(ListRequest) returns (FileList) {} + rpc Upload(UploadRequest) returns (StoredFile) {} +} + +message DeleteRequest { + string file_id = 1; +} + +message DeleteResult { + string id = 1; + bool deleted = 2; +} + +message DownloadRequest { + string file_id = 1; +} + +message FileContent { + StoredFile file = 1; + bytes content = 2; +} + +message FileList { + repeated StoredFile files = 1; + int32 total = 2; + int32 limit = 3; + int32 offset = 4; +} + +message GetRequest { + string file_id = 1; +} + +message ListRequest { + int32 limit = 1; + int32 offset = 2; +} + +message StoredFile { + string id = 1; + string owner_id = 2; + string name = 3; + string content_type = 4; + int32 size = 5; + string created_at = 6; +} + +message UploadRequest { + string name = 1; + bytes content = 2; +} + diff --git a/src/apps/files/grpc/files_pb2.py b/src/apps/files/grpc/files_pb2.py new file mode 100644 index 0000000..dfc7db5 --- /dev/null +++ b/src/apps/files/grpc/files_pb2.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: apps/files/grpc/files.proto +# Protobuf Python Version: 7.35.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 7, + 35, + 1, + '', + 'apps/files/grpc/files.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1b\x61pps/files/grpc/files.proto\x12\x0c\x63onfig.files\" \n\rDeleteRequest\x12\x0f\n\x07\x66ile_id\x18\x01 \x01(\t\"+\n\x0c\x44\x65leteResult\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0f\n\x07\x64\x65leted\x18\x02 \x01(\x08\"\"\n\x0f\x44ownloadRequest\x12\x0f\n\x07\x66ile_id\x18\x01 \x01(\t\"F\n\x0b\x46ileContent\x12&\n\x04\x66ile\x18\x01 \x01(\x0b\x32\x18.config.files.StoredFile\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\x0c\"a\n\x08\x46ileList\x12\'\n\x05\x66iles\x18\x01 \x03(\x0b\x32\x18.config.files.StoredFile\x12\r\n\x05total\x18\x02 \x01(\x05\x12\r\n\x05limit\x18\x03 \x01(\x05\x12\x0e\n\x06offset\x18\x04 \x01(\x05\"\x1d\n\nGetRequest\x12\x0f\n\x07\x66ile_id\x18\x01 \x01(\t\",\n\x0bListRequest\x12\r\n\x05limit\x18\x01 \x01(\x05\x12\x0e\n\x06offset\x18\x02 \x01(\x05\"p\n\nStoredFile\x12\n\n\x02id\x18\x01 \x01(\t\x12\x10\n\x08owner_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x14\n\x0c\x63ontent_type\x18\x04 \x01(\t\x12\x0c\n\x04size\x18\x05 \x01(\x05\x12\x12\n\ncreated_at\x18\x06 \x01(\t\".\n\rUploadRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\x0c\x32\xda\x02\n\x0e\x46ileController\x12\x43\n\x06\x44\x65lete\x12\x1b.config.files.DeleteRequest\x1a\x1a.config.files.DeleteResult\"\x00\x12\x46\n\x08\x44ownload\x12\x1d.config.files.DownloadRequest\x1a\x19.config.files.FileContent\"\x00\x12;\n\x03Get\x12\x18.config.files.GetRequest\x1a\x18.config.files.StoredFile\"\x00\x12;\n\x04List\x12\x19.config.files.ListRequest\x1a\x16.config.files.FileList\"\x00\x12\x41\n\x06Upload\x12\x1b.config.files.UploadRequest\x1a\x18.config.files.StoredFile\"\x00\x62\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.files.grpc.files_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR._loaded_options = None + _globals['_DELETEREQUEST']._serialized_start=45 + _globals['_DELETEREQUEST']._serialized_end=77 + _globals['_DELETERESULT']._serialized_start=79 + _globals['_DELETERESULT']._serialized_end=122 + _globals['_DOWNLOADREQUEST']._serialized_start=124 + _globals['_DOWNLOADREQUEST']._serialized_end=158 + _globals['_FILECONTENT']._serialized_start=160 + _globals['_FILECONTENT']._serialized_end=230 + _globals['_FILELIST']._serialized_start=232 + _globals['_FILELIST']._serialized_end=329 + _globals['_GETREQUEST']._serialized_start=331 + _globals['_GETREQUEST']._serialized_end=360 + _globals['_LISTREQUEST']._serialized_start=362 + _globals['_LISTREQUEST']._serialized_end=406 + _globals['_STOREDFILE']._serialized_start=408 + _globals['_STOREDFILE']._serialized_end=520 + _globals['_UPLOADREQUEST']._serialized_start=522 + _globals['_UPLOADREQUEST']._serialized_end=568 + _globals['_FILECONTROLLER']._serialized_start=571 + _globals['_FILECONTROLLER']._serialized_end=917 +# @@protoc_insertion_point(module_scope) diff --git a/src/apps/files/grpc/files_pb2.pyi b/src/apps/files/grpc/files_pb2.pyi new file mode 100644 index 0000000..454d071 --- /dev/null +++ b/src/apps/files/grpc/files_pb2.pyi @@ -0,0 +1,228 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from collections import abc as _abc +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers +import builtins as _builtins +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import TypeAlias as _TypeAlias, Never as _Never +else: + from typing_extensions import TypeAlias as _TypeAlias, Never as _Never + +DESCRIPTOR: _descriptor.FileDescriptor + +@_typing.final +class DeleteRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_ID_FIELD_NUMBER: _builtins.int + file_id: _builtins.str + def __init__( + self, + *, + file_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["file_id", b"file_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteRequest: _TypeAlias = DeleteRequest # noqa: Y015 + +@_typing.final +class DeleteResult(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + DELETED_FIELD_NUMBER: _builtins.int + id: _builtins.str + deleted: _builtins.bool + def __init__( + self, + *, + id: _builtins.str = ..., + deleted: _builtins.bool = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["deleted", b"deleted", "id", b"id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteResult: _TypeAlias = DeleteResult # noqa: Y015 + +@_typing.final +class DownloadRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_ID_FIELD_NUMBER: _builtins.int + file_id: _builtins.str + def __init__( + self, + *, + file_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["file_id", b"file_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DownloadRequest: _TypeAlias = DownloadRequest # noqa: Y015 + +@_typing.final +class FileContent(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_FIELD_NUMBER: _builtins.int + CONTENT_FIELD_NUMBER: _builtins.int + content: _builtins.bytes + @_builtins.property + def file(self) -> Global___StoredFile: ... + def __init__( + self, + *, + file: Global___StoredFile | None = ..., + content: _builtins.bytes = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["file", b"file"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["content", b"content", "file", b"file"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___FileContent: _TypeAlias = FileContent # noqa: Y015 + +@_typing.final +class FileList(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILES_FIELD_NUMBER: _builtins.int + TOTAL_FIELD_NUMBER: _builtins.int + LIMIT_FIELD_NUMBER: _builtins.int + OFFSET_FIELD_NUMBER: _builtins.int + total: _builtins.int + limit: _builtins.int + offset: _builtins.int + @_builtins.property + def files(self) -> _containers.RepeatedCompositeFieldContainer[Global___StoredFile]: ... + def __init__( + self, + *, + files: _abc.Iterable[Global___StoredFile] | None = ..., + total: _builtins.int = ..., + limit: _builtins.int = ..., + offset: _builtins.int = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["files", b"files", "limit", b"limit", "offset", b"offset", "total", b"total"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___FileList: _TypeAlias = FileList # noqa: Y015 + +@_typing.final +class GetRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_ID_FIELD_NUMBER: _builtins.int + file_id: _builtins.str + def __init__( + self, + *, + file_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["file_id", b"file_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___GetRequest: _TypeAlias = GetRequest # noqa: Y015 + +@_typing.final +class ListRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + LIMIT_FIELD_NUMBER: _builtins.int + OFFSET_FIELD_NUMBER: _builtins.int + limit: _builtins.int + offset: _builtins.int + def __init__( + self, + *, + limit: _builtins.int = ..., + offset: _builtins.int = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["limit", b"limit", "offset", b"offset"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___ListRequest: _TypeAlias = ListRequest # noqa: Y015 + +@_typing.final +class StoredFile(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + OWNER_ID_FIELD_NUMBER: _builtins.int + NAME_FIELD_NUMBER: _builtins.int + CONTENT_TYPE_FIELD_NUMBER: _builtins.int + SIZE_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + id: _builtins.str + owner_id: _builtins.str + name: _builtins.str + content_type: _builtins.str + size: _builtins.int + created_at: _builtins.str + def __init__( + self, + *, + id: _builtins.str = ..., + owner_id: _builtins.str = ..., + name: _builtins.str = ..., + content_type: _builtins.str = ..., + size: _builtins.int = ..., + created_at: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["content_type", b"content_type", "created_at", b"created_at", "id", b"id", "name", b"name", "owner_id", b"owner_id", "size", b"size"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___StoredFile: _TypeAlias = StoredFile # noqa: Y015 + +@_typing.final +class UploadRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + NAME_FIELD_NUMBER: _builtins.int + CONTENT_FIELD_NUMBER: _builtins.int + name: _builtins.str + content: _builtins.bytes + def __init__( + self, + *, + name: _builtins.str = ..., + content: _builtins.bytes = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["content", b"content", "name", b"name"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___UploadRequest: _TypeAlias = UploadRequest # noqa: Y015 diff --git a/src/apps/files/grpc/files_pb2_grpc.py b/src/apps/files/grpc/files_pb2_grpc.py new file mode 100644 index 0000000..daf42ea --- /dev/null +++ b/src/apps/files/grpc/files_pb2_grpc.py @@ -0,0 +1,269 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc +import warnings + +from apps.files.grpc import files_pb2 as apps_dot_files_dot_grpc_dot_files__pb2 + +GRPC_GENERATED_VERSION = '1.84.0' +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) +except ImportError: + _version_not_supported = True + +if _version_not_supported: + raise RuntimeError( + f'The grpc package installed is at version {GRPC_VERSION},' + + ' but the generated code in apps/files/grpc/files_pb2_grpc.py depends on' + + f' grpcio>={GRPC_GENERATED_VERSION}.' + + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' + + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' + ) + + +class FileControllerStub: + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Delete = channel.unary_unary( + '/config.files.FileController/Delete', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteResult.FromString, + _registered_method=True) + self.Download = channel.unary_unary( + '/config.files.FileController/Download', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.DownloadRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.FileContent.FromString, + _registered_method=True) + self.Get = channel.unary_unary( + '/config.files.FileController/Get', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.GetRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + _registered_method=True) + self.List = channel.unary_unary( + '/config.files.FileController/List', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.ListRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.FileList.FromString, + _registered_method=True) + self.Upload = channel.unary_unary( + '/config.files.FileController/Upload', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.UploadRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + _registered_method=True) + + +class FileControllerServicer: + """Missing associated documentation comment in .proto file.""" + + def Delete(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Download(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Get(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def List(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Upload(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_FileControllerServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Delete': grpc.unary_unary_rpc_method_handler( + servicer.Delete, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteResult.SerializeToString, + ), + 'Download': grpc.unary_unary_rpc_method_handler( + servicer.Download, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.DownloadRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.FileContent.SerializeToString, + ), + 'Get': grpc.unary_unary_rpc_method_handler( + servicer.Get, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.GetRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.SerializeToString, + ), + 'List': grpc.unary_unary_rpc_method_handler( + servicer.List, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.ListRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.FileList.SerializeToString, + ), + 'Upload': grpc.unary_unary_rpc_method_handler( + servicer.Upload, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.UploadRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'config.files.FileController', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + server.add_registered_method_handlers('config.files.FileController', rpc_method_handlers) + + + # This class is part of an EXPERIMENTAL API. +class FileController: + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def Delete(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Delete', + apps_dot_files_dot_grpc_dot_files__pb2.DeleteRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.DeleteResult.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Download(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Download', + apps_dot_files_dot_grpc_dot_files__pb2.DownloadRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.FileContent.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Get(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Get', + apps_dot_files_dot_grpc_dot_files__pb2.GetRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def List(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/List', + apps_dot_files_dot_grpc_dot_files__pb2.ListRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.FileList.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Upload(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Upload', + apps_dot_files_dot_grpc_dot_files__pb2.UploadRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) diff --git a/src/apps/files/grpc/files_pb2_grpc.pyi b/src/apps/files/grpc/files_pb2_grpc.pyi new file mode 100644 index 0000000..b5a4105 --- /dev/null +++ b/src/apps/files/grpc/files_pb2_grpc.pyi @@ -0,0 +1,85 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from apps.files.grpc import files_pb2 as _files_pb2 +from collections import abc as _abc +from grpc import aio as _aio +import abc as _abc_1 +import grpc as _grpc +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import Self as _Self +else: + from typing_extensions import Self as _Self + +_T = _typing.TypeVar("_T") + +class _MaybeAsyncIterator(_abc.AsyncIterator[_T], _abc.Iterator[_T], metaclass=_abc_1.ABCMeta): ... + +class _ServicerContext(_grpc.ServicerContext, _aio.ServicerContext): # type: ignore[misc, type-arg] + ... + +GRPC_GENERATED_VERSION: str +GRPC_VERSION: str + +class FileControllerStub: + @_typing.overload + def __new__(cls, channel: _grpc.Channel) -> _Self: ... + @_typing.overload + def __new__(cls, channel: _aio.Channel) -> FileControllerAsyncStub: ... + Delete: _grpc.UnaryUnaryMultiCallable[_files_pb2.DeleteRequest, _files_pb2.DeleteResult] + Download: _grpc.UnaryUnaryMultiCallable[_files_pb2.DownloadRequest, _files_pb2.FileContent] + Get: _grpc.UnaryUnaryMultiCallable[_files_pb2.GetRequest, _files_pb2.StoredFile] + List: _grpc.UnaryUnaryMultiCallable[_files_pb2.ListRequest, _files_pb2.FileList] + Upload: _grpc.UnaryUnaryMultiCallable[_files_pb2.UploadRequest, _files_pb2.StoredFile] + +@_typing.type_check_only +class FileControllerAsyncStub(FileControllerStub): + def __init__(self, channel: _aio.Channel) -> None: ... + Delete: _aio.UnaryUnaryMultiCallable[_files_pb2.DeleteRequest, _files_pb2.DeleteResult] # type: ignore[assignment] + Download: _aio.UnaryUnaryMultiCallable[_files_pb2.DownloadRequest, _files_pb2.FileContent] # type: ignore[assignment] + Get: _aio.UnaryUnaryMultiCallable[_files_pb2.GetRequest, _files_pb2.StoredFile] # type: ignore[assignment] + List: _aio.UnaryUnaryMultiCallable[_files_pb2.ListRequest, _files_pb2.FileList] # type: ignore[assignment] + Upload: _aio.UnaryUnaryMultiCallable[_files_pb2.UploadRequest, _files_pb2.StoredFile] # type: ignore[assignment] + +class FileControllerServicer(metaclass=_abc_1.ABCMeta): + @_abc_1.abstractmethod + def Delete( + self, + request: _files_pb2.DeleteRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.DeleteResult, _abc.Awaitable[_files_pb2.DeleteResult]]: ... + + @_abc_1.abstractmethod + def Download( + self, + request: _files_pb2.DownloadRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.FileContent, _abc.Awaitable[_files_pb2.FileContent]]: ... + + @_abc_1.abstractmethod + def Get( + self, + request: _files_pb2.GetRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.StoredFile, _abc.Awaitable[_files_pb2.StoredFile]]: ... + + @_abc_1.abstractmethod + def List( + self, + request: _files_pb2.ListRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.FileList, _abc.Awaitable[_files_pb2.FileList]]: ... + + @_abc_1.abstractmethod + def Upload( + self, + request: _files_pb2.UploadRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.StoredFile, _abc.Awaitable[_files_pb2.StoredFile]]: ... + +def add_FileControllerServicer_to_server(servicer: FileControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ... diff --git a/src/apps/files/grpc/serializers.py b/src/apps/files/grpc/serializers.py new file mode 100644 index 0000000..c50d38a --- /dev/null +++ b/src/apps/files/grpc/serializers.py @@ -0,0 +1,14 @@ +"""The nested message the file service answers with.""" + +from rest_framework import serializers + + +class StoredFile(serializers.Serializer[dict[str, object]]): + """One stored file's metadata.""" + + id = serializers.CharField() + owner_id = serializers.CharField() + name = serializers.CharField() + content_type = serializers.CharField() + size = serializers.IntegerField() + created_at = serializers.CharField() diff --git a/src/apps/files/grpc/services.py b/src/apps/files/grpc/services.py new file mode 100644 index 0000000..a2ecb81 --- /dev/null +++ b/src/apps/files/grpc/services.py @@ -0,0 +1,123 @@ +"""Uploading, listing, downloading and deleting files over gRPC. + +The calls mirror the REST endpoints one for one, with the bytes carried as a +protobuf ``bytes`` field rather than a multipart body. +""" + +from typing import Any + +from asgiref.sync import sync_to_async +from django.core.exceptions import ValidationError +from django.core.files.base import ContentFile +from django_socio_grpc import generics +from django_socio_grpc.decorators import grpc_action + +from apps.files import services +from apps.files.grpc.serializers import StoredFile +from infrastructure.common.errors import ApiError +from infrastructure.common.grpc.errors import action, require_caller +from infrastructure.common.identity import grpc_caller +from infrastructure.common.responses import ResponseTitle + +FILE_ID = [{"name": "file_id", "type": "string"}] + + +def _pb2() -> Any: + from apps.files.grpc import files_pb2 + + return files_pb2 + + +def _message(row: dict[str, Any]) -> Any: + return _pb2().StoredFile(**row) + + +async def _found(method: Any, *args: Any) -> Any: + try: + return await sync_to_async(method)(*args) + except services.FileNotFound as error: + raise ApiError("No such file.", status=404, title=ResponseTitle.NOT_FOUND) from error + + +def _store(user: Any, name: str, content: bytes) -> dict[str, Any]: + try: + return services.upload(user, name, ContentFile(content), len(content)) + except ValidationError as refused: + raise ApiError("; ".join(refused.messages), status=400) from refused + + +class FileService(generics.GenericService): + """The same calls the REST router publishes under `/files`.""" + + @grpc_action( + request=[{"name": "limit", "type": "int32"}, {"name": "offset", "type": "int32"}], + request_name="ListRequest", + response=[ + {"name": "files", "cardinality": "repeated", "type": StoredFile}, + {"name": "total", "type": "int32"}, + {"name": "limit", "type": "int32"}, + {"name": "offset", "type": "int32"}, + ], + response_name="FileList", + ) + @action + async def List(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + page = await sync_to_async(services.list_files)( + user, limit=request.limit or services.DEFAULT_PAGE, offset=request.offset + ) + return _pb2().FileList( + files=[_message(row) for row in page["files"]], + total=page["total"], + limit=page["limit"], + offset=page["offset"], + ) + + @grpc_action( + request=FILE_ID, request_name="GetRequest", response=StoredFile, response_name="StoredFile" + ) + @action + async def Get(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + return _message(await _found(services.get, user, request.file_id)) + + @grpc_action( + request=[{"name": "name", "type": "string"}, {"name": "content", "type": "bytes"}], + request_name="UploadRequest", + response=StoredFile, + response_name="StoredFile", + ) + @action + async def Upload(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + return _message(await sync_to_async(_store)(user, request.name, request.content)) + + @grpc_action( + request=FILE_ID, + request_name="DownloadRequest", + response=[ + {"name": "file", "type": StoredFile}, + {"name": "content", "type": "bytes"}, + ], + response_name="FileContent", + ) + @action + async def Download(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + meta, content = await _found(services.read, user, request.file_id) + return _pb2().FileContent(file=_message(meta), content=content) + + @grpc_action( + request=FILE_ID, + request_name="DeleteRequest", + response=[{"name": "id", "type": "string"}, {"name": "deleted", "type": "bool"}], + response_name="DeleteResult", + ) + @action + async def Delete(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + await _found(services.delete, user, request.file_id) + return _pb2().DeleteResult(id=request.file_id, deleted=True) + + +GRPC_SERVICES = [FileService] diff --git a/src/apps/files/migrations/0001_initial.py b/src/apps/files/migrations/0001_initial.py new file mode 100644 index 0000000..48ea404 --- /dev/null +++ b/src/apps/files/migrations/0001_initial.py @@ -0,0 +1,65 @@ +# Generated by Django 6.1.3 on 2026-11-26 14:29 + +import uuid + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="StoredFile", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, editable=False, primary_key=True, serialize=False + ), + ), + ( + "name", + models.CharField( + help_text="The name the uploader gave the file.", max_length=255 + ), + ), + ( + "storage_key", + models.CharField( + editable=False, + help_text="Where the bytes live in the configured storage. Random, never the upload name.", + max_length=255, + unique=True, + ), + ), + ( + "content_type", + models.CharField( + help_text="What the content was sniffed to be, not what the client said.", + max_length=120, + ), + ), + ("size", models.PositiveBigIntegerField()), + ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)), + ( + "owner", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="stored_files", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "verbose_name": "file", + "ordering": ("-created_at",), + }, + ), + ] diff --git a/src/apps/files/migrations/__init__.py b/src/apps/files/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/files/models.py b/src/apps/files/models.py new file mode 100644 index 0000000..d95ec1f --- /dev/null +++ b/src/apps/files/models.py @@ -0,0 +1,47 @@ +"""A file somebody uploaded, and who it belongs to. + +The bytes live in Django's configured storage (local disk by default, S3 when +``DJANGO_STORAGE_BACKEND=s3``); the row holds the key it was saved under, the +name the uploader gave it, and what its content was sniffed to be. +""" + +import uuid +from typing import Any + +from django.conf import settings +from django.core.files.storage import default_storage +from django.db import models +from django.db.models.signals import post_delete +from django.dispatch import receiver + + +class StoredFile(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + owner = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="stored_files" + ) + name = models.CharField(max_length=255, help_text="The name the uploader gave the file.") + storage_key = models.CharField( + max_length=255, + unique=True, + editable=False, + help_text="Where the bytes live in the configured storage. Random, never the upload name.", + ) + content_type = models.CharField( + max_length=120, help_text="What the content was sniffed to be, not what the client said." + ) + size = models.PositiveBigIntegerField() + created_at = models.DateTimeField(auto_now_add=True, db_index=True) + + class Meta: + ordering = ("-created_at",) + verbose_name = "file" + + def __str__(self) -> str: + return self.name + + +@receiver(post_delete, sender=StoredFile) +def _delete_bytes(sender: Any, instance: StoredFile, **kwargs: Any) -> None: + """Delete the bytes with the row, however the row went (service, admin, cascade).""" + default_storage.delete(instance.storage_key) diff --git a/src/apps/files/rest/__init__.py b/src/apps/files/rest/__init__.py new file mode 100644 index 0000000..14dbb6e --- /dev/null +++ b/src/apps/files/rest/__init__.py @@ -0,0 +1,5 @@ +"""The HTTP transport for the files app.""" + +from apps.files.rest.v1 import router + +__all__ = ["router"] diff --git a/src/apps/files/rest/schemas.py b/src/apps/files/rest/schemas.py new file mode 100644 index 0000000..8f6ba55 --- /dev/null +++ b/src/apps/files/rest/schemas.py @@ -0,0 +1,29 @@ +"""The contract the file endpoints publish.""" + +from datetime import datetime +from uuid import UUID + +from ninja import Schema + + +class FileOut(Schema): + """One stored file's metadata. The bytes come from `/files/{id}/download`.""" + + id: UUID + owner_id: str + name: str + content_type: str + size: int + created_at: datetime + + +class FilePage(Schema): + files: list[FileOut] + total: int + limit: int + offset: int + + +class DeletedOut(Schema): + id: UUID + deleted: bool diff --git a/src/apps/files/rest/v1.py b/src/apps/files/rest/v1.py new file mode 100644 index 0000000..c4d5109 --- /dev/null +++ b/src/apps/files/rest/v1.py @@ -0,0 +1,79 @@ +"""Uploading, listing, downloading and deleting files over HTTP. + +Every decision is :mod:`apps.files.services`'s. A file belonging to somebody +else answers 404, exactly as a missing one does, unless the caller is staff. +""" + +from typing import Any +from uuid import UUID + +from django.core.exceptions import ValidationError +from django.http import FileResponse, HttpRequest +from ninja import File, Router +from ninja.errors import HttpError +from ninja.files import UploadedFile + +from apps.files import services +from apps.files.rest.schemas import DeletedOut, FileOut, FilePage + +try: # pragma: no cover - exercised by whichever branch the project installs + from infrastructure.auth.core.sessions import api_auth +except ImportError: # pragma: no cover - only in a project without the auth apps + from ninja.security import django_auth as api_auth # type: ignore[assignment] + +from infrastructure.common.throttling import upload_throttles + +router = Router(auth=api_auth) + + +def _found(method: Any, *args: Any) -> Any: + try: + return method(*args) + except services.FileNotFound as missing: + raise HttpError(404, str(missing)) from None + + +@router.post( + "", + response={201: FileOut}, + throttle=upload_throttles(), + summary="Upload a file", +) +def upload_file( + request: HttpRequest, + # `File(...)` in the default is how django-ninja declares a multipart body. + file: UploadedFile = File(...), # noqa: B008 +) -> tuple[int, dict[str, Any]]: + """Store one file owned by the caller. The content is sniffed, not trusted.""" + try: + return 201, services.upload(request.user, file.name or "", file, file.size or 0) + except ValidationError as refused: + raise HttpError(400, "; ".join(refused.messages)) from None + + +@router.get("", response=FilePage, summary="List files this account may see") +def list_files( + request: HttpRequest, limit: int = services.DEFAULT_PAGE, offset: int = 0 +) -> dict[str, Any]: + """The caller's own files, newest first; every file for staff.""" + return services.list_files(request.user, limit=limit, offset=offset) + + +@router.get("/{file_id}", response=FileOut, summary="Read one file's metadata") +def get_file(request: HttpRequest, file_id: UUID) -> dict[str, Any]: + return _found(services.get, request.user, file_id) + + +@router.get("/{file_id}/download", summary="Download one file's bytes") +def download_file(request: HttpRequest, file_id: UUID) -> FileResponse: + """Always an attachment, with the sniffed type, so nothing renders inline.""" + meta, handle = _found(services.open_file, request.user, file_id) + return FileResponse( + handle, as_attachment=True, filename=meta["name"], content_type=meta["content_type"] + ) + + +@router.delete("/{file_id}", response=DeletedOut, summary="Delete one file") +def delete_file(request: HttpRequest, file_id: UUID) -> dict[str, Any]: + _found(services.delete, request.user, file_id) + return {"id": file_id, "deleted": True} diff --git a/src/apps/files/services.py b/src/apps/files/services.py new file mode 100644 index 0000000..bb76567 --- /dev/null +++ b/src/apps/files/services.py @@ -0,0 +1,150 @@ +"""Every decision the files app makes, for all three transports. + +* **What may be stored.** A size limit checked before anything is read, then + the content sniffed from its first bytes. The extension must be one the + sniffed type is known by: a PNG named ``.pdf`` and an HTML page named ``.txt`` + are both refused, and nothing that is not on :data:`ALLOWED_TYPES` gets in. +* **Where it goes.** A random key under ``FILES_UPLOAD_PATH``, grouped by day. + The uploader's name is kept on the row, never in the key. +* **Who may see it.** The owner, and staff. Anybody else gets the same "not + found" a missing id gets, so an id never confirms another account's file. +""" + +import posixpath +import uuid +from typing import IO, Any +from uuid import UUID + +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.files.storage import default_storage +from django.db.models import QuerySet +from django.utils import timezone + +from apps.files.models import StoredFile +from infrastructure.common.uploads import SNIFF_BYTES, check_size, extension_of, sniff + +DEFAULT_PAGE = 50 +MAX_PAGE = 100 + +#: Sniffed type -> the extensions a file of that type may be named with. Office +#: documents are zip archives, so they sniff as one. Nothing a browser executes +#: is here: text is served as ``text/plain`` whatever it is named, and ``.html``, +#: ``.svg`` and ``.xml`` are not on any list. +ALLOWED_TYPES: dict[str, tuple[str, ...]] = { + "image/png": (".png",), + "image/jpeg": (".jpg", ".jpeg"), + "image/gif": (".gif",), + "image/webp": (".webp",), + "application/pdf": (".pdf",), + "application/zip": (".zip", ".docx", ".xlsx", ".pptx"), + "application/gzip": (".gz",), + "text/plain": (".txt", ".csv", ".json", ".md", ".log"), +} + + +class FileNotFound(LookupError): + """No such file, or not one this account may see. Deliberately the same thing.""" + + +def upload_root() -> str: + return str(settings.FILES_UPLOAD_PATH).strip("/") + + +def window(limit: int, offset: int) -> tuple[int, int]: + """Clamp a page request to something the database should be asked for.""" + return max(1, min(limit, MAX_PAGE)), max(0, offset) + + +def payload(row: StoredFile) -> dict[str, Any]: + return { + "id": str(row.id), + "owner_id": str(row.owner_id), + "name": row.name, + "content_type": row.content_type, + "size": row.size, + "created_at": row.created_at.isoformat(), + } + + +def _visible(user: Any) -> QuerySet[StoredFile]: + if user.is_staff: + return StoredFile.objects.all() + return StoredFile.objects.filter(owner=user) + + +def _row(user: Any, file_id: UUID | str) -> StoredFile: + try: + return _visible(user).get(pk=UUID(str(file_id))) + except (StoredFile.DoesNotExist, ValueError): + raise FileNotFound("No such file.") from None + + +def validate(name: str, content: IO[bytes], size: int) -> str: + """Return the sniffed content type, or raise :class:`ValidationError`.""" + check_size(size, int(settings.FILES_MAX_UPLOAD_BYTES)) + content.seek(0) + content_type = sniff(content.read(SNIFF_BYTES)) + content.seek(0) + if content_type not in ALLOWED_TYPES: + raise ValidationError("That kind of file is not accepted.") + extension = extension_of(name) + if extension not in ALLOWED_TYPES[content_type]: + raise ValidationError( + f"The content is {content_type}, which may be named " + f"{', '.join(ALLOWED_TYPES[content_type])}, not {extension or 'with no extension'}." + ) + return content_type + + +def upload(user: Any, name: str, content: IO[bytes], size: int) -> dict[str, Any]: + """Validate and store one file owned by ``user``.""" + content_type = validate(name, content, size) + key = posixpath.join( + upload_root(), f"{timezone.now():%Y/%m/%d}", uuid.uuid4().hex + extension_of(name) + ) + stored = default_storage.save(key, content) + try: + row = StoredFile.objects.create( + owner=user, + name=posixpath.basename(name.replace("\\", "/"))[:255] or "file", + storage_key=stored, + content_type=content_type, + size=size, + ) + except Exception: + default_storage.delete(stored) + raise + return payload(row) + + +def list_files(user: Any, *, limit: int = DEFAULT_PAGE, offset: int = 0) -> dict[str, Any]: + limit, offset = window(limit, offset) + rows = _visible(user) + return { + "files": [payload(row) for row in rows[offset : offset + limit]], + "total": rows.count(), + "limit": limit, + "offset": offset, + } + + +def get(user: Any, file_id: UUID | str) -> dict[str, Any]: + return payload(_row(user, file_id)) + + +def open_file(user: Any, file_id: UUID | str) -> tuple[dict[str, Any], IO[bytes]]: + """The file's metadata and an open binary handle the caller must close.""" + row = _row(user, file_id) + return payload(row), default_storage.open(row.storage_key, "rb") + + +def read(user: Any, file_id: UUID | str) -> tuple[dict[str, Any], bytes]: + meta, handle = open_file(user, file_id) + with handle: + return meta, handle.read() + + +def delete(user: Any, file_id: UUID | str) -> None: + """Remove the row; its ``post_delete`` signal removes the bytes.""" + _row(user, file_id).delete() diff --git a/src/apps/files/tests/__init__.py b/src/apps/files/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/files/tests/conftest.py b/src/apps/files/tests/conftest.py new file mode 100644 index 0000000..204cf58 --- /dev/null +++ b/src/apps/files/tests/conftest.py @@ -0,0 +1,45 @@ +"""Shared fixtures: two accounts, a member of staff, and storage in memory.""" + +from typing import Any + +import pytest +from django.contrib.auth import get_user_model +from django.test import RequestFactory + +PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64 +PDF = b"%PDF-1.7\n" + b"x" * 64 + + +@pytest.fixture(autouse=True) +def _memory_storage(settings: Any) -> None: + settings.STORAGES = { + **settings.STORAGES, + "default": {"BACKEND": "django.core.files.storage.InMemoryStorage"}, + } + + +@pytest.fixture +def alice(transactional_db: None) -> Any: + return get_user_model().objects.create_user(username="alice", email="alice@example.test") + + +@pytest.fixture +def bob(transactional_db: None) -> Any: + return get_user_model().objects.create_user(username="bob", email="bob@example.test") + + +@pytest.fixture +def staff(transactional_db: None) -> Any: + return get_user_model().objects.create_user( + username="staff", email="staff@example.test", is_staff=True + ) + + +def access_token(user: Any) -> str: + from infrastructure.auth.core.sessions import issue_credentials + + return issue_credentials(RequestFactory().post("/"), user, method="password").access_token + + +def bearer(user: Any) -> dict[str, str]: + return {"HTTP_AUTHORIZATION": f"Bearer {access_token(user)}"} diff --git a/src/apps/files/tests/test_api.py b/src/apps/files/tests/test_api.py new file mode 100644 index 0000000..1297697 --- /dev/null +++ b/src/apps/files/tests/test_api.py @@ -0,0 +1,61 @@ +"""The HTTP transport.""" + +from typing import Any + +import pytest +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import Client + +from apps.files.tests.conftest import PNG, bearer + +LIST = "/api/v1/files" + + +def _upload(client: Client, user: Any, name: str = "shot.png", content: bytes = PNG) -> Any: + return client.post(LIST, {"file": SimpleUploadedFile(name, content)}, **bearer(user)) + + +@pytest.mark.parametrize( + ("method", "path"), + [ + ("get", LIST), + ("post", LIST), + ("get", f"{LIST}/00000000-0000-0000-0000-000000000000"), + ("get", f"{LIST}/00000000-0000-0000-0000-000000000000/download"), + ("delete", f"{LIST}/00000000-0000-0000-0000-000000000000"), + ], +) +def test_every_endpoint_needs_a_credential(method: str, path: str, transactional_db: None) -> None: + assert getattr(Client(), method)(path).status_code == 401 + + +def test_upload_list_download_delete(alice: Any) -> None: + client = Client() + created = _upload(client, alice) + assert created.status_code == 201, created.content + file_id = created.json()["data"]["id"] + + assert client.get(LIST, **bearer(alice)).json()["data"]["total"] == 1 + download = client.get(f"{LIST}/{file_id}/download", **bearer(alice)) + assert download.status_code == 200 + assert download["Content-Type"] == "image/png" + assert download["Content-Disposition"].startswith("attachment") + assert b"".join(download.streaming_content) == PNG + + assert client.delete(f"{LIST}/{file_id}", **bearer(alice)).json()["data"]["deleted"] + assert client.get(f"{LIST}/{file_id}", **bearer(alice)).status_code == 404 + + +def test_a_disguised_file_is_a_400(alice: Any) -> None: + assert _upload(Client(), alice, "shot.pdf").status_code == 400 + + +def test_another_account_gets_404_and_staff_get_through(alice: Any, bob: Any, staff: Any) -> None: + client = Client() + file_id = _upload(client, alice).json()["data"]["id"] + + for path in (f"{LIST}/{file_id}", f"{LIST}/{file_id}/download"): + assert client.get(path, **bearer(bob)).status_code == 404 + assert client.get(path, **bearer(staff)).status_code == 200 + assert client.delete(f"{LIST}/{file_id}", **bearer(bob)).status_code == 404 + assert client.get(LIST, **bearer(bob)).json()["data"]["total"] == 0 diff --git a/src/apps/files/tests/test_graph.py b/src/apps/files/tests/test_graph.py new file mode 100644 index 0000000..705e529 --- /dev/null +++ b/src/apps/files/tests/test_graph.py @@ -0,0 +1,49 @@ +"""The GraphQL transport: bytes travel base64-encoded.""" + +import base64 +import json +from typing import Any + +from django.test import Client + +from apps.files.tests.conftest import PNG, bearer + +UPLOAD = ( + "mutation($n: String!, $c: String!) { uploadFile(name: $n, contentBase64: $c) { id name } }" +) +LIST = "{ files { total files { id } } }" +CONTENT = "query($id: String!) { fileContent(fileId: $id) { contentBase64 file { contentType } } }" +DELETE = "mutation($id: String!) { deleteFile(fileId: $id) }" + + +def _graph(user: Any, query: str, **variables: Any) -> dict[str, Any]: + response = Client().post( + "/graphql", + data={"query": query, "variables": variables}, + content_type="application/json", + **(bearer(user) if user else {}), + ) + assert response.status_code == 200, response.content + return json.loads(response.content) + + +def test_round_trip(alice: Any, bob: Any) -> None: + encoded = base64.b64encode(PNG).decode() + file_id = _graph(alice, UPLOAD, n="a.png", c=encoded)["data"]["uploadFile"]["id"] + + assert _graph(alice, LIST)["data"]["files"]["total"] == 1 + assert _graph(bob, LIST)["data"]["files"]["total"] == 0 + content = _graph(alice, CONTENT, id=file_id)["data"]["fileContent"] + assert content["contentBase64"] == encoded + assert content["file"]["contentType"] == "image/png" + assert _graph(bob, CONTENT, id=file_id)["errors"] + assert _graph(bob, DELETE, id=file_id)["errors"] + assert _graph(alice, DELETE, id=file_id)["data"]["deleteFile"] is True + + +def test_refusals(alice: Any, settings: Any) -> None: + assert _graph(None, LIST)["errors"] + assert _graph(alice, UPLOAD, n="a.pdf", c=base64.b64encode(PNG).decode())["errors"] + assert _graph(alice, UPLOAD, n="a.png", c="not base64!")["errors"] + settings.FILES_MAX_UPLOAD_BYTES = 8 + assert _graph(alice, UPLOAD, n="a.png", c=base64.b64encode(PNG).decode())["errors"] diff --git a/src/apps/files/tests/test_grpc.py b/src/apps/files/tests/test_grpc.py new file mode 100644 index 0000000..c58a039 --- /dev/null +++ b/src/apps/files/tests/test_grpc.py @@ -0,0 +1,41 @@ +"""The gRPC transport: bytes travel as a protobuf ``bytes`` field.""" + +from collections.abc import Callable +from typing import Any + +import grpc +import pytest + +from apps.files.grpc import files_pb2, files_pb2_grpc +from apps.files.tests.conftest import PNG, access_token + +Stub = files_pb2_grpc.FileControllerStub + + +def test_needs_a_credential(transactional_db: None, grpc_call: Callable[..., Any]) -> None: + with pytest.raises(grpc.aio.AioRpcError) as refusal: + grpc_call(Stub, "List", files_pb2.ListRequest()) + assert refusal.value.code() is grpc.StatusCode.UNAUTHENTICATED + + +def test_round_trip(alice: Any, bob: Any, grpc_call: Callable[..., Any]) -> None: + mine, theirs = access_token(alice), access_token(bob) + stored = grpc_call(Stub, "Upload", files_pb2.UploadRequest(name="a.png", content=PNG), mine) + assert stored.content_type == "image/png" + + assert grpc_call(Stub, "List", files_pb2.ListRequest(), mine).total == 1 + assert grpc_call(Stub, "Get", files_pb2.GetRequest(file_id=stored.id), mine).name == "a.png" + download = grpc_call(Stub, "Download", files_pb2.DownloadRequest(file_id=stored.id), mine) + assert download.content == PNG + with pytest.raises(grpc.aio.AioRpcError) as refusal: + grpc_call(Stub, "Download", files_pb2.DownloadRequest(file_id=stored.id), theirs) + assert refusal.value.code() is grpc.StatusCode.NOT_FOUND + deleted = grpc_call(Stub, "Delete", files_pb2.DeleteRequest(file_id=stored.id), mine) + assert deleted.deleted + + +def test_a_disguised_file_is_invalid(alice: Any, grpc_call: Callable[..., Any]) -> None: + with pytest.raises(grpc.aio.AioRpcError) as refusal: + request = files_pb2.UploadRequest(name="a.pdf", content=PNG) + grpc_call(Stub, "Upload", request, access_token(alice)) + assert refusal.value.code() is grpc.StatusCode.INVALID_ARGUMENT diff --git a/src/apps/files/tests/test_services.py b/src/apps/files/tests/test_services.py new file mode 100644 index 0000000..3e43185 --- /dev/null +++ b/src/apps/files/tests/test_services.py @@ -0,0 +1,82 @@ +"""What may be stored, where it goes, and who may see it.""" + +from typing import Any + +import pytest +from django.core.exceptions import ValidationError +from django.core.files.base import ContentFile +from django.core.files.storage import default_storage + +from apps.files import services +from apps.files.models import StoredFile +from apps.files.tests.conftest import PDF, PNG + + +def _upload(user: Any, name: str = "shot.png", content: bytes = PNG) -> dict[str, Any]: + return services.upload(user, name, ContentFile(content), len(content)) + + +def test_a_file_is_stored_under_a_random_key_and_keeps_its_name(alice: Any) -> None: + row = _upload(alice, "../My Shot.png") + stored = StoredFile.objects.get(pk=row["id"]) + + assert row["name"] == "My Shot.png" + assert row["content_type"] == "image/png" + assert stored.storage_key.startswith("files/") + assert "Shot" not in stored.storage_key + assert stored.storage_key.endswith(".png") + assert default_storage.exists(stored.storage_key) + + +@pytest.mark.parametrize( + ("name", "content"), + [ + ("shot.pdf", PNG), # renamed image + ("page.txt", b"\x00\x01binary"), # binary named as text + ("page.html", b""), # text, but not an allowed name + ("evil.exe", b"MZ\x90\x00" + b"\x00" * 10), # unknown content + ("noext", PDF), + ], +) +def test_content_that_does_not_match_its_name_is_refused( + alice: Any, name: str, content: bytes +) -> None: + with pytest.raises(ValidationError): + _upload(alice, name, content) + assert not StoredFile.objects.exists() + + +def test_an_oversized_file_is_refused_before_it_is_read(alice: Any, settings: Any) -> None: + settings.FILES_MAX_UPLOAD_BYTES = 10 + + with pytest.raises(ValidationError, match="limit"): + _upload(alice) + + +def test_owners_see_their_own_and_staff_see_everything(alice: Any, bob: Any, staff: Any) -> None: + mine = _upload(alice) + _upload(bob, "b.pdf", PDF) + + assert [row["id"] for row in services.list_files(alice)["files"]] == [mine["id"]] + assert services.list_files(staff)["total"] == 2 + with pytest.raises(services.FileNotFound): + services.get(bob, mine["id"]) + with pytest.raises(services.FileNotFound): + services.delete(bob, mine["id"]) + with pytest.raises(services.FileNotFound): + services.get(alice, "not-a-uuid") + assert services.read(staff, mine["id"])[1] == PNG + + +def test_deleting_removes_the_bytes(alice: Any) -> None: + row = _upload(alice) + key = StoredFile.objects.get(pk=row["id"]).storage_key + + services.delete(alice, row["id"]) + + assert not StoredFile.objects.exists() + assert not default_storage.exists(key) + + +def test_the_page_is_clamped(alice: Any) -> None: + assert services.window(10_000, -5) == (services.MAX_PAGE, 0) diff --git a/src/apps/files/tests/test_uploads.py b/src/apps/files/tests/test_uploads.py new file mode 100644 index 0000000..dff6848 --- /dev/null +++ b/src/apps/files/tests/test_uploads.py @@ -0,0 +1,40 @@ +"""The shared sniffing and naming helpers.""" + +import pytest +from django.core.exceptions import ValidationError + +from infrastructure.common.uploads import check_size, extension_of, safe_name, sniff + + +@pytest.mark.parametrize( + ("head", "expected"), + [ + (b"\x89PNG\r\n\x1a\nrest", "image/png"), + (b"\xff\xd8\xff\xe0", "image/jpeg"), + (b"GIF89a", "image/gif"), + (b"RIFF\x00\x00\x00\x00WEBPVP8 ", "image/webp"), + (b"%PDF-1.4", "application/pdf"), + (b"PK\x03\x04", "application/zip"), + (b"\x1f\x8b\x08", "application/gzip"), + (b"a,b\n1,2\n", "text/plain"), + ("héllo".encode()[:2], "text/plain"), + (b"MZ\x90\x00", None), + (b"\xff\xfe\xfd\xfc garbage" * 10, None), + (b"", None), + ], +) +def test_sniff_reads_the_content_not_the_name(head: bytes, expected: str | None) -> None: + assert sniff(head) == expected + + +def test_size_limit_zero_means_none() -> None: + check_size(10**12, 0) + with pytest.raises(ValidationError): + check_size(2048, 1024) + + +def test_safe_name_and_extension() -> None: + assert safe_name("../../etc/Pass wd.PNG").endswith(".png") + assert "/" not in safe_name("../../x.png") + assert extension_of("Shot.PNG") == ".png" + assert extension_of("noext") == "" diff --git a/src/apps/support/uploads.py b/src/apps/support/uploads.py index 17a0bfb..53b7dff 100644 --- a/src/apps/support/uploads.py +++ b/src/apps/support/uploads.py @@ -34,9 +34,6 @@ """ import posixpath -import re -import unicodedata -import uuid from pathlib import PurePosixPath from typing import Any @@ -46,12 +43,9 @@ from django.utils import timezone from apps.support.models import Upload +from infrastructure.common.uploads import check_size, extension_of, safe_name -#: What survives of an uploaded file's own name. Everything else becomes a -#: hyphen, because the name ends up in a URL and a storage key, and -#: "screenshot (2)+copy.png" is a different string in each of the places it is -#: written. -UNSAFE = re.compile(r"[^a-zA-Z0-9._-]+") +__all__ = ["check", "extension_of", "safe_name", "store"] #: What a client may send the desk. A allowlist rather than a blocklist: the #: interesting extensions are the ones nobody thought of, and a blocklist is a @@ -114,36 +108,9 @@ def allowed_extensions() -> tuple[str, ...]: return tuple(str(item).lower() for item in configured) -def safe_name(name: str) -> str: - """A storage-safe, URL-safe version of an uploaded file's own name. - - The stem is kept -- shortened, ASCII-folded and stripped of anything that - would need escaping -- because a folder of ``a1b2c3.png`` is unsearchable - for the agent looking for the screenshot a client sent this morning. - Uniqueness comes from a suffix rather than from the name, so two people - sending ``screenshot.png`` do not overwrite each other. - """ - stem = PurePosixPath(name or "file").name - folded = unicodedata.normalize("NFKD", stem).encode("ascii", "ignore").decode() - cleaned = UNSAFE.sub("-", folded).strip("-.") or "file" - root, _, extension = cleaned.rpartition(".") - root = (root or cleaned)[:60].strip("-") or "file" - suffix = uuid.uuid4().hex[:8] - return f"{root}-{suffix}.{extension.lower()}" if extension else f"{root}-{suffix}" - - -def extension_of(name: str) -> str: - """``"Shot.PNG"`` -> ``".png"``. Empty when the name has no extension at all.""" - _, dot, extension = PurePosixPath(name or "").name.rpartition(".") - return f".{extension.lower()}" if dot else "" - - def check(user: Any, upload: Any) -> None: """Raise :class:`ValidationError` if this file may not be stored by this account.""" - limit = max_upload_bytes() - size = getattr(upload, "size", 0) or 0 - if limit and size > limit: - raise ValidationError(f"That file is {size // 1024} KB. The limit is {limit // 1024} KB.") + check_size(getattr(upload, "size", 0) or 0, max_upload_bytes()) allowed = allowed_extensions() if allowed: # The name it will be stored under, which `safe_name` folds and trims. diff --git a/src/config/api.py b/src/config/api.py index 0dd3758..d136d45 100644 --- a/src/config/api.py +++ b/src/config/api.py @@ -48,6 +48,7 @@ def build_apis() -> dict[str, NinjaAPI]: *settings.SUPPORT_ROUTERS, *settings.WALLET_ROUTERS, *settings.WEBHOOKS_ROUTERS, + *settings.FILES_ROUTERS, ] guarded = {id(route["router"]) for route in credential_routes} api = EnvelopeAPI( diff --git a/src/config/settings/base.py b/src/config/settings/base.py index bbfca73..759324d 100644 --- a/src/config/settings/base.py +++ b/src/config/settings/base.py @@ -882,6 +882,34 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: if extension.strip().strip(".") ] or None +# The files app. Optional the same way the others are: naming it installs its +# table, its routes and its admin. Files go through `STORAGES["default"]`, so +# pointing that at S3 (below) moves them without this app knowing. +FILES_ENABLED = os.getenv("DJANGO_FILES_ENABLED", "false").lower() == "true" +FILES_APP = "apps.files.apps.FilesConfig" +FILES_INSTALLED_APPS = [FILES_APP] if FILES_ENABLED else [] +FILES_TRANSPORTS = app_transports("files", ("rest", "graph", "grpc")) if FILES_ENABLED else () +FILES_ROUTERS = ( + [ + { + "prefix": "/files", + "router": "apps.files.rest.router", + "tag": "Files", + "description": ( + "Files an account uploads and owns. The content is sniffed rather " + "than trusted, stored under a random name, and only its owner or " + "staff may list, download or delete it." + ), + } + ] + if "rest" in FILES_TRANSPORTS + else [] +) +FILES_UPLOAD_PATH = os.getenv("DJANGO_FILES_UPLOAD_PATH", "files") +# Zero means no limit, for a deployment whose proxy already imposes one. +FILES_MAX_UPLOAD_MB = int(os.getenv("DJANGO_FILES_MAX_UPLOAD_MB", "10")) +FILES_MAX_UPLOAD_BYTES = FILES_MAX_UPLOAD_MB * 1024 * 1024 + OAUTH_ENCRYPTION_KEY = os.getenv("DJANGO_OAUTH_ENCRYPTION_KEY", "") OAUTH_STATE_TTL_SECONDS = int(os.getenv("DJANGO_OAUTH_STATE_TTL_SECONDS", "600")) OAUTH_HTTP_TIMEOUT_SECONDS = float(os.getenv("DJANGO_OAUTH_HTTP_TIMEOUT_SECONDS", "10")) @@ -940,6 +968,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: "apps.wallet": WALLET_TRANSPORTS, "apps.club": CLUB_TRANSPORTS, "apps.webhooks": WEBHOOKS_TRANSPORTS, + "apps.files": FILES_TRANSPORTS, } # How often one caller may ask, whichever endpoint they are asking. A correct @@ -1053,6 +1082,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: *WALLET_INSTALLED_APPS, *CLUB_INSTALLED_APPS, *WEBHOOKS_INSTALLED_APPS, + *FILES_INSTALLED_APPS, # The transports beside REST. Both are installed whether or not they are # published: `generateproto` and the schema check have to be able to run in a # deployment that serves neither. @@ -1189,4 +1219,29 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: # and a project on S3 overrides STORAGES and leaves both of these unused. MEDIA_URL = os.getenv("DJANGO_MEDIA_URL", "media/") MEDIA_ROOT = os.getenv("DJANGO_MEDIA_ROOT", "") or BASE_DIR / "media" +# Where uploaded files go. `filesystem` is MEDIA_ROOT; `s3` is a bucket through +# django-storages (`pip install 'django-storages[s3]'`), configured by the +# AWS_* variables below, which django-storages reads from these settings. +STORAGE_BACKEND = os.getenv("DJANGO_STORAGE_BACKEND", "filesystem").lower() +STORAGE_BACKENDS = { + "filesystem": "django.core.files.storage.FileSystemStorage", + "s3": "storages.backends.s3.S3Storage", +} +if STORAGE_BACKEND not in STORAGE_BACKENDS: + raise ImproperlyConfigured( + f"Unknown DJANGO_STORAGE_BACKEND: {STORAGE_BACKEND}. One of: {', '.join(STORAGE_BACKENDS)}." + ) +STORAGES = { + "default": {"BACKEND": STORAGE_BACKENDS[STORAGE_BACKEND]}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}, +} +AWS_STORAGE_BUCKET_NAME = os.getenv("DJANGO_AWS_STORAGE_BUCKET_NAME", "") +AWS_S3_REGION_NAME = os.getenv("DJANGO_AWS_S3_REGION_NAME", "") or None +AWS_S3_ENDPOINT_URL = os.getenv("DJANGO_AWS_S3_ENDPOINT_URL", "") or None +AWS_ACCESS_KEY_ID = os.getenv("DJANGO_AWS_ACCESS_KEY_ID", "") or None +AWS_SECRET_ACCESS_KEY = os.getenv("DJANGO_AWS_SECRET_ACCESS_KEY", "") or None +# Private objects and signed URLs: these are people's files, not a public site. +AWS_DEFAULT_ACL = None +AWS_QUERYSTRING_AUTH = True +AWS_S3_FILE_OVERWRITE = False DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/src/config/settings/test.py b/src/config/settings/test.py index b52d4ab..541594f 100644 --- a/src/config/settings/test.py +++ b/src/config/settings/test.py @@ -7,6 +7,7 @@ os.environ.setdefault("DJANGO_WALLET_ENABLED", "true") os.environ.setdefault("DJANGO_CLUB_ENABLED", "true") os.environ.setdefault("DJANGO_WEBHOOKS_ENABLED", "true") +os.environ.setdefault("DJANGO_FILES_ENABLED", "true") os.environ.setdefault("DJANGO_OAUTH_MODE", "all") os.environ.setdefault("DJANGO_AUTH_TOKEN_MODE", "rotation") os.environ.setdefault("DJANGO_AUTH_METHODS", "password,email_code,sms_code,magic_link") diff --git a/src/django_ninja_starter/template/Makefile b/src/django_ninja_starter/template/Makefile index 615c66b..b1ae24f 100644 --- a/src/django_ninja_starter/template/Makefile +++ b/src/django_ninja_starter/template/Makefile @@ -6,7 +6,7 @@ install: # Every optional app turned on, so the checks below see the whole project # rather than whatever this developer happens to have in their `.env`. An app # left off is an app whose models, admin, migrations and protos nobody checked. -ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true DJANGO_WEBHOOKS_ENABLED=true +ALL_APPS = DJANGO_CMS_ENABLED=true DJANGO_NOTIFICATIONS_ENABLED=true DJANGO_SHOP_ENABLED=true DJANGO_SUPPORT_ENABLED=true DJANGO_WALLET_ENABLED=true DJANGO_CLUB_ENABLED=true DJANGO_WEBHOOKS_ENABLED=true DJANGO_FILES_ENABLED=true check: ruff check --no-cache . diff --git a/src/django_ninja_starter/template/_env.example b/src/django_ninja_starter/template/_env.example index a997671..da98921 100644 --- a/src/django_ninja_starter/template/_env.example +++ b/src/django_ninja_starter/template/_env.example @@ -112,6 +112,20 @@ DJANGO_SUPPORT_UPLOAD_EXTENSIONS= # Zero keeps everything. Set a window and schedule `manage.py support_prune`; # nothing deletes a customer's support history until you run it. DJANGO_SUPPORT_RETENTION_DAYS=0 +DJANGO_FILES_ENABLED=false +# DJANGO_FILES_TRANSPORTS=rest,graph,grpc +# A prefix inside STORAGES["default"], not a filesystem path. +DJANGO_FILES_UPLOAD_PATH=files +# The largest file anybody may upload. Zero means no limit. +DJANGO_FILES_MAX_UPLOAD_MB=10 +# Where uploads are stored: `filesystem` (MEDIA_ROOT) or `s3` (needs +# `pip install '.[s3]'` and the bucket settings below). +DJANGO_STORAGE_BACKEND=filesystem +DJANGO_AWS_STORAGE_BUCKET_NAME= +DJANGO_AWS_S3_REGION_NAME= +DJANGO_AWS_S3_ENDPOINT_URL= +DJANGO_AWS_ACCESS_KEY_ID= +DJANGO_AWS_SECRET_ACCESS_KEY= DJANGO_SHOP_ENABLED=false # DJANGO_SHOP_TRANSPORTS=rest,graph,grpc DJANGO_SHOP_CURRENCY=USD diff --git a/src/django_ninja_starter/template/docs/README.md b/src/django_ninja_starter/template/docs/README.md index 6f2160f..c3dde57 100644 --- a/src/django_ninja_starter/template/docs/README.md +++ b/src/django_ninja_starter/template/docs/README.md @@ -15,7 +15,7 @@ themselves — see [keeping these pages honest](#keeping-these-pages-honest). | Social providers | [`oauth_google`](oauth/google.md), [`oauth_apple`](oauth/apple.md), [`oauth_microsoft`](oauth/microsoft.md), [`oauth_github`](oauth/github.md) | | Token modes | [`oauth_sliding`](oauth/sliding.md), [`oauth_session`](oauth/session.md), [`oauth_rotation`](oauth/rotation.md) | | Shared by those | [`auth_core`](auth/core.md), [`oauth_core`](oauth/core.md) | -| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md), [`webhooks`](webhooks.md) | +| Feature apps | [`cms`](cms.md), [`notifications`](notifications.md), [`shop`](shop.md), [`support`](support.md), [`wallet`](wallet.md), [`club`](club.md), [`webhooks`](webhooks.md), [`files`](files.md) | | Cross-cutting | [The response envelope](responses.md), [Signing in](signing-in.md), [Credentials](credentials.md), [The admin](admin.md) | ## Start here @@ -103,6 +103,7 @@ features a project chooses rather than the plumbing under them. | [`wallet`](wallet.md) | `DJANGO_WALLET_ENABLED=true` | A wallet per account with the balance derived from its movements rather than stored, payment methods an administrator configures rather than code declares, fees and taxes priced by the same function that quotes them, crypto with its chains, currency conversion at a published rate, and deposits that stay requests until an operator applies them | | [`club`](club.md) | `DJANGO_CLUB_ENABLED=true` | Clubs with a levelled ladder, an account in one club at a time, XP derived from an immutable award ledger rather than stored, and missions that complete themselves from events the other apps emit -- including events an app of your own registers, which is what lets a mission be built out of code this starter has never seen | | [`webhooks`](webhooks.md) | `DJANGO_WEBHOOKS_ENABLED=true` | Outgoing webhooks: https endpoints per account with their own secret and event types, HMAC-SHA256-signed deliveries retried with exponential backoff by `manage.py webhooks_deliver`, every attempt recorded, and private, loopback and link-local targets refused at send time | +| [`files`](files.md) | `DJANGO_FILES_ENABLED=true` | Owned file uploads through Django's storage API (local or S3): sniffed content types, random storage names, and owner-or-staff access over REST, GraphQL and gRPC | All five ship **off**, which is why a fresh `/api/docs` lists none of them: an app nobody named has no tables, no routes and no admin, and never imports its diff --git a/src/django_ninja_starter/template/docs/files.md b/src/django_ninja_starter/template/docs/files.md new file mode 100644 index 0000000..10430eb --- /dev/null +++ b/src/django_ninja_starter/template/docs/files.md @@ -0,0 +1,72 @@ +# Files + +Owned file uploads over REST, GraphQL and gRPC. Optional: naming it in +`DJANGO_FILES_ENABLED` installs its table, routes and admin; a project that does +not name it never imports the package. It lives in `src/apps/files`. + +- **Storage** is Django's storage API. `DJANGO_STORAGE_BACKEND=filesystem` (the + default) writes under `MEDIA_ROOT`; `DJANGO_STORAGE_BACKEND=s3` writes to a + private bucket through django-storages (`pip install '.[s3]'`), configured by + `DJANGO_AWS_STORAGE_BUCKET_NAME`, `DJANGO_AWS_S3_REGION_NAME`, + `DJANGO_AWS_S3_ENDPOINT_URL`, `DJANGO_AWS_ACCESS_KEY_ID` and + `DJANGO_AWS_SECRET_ACCESS_KEY`. +- **Validation**: a size limit (`DJANGO_FILES_MAX_UPLOAD_MB`) checked before the + content is read, then the content type sniffed from the first bytes. The + extension must be one the sniffed type is known by, so a renamed file is + refused. Accepted: PNG, JPEG, GIF, WebP, PDF, zip (and Office documents), + gzip, and plain text (`.txt .csv .json .md .log`). Nothing a browser executes. +- **Names**: stored under `/YYYY/MM/DD/.`; + the uploader's name is kept on the row and used only as the download filename. +- **Access**: the owner and staff may list, read, download and delete. Anybody + else gets 404, the same as a missing id. Downloads are always attachments. +- Uploads share the `upload` rate-limit scope (`DJANGO_API_THROTTLE_UPLOAD`). + +## Routes + + +| Method | Path | Auth | Purpose | +| --- | --- | --- | --- | +| `GET` | `/api/v1/files` | Bearer | List files this account may see | +| `POST` | `/api/v1/files` | Bearer | Upload a file | +| `DELETE` | `/api/v1/files/{file_id}` | Bearer | Delete one file | +| `GET` | `/api/v1/files/{file_id}` | Bearer | Read one file's metadata | +| `GET` | `/api/v1/files/{file_id}/download` | Bearer | Download one file's bytes | + + +GraphQL: `files`, `file`, `fileContent` (base64), `uploadFile(name, contentBase64)`, +`deleteFile`. gRPC: `FileController` with `List`, `Get`, `Upload`, `Download`, +`Delete`, the bytes as a protobuf `bytes` field. + +## Models + + +#### `StoredFile` + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | UUID | primary key, not editable | +| `owner` | ForeignKey | → `accounts.User` | +| `name` | Char | | +| `storage_key` | Char | unique, not editable | +| `content_type` | Char | | +| `size` | PositiveBigInteger | | +| `created_at` | DateTime | not editable | + + +## Admin + + +| Model | Editable | Actions | Columns | +| --- | --- | --- | --- | +| `StoredFile` | Yes | — | `name`, `owner`, `content_type`, `size`, `created_at` | + + +## Settings + + +| Environment variable | Required | Purpose | +| --- | --- | --- | +| `DJANGO_FILES_ENABLED` | **Yes** | whether this deployment carries file uploads at all. | +| `DJANGO_FILES_UPLOAD_PATH` | **Yes** | the folder or key prefix inside the configured storage files go under. | +| `DJANGO_FILES_MAX_UPLOAD_MB` | Optional | the largest file anybody may upload, in megabytes; zero means no limit. 0 or more. | + diff --git a/src/django_ninja_starter/template/pyproject.toml b/src/django_ninja_starter/template/pyproject.toml index 099f87d..151dd96 100644 --- a/src/django_ninja_starter/template/pyproject.toml +++ b/src/django_ninja_starter/template/pyproject.toml @@ -35,6 +35,8 @@ dependencies = [ ] [project.optional-dependencies] +# The S3 backend for DJANGO_STORAGE_BACKEND=s3. +s3 = ["django-storages[s3]>=1.14,<2.0"] # Social sign-in, for talking to the providers. oauth = ["httpx>=0.28,<1.0"] # The challenge store that survives a restart and reaches every worker. diff --git a/src/django_ninja_starter/template/src/apps/files/__init__.py b/src/django_ninja_starter/template/src/apps/files/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/files/admin.py b/src/django_ninja_starter/template/src/apps/files/admin.py new file mode 100644 index 0000000..3715ec4 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/admin.py @@ -0,0 +1,29 @@ +"""The admin: who uploaded what. Read-only, because a file's metadata is a record +of what was sniffed and stored, and editing it by hand would make it a lie. +Deleting a row deletes its bytes (see the model's ``post_delete``).""" + +from typing import Any + +from django.contrib import admin +from django.http import HttpRequest + +from apps.files.models import StoredFile + +try: # pragma: no cover - exercised by whichever branch the project installs + from unfold.admin import ModelAdmin +except ImportError: # pragma: no cover - only in a project without Unfold + from django.contrib.admin import ModelAdmin + + +@admin.register(StoredFile) +class StoredFileAdmin(ModelAdmin): + list_display = ("name", "owner", "content_type", "size", "created_at") + list_filter = ("content_type",) + search_fields = ("name", "owner__username", "owner__email") + readonly_fields = ("id", "owner", "name", "storage_key", "content_type", "size", "created_at") + + def has_add_permission(self, request: HttpRequest) -> bool: + return False + + def has_change_permission(self, request: HttpRequest, obj: Any = None) -> bool: + return False diff --git a/src/django_ninja_starter/template/src/apps/files/adminui.py b/src/django_ninja_starter/template/src/apps/files/adminui.py new file mode 100644 index 0000000..d5dd65e --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/adminui.py @@ -0,0 +1,42 @@ +"""This app's sidebar group and dashboard numbers. See :mod:`infrastructure.common.adminui`.""" + +from typing import Any + +from django.db.models import Sum +from django.http import HttpRequest + +from infrastructure.common.adminui import Section, card, changelist, item, may + +NAVIGATION_ORDER = 45 +DASHBOARD_ORDER = 45 + + +def navigation(request: HttpRequest) -> dict[str, Any]: + return { + "title": "Files", + "separator": False, + "collapsible": False, + "items": [ + item("Files", "folder", changelist("files", "storedfile"), "files.view_storedfile"), + ], + } + + +def dashboard(request: HttpRequest) -> Section | None: + if not may(request, "files.view_storedfile"): + return None + from apps.files.models import StoredFile + + totals = StoredFile.objects.aggregate(size=Sum("size")) + return Section( + title="Files", + cards=[ + card( + "Stored files", + StoredFile.objects.count(), + hint=f"{(totals['size'] or 0) // (1024 * 1024)} MB in storage", + icon="folder", + link=changelist("files", "storedfile"), + ), + ], + ) diff --git a/src/django_ninja_starter/template/src/apps/files/apps.py b/src/django_ninja_starter/template/src/apps/files/apps.py new file mode 100644 index 0000000..b174c16 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/apps.py @@ -0,0 +1,42 @@ +from django.apps import AppConfig + +from infrastructure.common.appsettings import AppSettings, Requirement + + +class FilesConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.files" + label = "files" + verbose_name = "Files" + + settings_spec = AppSettings( + title="Files", + summary=( + "Owned file uploads over REST, GraphQL and gRPC, stored through Django's " + "storage API: local disk by default, S3 when configured." + ), + requirements=( + Requirement( + "FILES_ENABLED", + env="DJANGO_FILES_ENABLED", + purpose="whether this deployment carries file uploads at all", + required=True, + hint=( + "The app is installed, so something put it in INSTALLED_APPS while " + "DJANGO_FILES_ENABLED was off. Set it to true, or drop the app." + ), + ), + Requirement( + "FILES_UPLOAD_PATH", + env="DJANGO_FILES_UPLOAD_PATH", + purpose="the folder or key prefix inside the configured storage files go under", + required=True, + ), + Requirement( + "FILES_MAX_UPLOAD_MB", + env="DJANGO_FILES_MAX_UPLOAD_MB", + purpose="the largest file anybody may upload, in megabytes; zero means no limit", + minimum=0, + ), + ), + ) diff --git a/src/django_ninja_starter/template/src/apps/files/graph/__init__.py b/src/django_ninja_starter/template/src/apps/files/graph/__init__.py new file mode 100644 index 0000000..b97fc52 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/graph/__init__.py @@ -0,0 +1,5 @@ +"""The GraphQL transport for the files app.""" + +from apps.files.graph.schema import Mutation, Query + +__all__ = ["Mutation", "Query"] diff --git a/src/django_ninja_starter/template/src/apps/files/graph/schema.py b/src/django_ninja_starter/template/src/apps/files/graph/schema.py new file mode 100644 index 0000000..14be895 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/graph/schema.py @@ -0,0 +1,93 @@ +"""The files app's contribution to the project's GraphQL schema. + +GraphQL has no binary type, so bytes travel base64-encoded both ways. The size +limit is checked against the encoded length before decoding, so an oversized +upload costs a rejection rather than the memory to decode it. +""" + +import base64 +import binascii +from typing import Any + +import strawberry +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.files.base import ContentFile +from strawberry.types import Info + +from apps.files import services +from apps.files.graph.types import FileContentType, FilePageType, FileType, file_type +from infrastructure.common.errors import ApiError +from infrastructure.common.graph.errors import require_caller, resolver +from infrastructure.common.identity import caller +from infrastructure.common.responses import ResponseTitle + + +def _caller(info: Info[Any, Any]) -> Any: + return require_caller(caller(info.context.request)) + + +def _found(method: Any, *args: Any) -> Any: + try: + return method(*args) + except services.FileNotFound as error: + raise ApiError("No such file.", status=404, title=ResponseTitle.NOT_FOUND) from error + + +def decode(content_base64: str) -> bytes: + """Decode an upload, refusing one too large before spending memory on it.""" + limit = int(settings.FILES_MAX_UPLOAD_BYTES) + if limit and len(content_base64) * 3 // 4 > limit + 2: + raise ApiError(f"The limit is {limit // 1024} KB.", status=400) + try: + return base64.b64decode(content_base64, validate=True) + except (binascii.Error, ValueError) as error: + raise ApiError("contentBase64 is not valid base64.", status=400) from error + + +@strawberry.type +class Query: + @strawberry.field(description="Files this account may see, newest first.") + @resolver + def files( + self, info: Info[Any, Any], limit: int = services.DEFAULT_PAGE, offset: int = 0 + ) -> FilePageType: + page = services.list_files(_caller(info), limit=limit, offset=offset) + return FilePageType( + files=[file_type(row) for row in page["files"]], + total=page["total"], + limit=page["limit"], + offset=page["offset"], + ) + + @strawberry.field(description="One file's metadata.") + @resolver + def file(self, info: Info[Any, Any], file_id: str) -> FileType: + return file_type(_found(services.get, _caller(info), file_id)) + + @strawberry.field(description="One file's metadata and its bytes, base64-encoded.") + @resolver + def file_content(self, info: Info[Any, Any], file_id: str) -> FileContentType: + meta, content = _found(services.read, _caller(info), file_id) + return FileContentType( + file=file_type(meta), content_base64=base64.b64encode(content).decode() + ) + + +@strawberry.type +class Mutation: + @strawberry.mutation(description="Upload a file. The content is sniffed, not trusted.") + @resolver + def upload_file(self, info: Info[Any, Any], name: str, content_base64: str) -> FileType: + user = _caller(info) + content = decode(content_base64) + try: + return file_type(services.upload(user, name, ContentFile(content), len(content))) + except ValidationError as refused: + raise ApiError("; ".join(refused.messages), status=400) from refused + + @strawberry.mutation(description="Delete one file.") + @resolver + def delete_file(self, info: Info[Any, Any], file_id: str) -> bool: + _found(services.delete, _caller(info), file_id) + return True diff --git a/src/django_ninja_starter/template/src/apps/files/graph/types.py b/src/django_ninja_starter/template/src/apps/files/graph/types.py new file mode 100644 index 0000000..7b271f2 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/graph/types.py @@ -0,0 +1,35 @@ +"""GraphQL types for stored files.""" + +from typing import Any + +import strawberry + + +@strawberry.type +class FileType: + id: str + owner_id: str + name: str + content_type: str + size: int + created_at: str + + +@strawberry.type +class FilePageType: + files: list[FileType] + total: int + limit: int + offset: int + + +@strawberry.type +class FileContentType: + """A file and its bytes, base64-encoded because GraphQL has no binary scalar.""" + + file: FileType + content_base64: str + + +def file_type(row: dict[str, Any]) -> FileType: + return FileType(**row) diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/__init__.py b/src/django_ninja_starter/template/src/apps/files/grpc/__init__.py new file mode 100644 index 0000000..889fde6 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/__init__.py @@ -0,0 +1,5 @@ +"""The gRPC transport for the files app. + +The generated stubs live here beside the ``.proto`` that produced them. +Regenerate with ``python manage.py protos``. +""" diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/files.proto b/src/django_ninja_starter/template/src/apps/files/grpc/files.proto new file mode 100644 index 0000000..3a06cbe --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/files.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package config.files; + +service FileController { + rpc Delete(DeleteRequest) returns (DeleteResult) {} + rpc Download(DownloadRequest) returns (FileContent) {} + rpc Get(GetRequest) returns (StoredFile) {} + rpc List(ListRequest) returns (FileList) {} + rpc Upload(UploadRequest) returns (StoredFile) {} +} + +message DeleteRequest { + string file_id = 1; +} + +message DeleteResult { + string id = 1; + bool deleted = 2; +} + +message DownloadRequest { + string file_id = 1; +} + +message FileContent { + StoredFile file = 1; + bytes content = 2; +} + +message FileList { + repeated StoredFile files = 1; + int32 total = 2; + int32 limit = 3; + int32 offset = 4; +} + +message GetRequest { + string file_id = 1; +} + +message ListRequest { + int32 limit = 1; + int32 offset = 2; +} + +message StoredFile { + string id = 1; + string owner_id = 2; + string name = 3; + string content_type = 4; + int32 size = 5; + string created_at = 6; +} + +message UploadRequest { + string name = 1; + bytes content = 2; +} + diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.py b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.py new file mode 100644 index 0000000..dfc7db5 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: apps/files/grpc/files.proto +# Protobuf Python Version: 7.35.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 7, + 35, + 1, + '', + 'apps/files/grpc/files.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1b\x61pps/files/grpc/files.proto\x12\x0c\x63onfig.files\" \n\rDeleteRequest\x12\x0f\n\x07\x66ile_id\x18\x01 \x01(\t\"+\n\x0c\x44\x65leteResult\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0f\n\x07\x64\x65leted\x18\x02 \x01(\x08\"\"\n\x0f\x44ownloadRequest\x12\x0f\n\x07\x66ile_id\x18\x01 \x01(\t\"F\n\x0b\x46ileContent\x12&\n\x04\x66ile\x18\x01 \x01(\x0b\x32\x18.config.files.StoredFile\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\x0c\"a\n\x08\x46ileList\x12\'\n\x05\x66iles\x18\x01 \x03(\x0b\x32\x18.config.files.StoredFile\x12\r\n\x05total\x18\x02 \x01(\x05\x12\r\n\x05limit\x18\x03 \x01(\x05\x12\x0e\n\x06offset\x18\x04 \x01(\x05\"\x1d\n\nGetRequest\x12\x0f\n\x07\x66ile_id\x18\x01 \x01(\t\",\n\x0bListRequest\x12\r\n\x05limit\x18\x01 \x01(\x05\x12\x0e\n\x06offset\x18\x02 \x01(\x05\"p\n\nStoredFile\x12\n\n\x02id\x18\x01 \x01(\t\x12\x10\n\x08owner_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x14\n\x0c\x63ontent_type\x18\x04 \x01(\t\x12\x0c\n\x04size\x18\x05 \x01(\x05\x12\x12\n\ncreated_at\x18\x06 \x01(\t\".\n\rUploadRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\x0c\x32\xda\x02\n\x0e\x46ileController\x12\x43\n\x06\x44\x65lete\x12\x1b.config.files.DeleteRequest\x1a\x1a.config.files.DeleteResult\"\x00\x12\x46\n\x08\x44ownload\x12\x1d.config.files.DownloadRequest\x1a\x19.config.files.FileContent\"\x00\x12;\n\x03Get\x12\x18.config.files.GetRequest\x1a\x18.config.files.StoredFile\"\x00\x12;\n\x04List\x12\x19.config.files.ListRequest\x1a\x16.config.files.FileList\"\x00\x12\x41\n\x06Upload\x12\x1b.config.files.UploadRequest\x1a\x18.config.files.StoredFile\"\x00\x62\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.files.grpc.files_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR._loaded_options = None + _globals['_DELETEREQUEST']._serialized_start=45 + _globals['_DELETEREQUEST']._serialized_end=77 + _globals['_DELETERESULT']._serialized_start=79 + _globals['_DELETERESULT']._serialized_end=122 + _globals['_DOWNLOADREQUEST']._serialized_start=124 + _globals['_DOWNLOADREQUEST']._serialized_end=158 + _globals['_FILECONTENT']._serialized_start=160 + _globals['_FILECONTENT']._serialized_end=230 + _globals['_FILELIST']._serialized_start=232 + _globals['_FILELIST']._serialized_end=329 + _globals['_GETREQUEST']._serialized_start=331 + _globals['_GETREQUEST']._serialized_end=360 + _globals['_LISTREQUEST']._serialized_start=362 + _globals['_LISTREQUEST']._serialized_end=406 + _globals['_STOREDFILE']._serialized_start=408 + _globals['_STOREDFILE']._serialized_end=520 + _globals['_UPLOADREQUEST']._serialized_start=522 + _globals['_UPLOADREQUEST']._serialized_end=568 + _globals['_FILECONTROLLER']._serialized_start=571 + _globals['_FILECONTROLLER']._serialized_end=917 +# @@protoc_insertion_point(module_scope) diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.pyi b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.pyi new file mode 100644 index 0000000..454d071 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2.pyi @@ -0,0 +1,228 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from collections import abc as _abc +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers +import builtins as _builtins +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import TypeAlias as _TypeAlias, Never as _Never +else: + from typing_extensions import TypeAlias as _TypeAlias, Never as _Never + +DESCRIPTOR: _descriptor.FileDescriptor + +@_typing.final +class DeleteRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_ID_FIELD_NUMBER: _builtins.int + file_id: _builtins.str + def __init__( + self, + *, + file_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["file_id", b"file_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteRequest: _TypeAlias = DeleteRequest # noqa: Y015 + +@_typing.final +class DeleteResult(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + DELETED_FIELD_NUMBER: _builtins.int + id: _builtins.str + deleted: _builtins.bool + def __init__( + self, + *, + id: _builtins.str = ..., + deleted: _builtins.bool = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["deleted", b"deleted", "id", b"id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DeleteResult: _TypeAlias = DeleteResult # noqa: Y015 + +@_typing.final +class DownloadRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_ID_FIELD_NUMBER: _builtins.int + file_id: _builtins.str + def __init__( + self, + *, + file_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["file_id", b"file_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DownloadRequest: _TypeAlias = DownloadRequest # noqa: Y015 + +@_typing.final +class FileContent(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_FIELD_NUMBER: _builtins.int + CONTENT_FIELD_NUMBER: _builtins.int + content: _builtins.bytes + @_builtins.property + def file(self) -> Global___StoredFile: ... + def __init__( + self, + *, + file: Global___StoredFile | None = ..., + content: _builtins.bytes = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["file", b"file"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["content", b"content", "file", b"file"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___FileContent: _TypeAlias = FileContent # noqa: Y015 + +@_typing.final +class FileList(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILES_FIELD_NUMBER: _builtins.int + TOTAL_FIELD_NUMBER: _builtins.int + LIMIT_FIELD_NUMBER: _builtins.int + OFFSET_FIELD_NUMBER: _builtins.int + total: _builtins.int + limit: _builtins.int + offset: _builtins.int + @_builtins.property + def files(self) -> _containers.RepeatedCompositeFieldContainer[Global___StoredFile]: ... + def __init__( + self, + *, + files: _abc.Iterable[Global___StoredFile] | None = ..., + total: _builtins.int = ..., + limit: _builtins.int = ..., + offset: _builtins.int = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["files", b"files", "limit", b"limit", "offset", b"offset", "total", b"total"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___FileList: _TypeAlias = FileList # noqa: Y015 + +@_typing.final +class GetRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + FILE_ID_FIELD_NUMBER: _builtins.int + file_id: _builtins.str + def __init__( + self, + *, + file_id: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["file_id", b"file_id"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___GetRequest: _TypeAlias = GetRequest # noqa: Y015 + +@_typing.final +class ListRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + LIMIT_FIELD_NUMBER: _builtins.int + OFFSET_FIELD_NUMBER: _builtins.int + limit: _builtins.int + offset: _builtins.int + def __init__( + self, + *, + limit: _builtins.int = ..., + offset: _builtins.int = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["limit", b"limit", "offset", b"offset"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___ListRequest: _TypeAlias = ListRequest # noqa: Y015 + +@_typing.final +class StoredFile(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + ID_FIELD_NUMBER: _builtins.int + OWNER_ID_FIELD_NUMBER: _builtins.int + NAME_FIELD_NUMBER: _builtins.int + CONTENT_TYPE_FIELD_NUMBER: _builtins.int + SIZE_FIELD_NUMBER: _builtins.int + CREATED_AT_FIELD_NUMBER: _builtins.int + id: _builtins.str + owner_id: _builtins.str + name: _builtins.str + content_type: _builtins.str + size: _builtins.int + created_at: _builtins.str + def __init__( + self, + *, + id: _builtins.str = ..., + owner_id: _builtins.str = ..., + name: _builtins.str = ..., + content_type: _builtins.str = ..., + size: _builtins.int = ..., + created_at: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["content_type", b"content_type", "created_at", b"created_at", "id", b"id", "name", b"name", "owner_id", b"owner_id", "size", b"size"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___StoredFile: _TypeAlias = StoredFile # noqa: Y015 + +@_typing.final +class UploadRequest(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + NAME_FIELD_NUMBER: _builtins.int + CONTENT_FIELD_NUMBER: _builtins.int + name: _builtins.str + content: _builtins.bytes + def __init__( + self, + *, + name: _builtins.str = ..., + content: _builtins.bytes = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["content", b"content", "name", b"name"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___UploadRequest: _TypeAlias = UploadRequest # noqa: Y015 diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.py new file mode 100644 index 0000000..daf42ea --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.py @@ -0,0 +1,269 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc +import warnings + +from apps.files.grpc import files_pb2 as apps_dot_files_dot_grpc_dot_files__pb2 + +GRPC_GENERATED_VERSION = '1.84.0' +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) +except ImportError: + _version_not_supported = True + +if _version_not_supported: + raise RuntimeError( + f'The grpc package installed is at version {GRPC_VERSION},' + + ' but the generated code in apps/files/grpc/files_pb2_grpc.py depends on' + + f' grpcio>={GRPC_GENERATED_VERSION}.' + + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' + + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' + ) + + +class FileControllerStub: + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Delete = channel.unary_unary( + '/config.files.FileController/Delete', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteResult.FromString, + _registered_method=True) + self.Download = channel.unary_unary( + '/config.files.FileController/Download', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.DownloadRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.FileContent.FromString, + _registered_method=True) + self.Get = channel.unary_unary( + '/config.files.FileController/Get', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.GetRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + _registered_method=True) + self.List = channel.unary_unary( + '/config.files.FileController/List', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.ListRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.FileList.FromString, + _registered_method=True) + self.Upload = channel.unary_unary( + '/config.files.FileController/Upload', + request_serializer=apps_dot_files_dot_grpc_dot_files__pb2.UploadRequest.SerializeToString, + response_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + _registered_method=True) + + +class FileControllerServicer: + """Missing associated documentation comment in .proto file.""" + + def Delete(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Download(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Get(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def List(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Upload(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_FileControllerServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Delete': grpc.unary_unary_rpc_method_handler( + servicer.Delete, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.DeleteResult.SerializeToString, + ), + 'Download': grpc.unary_unary_rpc_method_handler( + servicer.Download, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.DownloadRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.FileContent.SerializeToString, + ), + 'Get': grpc.unary_unary_rpc_method_handler( + servicer.Get, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.GetRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.SerializeToString, + ), + 'List': grpc.unary_unary_rpc_method_handler( + servicer.List, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.ListRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.FileList.SerializeToString, + ), + 'Upload': grpc.unary_unary_rpc_method_handler( + servicer.Upload, + request_deserializer=apps_dot_files_dot_grpc_dot_files__pb2.UploadRequest.FromString, + response_serializer=apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'config.files.FileController', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + server.add_registered_method_handlers('config.files.FileController', rpc_method_handlers) + + + # This class is part of an EXPERIMENTAL API. +class FileController: + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def Delete(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Delete', + apps_dot_files_dot_grpc_dot_files__pb2.DeleteRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.DeleteResult.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Download(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Download', + apps_dot_files_dot_grpc_dot_files__pb2.DownloadRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.FileContent.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Get(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Get', + apps_dot_files_dot_grpc_dot_files__pb2.GetRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def List(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/List', + apps_dot_files_dot_grpc_dot_files__pb2.ListRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.FileList.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def Upload(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/config.files.FileController/Upload', + apps_dot_files_dot_grpc_dot_files__pb2.UploadRequest.SerializeToString, + apps_dot_files_dot_grpc_dot_files__pb2.StoredFile.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.pyi b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.pyi new file mode 100644 index 0000000..b5a4105 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/files_pb2_grpc.pyi @@ -0,0 +1,85 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +from apps.files.grpc import files_pb2 as _files_pb2 +from collections import abc as _abc +from grpc import aio as _aio +import abc as _abc_1 +import grpc as _grpc +import sys +import typing as _typing + +if sys.version_info >= (3, 11): + from typing import Self as _Self +else: + from typing_extensions import Self as _Self + +_T = _typing.TypeVar("_T") + +class _MaybeAsyncIterator(_abc.AsyncIterator[_T], _abc.Iterator[_T], metaclass=_abc_1.ABCMeta): ... + +class _ServicerContext(_grpc.ServicerContext, _aio.ServicerContext): # type: ignore[misc, type-arg] + ... + +GRPC_GENERATED_VERSION: str +GRPC_VERSION: str + +class FileControllerStub: + @_typing.overload + def __new__(cls, channel: _grpc.Channel) -> _Self: ... + @_typing.overload + def __new__(cls, channel: _aio.Channel) -> FileControllerAsyncStub: ... + Delete: _grpc.UnaryUnaryMultiCallable[_files_pb2.DeleteRequest, _files_pb2.DeleteResult] + Download: _grpc.UnaryUnaryMultiCallable[_files_pb2.DownloadRequest, _files_pb2.FileContent] + Get: _grpc.UnaryUnaryMultiCallable[_files_pb2.GetRequest, _files_pb2.StoredFile] + List: _grpc.UnaryUnaryMultiCallable[_files_pb2.ListRequest, _files_pb2.FileList] + Upload: _grpc.UnaryUnaryMultiCallable[_files_pb2.UploadRequest, _files_pb2.StoredFile] + +@_typing.type_check_only +class FileControllerAsyncStub(FileControllerStub): + def __init__(self, channel: _aio.Channel) -> None: ... + Delete: _aio.UnaryUnaryMultiCallable[_files_pb2.DeleteRequest, _files_pb2.DeleteResult] # type: ignore[assignment] + Download: _aio.UnaryUnaryMultiCallable[_files_pb2.DownloadRequest, _files_pb2.FileContent] # type: ignore[assignment] + Get: _aio.UnaryUnaryMultiCallable[_files_pb2.GetRequest, _files_pb2.StoredFile] # type: ignore[assignment] + List: _aio.UnaryUnaryMultiCallable[_files_pb2.ListRequest, _files_pb2.FileList] # type: ignore[assignment] + Upload: _aio.UnaryUnaryMultiCallable[_files_pb2.UploadRequest, _files_pb2.StoredFile] # type: ignore[assignment] + +class FileControllerServicer(metaclass=_abc_1.ABCMeta): + @_abc_1.abstractmethod + def Delete( + self, + request: _files_pb2.DeleteRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.DeleteResult, _abc.Awaitable[_files_pb2.DeleteResult]]: ... + + @_abc_1.abstractmethod + def Download( + self, + request: _files_pb2.DownloadRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.FileContent, _abc.Awaitable[_files_pb2.FileContent]]: ... + + @_abc_1.abstractmethod + def Get( + self, + request: _files_pb2.GetRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.StoredFile, _abc.Awaitable[_files_pb2.StoredFile]]: ... + + @_abc_1.abstractmethod + def List( + self, + request: _files_pb2.ListRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.FileList, _abc.Awaitable[_files_pb2.FileList]]: ... + + @_abc_1.abstractmethod + def Upload( + self, + request: _files_pb2.UploadRequest, + context: _ServicerContext, + ) -> _typing.Union[_files_pb2.StoredFile, _abc.Awaitable[_files_pb2.StoredFile]]: ... + +def add_FileControllerServicer_to_server(servicer: FileControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ... diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/serializers.py b/src/django_ninja_starter/template/src/apps/files/grpc/serializers.py new file mode 100644 index 0000000..c50d38a --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/serializers.py @@ -0,0 +1,14 @@ +"""The nested message the file service answers with.""" + +from rest_framework import serializers + + +class StoredFile(serializers.Serializer[dict[str, object]]): + """One stored file's metadata.""" + + id = serializers.CharField() + owner_id = serializers.CharField() + name = serializers.CharField() + content_type = serializers.CharField() + size = serializers.IntegerField() + created_at = serializers.CharField() diff --git a/src/django_ninja_starter/template/src/apps/files/grpc/services.py b/src/django_ninja_starter/template/src/apps/files/grpc/services.py new file mode 100644 index 0000000..a2ecb81 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/grpc/services.py @@ -0,0 +1,123 @@ +"""Uploading, listing, downloading and deleting files over gRPC. + +The calls mirror the REST endpoints one for one, with the bytes carried as a +protobuf ``bytes`` field rather than a multipart body. +""" + +from typing import Any + +from asgiref.sync import sync_to_async +from django.core.exceptions import ValidationError +from django.core.files.base import ContentFile +from django_socio_grpc import generics +from django_socio_grpc.decorators import grpc_action + +from apps.files import services +from apps.files.grpc.serializers import StoredFile +from infrastructure.common.errors import ApiError +from infrastructure.common.grpc.errors import action, require_caller +from infrastructure.common.identity import grpc_caller +from infrastructure.common.responses import ResponseTitle + +FILE_ID = [{"name": "file_id", "type": "string"}] + + +def _pb2() -> Any: + from apps.files.grpc import files_pb2 + + return files_pb2 + + +def _message(row: dict[str, Any]) -> Any: + return _pb2().StoredFile(**row) + + +async def _found(method: Any, *args: Any) -> Any: + try: + return await sync_to_async(method)(*args) + except services.FileNotFound as error: + raise ApiError("No such file.", status=404, title=ResponseTitle.NOT_FOUND) from error + + +def _store(user: Any, name: str, content: bytes) -> dict[str, Any]: + try: + return services.upload(user, name, ContentFile(content), len(content)) + except ValidationError as refused: + raise ApiError("; ".join(refused.messages), status=400) from refused + + +class FileService(generics.GenericService): + """The same calls the REST router publishes under `/files`.""" + + @grpc_action( + request=[{"name": "limit", "type": "int32"}, {"name": "offset", "type": "int32"}], + request_name="ListRequest", + response=[ + {"name": "files", "cardinality": "repeated", "type": StoredFile}, + {"name": "total", "type": "int32"}, + {"name": "limit", "type": "int32"}, + {"name": "offset", "type": "int32"}, + ], + response_name="FileList", + ) + @action + async def List(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + page = await sync_to_async(services.list_files)( + user, limit=request.limit or services.DEFAULT_PAGE, offset=request.offset + ) + return _pb2().FileList( + files=[_message(row) for row in page["files"]], + total=page["total"], + limit=page["limit"], + offset=page["offset"], + ) + + @grpc_action( + request=FILE_ID, request_name="GetRequest", response=StoredFile, response_name="StoredFile" + ) + @action + async def Get(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + return _message(await _found(services.get, user, request.file_id)) + + @grpc_action( + request=[{"name": "name", "type": "string"}, {"name": "content", "type": "bytes"}], + request_name="UploadRequest", + response=StoredFile, + response_name="StoredFile", + ) + @action + async def Upload(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + return _message(await sync_to_async(_store)(user, request.name, request.content)) + + @grpc_action( + request=FILE_ID, + request_name="DownloadRequest", + response=[ + {"name": "file", "type": StoredFile}, + {"name": "content", "type": "bytes"}, + ], + response_name="FileContent", + ) + @action + async def Download(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + meta, content = await _found(services.read, user, request.file_id) + return _pb2().FileContent(file=_message(meta), content=content) + + @grpc_action( + request=FILE_ID, + request_name="DeleteRequest", + response=[{"name": "id", "type": "string"}, {"name": "deleted", "type": "bool"}], + response_name="DeleteResult", + ) + @action + async def Delete(self, request: Any, context: Any) -> Any: + user = require_caller(await grpc_caller(context)) + await _found(services.delete, user, request.file_id) + return _pb2().DeleteResult(id=request.file_id, deleted=True) + + +GRPC_SERVICES = [FileService] diff --git a/src/django_ninja_starter/template/src/apps/files/migrations/0001_initial.py b/src/django_ninja_starter/template/src/apps/files/migrations/0001_initial.py new file mode 100644 index 0000000..48ea404 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/migrations/0001_initial.py @@ -0,0 +1,65 @@ +# Generated by Django 6.1.3 on 2026-11-26 14:29 + +import uuid + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="StoredFile", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, editable=False, primary_key=True, serialize=False + ), + ), + ( + "name", + models.CharField( + help_text="The name the uploader gave the file.", max_length=255 + ), + ), + ( + "storage_key", + models.CharField( + editable=False, + help_text="Where the bytes live in the configured storage. Random, never the upload name.", + max_length=255, + unique=True, + ), + ), + ( + "content_type", + models.CharField( + help_text="What the content was sniffed to be, not what the client said.", + max_length=120, + ), + ), + ("size", models.PositiveBigIntegerField()), + ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)), + ( + "owner", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="stored_files", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "verbose_name": "file", + "ordering": ("-created_at",), + }, + ), + ] diff --git a/src/django_ninja_starter/template/src/apps/files/migrations/__init__.py b/src/django_ninja_starter/template/src/apps/files/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/files/models.py b/src/django_ninja_starter/template/src/apps/files/models.py new file mode 100644 index 0000000..d95ec1f --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/models.py @@ -0,0 +1,47 @@ +"""A file somebody uploaded, and who it belongs to. + +The bytes live in Django's configured storage (local disk by default, S3 when +``DJANGO_STORAGE_BACKEND=s3``); the row holds the key it was saved under, the +name the uploader gave it, and what its content was sniffed to be. +""" + +import uuid +from typing import Any + +from django.conf import settings +from django.core.files.storage import default_storage +from django.db import models +from django.db.models.signals import post_delete +from django.dispatch import receiver + + +class StoredFile(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + owner = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="stored_files" + ) + name = models.CharField(max_length=255, help_text="The name the uploader gave the file.") + storage_key = models.CharField( + max_length=255, + unique=True, + editable=False, + help_text="Where the bytes live in the configured storage. Random, never the upload name.", + ) + content_type = models.CharField( + max_length=120, help_text="What the content was sniffed to be, not what the client said." + ) + size = models.PositiveBigIntegerField() + created_at = models.DateTimeField(auto_now_add=True, db_index=True) + + class Meta: + ordering = ("-created_at",) + verbose_name = "file" + + def __str__(self) -> str: + return self.name + + +@receiver(post_delete, sender=StoredFile) +def _delete_bytes(sender: Any, instance: StoredFile, **kwargs: Any) -> None: + """Delete the bytes with the row, however the row went (service, admin, cascade).""" + default_storage.delete(instance.storage_key) diff --git a/src/django_ninja_starter/template/src/apps/files/rest/__init__.py b/src/django_ninja_starter/template/src/apps/files/rest/__init__.py new file mode 100644 index 0000000..14dbb6e --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/rest/__init__.py @@ -0,0 +1,5 @@ +"""The HTTP transport for the files app.""" + +from apps.files.rest.v1 import router + +__all__ = ["router"] diff --git a/src/django_ninja_starter/template/src/apps/files/rest/schemas.py b/src/django_ninja_starter/template/src/apps/files/rest/schemas.py new file mode 100644 index 0000000..8f6ba55 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/rest/schemas.py @@ -0,0 +1,29 @@ +"""The contract the file endpoints publish.""" + +from datetime import datetime +from uuid import UUID + +from ninja import Schema + + +class FileOut(Schema): + """One stored file's metadata. The bytes come from `/files/{id}/download`.""" + + id: UUID + owner_id: str + name: str + content_type: str + size: int + created_at: datetime + + +class FilePage(Schema): + files: list[FileOut] + total: int + limit: int + offset: int + + +class DeletedOut(Schema): + id: UUID + deleted: bool diff --git a/src/django_ninja_starter/template/src/apps/files/rest/v1.py b/src/django_ninja_starter/template/src/apps/files/rest/v1.py new file mode 100644 index 0000000..c4d5109 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/rest/v1.py @@ -0,0 +1,79 @@ +"""Uploading, listing, downloading and deleting files over HTTP. + +Every decision is :mod:`apps.files.services`'s. A file belonging to somebody +else answers 404, exactly as a missing one does, unless the caller is staff. +""" + +from typing import Any +from uuid import UUID + +from django.core.exceptions import ValidationError +from django.http import FileResponse, HttpRequest +from ninja import File, Router +from ninja.errors import HttpError +from ninja.files import UploadedFile + +from apps.files import services +from apps.files.rest.schemas import DeletedOut, FileOut, FilePage + +try: # pragma: no cover - exercised by whichever branch the project installs + from infrastructure.auth.core.sessions import api_auth +except ImportError: # pragma: no cover - only in a project without the auth apps + from ninja.security import django_auth as api_auth # type: ignore[assignment] + +from infrastructure.common.throttling import upload_throttles + +router = Router(auth=api_auth) + + +def _found(method: Any, *args: Any) -> Any: + try: + return method(*args) + except services.FileNotFound as missing: + raise HttpError(404, str(missing)) from None + + +@router.post( + "", + response={201: FileOut}, + throttle=upload_throttles(), + summary="Upload a file", +) +def upload_file( + request: HttpRequest, + # `File(...)` in the default is how django-ninja declares a multipart body. + file: UploadedFile = File(...), # noqa: B008 +) -> tuple[int, dict[str, Any]]: + """Store one file owned by the caller. The content is sniffed, not trusted.""" + try: + return 201, services.upload(request.user, file.name or "", file, file.size or 0) + except ValidationError as refused: + raise HttpError(400, "; ".join(refused.messages)) from None + + +@router.get("", response=FilePage, summary="List files this account may see") +def list_files( + request: HttpRequest, limit: int = services.DEFAULT_PAGE, offset: int = 0 +) -> dict[str, Any]: + """The caller's own files, newest first; every file for staff.""" + return services.list_files(request.user, limit=limit, offset=offset) + + +@router.get("/{file_id}", response=FileOut, summary="Read one file's metadata") +def get_file(request: HttpRequest, file_id: UUID) -> dict[str, Any]: + return _found(services.get, request.user, file_id) + + +@router.get("/{file_id}/download", summary="Download one file's bytes") +def download_file(request: HttpRequest, file_id: UUID) -> FileResponse: + """Always an attachment, with the sniffed type, so nothing renders inline.""" + meta, handle = _found(services.open_file, request.user, file_id) + return FileResponse( + handle, as_attachment=True, filename=meta["name"], content_type=meta["content_type"] + ) + + +@router.delete("/{file_id}", response=DeletedOut, summary="Delete one file") +def delete_file(request: HttpRequest, file_id: UUID) -> dict[str, Any]: + _found(services.delete, request.user, file_id) + return {"id": file_id, "deleted": True} diff --git a/src/django_ninja_starter/template/src/apps/files/services.py b/src/django_ninja_starter/template/src/apps/files/services.py new file mode 100644 index 0000000..bb76567 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/services.py @@ -0,0 +1,150 @@ +"""Every decision the files app makes, for all three transports. + +* **What may be stored.** A size limit checked before anything is read, then + the content sniffed from its first bytes. The extension must be one the + sniffed type is known by: a PNG named ``.pdf`` and an HTML page named ``.txt`` + are both refused, and nothing that is not on :data:`ALLOWED_TYPES` gets in. +* **Where it goes.** A random key under ``FILES_UPLOAD_PATH``, grouped by day. + The uploader's name is kept on the row, never in the key. +* **Who may see it.** The owner, and staff. Anybody else gets the same "not + found" a missing id gets, so an id never confirms another account's file. +""" + +import posixpath +import uuid +from typing import IO, Any +from uuid import UUID + +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.files.storage import default_storage +from django.db.models import QuerySet +from django.utils import timezone + +from apps.files.models import StoredFile +from infrastructure.common.uploads import SNIFF_BYTES, check_size, extension_of, sniff + +DEFAULT_PAGE = 50 +MAX_PAGE = 100 + +#: Sniffed type -> the extensions a file of that type may be named with. Office +#: documents are zip archives, so they sniff as one. Nothing a browser executes +#: is here: text is served as ``text/plain`` whatever it is named, and ``.html``, +#: ``.svg`` and ``.xml`` are not on any list. +ALLOWED_TYPES: dict[str, tuple[str, ...]] = { + "image/png": (".png",), + "image/jpeg": (".jpg", ".jpeg"), + "image/gif": (".gif",), + "image/webp": (".webp",), + "application/pdf": (".pdf",), + "application/zip": (".zip", ".docx", ".xlsx", ".pptx"), + "application/gzip": (".gz",), + "text/plain": (".txt", ".csv", ".json", ".md", ".log"), +} + + +class FileNotFound(LookupError): + """No such file, or not one this account may see. Deliberately the same thing.""" + + +def upload_root() -> str: + return str(settings.FILES_UPLOAD_PATH).strip("/") + + +def window(limit: int, offset: int) -> tuple[int, int]: + """Clamp a page request to something the database should be asked for.""" + return max(1, min(limit, MAX_PAGE)), max(0, offset) + + +def payload(row: StoredFile) -> dict[str, Any]: + return { + "id": str(row.id), + "owner_id": str(row.owner_id), + "name": row.name, + "content_type": row.content_type, + "size": row.size, + "created_at": row.created_at.isoformat(), + } + + +def _visible(user: Any) -> QuerySet[StoredFile]: + if user.is_staff: + return StoredFile.objects.all() + return StoredFile.objects.filter(owner=user) + + +def _row(user: Any, file_id: UUID | str) -> StoredFile: + try: + return _visible(user).get(pk=UUID(str(file_id))) + except (StoredFile.DoesNotExist, ValueError): + raise FileNotFound("No such file.") from None + + +def validate(name: str, content: IO[bytes], size: int) -> str: + """Return the sniffed content type, or raise :class:`ValidationError`.""" + check_size(size, int(settings.FILES_MAX_UPLOAD_BYTES)) + content.seek(0) + content_type = sniff(content.read(SNIFF_BYTES)) + content.seek(0) + if content_type not in ALLOWED_TYPES: + raise ValidationError("That kind of file is not accepted.") + extension = extension_of(name) + if extension not in ALLOWED_TYPES[content_type]: + raise ValidationError( + f"The content is {content_type}, which may be named " + f"{', '.join(ALLOWED_TYPES[content_type])}, not {extension or 'with no extension'}." + ) + return content_type + + +def upload(user: Any, name: str, content: IO[bytes], size: int) -> dict[str, Any]: + """Validate and store one file owned by ``user``.""" + content_type = validate(name, content, size) + key = posixpath.join( + upload_root(), f"{timezone.now():%Y/%m/%d}", uuid.uuid4().hex + extension_of(name) + ) + stored = default_storage.save(key, content) + try: + row = StoredFile.objects.create( + owner=user, + name=posixpath.basename(name.replace("\\", "/"))[:255] or "file", + storage_key=stored, + content_type=content_type, + size=size, + ) + except Exception: + default_storage.delete(stored) + raise + return payload(row) + + +def list_files(user: Any, *, limit: int = DEFAULT_PAGE, offset: int = 0) -> dict[str, Any]: + limit, offset = window(limit, offset) + rows = _visible(user) + return { + "files": [payload(row) for row in rows[offset : offset + limit]], + "total": rows.count(), + "limit": limit, + "offset": offset, + } + + +def get(user: Any, file_id: UUID | str) -> dict[str, Any]: + return payload(_row(user, file_id)) + + +def open_file(user: Any, file_id: UUID | str) -> tuple[dict[str, Any], IO[bytes]]: + """The file's metadata and an open binary handle the caller must close.""" + row = _row(user, file_id) + return payload(row), default_storage.open(row.storage_key, "rb") + + +def read(user: Any, file_id: UUID | str) -> tuple[dict[str, Any], bytes]: + meta, handle = open_file(user, file_id) + with handle: + return meta, handle.read() + + +def delete(user: Any, file_id: UUID | str) -> None: + """Remove the row; its ``post_delete`` signal removes the bytes.""" + _row(user, file_id).delete() diff --git a/src/django_ninja_starter/template/src/apps/files/tests/__init__.py b/src/django_ninja_starter/template/src/apps/files/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_ninja_starter/template/src/apps/files/tests/conftest.py b/src/django_ninja_starter/template/src/apps/files/tests/conftest.py new file mode 100644 index 0000000..204cf58 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/tests/conftest.py @@ -0,0 +1,45 @@ +"""Shared fixtures: two accounts, a member of staff, and storage in memory.""" + +from typing import Any + +import pytest +from django.contrib.auth import get_user_model +from django.test import RequestFactory + +PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64 +PDF = b"%PDF-1.7\n" + b"x" * 64 + + +@pytest.fixture(autouse=True) +def _memory_storage(settings: Any) -> None: + settings.STORAGES = { + **settings.STORAGES, + "default": {"BACKEND": "django.core.files.storage.InMemoryStorage"}, + } + + +@pytest.fixture +def alice(transactional_db: None) -> Any: + return get_user_model().objects.create_user(username="alice", email="alice@example.test") + + +@pytest.fixture +def bob(transactional_db: None) -> Any: + return get_user_model().objects.create_user(username="bob", email="bob@example.test") + + +@pytest.fixture +def staff(transactional_db: None) -> Any: + return get_user_model().objects.create_user( + username="staff", email="staff@example.test", is_staff=True + ) + + +def access_token(user: Any) -> str: + from infrastructure.auth.core.sessions import issue_credentials + + return issue_credentials(RequestFactory().post("/"), user, method="password").access_token + + +def bearer(user: Any) -> dict[str, str]: + return {"HTTP_AUTHORIZATION": f"Bearer {access_token(user)}"} diff --git a/src/django_ninja_starter/template/src/apps/files/tests/test_api.py b/src/django_ninja_starter/template/src/apps/files/tests/test_api.py new file mode 100644 index 0000000..1297697 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/tests/test_api.py @@ -0,0 +1,61 @@ +"""The HTTP transport.""" + +from typing import Any + +import pytest +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import Client + +from apps.files.tests.conftest import PNG, bearer + +LIST = "/api/v1/files" + + +def _upload(client: Client, user: Any, name: str = "shot.png", content: bytes = PNG) -> Any: + return client.post(LIST, {"file": SimpleUploadedFile(name, content)}, **bearer(user)) + + +@pytest.mark.parametrize( + ("method", "path"), + [ + ("get", LIST), + ("post", LIST), + ("get", f"{LIST}/00000000-0000-0000-0000-000000000000"), + ("get", f"{LIST}/00000000-0000-0000-0000-000000000000/download"), + ("delete", f"{LIST}/00000000-0000-0000-0000-000000000000"), + ], +) +def test_every_endpoint_needs_a_credential(method: str, path: str, transactional_db: None) -> None: + assert getattr(Client(), method)(path).status_code == 401 + + +def test_upload_list_download_delete(alice: Any) -> None: + client = Client() + created = _upload(client, alice) + assert created.status_code == 201, created.content + file_id = created.json()["data"]["id"] + + assert client.get(LIST, **bearer(alice)).json()["data"]["total"] == 1 + download = client.get(f"{LIST}/{file_id}/download", **bearer(alice)) + assert download.status_code == 200 + assert download["Content-Type"] == "image/png" + assert download["Content-Disposition"].startswith("attachment") + assert b"".join(download.streaming_content) == PNG + + assert client.delete(f"{LIST}/{file_id}", **bearer(alice)).json()["data"]["deleted"] + assert client.get(f"{LIST}/{file_id}", **bearer(alice)).status_code == 404 + + +def test_a_disguised_file_is_a_400(alice: Any) -> None: + assert _upload(Client(), alice, "shot.pdf").status_code == 400 + + +def test_another_account_gets_404_and_staff_get_through(alice: Any, bob: Any, staff: Any) -> None: + client = Client() + file_id = _upload(client, alice).json()["data"]["id"] + + for path in (f"{LIST}/{file_id}", f"{LIST}/{file_id}/download"): + assert client.get(path, **bearer(bob)).status_code == 404 + assert client.get(path, **bearer(staff)).status_code == 200 + assert client.delete(f"{LIST}/{file_id}", **bearer(bob)).status_code == 404 + assert client.get(LIST, **bearer(bob)).json()["data"]["total"] == 0 diff --git a/src/django_ninja_starter/template/src/apps/files/tests/test_graph.py b/src/django_ninja_starter/template/src/apps/files/tests/test_graph.py new file mode 100644 index 0000000..705e529 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/tests/test_graph.py @@ -0,0 +1,49 @@ +"""The GraphQL transport: bytes travel base64-encoded.""" + +import base64 +import json +from typing import Any + +from django.test import Client + +from apps.files.tests.conftest import PNG, bearer + +UPLOAD = ( + "mutation($n: String!, $c: String!) { uploadFile(name: $n, contentBase64: $c) { id name } }" +) +LIST = "{ files { total files { id } } }" +CONTENT = "query($id: String!) { fileContent(fileId: $id) { contentBase64 file { contentType } } }" +DELETE = "mutation($id: String!) { deleteFile(fileId: $id) }" + + +def _graph(user: Any, query: str, **variables: Any) -> dict[str, Any]: + response = Client().post( + "/graphql", + data={"query": query, "variables": variables}, + content_type="application/json", + **(bearer(user) if user else {}), + ) + assert response.status_code == 200, response.content + return json.loads(response.content) + + +def test_round_trip(alice: Any, bob: Any) -> None: + encoded = base64.b64encode(PNG).decode() + file_id = _graph(alice, UPLOAD, n="a.png", c=encoded)["data"]["uploadFile"]["id"] + + assert _graph(alice, LIST)["data"]["files"]["total"] == 1 + assert _graph(bob, LIST)["data"]["files"]["total"] == 0 + content = _graph(alice, CONTENT, id=file_id)["data"]["fileContent"] + assert content["contentBase64"] == encoded + assert content["file"]["contentType"] == "image/png" + assert _graph(bob, CONTENT, id=file_id)["errors"] + assert _graph(bob, DELETE, id=file_id)["errors"] + assert _graph(alice, DELETE, id=file_id)["data"]["deleteFile"] is True + + +def test_refusals(alice: Any, settings: Any) -> None: + assert _graph(None, LIST)["errors"] + assert _graph(alice, UPLOAD, n="a.pdf", c=base64.b64encode(PNG).decode())["errors"] + assert _graph(alice, UPLOAD, n="a.png", c="not base64!")["errors"] + settings.FILES_MAX_UPLOAD_BYTES = 8 + assert _graph(alice, UPLOAD, n="a.png", c=base64.b64encode(PNG).decode())["errors"] diff --git a/src/django_ninja_starter/template/src/apps/files/tests/test_grpc.py b/src/django_ninja_starter/template/src/apps/files/tests/test_grpc.py new file mode 100644 index 0000000..c58a039 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/tests/test_grpc.py @@ -0,0 +1,41 @@ +"""The gRPC transport: bytes travel as a protobuf ``bytes`` field.""" + +from collections.abc import Callable +from typing import Any + +import grpc +import pytest + +from apps.files.grpc import files_pb2, files_pb2_grpc +from apps.files.tests.conftest import PNG, access_token + +Stub = files_pb2_grpc.FileControllerStub + + +def test_needs_a_credential(transactional_db: None, grpc_call: Callable[..., Any]) -> None: + with pytest.raises(grpc.aio.AioRpcError) as refusal: + grpc_call(Stub, "List", files_pb2.ListRequest()) + assert refusal.value.code() is grpc.StatusCode.UNAUTHENTICATED + + +def test_round_trip(alice: Any, bob: Any, grpc_call: Callable[..., Any]) -> None: + mine, theirs = access_token(alice), access_token(bob) + stored = grpc_call(Stub, "Upload", files_pb2.UploadRequest(name="a.png", content=PNG), mine) + assert stored.content_type == "image/png" + + assert grpc_call(Stub, "List", files_pb2.ListRequest(), mine).total == 1 + assert grpc_call(Stub, "Get", files_pb2.GetRequest(file_id=stored.id), mine).name == "a.png" + download = grpc_call(Stub, "Download", files_pb2.DownloadRequest(file_id=stored.id), mine) + assert download.content == PNG + with pytest.raises(grpc.aio.AioRpcError) as refusal: + grpc_call(Stub, "Download", files_pb2.DownloadRequest(file_id=stored.id), theirs) + assert refusal.value.code() is grpc.StatusCode.NOT_FOUND + deleted = grpc_call(Stub, "Delete", files_pb2.DeleteRequest(file_id=stored.id), mine) + assert deleted.deleted + + +def test_a_disguised_file_is_invalid(alice: Any, grpc_call: Callable[..., Any]) -> None: + with pytest.raises(grpc.aio.AioRpcError) as refusal: + request = files_pb2.UploadRequest(name="a.pdf", content=PNG) + grpc_call(Stub, "Upload", request, access_token(alice)) + assert refusal.value.code() is grpc.StatusCode.INVALID_ARGUMENT diff --git a/src/django_ninja_starter/template/src/apps/files/tests/test_services.py b/src/django_ninja_starter/template/src/apps/files/tests/test_services.py new file mode 100644 index 0000000..3e43185 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/tests/test_services.py @@ -0,0 +1,82 @@ +"""What may be stored, where it goes, and who may see it.""" + +from typing import Any + +import pytest +from django.core.exceptions import ValidationError +from django.core.files.base import ContentFile +from django.core.files.storage import default_storage + +from apps.files import services +from apps.files.models import StoredFile +from apps.files.tests.conftest import PDF, PNG + + +def _upload(user: Any, name: str = "shot.png", content: bytes = PNG) -> dict[str, Any]: + return services.upload(user, name, ContentFile(content), len(content)) + + +def test_a_file_is_stored_under_a_random_key_and_keeps_its_name(alice: Any) -> None: + row = _upload(alice, "../My Shot.png") + stored = StoredFile.objects.get(pk=row["id"]) + + assert row["name"] == "My Shot.png" + assert row["content_type"] == "image/png" + assert stored.storage_key.startswith("files/") + assert "Shot" not in stored.storage_key + assert stored.storage_key.endswith(".png") + assert default_storage.exists(stored.storage_key) + + +@pytest.mark.parametrize( + ("name", "content"), + [ + ("shot.pdf", PNG), # renamed image + ("page.txt", b"\x00\x01binary"), # binary named as text + ("page.html", b""), # text, but not an allowed name + ("evil.exe", b"MZ\x90\x00" + b"\x00" * 10), # unknown content + ("noext", PDF), + ], +) +def test_content_that_does_not_match_its_name_is_refused( + alice: Any, name: str, content: bytes +) -> None: + with pytest.raises(ValidationError): + _upload(alice, name, content) + assert not StoredFile.objects.exists() + + +def test_an_oversized_file_is_refused_before_it_is_read(alice: Any, settings: Any) -> None: + settings.FILES_MAX_UPLOAD_BYTES = 10 + + with pytest.raises(ValidationError, match="limit"): + _upload(alice) + + +def test_owners_see_their_own_and_staff_see_everything(alice: Any, bob: Any, staff: Any) -> None: + mine = _upload(alice) + _upload(bob, "b.pdf", PDF) + + assert [row["id"] for row in services.list_files(alice)["files"]] == [mine["id"]] + assert services.list_files(staff)["total"] == 2 + with pytest.raises(services.FileNotFound): + services.get(bob, mine["id"]) + with pytest.raises(services.FileNotFound): + services.delete(bob, mine["id"]) + with pytest.raises(services.FileNotFound): + services.get(alice, "not-a-uuid") + assert services.read(staff, mine["id"])[1] == PNG + + +def test_deleting_removes_the_bytes(alice: Any) -> None: + row = _upload(alice) + key = StoredFile.objects.get(pk=row["id"]).storage_key + + services.delete(alice, row["id"]) + + assert not StoredFile.objects.exists() + assert not default_storage.exists(key) + + +def test_the_page_is_clamped(alice: Any) -> None: + assert services.window(10_000, -5) == (services.MAX_PAGE, 0) diff --git a/src/django_ninja_starter/template/src/apps/files/tests/test_uploads.py b/src/django_ninja_starter/template/src/apps/files/tests/test_uploads.py new file mode 100644 index 0000000..dff6848 --- /dev/null +++ b/src/django_ninja_starter/template/src/apps/files/tests/test_uploads.py @@ -0,0 +1,40 @@ +"""The shared sniffing and naming helpers.""" + +import pytest +from django.core.exceptions import ValidationError + +from infrastructure.common.uploads import check_size, extension_of, safe_name, sniff + + +@pytest.mark.parametrize( + ("head", "expected"), + [ + (b"\x89PNG\r\n\x1a\nrest", "image/png"), + (b"\xff\xd8\xff\xe0", "image/jpeg"), + (b"GIF89a", "image/gif"), + (b"RIFF\x00\x00\x00\x00WEBPVP8 ", "image/webp"), + (b"%PDF-1.4", "application/pdf"), + (b"PK\x03\x04", "application/zip"), + (b"\x1f\x8b\x08", "application/gzip"), + (b"a,b\n1,2\n", "text/plain"), + ("héllo".encode()[:2], "text/plain"), + (b"MZ\x90\x00", None), + (b"\xff\xfe\xfd\xfc garbage" * 10, None), + (b"", None), + ], +) +def test_sniff_reads_the_content_not_the_name(head: bytes, expected: str | None) -> None: + assert sniff(head) == expected + + +def test_size_limit_zero_means_none() -> None: + check_size(10**12, 0) + with pytest.raises(ValidationError): + check_size(2048, 1024) + + +def test_safe_name_and_extension() -> None: + assert safe_name("../../etc/Pass wd.PNG").endswith(".png") + assert "/" not in safe_name("../../x.png") + assert extension_of("Shot.PNG") == ".png" + assert extension_of("noext") == "" diff --git a/src/django_ninja_starter/template/src/apps/support/uploads.py b/src/django_ninja_starter/template/src/apps/support/uploads.py index 17a0bfb..53b7dff 100644 --- a/src/django_ninja_starter/template/src/apps/support/uploads.py +++ b/src/django_ninja_starter/template/src/apps/support/uploads.py @@ -34,9 +34,6 @@ """ import posixpath -import re -import unicodedata -import uuid from pathlib import PurePosixPath from typing import Any @@ -46,12 +43,9 @@ from django.utils import timezone from apps.support.models import Upload +from infrastructure.common.uploads import check_size, extension_of, safe_name -#: What survives of an uploaded file's own name. Everything else becomes a -#: hyphen, because the name ends up in a URL and a storage key, and -#: "screenshot (2)+copy.png" is a different string in each of the places it is -#: written. -UNSAFE = re.compile(r"[^a-zA-Z0-9._-]+") +__all__ = ["check", "extension_of", "safe_name", "store"] #: What a client may send the desk. A allowlist rather than a blocklist: the #: interesting extensions are the ones nobody thought of, and a blocklist is a @@ -114,36 +108,9 @@ def allowed_extensions() -> tuple[str, ...]: return tuple(str(item).lower() for item in configured) -def safe_name(name: str) -> str: - """A storage-safe, URL-safe version of an uploaded file's own name. - - The stem is kept -- shortened, ASCII-folded and stripped of anything that - would need escaping -- because a folder of ``a1b2c3.png`` is unsearchable - for the agent looking for the screenshot a client sent this morning. - Uniqueness comes from a suffix rather than from the name, so two people - sending ``screenshot.png`` do not overwrite each other. - """ - stem = PurePosixPath(name or "file").name - folded = unicodedata.normalize("NFKD", stem).encode("ascii", "ignore").decode() - cleaned = UNSAFE.sub("-", folded).strip("-.") or "file" - root, _, extension = cleaned.rpartition(".") - root = (root or cleaned)[:60].strip("-") or "file" - suffix = uuid.uuid4().hex[:8] - return f"{root}-{suffix}.{extension.lower()}" if extension else f"{root}-{suffix}" - - -def extension_of(name: str) -> str: - """``"Shot.PNG"`` -> ``".png"``. Empty when the name has no extension at all.""" - _, dot, extension = PurePosixPath(name or "").name.rpartition(".") - return f".{extension.lower()}" if dot else "" - - def check(user: Any, upload: Any) -> None: """Raise :class:`ValidationError` if this file may not be stored by this account.""" - limit = max_upload_bytes() - size = getattr(upload, "size", 0) or 0 - if limit and size > limit: - raise ValidationError(f"That file is {size // 1024} KB. The limit is {limit // 1024} KB.") + check_size(getattr(upload, "size", 0) or 0, max_upload_bytes()) allowed = allowed_extensions() if allowed: # The name it will be stored under, which `safe_name` folds and trims. diff --git a/src/django_ninja_starter/template/src/config/api.py b/src/django_ninja_starter/template/src/config/api.py index 2ccd527..ae14591 100644 --- a/src/django_ninja_starter/template/src/config/api.py +++ b/src/django_ninja_starter/template/src/config/api.py @@ -48,6 +48,7 @@ def build_apis() -> dict[str, NinjaAPI]: *settings.SUPPORT_ROUTERS, *settings.WALLET_ROUTERS, *settings.WEBHOOKS_ROUTERS, + *settings.FILES_ROUTERS, ] guarded = {id(route["router"]) for route in credential_routes} api = EnvelopeAPI( diff --git a/src/django_ninja_starter/template/src/config/settings/base.py b/src/django_ninja_starter/template/src/config/settings/base.py index cbcbd3b..de026ce 100644 --- a/src/django_ninja_starter/template/src/config/settings/base.py +++ b/src/django_ninja_starter/template/src/config/settings/base.py @@ -882,6 +882,34 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: if extension.strip().strip(".") ] or None +# The files app. Optional the same way the others are: naming it installs its +# table, its routes and its admin. Files go through `STORAGES["default"]`, so +# pointing that at S3 (below) moves them without this app knowing. +FILES_ENABLED = os.getenv("DJANGO_FILES_ENABLED", "false").lower() == "true" +FILES_APP = "apps.files.apps.FilesConfig" +FILES_INSTALLED_APPS = [FILES_APP] if FILES_ENABLED else [] +FILES_TRANSPORTS = app_transports("files", ("rest", "graph", "grpc")) if FILES_ENABLED else () +FILES_ROUTERS = ( + [ + { + "prefix": "/files", + "router": "apps.files.rest.router", + "tag": "Files", + "description": ( + "Files an account uploads and owns. The content is sniffed rather " + "than trusted, stored under a random name, and only its owner or " + "staff may list, download or delete it." + ), + } + ] + if "rest" in FILES_TRANSPORTS + else [] +) +FILES_UPLOAD_PATH = os.getenv("DJANGO_FILES_UPLOAD_PATH", "files") +# Zero means no limit, for a deployment whose proxy already imposes one. +FILES_MAX_UPLOAD_MB = int(os.getenv("DJANGO_FILES_MAX_UPLOAD_MB", "10")) +FILES_MAX_UPLOAD_BYTES = FILES_MAX_UPLOAD_MB * 1024 * 1024 + OAUTH_ENCRYPTION_KEY = os.getenv("DJANGO_OAUTH_ENCRYPTION_KEY", "") OAUTH_STATE_TTL_SECONDS = int(os.getenv("DJANGO_OAUTH_STATE_TTL_SECONDS", "600")) OAUTH_HTTP_TIMEOUT_SECONDS = float(os.getenv("DJANGO_OAUTH_HTTP_TIMEOUT_SECONDS", "10")) @@ -940,6 +968,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: "apps.wallet": WALLET_TRANSPORTS, "apps.club": CLUB_TRANSPORTS, "apps.webhooks": WEBHOOKS_TRANSPORTS, + "apps.files": FILES_TRANSPORTS, } # How often one caller may ask, whichever endpoint they are asking. A correct @@ -1053,6 +1082,7 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: *WALLET_INSTALLED_APPS, *CLUB_INSTALLED_APPS, *WEBHOOKS_INSTALLED_APPS, + *FILES_INSTALLED_APPS, # The transports beside REST. Both are installed whether or not they are # published: `generateproto` and the schema check have to be able to run in a # deployment that serves neither. @@ -1189,4 +1219,29 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]: # and a project on S3 overrides STORAGES and leaves both of these unused. MEDIA_URL = os.getenv("DJANGO_MEDIA_URL", "media/") MEDIA_ROOT = os.getenv("DJANGO_MEDIA_ROOT", "") or BASE_DIR / "media" +# Where uploaded files go. `filesystem` is MEDIA_ROOT; `s3` is a bucket through +# django-storages (`pip install 'django-storages[s3]'`), configured by the +# AWS_* variables below, which django-storages reads from these settings. +STORAGE_BACKEND = os.getenv("DJANGO_STORAGE_BACKEND", "filesystem").lower() +STORAGE_BACKENDS = { + "filesystem": "django.core.files.storage.FileSystemStorage", + "s3": "storages.backends.s3.S3Storage", +} +if STORAGE_BACKEND not in STORAGE_BACKENDS: + raise ImproperlyConfigured( + f"Unknown DJANGO_STORAGE_BACKEND: {STORAGE_BACKEND}. One of: {', '.join(STORAGE_BACKENDS)}." + ) +STORAGES = { + "default": {"BACKEND": STORAGE_BACKENDS[STORAGE_BACKEND]}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}, +} +AWS_STORAGE_BUCKET_NAME = os.getenv("DJANGO_AWS_STORAGE_BUCKET_NAME", "") +AWS_S3_REGION_NAME = os.getenv("DJANGO_AWS_S3_REGION_NAME", "") or None +AWS_S3_ENDPOINT_URL = os.getenv("DJANGO_AWS_S3_ENDPOINT_URL", "") or None +AWS_ACCESS_KEY_ID = os.getenv("DJANGO_AWS_ACCESS_KEY_ID", "") or None +AWS_SECRET_ACCESS_KEY = os.getenv("DJANGO_AWS_SECRET_ACCESS_KEY", "") or None +# Private objects and signed URLs: these are people's files, not a public site. +AWS_DEFAULT_ACL = None +AWS_QUERYSTRING_AUTH = True +AWS_S3_FILE_OVERWRITE = False DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/src/django_ninja_starter/template/src/config/settings/test.py b/src/django_ninja_starter/template/src/config/settings/test.py index b52d4ab..541594f 100644 --- a/src/django_ninja_starter/template/src/config/settings/test.py +++ b/src/django_ninja_starter/template/src/config/settings/test.py @@ -7,6 +7,7 @@ os.environ.setdefault("DJANGO_WALLET_ENABLED", "true") os.environ.setdefault("DJANGO_CLUB_ENABLED", "true") os.environ.setdefault("DJANGO_WEBHOOKS_ENABLED", "true") +os.environ.setdefault("DJANGO_FILES_ENABLED", "true") os.environ.setdefault("DJANGO_OAUTH_MODE", "all") os.environ.setdefault("DJANGO_AUTH_TOKEN_MODE", "rotation") os.environ.setdefault("DJANGO_AUTH_METHODS", "password,email_code,sms_code,magic_link") diff --git a/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py b/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py index 9d54807..373e1a2 100644 --- a/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py +++ b/src/django_ninja_starter/template/src/infrastructure/common/management/commands/authdocs.py @@ -43,7 +43,18 @@ # and still get a page: the foundation every project carries, the accounts it # resolves to, and the optional feature apps. PROJECT_LABELS = frozenset( - {"accounts", "common", "cms", "club", "notifications", "shop", "support", "wallet", "webhooks"} + { + "accounts", + "common", + "cms", + "club", + "files", + "notifications", + "shop", + "support", + "wallet", + "webhooks", + } ) NONE = "_None._" diff --git a/src/django_ninja_starter/template/src/infrastructure/common/uploads.py b/src/django_ninja_starter/template/src/infrastructure/common/uploads.py new file mode 100644 index 0000000..fe372aa --- /dev/null +++ b/src/django_ninja_starter/template/src/infrastructure/common/uploads.py @@ -0,0 +1,88 @@ +"""The parts of accepting a file that do not depend on which app is accepting it. + +Shared by ``apps.support`` (attachments) and ``apps.files`` (owned files), so the +two agree on what a safe name is, how a size limit is worded and what a file's +first bytes say it is. +""" + +import re +import unicodedata +import uuid +from pathlib import PurePosixPath + +from django.core.exceptions import ValidationError + +#: What survives of an uploaded file's own name. Everything else becomes a +#: hyphen, because the name ends up in a URL and a storage key, and +#: "screenshot (2)+copy.png" is a different string in each of the places it is +#: written. +UNSAFE = re.compile(r"[^a-zA-Z0-9._-]+") + +#: How many leading bytes :func:`sniff` needs. Enough for every signature below +#: and for a fair look at whether a text file is text. +SNIFF_BYTES = 2048 + +#: Magic numbers, checked in order. ``RIFF`` needs a second look (WEBP vs WAV), +#: so it is handled in :func:`sniff` rather than here. +SIGNATURES: tuple[tuple[bytes, str], ...] = ( + (b"\x89PNG\r\n\x1a\n", "image/png"), + (b"\xff\xd8\xff", "image/jpeg"), + (b"GIF87a", "image/gif"), + (b"GIF89a", "image/gif"), + (b"%PDF-", "application/pdf"), + (b"PK\x03\x04", "application/zip"), + (b"\x1f\x8b", "application/gzip"), +) + + +def safe_name(name: str) -> str: + """A storage-safe, URL-safe version of an uploaded file's own name. + + The stem is kept -- shortened, ASCII-folded and stripped of anything that + would need escaping -- because a folder of ``a1b2c3.png`` is unsearchable + for the agent looking for the screenshot a client sent this morning. + Uniqueness comes from a suffix rather than from the name, so two people + sending ``screenshot.png`` do not overwrite each other. + """ + stem = PurePosixPath(name or "file").name + folded = unicodedata.normalize("NFKD", stem).encode("ascii", "ignore").decode() + cleaned = UNSAFE.sub("-", folded).strip("-.") or "file" + root, _, extension = cleaned.rpartition(".") + root = (root or cleaned)[:60].strip("-") or "file" + suffix = uuid.uuid4().hex[:8] + return f"{root}-{suffix}.{extension.lower()}" if extension else f"{root}-{suffix}" + + +def extension_of(name: str) -> str: + """``"Shot.PNG"`` -> ``".png"``. Empty when the name has no extension at all.""" + _, dot, extension = PurePosixPath(name or "").name.rpartition(".") + return f".{extension.lower()}" if dot else "" + + +def check_size(size: int, limit: int) -> None: + """Refuse a file over ``limit`` bytes. A limit of ``0`` means none.""" + if limit and size > limit: + raise ValidationError(f"That file is {size // 1024} KB. The limit is {limit // 1024} KB.") + + +def sniff(head: bytes) -> str | None: + """What a file's first bytes say it is, or ``None`` when they say nothing known. + + Text is anything that decodes as UTF-8 with no NUL byte in it -- a CSV, a log + and a JSON file all look the same from here, which is why the caller still + checks the extension against what was sniffed. + """ + for magic, content_type in SIGNATURES: + if head.startswith(magic): + return content_type + if head[:4] == b"RIFF" and head[8:12] == b"WEBP": + return "image/webp" + if not head or b"\x00" in head: + return None + try: + # A multi-byte character cut off at the end of the sample is still text. + head.decode("utf-8") + except UnicodeDecodeError as error: + if error.start < len(head) - 3: + return None + return "text/plain" diff --git a/src/infrastructure/common/management/commands/authdocs.py b/src/infrastructure/common/management/commands/authdocs.py index 9d54807..373e1a2 100644 --- a/src/infrastructure/common/management/commands/authdocs.py +++ b/src/infrastructure/common/management/commands/authdocs.py @@ -43,7 +43,18 @@ # and still get a page: the foundation every project carries, the accounts it # resolves to, and the optional feature apps. PROJECT_LABELS = frozenset( - {"accounts", "common", "cms", "club", "notifications", "shop", "support", "wallet", "webhooks"} + { + "accounts", + "common", + "cms", + "club", + "files", + "notifications", + "shop", + "support", + "wallet", + "webhooks", + } ) NONE = "_None._" diff --git a/src/infrastructure/common/uploads.py b/src/infrastructure/common/uploads.py new file mode 100644 index 0000000..fe372aa --- /dev/null +++ b/src/infrastructure/common/uploads.py @@ -0,0 +1,88 @@ +"""The parts of accepting a file that do not depend on which app is accepting it. + +Shared by ``apps.support`` (attachments) and ``apps.files`` (owned files), so the +two agree on what a safe name is, how a size limit is worded and what a file's +first bytes say it is. +""" + +import re +import unicodedata +import uuid +from pathlib import PurePosixPath + +from django.core.exceptions import ValidationError + +#: What survives of an uploaded file's own name. Everything else becomes a +#: hyphen, because the name ends up in a URL and a storage key, and +#: "screenshot (2)+copy.png" is a different string in each of the places it is +#: written. +UNSAFE = re.compile(r"[^a-zA-Z0-9._-]+") + +#: How many leading bytes :func:`sniff` needs. Enough for every signature below +#: and for a fair look at whether a text file is text. +SNIFF_BYTES = 2048 + +#: Magic numbers, checked in order. ``RIFF`` needs a second look (WEBP vs WAV), +#: so it is handled in :func:`sniff` rather than here. +SIGNATURES: tuple[tuple[bytes, str], ...] = ( + (b"\x89PNG\r\n\x1a\n", "image/png"), + (b"\xff\xd8\xff", "image/jpeg"), + (b"GIF87a", "image/gif"), + (b"GIF89a", "image/gif"), + (b"%PDF-", "application/pdf"), + (b"PK\x03\x04", "application/zip"), + (b"\x1f\x8b", "application/gzip"), +) + + +def safe_name(name: str) -> str: + """A storage-safe, URL-safe version of an uploaded file's own name. + + The stem is kept -- shortened, ASCII-folded and stripped of anything that + would need escaping -- because a folder of ``a1b2c3.png`` is unsearchable + for the agent looking for the screenshot a client sent this morning. + Uniqueness comes from a suffix rather than from the name, so two people + sending ``screenshot.png`` do not overwrite each other. + """ + stem = PurePosixPath(name or "file").name + folded = unicodedata.normalize("NFKD", stem).encode("ascii", "ignore").decode() + cleaned = UNSAFE.sub("-", folded).strip("-.") or "file" + root, _, extension = cleaned.rpartition(".") + root = (root or cleaned)[:60].strip("-") or "file" + suffix = uuid.uuid4().hex[:8] + return f"{root}-{suffix}.{extension.lower()}" if extension else f"{root}-{suffix}" + + +def extension_of(name: str) -> str: + """``"Shot.PNG"`` -> ``".png"``. Empty when the name has no extension at all.""" + _, dot, extension = PurePosixPath(name or "").name.rpartition(".") + return f".{extension.lower()}" if dot else "" + + +def check_size(size: int, limit: int) -> None: + """Refuse a file over ``limit`` bytes. A limit of ``0`` means none.""" + if limit and size > limit: + raise ValidationError(f"That file is {size // 1024} KB. The limit is {limit // 1024} KB.") + + +def sniff(head: bytes) -> str | None: + """What a file's first bytes say it is, or ``None`` when they say nothing known. + + Text is anything that decodes as UTF-8 with no NUL byte in it -- a CSV, a log + and a JSON file all look the same from here, which is why the caller still + checks the extension against what was sniffed. + """ + for magic, content_type in SIGNATURES: + if head.startswith(magic): + return content_type + if head[:4] == b"RIFF" and head[8:12] == b"WEBP": + return "image/webp" + if not head or b"\x00" in head: + return None + try: + # A multi-byte character cut off at the end of the sample is still text. + head.decode("utf-8") + except UnicodeDecodeError as error: + if error.start < len(head) - 3: + return None + return "text/plain" diff --git a/tests/test_app_isolation.py b/tests/test_app_isolation.py index 9713aec..15b75fd 100644 --- a/tests/test_app_isolation.py +++ b/tests/test_app_isolation.py @@ -38,7 +38,7 @@ METHODS = ["password", "email_code", "sms_code", "magic_link"] #: The optional apps, each of which has to install, work and be removable on its #: own. Adding an app here is what gives it isolation coverage. -FEATURE_APPS = ["cms", "club", "notifications", "shop", "support", "wallet"] +FEATURE_APPS = ["cms", "club", "files", "notifications", "shop", "support", "wallet"] TOKEN_MODES = ["sliding", "session", "rotation"] PROVIDERS = { "google": { @@ -418,6 +418,7 @@ def _admin_page(environment: dict[str, str], database: Path) -> dict[str, list[s ADMIN_SECTIONS = { "cms": "Content", "club": "Club", + "files": "Files", "notifications": "Notifications", "shop": "Shop", "support": "Support", diff --git a/tests/test_env_samples.py b/tests/test_env_samples.py index 0392250..b5fb9ec 100644 --- a/tests/test_env_samples.py +++ b/tests/test_env_samples.py @@ -29,7 +29,7 @@ EXAMPLE_SAMPLE = ROOT / "examples" / "env.example" SETTINGS = ROOT / "src" / "config" / "settings" / "base.py" -FEATURE_APPS = ("CMS", "NOTIFICATIONS", "SHOP", "SUPPORT", "WALLET", "CLUB", "WEBHOOKS") +FEATURE_APPS = ("CMS", "NOTIFICATIONS", "SHOP", "SUPPORT", "WALLET", "CLUB", "WEBHOOKS", "FILES") def flag(sample: Path, app: str) -> str | None: