diff --git a/.env.example b/.env.example
index 70645ca..da06c7a 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
@@ -218,6 +232,10 @@ DJANGO_CLUB_ENABLED=true
DJANGO_CLUB_JOIN_ON_SIGNUP=
DJANGO_CLUB_PAGE_SIZE=50
DJANGO_CLUB_MAX_PAGE_SIZE=200
+# Feature flags: a global switch, per-account overrides and a percentage
+# rollout. `apps.flags.is_enabled(key, user)` answers False while this is off.
+DJANGO_FLAGS_ENABLED=true
+# DJANGO_FLAGS_TRANSPORTS=rest,graph,grpc
# The two transports beside REST. These decide which doors are open, never what
# is behind them.
DJANGO_GRAPHQL_ENABLED=true
@@ -268,3 +286,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/.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..062aa9d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,30 +1,69 @@
-name: Publish to PyPI
+# =============================================================================
+# Release: build once, publish to PyPI with trusted publishing.
+# =============================================================================
+# 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).
+#
+# 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]
-permissions:
- contents: read
+permissions: {}
jobs:
- publish:
+ build:
+ name: Build
runs-on: ubuntu-latest
- environment:
- name: pypi
- url: https://pypi.org/p/django-ninja-starter
+ timeout-minutes: 10
permissions:
- id-token: write
+ contents: read
steps:
- - uses: actions/checkout@v6
+ - uses: actions/checkout@v7
with:
persist-credentials: false
- - uses: actions/setup-python@v6
+ - uses: astral-sh/setup-uv@v7
with:
python-version: "3.12"
- - name: Build distributions
+ - name: Tag matches the package version
run: |
- python -m pip install build
- python -m build
- - name: Publish distributions
- uses: pypa/gh-action-pypi-publish@release/v1
+ 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/CHANGELOG.md b/CHANGELOG.md
index e858309..c71895e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,34 @@ 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
+
+### Added
+
+- **`apps.audit`: an append-only audit log.** Who changed what and when (actor,
+ action, target, JSON diff, request IP), readable by staff over REST, GraphQL and
+ gRPC and never editable on any transport. Shop orders and wallet back-office
+ changes write entries. Always installed.
+- **`apps.files`: owned file uploads** (`DJANGO_FILES_ENABLED`). Django's storage
+ API, local or S3; sniffed content types, random storage names, owner-or-staff
+ access. Shares its validation with support attachments.
+- **`apps.webhooks`: signed outgoing webhooks** (`DJANGO_WEBHOOKS_ENABLED`).
+ Per-endpoint secrets, HMAC-SHA256 signatures, retries with exponential backoff
+ through `manage.py webhooks_deliver`, every attempt recorded, and private,
+ loopback and link-local targets refused at send time.
+- **`apps.flags`: feature flags** (`DJANGO_FLAGS_ENABLED`). A global switch,
+ per-account overrides and a stable percentage rollout; `is_enabled(key, user)`
+ is cached and invalidated on save.
+
+### 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.** PyPI's
+ trusted publishing rejects the shared reusable publish workflow with
+ `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
### Changed
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/Makefile b/Makefile
index 6ff442d..ce1e2f7 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 DJANGO_FILES_ENABLED=true DJANGO_FLAGS_ENABLED=true
check:
ruff check --no-cache .
diff --git a/README.md b/README.md
index ef6654a..ac5cf40 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,13 @@
# Django Ninja Starter
[](https://pypi.org/project/django-ninja-starter/)
+[](https://github.com/CtrlAltDevelop/django-ninja-starter/actions/workflows/ci.yml)
+[](https://github.com/CtrlAltDevelop/django-ninja-starter/blob/main/LICENSE)
+[](https://www.python.org)
+[](https://www.djangoproject.com)
+[](https://django-ninja.dev)
+[](https://www.postgresql.org)
+[](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.
@@ -394,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 |
@@ -562,14 +570,19 @@ 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. 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
+
+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).
diff --git a/docs/README.md b/docs/README.md
index 11d1e04..a597045 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), [`files`](files.md), [`flags`](flags.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,9 @@ 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 |
+| [`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 |
+| [`flags`](flags.md) | `DJANGO_FLAGS_ENABLED=true` | Feature flags with a global switch, per-account overrides and a stable percentage rollout; `apps.flags.is_enabled(key, user)` is cached and invalidated on save |
| [`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/docs/flags.md b/docs/flags.md
new file mode 100644
index 0000000..1719e68
--- /dev/null
+++ b/docs/flags.md
@@ -0,0 +1,98 @@
+# Feature flags
+
+A flag has a key, a global on/off switch, optional per-account overrides and an
+optional percentage rollout. Optional like every feature app: naming it in
+`DJANGO_FLAGS_ENABLED` installs its two tables, its routes and its admin, and a
+project that does not name it never imports the package.
+
+## Asking whether a flag is on
+
+ from apps.flags import is_enabled
+
+ if is_enabled("new-checkout", request.user):
+ ...
+
+`apps.flags.is_enabled` answers `False` when the app is not installed, so any
+app may call it unconditionally. An unknown key is off.
+
+## How a flag is evaluated
+
+1. An override for the account wins, whether it says on or off.
+2. Otherwise a flag whose switch is off is off.
+3. Otherwise, with no rollout (or 100), it is on for everybody.
+4. Otherwise the account is admitted when a stable hash of its id and the
+ key, reduced to 0-99, is below the rollout percentage. Hashing with the key
+ gives each flag a different slice of accounts, and raising the percentage
+ only ever adds accounts to the ones already in. Anonymous callers have no
+ id to hash, so a partial rollout leaves them out.
+
+Each flag's definition is cached for five minutes in the default cache and
+dropped whenever the flag or one of its overrides is saved or deleted (bulk
+`.update()` sends no signal; call `apps.flags.services.forget(key)` after one).
+
+## Who may do what
+
+Any signed-in account reads `GET /flags/me` (GraphQL `myFlags`, gRPC
+`MyFlags`): every flag, evaluated for itself. Everything else -- listing,
+saving, deleting, pinning an override -- is staff only, over all three
+transports and the admin. Over gRPC, protobuf has no null scalar, so a
+`rollout_percentage` of `-1` means none and an override is cleared with
+`clear: true`.
+
+## Routes
+
+
+| Method | Path | Auth | Purpose |
+| --- | --- | --- | --- |
+| `GET` | `/api/v1/flags/` | Bearer | Every flag (staff) |
+| `GET` | `/api/v1/flags/me` | Bearer | Every flag, evaluated for you |
+| `DELETE` | `/api/v1/flags/{key}` | Bearer | Delete a flag (staff) |
+| `GET` | `/api/v1/flags/{key}` | Bearer | One flag (staff) |
+| `PUT` | `/api/v1/flags/{key}` | Bearer | Create or replace a flag (staff) |
+| `PUT` | `/api/v1/flags/{key}/overrides/{user_id}` | Bearer | Pin a flag for one account (staff) |
+
+
+## Models
+
+
+#### `Flag`
+
+One feature switch.
+
+| Field | Type | Notes |
+| --- | --- | --- |
+| `id` | BigAuto | primary key |
+| `key` | Slug | unique |
+| `description` | Text | |
+| `is_enabled` | Boolean | |
+| `rollout_percentage` | PositiveSmallInteger | nullable |
+| `created_at` | DateTime | not editable |
+| `updated_at` | DateTime | not editable |
+
+#### `FlagOverride`
+
+One account's answer for one flag, whatever the switch and the rollout say.
+
+| Field | Type | Notes |
+| --- | --- | --- |
+| `id` | BigAuto | primary key |
+| `flag` | ForeignKey | → `flags.Flag` |
+| `user` | ForeignKey | → `accounts.User` |
+| `is_enabled` | Boolean | |
+
+
+## Admin
+
+
+| Model | Editable | Actions | Columns |
+| --- | --- | --- | --- |
+| `Flag` | Yes | — | `key`, `is_enabled`, `rollout_percentage`, `updated_at` |
+
+
+## Setup
+
+
+_This app requires no settings of its own._
+
+
+## Usage
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/README.md b/examples/README.md
index 929deb2..521ebe2 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -21,9 +21,9 @@ alone is enough.
1. Generates `example-api` with the packaged generator.
2. Copies `env.example` in as the project's `.env` — four login methods, four
second factors, four social providers and all three token modes installed
- with `rotation` issuing, plus all six feature apps the template ships: the
+ with `rotation` issuing, plus all seven feature apps the template ships: the
**CMS**, **notifications**, the **shop**, the **support desk**, the
- **wallet** and the **club**.
+ **wallet**, the **club** and **feature flags**.
3. Runs the project's own `manage.py startapi notes --api-version v1` and `v2`,
then copies `notes/` over the scaffolding it wrote.
4. Runs `migrate`, so `make serve` inside the built project serves the API —
@@ -58,15 +58,16 @@ tour runs them:
| 10 | A support desk | `apps.support` | One conversation from both sides: a ticket, a queue, a staff-only note, and then the same thing live over a socket |
| 11 | A wallet | `apps.wallet` | Every wallet route: configured payment methods, a priced deposit a signed webhook settles or fails, requests applied and refused, a payout cancelled, a free transfer, a chargeback the rail signs for, and a balance that survives being archived |
| 12 | A club | `apps.club` | A ladder, and missions nobody claims: a welcome paid on joining, then a sign-in, an order and a deposit each paying XP without the client reporting any of them, a replayed settlement paying nothing, and a ledger that adds up to the level |
-| 13 | One-time code by email | `auth_email_code` | Ticket to the client, code to the inbox, neither alone a login |
-| 14 | One-time code by SMS | `auth_sms_code` | The same two steps over a phone number and no address at all |
-| 15 | Magic link | `auth_magic_link` | One emailed link, good exactly once |
-| 16 | Second factors | `auth_twofactor` | TOTP, SMS, email and recovery codes, enrolled and then used to log in |
-| 17 | Token mode | `oauth_core`, `oauth_rotation` | Sessions, refresh, ending another session, revoking your own |
-| 18 | Social sign-in | `oauth_google`, `oauth_apple`, `oauth_microsoft`, `oauth_github` | The start half of all four redirects |
-| 19 | What was recorded | `auth_core`, `oauth_core` | The audit rows all of the above left, and the JWT claims |
-| 20 | The document all of that produced | `config.api` | Both OpenAPI schemas, group by group |
-| 21 | The admin, every app of it | all apps | Every model any installed app registered, opened as a superuser |
+| 13 | Feature flags | `apps.flags` | Members refused the staff routes, a 50% rollout, a pin that beats it, every flag evaluated for the caller, and a deleted flag that answers off |
+| 14 | One-time code by email | `auth_email_code` | Ticket to the client, code to the inbox, neither alone a login |
+| 15 | One-time code by SMS | `auth_sms_code` | The same two steps over a phone number and no address at all |
+| 16 | Magic link | `auth_magic_link` | One emailed link, good exactly once |
+| 17 | Second factors | `auth_twofactor` | TOTP, SMS, email and recovery codes, enrolled and then used to log in |
+| 18 | Token mode | `oauth_core`, `oauth_rotation` | Sessions, refresh, ending another session, revoking your own |
+| 19 | Social sign-in | `oauth_google`, `oauth_apple`, `oauth_microsoft`, `oauth_github` | The start half of all four redirects |
+| 20 | What was recorded | `auth_core`, `oauth_core` | The audit rows all of the above left, and the JWT claims |
+| 21 | The document all of that produced | `config.api` | Both OpenAPI schemas, group by group |
+| 22 | The admin, every app of it | all apps | Every model any installed app registered, opened as a superuser |
The rest of this section is what each one calls, and the property it is there to
demonstrate. Every path below is printed by the tour, and is the path a real
@@ -375,6 +376,19 @@ against the club's router, as the wallet and support ones do.
| `POST /api/v1/club/leave`, then `join` | The history stays, and coming back picks the ladder up where it was left |
| `POST /api/v1/club/missions/first-order/claim` | A **404**. No transport lets a client claim a mission |
+### Feature flags — `apps.flags`
+
+A switch, a pin for one account, and a percentage rollout. The section ends by
+checking it called every route the flags router publishes.
+
+| Call | What it shows |
+| --- | --- |
+| `GET /api/v1/flags/`, `PUT …/new-checkout` as a member | A **403**: managing flags is staff work |
+| `PUT /api/v1/flags/new-checkout`, `…/dark-mode` | Staff create a 50% rollout and a flag that is off |
+| `PUT /api/v1/flags/dark-mode/overrides/{id}` | A pin beats the switch and the rollout; `null` clears it |
+| `GET /api/v1/flags/me` | Every flag evaluated for the caller, matching `is_enabled()` |
+| `DELETE /api/v1/flags/dark-mode` | A deleted flag answers off |
+
### A feature app of your own — `apps.notes`
The app `build.py` adds, and the only one here that the starter does not ship.
@@ -462,16 +476,17 @@ An app that is not enabled is not skipped silently: the CMS, notification, shop,
support, wallet and club sections still print their heading and say which variable
would have turned them on.
-## The six feature apps that ship
+## The seven feature apps that ship
-`cms/`, `notifications/`, `shop/`, `support/`, `wallet/` and `club/` are not in this
+`cms/`, `notifications/`, `shop/`, `support/`, `wallet/`, `club/` and `flags/` are not in this
directory. They come out of the generator inside every project it writes, and the
`.env` above is the whole of what turns them on — which is the property worth
seeing, so the tour reads their settings back before it calls them. Their full
reference is [`docs/cms.md`](../docs/cms.md),
[`docs/notifications.md`](../docs/notifications.md),
[`docs/shop.md`](../docs/shop.md), [`docs/support.md`](../docs/support.md),
-[`docs/wallet.md`](../docs/wallet.md) and [`docs/club.md`](../docs/club.md).
+[`docs/wallet.md`](../docs/wallet.md), [`docs/club.md`](../docs/club.md) and
+[`docs/flags.md`](../docs/flags.md).
## The notes app
diff --git a/examples/build.py b/examples/build.py
index 801f288..d67e6e5 100644
--- a/examples/build.py
+++ b/examples/build.py
@@ -13,8 +13,8 @@
1. ``examples/env.example`` is copied in as the project's ``.env``, which is
what turns every login method, second factor, social provider and token
- mode on, along with all six feature apps the template ships -- the CMS,
- notifications, the shop, the support desk, the wallet and the club, whose
+ mode on, along with all seven feature apps the template ships -- the CMS,
+ notifications, the shop, the support desk, the wallet, the club and flags, whose
tables, routes and WebSockets exist only once they are named.
2. ``manage.py startapi notes`` scaffolds and registers a feature API at v1 and
again at v2, so the registry entries below are written by the project's own
diff --git a/examples/env.example b/examples/env.example
index 3683ba7..96a6495 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
@@ -314,6 +328,10 @@ DJANGO_CLUB_ENABLED=true
DJANGO_CLUB_JOIN_ON_SIGNUP=
DJANGO_CLUB_PAGE_SIZE=50
DJANGO_CLUB_MAX_PAGE_SIZE=200
+# Feature flags: a global switch, per-account overrides and a percentage
+# rollout. `apps.flags.is_enabled(key, user)` answers False while this is off.
+DJANGO_FLAGS_ENABLED=true
+# DJANGO_FLAGS_TRANSPORTS=rest,graph,grpc
# ---------------------------------------------------------------------------
# Uploaded files. Django serves MEDIA_URL itself only while DEBUG is on; in
@@ -347,3 +365,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/examples/walkthrough.py b/examples/walkthrough.py
index d0b5c3d..231cdba 100644
--- a/examples/walkthrough.py
+++ b/examples/walkthrough.py
@@ -4,10 +4,11 @@
python examples/walkthrough.py
Four login methods, four second factors, four social providers, a token mode,
-the accounts and health endpoints, all six feature apps the starter ships --
+the accounts and health endpoints, all seven feature apps the starter ships --
the CMS, notifications with its socket, the shop from catalogue to settled
invoice, the support desk from both sides of it, the wallet from an empty
-balance to a settled one, and the club paying for what the other apps did --
+balance to a settled one, the club paying for what the other apps did, feature
+flags from a rollout to a pin --
the notes app you would write yourself, the audit
trail, the generated OpenAPI documents, and every admin screen any of them
registers. All of it printed as a transcript of the calls a real client would
@@ -525,6 +526,7 @@ def section_configuration() -> None:
print(f" support {support}")
print(f" wallet {'on' if settings.WALLET_ENABLED else 'off'}")
print(f" club {'on' if settings.CLUB_ENABLED else 'off'}")
+ print(f" flags {'on' if settings.FLAGS_ENABLED else 'off'}")
print()
for app in settings.INSTALLED_APPS:
marker = " " if app.startswith("django.contrib") else "•"
@@ -2995,9 +2997,99 @@ def _club_surface_covered(api: Api) -> None:
print(f" {DIM}│ toured {total} of {total} club endpoints{OFF}")
-def section_email_code(api: Api) -> None:
+def section_flags(api: Api) -> None:
+ """Feature flags: a switch, a pin for one account, and a rollout nobody can game."""
+ from django.apps import apps as django_apps
+ from django.conf import settings
+
+ if not settings.FLAGS_ENABLED or not django_apps.is_installed("apps.flags"):
+ heading(
+ 13, "Feature flags", "apps.flags", "Not installed: DJANGO_FLAGS_ENABLED is not set."
+ )
+ return
+
+ from django.contrib.auth import get_user_model
+
+ from apps.flags import is_enabled
+
heading(
13,
+ "Feature flags",
+ "apps.flags",
+ "A global switch, a pin for one account, and a percentage rollout bucketed "
+ "by a stable hash. Staff manage them; every account reads its own answers.",
+ )
+
+ flora = get_user_model().objects.create_user(
+ username="flora", email="flora@example.com", is_staff=True
+ )
+ staff = desk_token(flora)
+ member = api.token
+
+ note("Managing flags is staff work. A member asking is refused, not ignored.")
+ api.get("/api/v1/flags/", expect=403, show=False)
+ api.put("/api/v1/flags/new-checkout", {"is_enabled": True}, expect=403, show=False)
+
+ note(
+ "An operator creates a flag that is on for half of everybody. Which half is "
+ "a hash of the account and the key, so it never changes between requests."
+ )
+ api.put(
+ "/api/v1/flags/new-checkout",
+ {"is_enabled": True, "rollout_percentage": 50, "description": "The new checkout."},
+ token=staff,
+ )
+ api.put("/api/v1/flags/dark-mode", {"is_enabled": False}, token=staff)
+ api.get("/api/v1/flags/new-checkout", token=staff)
+
+ note("A pin for one account beats the switch and the rollout, both ways.")
+ me = api.get("/api/v1/users/me", show=False)
+ api.put(f"/api/v1/flags/dark-mode/overrides/{me['id']}", {"enabled": True}, token=staff)
+
+ note("Every flag, evaluated for whoever is asking -- and only for them.")
+ mine = {row["key"]: row["enabled"] for row in api.get("/api/v1/flags/me", token=member)}
+ if mine["dark-mode"] is not True:
+ raise WalkthroughError("a pinned flag did not answer on for its account")
+ caller = get_user_model().objects.get(pk=me["id"])
+ if mine["new-checkout"] != is_enabled("new-checkout", caller):
+ raise WalkthroughError("the API and is_enabled() disagree")
+
+ note("Clearing the pin puts the flag's own rules back; deleting it makes it off.")
+ api.put(f"/api/v1/flags/dark-mode/overrides/{me['id']}", {"enabled": None}, token=staff)
+ api.get("/api/v1/flags/", token=staff, show=False)
+ api.delete("/api/v1/flags/dark-mode", token=staff)
+ if is_enabled("dark-mode", caller):
+ raise WalkthroughError("a deleted flag still answered on")
+
+ _flags_surface_covered(api)
+
+
+def _flags_surface_covered(api: Api) -> None:
+ """Assert the section above called every route the flags app publishes."""
+ from apps.flags.rest.v1 import router
+
+ missed: list[str] = []
+ total = 0
+ for path, view in router.path_operations.items():
+ literals = re.split(r"\{[^}]+\}", f"/api/v1/flags{path}")
+ pattern = re.compile("^" + "[^/]+".join(re.escape(part) for part in literals) + "$")
+ for operation in view.operations:
+ for method in operation.methods:
+ total += 1
+ if not any(
+ seen_method == method and pattern.match(seen_path)
+ for seen_method, seen_path in api.visited
+ ):
+ missed.append(f"{method} /api/v1/flags{path}")
+
+ if missed:
+ raise WalkthroughError("the flags tour skipped " + ", ".join(sorted(missed)))
+ print(f" {DIM}│ toured {total} of {total} flags endpoints{OFF}")
+
+
+def section_email_code(api: Api) -> None:
+ heading(
+ 14,
"One-time code by email",
"auth_email_code",
"No password at all: a ticket goes to the client, a code goes to the "
@@ -3043,7 +3135,7 @@ def section_email_code(api: Api) -> None:
def section_sms_code(api: Api) -> None:
heading(
- 14,
+ 15,
"One-time code by SMS",
"auth_sms_code",
"The same two steps over a phone number, which is the one identifier "
@@ -3060,7 +3152,7 @@ def section_sms_code(api: Api) -> None:
def section_magic_link(api: Api) -> None:
heading(
- 15,
+ 16,
"Magic link",
"auth_magic_link",
"One emailed link, good once. The client never sees a code: the token in "
@@ -3076,7 +3168,7 @@ def section_magic_link(api: Api) -> None:
def section_twofactor(api: Api) -> None:
heading(
- 16,
+ 17,
"Second factors",
"auth_twofactor",
"Four factors on one app. Enrolment is not real until a code confirms "
@@ -3168,7 +3260,7 @@ def section_tokens(api: Api) -> None:
mode = settings.AUTH_TOKEN_MODE
heading(
- 17,
+ 18,
f"Token mode: {mode}",
"no token app" if mode == "none" else f"oauth_core, oauth_{mode}",
"All three modes publish the same endpoints under /auth/token, so a "
@@ -3226,7 +3318,7 @@ def section_social(api: Api) -> None:
from django.conf import settings
heading(
- 18,
+ 19,
"Social sign-in",
", ".join(f"oauth_{name}" for name in settings.OAUTH_PROVIDERS),
"Each provider mounts a start and a callback. Start is the half this "
@@ -3246,7 +3338,7 @@ def section_audit(api: Api) -> None:
from infrastructure.oauth.core import jwt_tokens
heading(
- 19,
+ 20,
"What was recorded",
"auth_core, oauth_core",
"Every step above left an audit row, and every credential above was a "
@@ -3276,7 +3368,7 @@ def section_audit(api: Api) -> None:
def section_openapi(api: Api) -> None:
heading(
- 20,
+ 21,
"The document all of that produced",
"config.api",
"One NinjaAPI per registered version, every enabled app's router "
@@ -3364,7 +3456,7 @@ def section_admin(api: Api) -> None:
from django.urls import reverse
heading(
- 21,
+ 22,
"The admin, every app of it",
"all apps",
"The API is half the project; the other half is the screen the people "
@@ -3554,6 +3646,7 @@ def tour() -> int:
section_support(api)
section_wallet(api)
section_club(api)
+ section_flags(api)
section_email_code(api)
section_sms_code(api)
section_magic_link(api)
diff --git a/pyproject.toml b/pyproject.toml
index 4f8e78e..5292191 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",
@@ -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",
@@ -72,6 +74,10 @@ dev = [
"redis>=5.0,<9.0",
"fakeredis>=2.26,<3.0",
"mypy-protobuf>=3.6",
+ # protoc's output carries its version and `protos --check` compares bytes, so
+ # the committed stubs only match when everyone generates with this release.
+ # Bump it together with a `manage.py protos` run.
+ "grpcio-tools==1.84.0",
"ruff>=0.11",
"strawberry-graphql-django>=0.88,<1.0",
"twine>=6.0",
diff --git a/src/apps/audit/__init__.py b/src/apps/audit/__init__.py
new file mode 100644
index 0000000..a7ca09d
--- /dev/null
+++ b/src/apps/audit/__init__.py
@@ -0,0 +1 @@
+"""Append-only record of who changed what, and when."""
diff --git a/src/apps/audit/admin.py b/src/apps/audit/admin.py
new file mode 100644
index 0000000..07e6c91
--- /dev/null
+++ b/src/apps/audit/admin.py
@@ -0,0 +1,14 @@
+from django.contrib import admin
+
+from apps.audit.models import AuditEntry
+from infrastructure.common.admin import ReadOnlyAdmin
+
+
+@admin.register(AuditEntry)
+class AuditEntryAdmin(ReadOnlyAdmin):
+ """Read-only: the log is appended to by code, never typed into."""
+
+ list_display = ("created_at", "actor", "action", "target_model", "target_id", "ip")
+ list_filter = ("action", "target_model")
+ search_fields = ("target_id",)
+ date_hierarchy = "created_at"
diff --git a/src/apps/audit/apps.py b/src/apps/audit/apps.py
new file mode 100644
index 0000000..6320d23
--- /dev/null
+++ b/src/apps/audit/apps.py
@@ -0,0 +1,8 @@
+from django.apps import AppConfig
+
+
+class AuditConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "apps.audit"
+ label = "audit"
+ verbose_name = "Audit log"
diff --git a/src/apps/audit/graph/__init__.py b/src/apps/audit/graph/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/audit/graph/schema.py b/src/apps/audit/graph/schema.py
new file mode 100644
index 0000000..7549b59
--- /dev/null
+++ b/src/apps/audit/graph/schema.py
@@ -0,0 +1,59 @@
+"""The audit log over GraphQL: one staff-only query, no mutation."""
+
+from datetime import datetime
+from typing import Any
+
+import strawberry
+from strawberry.scalars import JSON
+from strawberry.types import Info
+
+from apps.audit.services import entries
+from infrastructure.common.graph.errors import require_caller, resolver
+from infrastructure.common.identity import caller
+
+
+@strawberry.type
+class AuditEntryType:
+ id: str
+ actor_id: str | None
+ action: str
+ target_model: str
+ target_id: str
+ changes: JSON
+ ip: str | None
+ created_at: str
+
+
+@strawberry.type
+class AuditEntryPage:
+ entries: list[AuditEntryType]
+ count: int
+
+
+@strawberry.type
+class Query:
+ @strawberry.field(description="Audit entries, newest first. Staff only.")
+ @resolver
+ def audit_entries(
+ self,
+ info: Info[Any, Any],
+ actor_id: str | None = None,
+ target_model: str | None = None,
+ target_id: str | None = None,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ limit: int | None = None,
+ offset: int = 0,
+ ) -> AuditEntryPage:
+ user = require_caller(caller(info.context.request))
+ rows, count = entries(
+ user,
+ actor_id=actor_id,
+ target_model=target_model,
+ target_id=target_id,
+ since=since,
+ until=until,
+ limit=limit,
+ offset=offset,
+ )
+ return AuditEntryPage(entries=[AuditEntryType(**row) for row in rows], count=count)
diff --git a/src/apps/audit/grpc/__init__.py b/src/apps/audit/grpc/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/audit/grpc/audit.proto b/src/apps/audit/grpc/audit.proto
new file mode 100644
index 0000000..48cdc94
--- /dev/null
+++ b/src/apps/audit/grpc/audit.proto
@@ -0,0 +1,36 @@
+syntax = "proto3";
+
+package config.audit;
+
+import "google/protobuf/struct.proto";
+
+service AuditController {
+ rpc ListEntries(ListEntriesRequest) returns (EntryList) {}
+}
+
+message Entry {
+ string id = 1;
+ string actor_id = 2;
+ string action = 3;
+ string target_model = 4;
+ string target_id = 5;
+ google.protobuf.Struct changes = 6;
+ string ip = 7;
+ string created_at = 8;
+}
+
+message EntryList {
+ repeated Entry entries = 1;
+ int32 count = 2;
+}
+
+message ListEntriesRequest {
+ string actor_id = 1;
+ string target_model = 2;
+ string target_id = 3;
+ string since = 4;
+ string until = 5;
+ int32 limit = 6;
+ int32 offset = 7;
+}
+
diff --git a/src/apps/audit/grpc/audit_pb2.py b/src/apps/audit/grpc/audit_pb2.py
new file mode 100644
index 0000000..d219fc0
--- /dev/null
+++ b/src/apps/audit/grpc/audit_pb2.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: apps/audit/grpc/audit.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/audit/grpc/audit.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1b\x61pps/audit/grpc/audit.proto\x12\x0c\x63onfig.audit\x1a\x1cgoogle/protobuf/struct.proto\"\xa8\x01\n\x05\x45ntry\x12\n\n\x02id\x18\x01 \x01(\t\x12\x10\n\x08\x61\x63tor_id\x18\x02 \x01(\t\x12\x0e\n\x06\x61\x63tion\x18\x03 \x01(\t\x12\x14\n\x0ctarget_model\x18\x04 \x01(\t\x12\x11\n\ttarget_id\x18\x05 \x01(\t\x12(\n\x07\x63hanges\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\n\n\x02ip\x18\x07 \x01(\t\x12\x12\n\ncreated_at\x18\x08 \x01(\t\"@\n\tEntryList\x12$\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x13.config.audit.Entry\x12\r\n\x05\x63ount\x18\x02 \x01(\x05\"\x8c\x01\n\x12ListEntriesRequest\x12\x10\n\x08\x61\x63tor_id\x18\x01 \x01(\t\x12\x14\n\x0ctarget_model\x18\x02 \x01(\t\x12\x11\n\ttarget_id\x18\x03 \x01(\t\x12\r\n\x05since\x18\x04 \x01(\t\x12\r\n\x05until\x18\x05 \x01(\t\x12\r\n\x05limit\x18\x06 \x01(\x05\x12\x0e\n\x06offset\x18\x07 \x01(\x05\x32]\n\x0f\x41uditController\x12J\n\x0bListEntries\x12 .config.audit.ListEntriesRequest\x1a\x17.config.audit.EntryList\"\x00\x62\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.audit.grpc.audit_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ DESCRIPTOR._loaded_options = None
+ _globals['_ENTRY']._serialized_start=76
+ _globals['_ENTRY']._serialized_end=244
+ _globals['_ENTRYLIST']._serialized_start=246
+ _globals['_ENTRYLIST']._serialized_end=310
+ _globals['_LISTENTRIESREQUEST']._serialized_start=313
+ _globals['_LISTENTRIESREQUEST']._serialized_end=453
+ _globals['_AUDITCONTROLLER']._serialized_start=455
+ _globals['_AUDITCONTROLLER']._serialized_end=548
+# @@protoc_insertion_point(module_scope)
diff --git a/src/apps/audit/grpc/audit_pb2.pyi b/src/apps/audit/grpc/audit_pb2.pyi
new file mode 100644
index 0000000..f6912e2
--- /dev/null
+++ b/src/apps/audit/grpc/audit_pb2.pyi
@@ -0,0 +1,121 @@
+"""
+@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 import struct_pb2 as _struct_pb2
+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 Entry(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ ID_FIELD_NUMBER: _builtins.int
+ ACTOR_ID_FIELD_NUMBER: _builtins.int
+ ACTION_FIELD_NUMBER: _builtins.int
+ TARGET_MODEL_FIELD_NUMBER: _builtins.int
+ TARGET_ID_FIELD_NUMBER: _builtins.int
+ CHANGES_FIELD_NUMBER: _builtins.int
+ IP_FIELD_NUMBER: _builtins.int
+ CREATED_AT_FIELD_NUMBER: _builtins.int
+ id: _builtins.str
+ actor_id: _builtins.str
+ action: _builtins.str
+ target_model: _builtins.str
+ target_id: _builtins.str
+ ip: _builtins.str
+ created_at: _builtins.str
+ @_builtins.property
+ def changes(self) -> _struct_pb2.Struct: ...
+ def __init__(
+ self,
+ *,
+ id: _builtins.str = ...,
+ actor_id: _builtins.str = ...,
+ action: _builtins.str = ...,
+ target_model: _builtins.str = ...,
+ target_id: _builtins.str = ...,
+ changes: _struct_pb2.Struct | None = ...,
+ ip: _builtins.str = ...,
+ created_at: _builtins.str = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _typing.Literal["changes", b"changes"] # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["action", b"action", "actor_id", b"actor_id", "changes", b"changes", "created_at", b"created_at", "id", b"id", "ip", b"ip", "target_id", b"target_id", "target_model", b"target_model"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___Entry: _TypeAlias = Entry # noqa: Y015
+
+@_typing.final
+class EntryList(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ ENTRIES_FIELD_NUMBER: _builtins.int
+ COUNT_FIELD_NUMBER: _builtins.int
+ count: _builtins.int
+ @_builtins.property
+ def entries(self) -> _containers.RepeatedCompositeFieldContainer[Global___Entry]: ...
+ def __init__(
+ self,
+ *,
+ entries: _abc.Iterable[Global___Entry] | None = ...,
+ count: _builtins.int = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["count", b"count", "entries", b"entries"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___EntryList: _TypeAlias = EntryList # noqa: Y015
+
+@_typing.final
+class ListEntriesRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ ACTOR_ID_FIELD_NUMBER: _builtins.int
+ TARGET_MODEL_FIELD_NUMBER: _builtins.int
+ TARGET_ID_FIELD_NUMBER: _builtins.int
+ SINCE_FIELD_NUMBER: _builtins.int
+ UNTIL_FIELD_NUMBER: _builtins.int
+ LIMIT_FIELD_NUMBER: _builtins.int
+ OFFSET_FIELD_NUMBER: _builtins.int
+ actor_id: _builtins.str
+ target_model: _builtins.str
+ target_id: _builtins.str
+ since: _builtins.str
+ until: _builtins.str
+ limit: _builtins.int
+ offset: _builtins.int
+ def __init__(
+ self,
+ *,
+ actor_id: _builtins.str = ...,
+ target_model: _builtins.str = ...,
+ target_id: _builtins.str = ...,
+ since: _builtins.str = ...,
+ until: _builtins.str = ...,
+ limit: _builtins.int = ...,
+ offset: _builtins.int = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["actor_id", b"actor_id", "limit", b"limit", "offset", b"offset", "since", b"since", "target_id", b"target_id", "target_model", b"target_model", "until", b"until"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___ListEntriesRequest: _TypeAlias = ListEntriesRequest # noqa: Y015
diff --git a/src/apps/audit/grpc/audit_pb2_grpc.py b/src/apps/audit/grpc/audit_pb2_grpc.py
new file mode 100644
index 0000000..b513342
--- /dev/null
+++ b/src/apps/audit/grpc/audit_pb2_grpc.py
@@ -0,0 +1,97 @@
+# 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.audit.grpc import audit_pb2 as apps_dot_audit_dot_grpc_dot_audit__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/audit/grpc/audit_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 AuditControllerStub:
+ """Missing associated documentation comment in .proto file."""
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.ListEntries = channel.unary_unary(
+ '/config.audit.AuditController/ListEntries',
+ request_serializer=apps_dot_audit_dot_grpc_dot_audit__pb2.ListEntriesRequest.SerializeToString,
+ response_deserializer=apps_dot_audit_dot_grpc_dot_audit__pb2.EntryList.FromString,
+ _registered_method=True)
+
+
+class AuditControllerServicer:
+ """Missing associated documentation comment in .proto file."""
+
+ def ListEntries(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_AuditControllerServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'ListEntries': grpc.unary_unary_rpc_method_handler(
+ servicer.ListEntries,
+ request_deserializer=apps_dot_audit_dot_grpc_dot_audit__pb2.ListEntriesRequest.FromString,
+ response_serializer=apps_dot_audit_dot_grpc_dot_audit__pb2.EntryList.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'config.audit.AuditController', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+ server.add_registered_method_handlers('config.audit.AuditController', rpc_method_handlers)
+
+
+ # This class is part of an EXPERIMENTAL API.
+class AuditController:
+ """Missing associated documentation comment in .proto file."""
+
+ @staticmethod
+ def ListEntries(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.audit.AuditController/ListEntries',
+ apps_dot_audit_dot_grpc_dot_audit__pb2.ListEntriesRequest.SerializeToString,
+ apps_dot_audit_dot_grpc_dot_audit__pb2.EntryList.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
diff --git a/src/apps/audit/grpc/audit_pb2_grpc.pyi b/src/apps/audit/grpc/audit_pb2_grpc.pyi
new file mode 100644
index 0000000..f4216b0
--- /dev/null
+++ b/src/apps/audit/grpc/audit_pb2_grpc.pyi
@@ -0,0 +1,49 @@
+"""
+@generated by mypy-protobuf. Do not edit manually!
+isort:skip_file
+"""
+
+from apps.audit.grpc import audit_pb2 as _audit_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 AuditControllerStub:
+ @_typing.overload
+ def __new__(cls, channel: _grpc.Channel) -> _Self: ...
+ @_typing.overload
+ def __new__(cls, channel: _aio.Channel) -> AuditControllerAsyncStub: ...
+ ListEntries: _grpc.UnaryUnaryMultiCallable[_audit_pb2.ListEntriesRequest, _audit_pb2.EntryList]
+
+@_typing.type_check_only
+class AuditControllerAsyncStub(AuditControllerStub):
+ def __init__(self, channel: _aio.Channel) -> None: ...
+ ListEntries: _aio.UnaryUnaryMultiCallable[_audit_pb2.ListEntriesRequest, _audit_pb2.EntryList] # type: ignore[assignment]
+
+class AuditControllerServicer(metaclass=_abc_1.ABCMeta):
+ @_abc_1.abstractmethod
+ def ListEntries(
+ self,
+ request: _audit_pb2.ListEntriesRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_audit_pb2.EntryList, _abc.Awaitable[_audit_pb2.EntryList]]: ...
+
+def add_AuditControllerServicer_to_server(servicer: AuditControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ...
diff --git a/src/apps/audit/grpc/serializers.py b/src/apps/audit/grpc/serializers.py
new file mode 100644
index 0000000..e1dff1b
--- /dev/null
+++ b/src/apps/audit/grpc/serializers.py
@@ -0,0 +1,14 @@
+"""The message one audit entry travels as. ``changes`` is a JSON string."""
+
+from rest_framework import serializers
+
+
+class Entry(serializers.Serializer[dict[str, object]]):
+ id = serializers.CharField()
+ actor_id = serializers.CharField(allow_blank=True)
+ action = serializers.CharField()
+ target_model = serializers.CharField()
+ target_id = serializers.CharField()
+ changes = serializers.JSONField()
+ ip = serializers.CharField(allow_blank=True)
+ created_at = serializers.CharField()
diff --git a/src/apps/audit/grpc/services.py b/src/apps/audit/grpc/services.py
new file mode 100644
index 0000000..24aafe6
--- /dev/null
+++ b/src/apps/audit/grpc/services.py
@@ -0,0 +1,81 @@
+"""The audit log over gRPC: one staff-only listing call, nothing that writes."""
+
+from __future__ import annotations
+
+from datetime import datetime
+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.audit.grpc.serializers import Entry
+from apps.audit.services import entries
+from infrastructure.common.errors import ApiError
+from infrastructure.common.grpc.errors import action, require_caller
+from infrastructure.common.identity import grpc_caller
+
+
+def _pb2() -> Any:
+ from apps.audit.grpc import audit_pb2
+
+ return audit_pb2
+
+
+def _when(value: str) -> datetime | None:
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value)
+ except ValueError:
+ raise ApiError(f"Not an ISO-8601 timestamp: {value!r}", status=400) from None
+
+
+def _entry(row: dict[str, Any]) -> Any:
+ return _pb2().Entry(
+ id=row["id"],
+ actor_id=row["actor_id"] or "",
+ action=row["action"],
+ target_model=row["target_model"],
+ target_id=row["target_id"],
+ changes=row["changes"],
+ ip=row["ip"] or "",
+ created_at=row["created_at"],
+ )
+
+
+class AuditService(generics.GenericService):
+ @grpc_action(
+ request=[
+ {"name": "actor_id", "type": "string"},
+ {"name": "target_model", "type": "string"},
+ {"name": "target_id", "type": "string"},
+ {"name": "since", "type": "string"},
+ {"name": "until", "type": "string"},
+ {"name": "limit", "type": "int32"},
+ {"name": "offset", "type": "int32"},
+ ],
+ request_name="ListEntriesRequest",
+ response=[
+ {"name": "entries", "cardinality": "repeated", "type": Entry},
+ {"name": "count", "type": "int32"},
+ ],
+ response_name="EntryList",
+ )
+ @action
+ async def ListEntries(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rows, count = await sync_to_async(entries)(
+ user,
+ actor_id=request.actor_id or None,
+ target_model=request.target_model or None,
+ target_id=request.target_id or None,
+ since=_when(request.since),
+ until=_when(request.until),
+ limit=request.limit or None,
+ offset=request.offset or 0,
+ )
+ return _pb2().EntryList(entries=[_entry(row) for row in rows], count=count)
+
+
+GRPC_SERVICES = [AuditService]
diff --git a/src/apps/audit/migrations/0001_initial.py b/src/apps/audit/migrations/0001_initial.py
new file mode 100644
index 0000000..01053a2
--- /dev/null
+++ b/src/apps/audit/migrations/0001_initial.py
@@ -0,0 +1,76 @@
+# Generated by Django 6.1.3 on 2026-11-26 14:25
+
+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="AuditEntry",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=uuid.uuid4, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ (
+ "action",
+ models.CharField(
+ help_text="What was done, e.g. create or update.", max_length=64
+ ),
+ ),
+ (
+ "target_model",
+ models.CharField(help_text="app_label.model of the target.", max_length=128),
+ ),
+ (
+ "target_id",
+ models.CharField(
+ help_text="Primary key of the target, as text.", max_length=64
+ ),
+ ),
+ (
+ "changes",
+ models.JSONField(blank=True, default=dict, help_text="Field -> [old, new]."),
+ ),
+ (
+ "ip",
+ models.GenericIPAddressField(
+ blank=True, help_text="The request's address.", null=True
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
+ (
+ "actor",
+ models.ForeignKey(
+ blank=True,
+ help_text="Who made the change. Empty for the system, or an account since deleted.",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="audit_entries",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "verbose_name_plural": "audit entries",
+ "ordering": ("-created_at",),
+ "indexes": [
+ models.Index(
+ fields=["target_model", "target_id"], name="audit_audit_target__53778f_idx"
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/src/apps/audit/migrations/__init__.py b/src/apps/audit/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/audit/models.py b/src/apps/audit/models.py
new file mode 100644
index 0000000..ab1cce9
--- /dev/null
+++ b/src/apps/audit/models.py
@@ -0,0 +1,46 @@
+"""One audit entry: who did what to which object, when, and from where.
+
+Entries are append-only. ``save`` refuses to rewrite a stored row and ``delete``
+refuses outright, so no transport and no admin screen can launder the record.
+Bulk ``QuerySet.update``/``delete`` bypass this; nothing in the project calls them.
+"""
+
+import uuid
+from typing import Any
+
+from django.conf import settings
+from django.db import models
+
+
+class AuditEntry(models.Model):
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ actor = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ null=True,
+ blank=True,
+ on_delete=models.SET_NULL,
+ related_name="audit_entries",
+ help_text="Who made the change. Empty for the system, or an account since deleted.",
+ )
+ action = models.CharField(max_length=64, help_text="What was done, e.g. create or update.")
+ target_model = models.CharField(max_length=128, help_text="app_label.model of the target.")
+ target_id = models.CharField(max_length=64, help_text="Primary key of the target, as text.")
+ changes = models.JSONField(default=dict, blank=True, help_text="Field -> [old, new].")
+ ip = models.GenericIPAddressField(null=True, blank=True, help_text="The request's address.")
+ created_at = models.DateTimeField(auto_now_add=True, db_index=True)
+
+ class Meta:
+ ordering = ("-created_at",)
+ indexes = [models.Index(fields=("target_model", "target_id"))]
+ verbose_name_plural = "audit entries"
+
+ def __str__(self) -> str:
+ return f"{self.action} {self.target_model}:{self.target_id}"
+
+ def save(self, *args: Any, **kwargs: Any) -> None:
+ if not self._state.adding:
+ raise PermissionError("Audit entries are append-only.")
+ super().save(*args, **kwargs)
+
+ def delete(self, *args: Any, **kwargs: Any) -> Any:
+ raise PermissionError("Audit entries are append-only.")
diff --git a/src/apps/audit/rest/__init__.py b/src/apps/audit/rest/__init__.py
new file mode 100644
index 0000000..45f9c00
--- /dev/null
+++ b/src/apps/audit/rest/__init__.py
@@ -0,0 +1,5 @@
+"""The HTTP transport for the audit app."""
+
+from apps.audit.rest.v1 import router
+
+__all__ = ["router"]
diff --git a/src/apps/audit/rest/v1.py b/src/apps/audit/rest/v1.py
new file mode 100644
index 0000000..2b332ee
--- /dev/null
+++ b/src/apps/audit/rest/v1.py
@@ -0,0 +1,56 @@
+"""The audit log over HTTP: read-only, staff only. There is no write route."""
+
+from datetime import datetime
+from typing import Any
+
+from django.http import HttpRequest
+from ninja import Router, Schema
+
+from apps.audit.services import entries
+
+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)
+
+
+class EntryOut(Schema):
+ id: str
+ actor_id: str | None
+ action: str
+ target_model: str
+ target_id: str
+ changes: dict[str, Any]
+ ip: str | None
+ created_at: str
+
+
+class EntryPage(Schema):
+ entries: list[EntryOut]
+ count: int
+
+
+@router.get("/entries", response=EntryPage, summary="Audit entries, newest first")
+def list_entries(
+ request: HttpRequest,
+ actor_id: str | None = None,
+ target_model: str | None = None,
+ target_id: str | None = None,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ limit: int | None = None,
+ offset: int = 0,
+) -> Any:
+ rows, count = entries(
+ request.user,
+ actor_id=actor_id,
+ target_model=target_model,
+ target_id=target_id,
+ since=since,
+ until=until,
+ limit=limit,
+ offset=offset,
+ )
+ return {"entries": rows, "count": count}
diff --git a/src/apps/audit/services.py b/src/apps/audit/services.py
new file mode 100644
index 0000000..e645472
--- /dev/null
+++ b/src/apps/audit/services.py
@@ -0,0 +1,81 @@
+"""Writing and reading the audit log. Every transport goes through here."""
+
+from datetime import datetime
+from typing import Any
+
+from django.db.models import Model
+
+from apps.audit.models import AuditEntry
+from infrastructure.common.errors import ApiError
+from infrastructure.common.responses import ResponseTitle
+
+DEFAULT_PAGE = 50
+MAX_PAGE = 200
+
+
+def request_ip(request: Any) -> str | None:
+ """The peer address. Forwarded headers are client-supplied, so not trusted here."""
+ meta = getattr(request, "META", None) or {}
+ return meta.get("REMOTE_ADDR") or None
+
+
+def record(
+ actor: Any,
+ action: str,
+ target: Model,
+ changes: dict[str, Any] | None = None,
+ *,
+ request: Any = None,
+) -> AuditEntry:
+ """Append one entry. ``actor`` may be ``None`` or anonymous for system changes."""
+ return AuditEntry.objects.create(
+ actor=actor if getattr(actor, "is_authenticated", False) else None,
+ action=action,
+ target_model=target._meta.label_lower,
+ target_id=str(target.pk),
+ changes=changes or {},
+ ip=request_ip(request),
+ )
+
+
+def entry_payload(entry: AuditEntry) -> dict[str, Any]:
+ return {
+ "id": str(entry.id),
+ "actor_id": str(entry.actor_id) if entry.actor_id is not None else None,
+ "action": entry.action,
+ "target_model": entry.target_model,
+ "target_id": entry.target_id,
+ "changes": entry.changes,
+ "ip": entry.ip,
+ "created_at": entry.created_at.isoformat(),
+ }
+
+
+def entries(
+ viewer: Any,
+ *,
+ actor_id: str | None = None,
+ target_model: str | None = None,
+ target_id: str | None = None,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ limit: int | None = None,
+ offset: int = 0,
+) -> tuple[list[dict[str, Any]], int]:
+ """One page of entries, newest first, and the total that matched. Staff only."""
+ if not getattr(viewer, "is_staff", False):
+ raise ApiError("Staff only.", status=403, title=ResponseTitle.FORBIDDEN)
+ rows = AuditEntry.objects.all()
+ if actor_id:
+ rows = rows.filter(actor_id=actor_id)
+ if target_model:
+ rows = rows.filter(target_model=target_model.lower())
+ if target_id:
+ rows = rows.filter(target_id=target_id)
+ if since:
+ rows = rows.filter(created_at__gte=since)
+ if until:
+ rows = rows.filter(created_at__lt=until)
+ page = max(1, min(limit or DEFAULT_PAGE, MAX_PAGE))
+ start = max(0, offset)
+ return [entry_payload(e) for e in rows[start : start + page]], rows.count()
diff --git a/src/apps/audit/tests/__init__.py b/src/apps/audit/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/audit/tests/test_audit.py b/src/apps/audit/tests/test_audit.py
new file mode 100644
index 0000000..df2efc4
--- /dev/null
+++ b/src/apps/audit/tests/test_audit.py
@@ -0,0 +1,133 @@
+"""The audit log: append-only, staff-read, same answer on every transport."""
+
+import json
+from collections.abc import Callable
+from datetime import timedelta
+from typing import Any
+
+import grpc
+import pytest
+from django.contrib.auth import get_user_model
+from django.test import Client, RequestFactory
+from django.utils import timezone
+
+from apps.audit.grpc import audit_pb2, audit_pb2_grpc
+from apps.audit.models import AuditEntry
+from apps.audit.services import entries, record
+
+
+def access_token(user: Any) -> str:
+ from infrastructure.auth.core.sessions import issue_credentials
+
+ return issue_credentials(RequestFactory().post("/"), user, method="password").access_token
+
+
+@pytest.fixture
+def alice(db: None) -> Any:
+ return get_user_model().objects.create_user(username="alice", email="alice@example.test")
+
+
+@pytest.fixture
+def staff(db: None) -> Any:
+ return get_user_model().objects.create_user(
+ username="ops", email="ops@example.test", is_staff=True
+ )
+
+
+@pytest.fixture
+def logged(alice: Any, staff: Any) -> list[AuditEntry]:
+ request = RequestFactory().post("/", REMOTE_ADDR="203.0.113.7")
+ return [
+ record(alice, "update", staff, {"email": ["a", "b"]}, request=request),
+ record(staff, "delete", alice),
+ ]
+
+
+def test_record_captures_target_actor_and_ip(logged: list[AuditEntry], alice: Any) -> None:
+ entry = logged[0]
+
+ assert entry.actor == alice
+ assert entry.target_model == entry.actor._meta.label_lower
+ assert entry.ip == "203.0.113.7"
+ assert entry.changes == {"email": ["a", "b"]}
+
+
+def test_entries_cannot_be_rewritten_or_deleted(logged: list[AuditEntry]) -> None:
+ entry = logged[0]
+ entry.action = "forged"
+
+ with pytest.raises(PermissionError):
+ entry.save()
+ with pytest.raises(PermissionError):
+ entry.delete()
+
+
+def test_only_staff_read(logged: list[AuditEntry], alice: Any) -> None:
+ from infrastructure.common.errors import ApiError
+
+ with pytest.raises(ApiError) as refused:
+ entries(alice)
+ assert refused.value.status == 403
+
+
+def test_filters_and_pagination(logged: list[AuditEntry], alice: Any, staff: Any) -> None:
+ by_actor, count = entries(staff, actor_id=str(alice.pk))
+ assert count == 1 and by_actor[0]["action"] == "update"
+
+ by_target, _ = entries(staff, target_id=str(alice.pk))
+ assert [row["action"] for row in by_target] == ["delete"]
+
+ _, future = entries(staff, since=timezone.now() + timedelta(minutes=1))
+ assert future == 0
+
+ page, total = entries(staff, limit=1, offset=1)
+ assert total == 2 and len(page) == 1
+
+
+def test_rest_lists_for_staff_and_refuses_others(
+ logged: list[AuditEntry], alice: Any, staff: Any
+) -> None:
+ client = Client()
+ ok = client.get("/api/v1/audit/entries", HTTP_AUTHORIZATION=f"Bearer {access_token(staff)}")
+ denied = client.get("/api/v1/audit/entries", HTTP_AUTHORIZATION=f"Bearer {access_token(alice)}")
+
+ assert ok.status_code == 200
+ assert ok.json()["data"]["count"] == 2
+ assert denied.status_code == 403
+
+
+def test_rest_has_no_write_route(logged: list[AuditEntry], staff: Any) -> None:
+ response = Client().delete(
+ f"/api/v1/audit/entries/{logged[0].id}",
+ HTTP_AUTHORIZATION=f"Bearer {access_token(staff)}",
+ )
+
+ assert response.status_code in (404, 405)
+
+
+def test_graphql_lists_for_staff(logged: list[AuditEntry], staff: Any) -> None:
+ response = Client().post(
+ "/graphql",
+ json.dumps({"query": "{ auditEntries(limit: 1) { count entries { action ip } } }"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {access_token(staff)}",
+ )
+
+ page = response.json()["data"]["auditEntries"]
+ assert page["count"] == 2 and len(page["entries"]) == 1
+
+
+def test_grpc_lists_for_staff_and_refuses_others(
+ transactional_db: None, alice: Any, staff: Any, grpc_call: Callable[..., Any]
+) -> None:
+ record(alice, "update", staff, {"x": [1, 2]})
+ stub = audit_pb2_grpc.AuditControllerStub
+
+ reply = grpc_call(
+ stub, "ListEntries", audit_pb2.ListEntriesRequest(), token=access_token(staff)
+ )
+ assert reply.count == 1 and reply.entries[0].action == "update"
+
+ with pytest.raises(grpc.RpcError) as refused:
+ grpc_call(stub, "ListEntries", audit_pb2.ListEntriesRequest(), token=access_token(alice))
+ assert refused.value.code() == grpc.StatusCode.PERMISSION_DENIED
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/flags/__init__.py b/src/apps/flags/__init__.py
new file mode 100644
index 0000000..b13e848
--- /dev/null
+++ b/src/apps/flags/__init__.py
@@ -0,0 +1,23 @@
+"""Feature flags: a global switch, per-user overrides and a percentage rollout.
+
+ from apps.flags import is_enabled
+ if is_enabled("new-checkout", request.user): ...
+
+Imported lazily, as ``apps.club.track`` is, so another app may call this
+unconditionally: it answers ``False`` when the flags app is not installed.
+"""
+
+from typing import Any
+
+__all__ = ["is_enabled"]
+
+
+def is_enabled(key: str, user: Any = None) -> bool:
+ """Whether ``key`` is on for ``user``. See :func:`apps.flags.services.is_enabled`."""
+ from django.apps import apps
+
+ if not apps.is_installed("apps.flags"):
+ return False
+ from apps.flags.services import is_enabled as _is_enabled
+
+ return _is_enabled(key, user)
diff --git a/src/apps/flags/admin.py b/src/apps/flags/admin.py
new file mode 100644
index 0000000..54f9f72
--- /dev/null
+++ b/src/apps/flags/admin.py
@@ -0,0 +1,20 @@
+"""Staff edit flags and their overrides here; saving clears the cache through signals."""
+
+from django.contrib import admin
+from unfold.admin import ModelAdmin, TabularInline
+
+from apps.flags.models import Flag, FlagOverride
+
+
+class FlagOverrideInline(TabularInline):
+ model = FlagOverride
+ extra = 0
+ autocomplete_fields = ["user"]
+
+
+@admin.register(Flag)
+class FlagAdmin(ModelAdmin):
+ list_display = ["key", "is_enabled", "rollout_percentage", "updated_at"]
+ list_filter = ["is_enabled"]
+ search_fields = ["key", "description"]
+ inlines = [FlagOverrideInline]
diff --git a/src/apps/flags/apps.py b/src/apps/flags/apps.py
new file mode 100644
index 0000000..a997f06
--- /dev/null
+++ b/src/apps/flags/apps.py
@@ -0,0 +1,13 @@
+"""The flags app. Saving or deleting a flag or an override clears its cache entry."""
+
+from django.apps import AppConfig
+
+
+class FlagsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "apps.flags"
+ label = "flags"
+ verbose_name = "Feature flags"
+
+ def ready(self) -> None:
+ from apps.flags import signals # noqa: F401
diff --git a/src/apps/flags/errors.py b/src/apps/flags/errors.py
new file mode 100644
index 0000000..b2044f3
--- /dev/null
+++ b/src/apps/flags/errors.py
@@ -0,0 +1,15 @@
+"""Every refusal this app makes, with the HTTP status it carries."""
+
+
+class FlagError(Exception):
+ """Something a caller asked for that this app will not do."""
+
+ status = 400
+
+
+class FlagNotFound(FlagError, LookupError):
+ status = 404
+
+
+class StaffOnly(FlagError):
+ status = 403
diff --git a/src/apps/flags/graph/__init__.py b/src/apps/flags/graph/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/flags/graph/schema.py b/src/apps/flags/graph/schema.py
new file mode 100644
index 0000000..e50bc5f
--- /dev/null
+++ b/src/apps/flags/graph/schema.py
@@ -0,0 +1,115 @@
+"""Feature flags over GraphQL. Fields are prefixed ``flag`` so the merge stays quiet."""
+
+from typing import Any
+
+import strawberry
+from strawberry.types import Info
+
+from apps.flags import services
+from apps.flags.errors import FlagError
+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
+
+TITLES = {
+ 403: ResponseTitle.FORBIDDEN,
+ 404: ResponseTitle.NOT_FOUND,
+}
+
+
+def _caller(info: Info[Any, Any]) -> Any:
+ return require_caller(caller(info.context.request))
+
+
+def _run(call: Any, *args: Any, **kwargs: Any) -> Any:
+ try:
+ return call(*args, **kwargs)
+ except FlagError as refusal:
+ raise ApiError(
+ str(refusal),
+ status=refusal.status,
+ title=TITLES.get(refusal.status, ResponseTitle.VALIDATION_ERROR),
+ ) from None
+
+
+@strawberry.type
+class EvaluatedFlagType:
+ key: str
+ enabled: bool
+
+
+@strawberry.type
+class FlagOverrideType:
+ user_id: str
+ is_enabled: bool
+
+
+@strawberry.type
+class FlagType:
+ key: str
+ description: str
+ is_enabled: bool
+ rollout_percentage: int | None
+ overrides: list[FlagOverrideType]
+
+
+def _flag(row: dict[str, Any]) -> FlagType:
+ return FlagType(
+ key=row["key"],
+ description=row["description"],
+ is_enabled=row["is_enabled"],
+ rollout_percentage=row["rollout_percentage"],
+ overrides=[FlagOverrideType(**override) for override in row["overrides"]],
+ )
+
+
+@strawberry.type
+class Query:
+ @strawberry.field(description="Every flag, evaluated for the caller.")
+ @resolver
+ def my_flags(self, info: Info[Any, Any]) -> list[EvaluatedFlagType]:
+ return [EvaluatedFlagType(**row) for row in services.evaluate_all(_caller(info))]
+
+ @strawberry.field(description="Every flag with its rules. Staff only.")
+ @resolver
+ def flags(self, info: Info[Any, Any]) -> list[FlagType]:
+ return [_flag(row) for row in _run(services.list_flags, _caller(info))]
+
+
+@strawberry.type
+class Mutation:
+ @strawberry.mutation(description="Create or replace a flag. Staff only.")
+ @resolver
+ def flag_save(
+ self,
+ info: Info[Any, Any],
+ key: str,
+ is_enabled: bool,
+ rollout_percentage: int | None = None,
+ description: str = "",
+ ) -> FlagType:
+ row = _run(
+ services.save_flag,
+ _caller(info),
+ key,
+ is_enabled=is_enabled,
+ rollout_percentage=rollout_percentage,
+ description=description,
+ )
+ return _flag(row)
+
+ @strawberry.mutation(description="Delete a flag. Staff only.")
+ @resolver
+ def flag_delete(self, info: Info[Any, Any], key: str) -> bool:
+ _run(services.delete_flag, _caller(info), key)
+ return True
+
+ @strawberry.mutation(
+ description="Pin a flag on or off for one account; null clears the pin. Staff only."
+ )
+ @resolver
+ def flag_override(
+ self, info: Info[Any, Any], key: str, user_id: str, enabled: bool | None
+ ) -> FlagType:
+ return _flag(_run(services.set_override, _caller(info), key, user_id, enabled))
diff --git a/src/apps/flags/grpc/__init__.py b/src/apps/flags/grpc/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/flags/grpc/flags.proto b/src/apps/flags/grpc/flags.proto
new file mode 100644
index 0000000..d540116
--- /dev/null
+++ b/src/apps/flags/grpc/flags.proto
@@ -0,0 +1,70 @@
+syntax = "proto3";
+
+package config.flags;
+
+import "google/protobuf/empty.proto";
+
+service FlagController {
+ rpc DeleteFlag(DeleteFlagRequest) returns (DeleteFlagResult) {}
+ rpc ListFlags(google.protobuf.Empty) returns (FlagList) {}
+ rpc MyFlags(google.protobuf.Empty) returns (EvaluatedFlagList) {}
+ rpc SaveFlag(SaveFlagRequest) returns (FlagResult) {}
+ rpc SetOverride(SetOverrideRequest) returns (OverrideResult) {}
+}
+
+message DeleteFlagRequest {
+ string key = 1;
+}
+
+message DeleteFlagResult {
+ bool deleted = 1;
+}
+
+message EvaluatedFlag {
+ string key = 1;
+ bool enabled = 2;
+}
+
+message EvaluatedFlagList {
+ repeated EvaluatedFlag flags = 1;
+}
+
+message Flag {
+ string key = 1;
+ string description = 2;
+ bool is_enabled = 3;
+ int32 rollout_percentage = 4;
+ repeated FlagOverride overrides = 5;
+}
+
+message FlagList {
+ repeated Flag flags = 1;
+}
+
+message FlagOverride {
+ string user_id = 1;
+ bool is_enabled = 2;
+}
+
+message FlagResult {
+ Flag flag = 1;
+}
+
+message OverrideResult {
+ Flag flag = 1;
+}
+
+message SaveFlagRequest {
+ string key = 1;
+ string description = 2;
+ bool is_enabled = 3;
+ int32 rollout_percentage = 4;
+}
+
+message SetOverrideRequest {
+ string key = 1;
+ string user_id = 2;
+ bool enabled = 3;
+ bool clear = 4;
+}
+
diff --git a/src/apps/flags/grpc/flags_pb2.py b/src/apps/flags/grpc/flags_pb2.py
new file mode 100644
index 0000000..828f350
--- /dev/null
+++ b/src/apps/flags/grpc/flags_pb2.py
@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: apps/flags/grpc/flags.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/flags/grpc/flags.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\x1b\x61pps/flags/grpc/flags.proto\x12\x0c\x63onfig.flags\x1a\x1bgoogle/protobuf/empty.proto\" \n\x11\x44\x65leteFlagRequest\x12\x0b\n\x03key\x18\x01 \x01(\t\"#\n\x10\x44\x65leteFlagResult\x12\x0f\n\x07\x64\x65leted\x18\x01 \x01(\x08\"-\n\rEvaluatedFlag\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08\"?\n\x11\x45valuatedFlagList\x12*\n\x05\x66lags\x18\x01 \x03(\x0b\x32\x1b.config.flags.EvaluatedFlag\"\x87\x01\n\x04\x46lag\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x12\n\nis_enabled\x18\x03 \x01(\x08\x12\x1a\n\x12rollout_percentage\x18\x04 \x01(\x05\x12-\n\toverrides\x18\x05 \x03(\x0b\x32\x1a.config.flags.FlagOverride\"-\n\x08\x46lagList\x12!\n\x05\x66lags\x18\x01 \x03(\x0b\x32\x12.config.flags.Flag\"3\n\x0c\x46lagOverride\x12\x0f\n\x07user_id\x18\x01 \x01(\t\x12\x12\n\nis_enabled\x18\x02 \x01(\x08\".\n\nFlagResult\x12 \n\x04\x66lag\x18\x01 \x01(\x0b\x32\x12.config.flags.Flag\"2\n\x0eOverrideResult\x12 \n\x04\x66lag\x18\x01 \x01(\x0b\x32\x12.config.flags.Flag\"c\n\x0fSaveFlagRequest\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x12\n\nis_enabled\x18\x03 \x01(\x08\x12\x1a\n\x12rollout_percentage\x18\x04 \x01(\x05\"R\n\x12SetOverrideRequest\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x0f\n\x07user_id\x18\x02 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x03 \x01(\x08\x12\r\n\x05\x63lear\x18\x04 \x01(\x08\x32\xfe\x02\n\x0e\x46lagController\x12O\n\nDeleteFlag\x12\x1f.config.flags.DeleteFlagRequest\x1a\x1e.config.flags.DeleteFlagResult\"\x00\x12=\n\tListFlags\x12\x16.google.protobuf.Empty\x1a\x16.config.flags.FlagList\"\x00\x12\x44\n\x07MyFlags\x12\x16.google.protobuf.Empty\x1a\x1f.config.flags.EvaluatedFlagList\"\x00\x12\x45\n\x08SaveFlag\x12\x1d.config.flags.SaveFlagRequest\x1a\x18.config.flags.FlagResult\"\x00\x12O\n\x0bSetOverride\x12 .config.flags.SetOverrideRequest\x1a\x1c.config.flags.OverrideResult\"\x00\x62\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.flags.grpc.flags_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ DESCRIPTOR._loaded_options = None
+ _globals['_DELETEFLAGREQUEST']._serialized_start=74
+ _globals['_DELETEFLAGREQUEST']._serialized_end=106
+ _globals['_DELETEFLAGRESULT']._serialized_start=108
+ _globals['_DELETEFLAGRESULT']._serialized_end=143
+ _globals['_EVALUATEDFLAG']._serialized_start=145
+ _globals['_EVALUATEDFLAG']._serialized_end=190
+ _globals['_EVALUATEDFLAGLIST']._serialized_start=192
+ _globals['_EVALUATEDFLAGLIST']._serialized_end=255
+ _globals['_FLAG']._serialized_start=258
+ _globals['_FLAG']._serialized_end=393
+ _globals['_FLAGLIST']._serialized_start=395
+ _globals['_FLAGLIST']._serialized_end=440
+ _globals['_FLAGOVERRIDE']._serialized_start=442
+ _globals['_FLAGOVERRIDE']._serialized_end=493
+ _globals['_FLAGRESULT']._serialized_start=495
+ _globals['_FLAGRESULT']._serialized_end=541
+ _globals['_OVERRIDERESULT']._serialized_start=543
+ _globals['_OVERRIDERESULT']._serialized_end=593
+ _globals['_SAVEFLAGREQUEST']._serialized_start=595
+ _globals['_SAVEFLAGREQUEST']._serialized_end=694
+ _globals['_SETOVERRIDEREQUEST']._serialized_start=696
+ _globals['_SETOVERRIDEREQUEST']._serialized_end=778
+ _globals['_FLAGCONTROLLER']._serialized_start=781
+ _globals['_FLAGCONTROLLER']._serialized_end=1163
+# @@protoc_insertion_point(module_scope)
diff --git a/src/apps/flags/grpc/flags_pb2.pyi b/src/apps/flags/grpc/flags_pb2.pyi
new file mode 100644
index 0000000..c89cdda
--- /dev/null
+++ b/src/apps/flags/grpc/flags_pb2.pyi
@@ -0,0 +1,269 @@
+"""
+@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 DeleteFlagRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___DeleteFlagRequest: _TypeAlias = DeleteFlagRequest # noqa: Y015
+
+@_typing.final
+class DeleteFlagResult(_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___DeleteFlagResult: _TypeAlias = DeleteFlagResult # noqa: Y015
+
+@_typing.final
+class EvaluatedFlag(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ ENABLED_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ enabled: _builtins.bool
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ enabled: _builtins.bool = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["enabled", b"enabled", "key", b"key"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___EvaluatedFlag: _TypeAlias = EvaluatedFlag # noqa: Y015
+
+@_typing.final
+class EvaluatedFlagList(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAGS_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flags(self) -> _containers.RepeatedCompositeFieldContainer[Global___EvaluatedFlag]: ...
+ def __init__(
+ self,
+ *,
+ flags: _abc.Iterable[Global___EvaluatedFlag] | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flags", b"flags"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___EvaluatedFlagList: _TypeAlias = EvaluatedFlagList # noqa: Y015
+
+@_typing.final
+class Flag(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ DESCRIPTION_FIELD_NUMBER: _builtins.int
+ IS_ENABLED_FIELD_NUMBER: _builtins.int
+ ROLLOUT_PERCENTAGE_FIELD_NUMBER: _builtins.int
+ OVERRIDES_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ description: _builtins.str
+ is_enabled: _builtins.bool
+ rollout_percentage: _builtins.int
+ @_builtins.property
+ def overrides(self) -> _containers.RepeatedCompositeFieldContainer[Global___FlagOverride]: ...
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ description: _builtins.str = ...,
+ is_enabled: _builtins.bool = ...,
+ rollout_percentage: _builtins.int = ...,
+ overrides: _abc.Iterable[Global___FlagOverride] | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["description", b"description", "is_enabled", b"is_enabled", "key", b"key", "overrides", b"overrides", "rollout_percentage", b"rollout_percentage"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___Flag: _TypeAlias = Flag # noqa: Y015
+
+@_typing.final
+class FlagList(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAGS_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flags(self) -> _containers.RepeatedCompositeFieldContainer[Global___Flag]: ...
+ def __init__(
+ self,
+ *,
+ flags: _abc.Iterable[Global___Flag] | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flags", b"flags"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___FlagList: _TypeAlias = FlagList # noqa: Y015
+
+@_typing.final
+class FlagOverride(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ USER_ID_FIELD_NUMBER: _builtins.int
+ IS_ENABLED_FIELD_NUMBER: _builtins.int
+ user_id: _builtins.str
+ is_enabled: _builtins.bool
+ def __init__(
+ self,
+ *,
+ user_id: _builtins.str = ...,
+ is_enabled: _builtins.bool = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["is_enabled", b"is_enabled", "user_id", b"user_id"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___FlagOverride: _TypeAlias = FlagOverride # noqa: Y015
+
+@_typing.final
+class FlagResult(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAG_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flag(self) -> Global___Flag: ...
+ def __init__(
+ self,
+ *,
+ flag: Global___Flag | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___FlagResult: _TypeAlias = FlagResult # noqa: Y015
+
+@_typing.final
+class OverrideResult(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAG_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flag(self) -> Global___Flag: ...
+ def __init__(
+ self,
+ *,
+ flag: Global___Flag | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___OverrideResult: _TypeAlias = OverrideResult # noqa: Y015
+
+@_typing.final
+class SaveFlagRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ DESCRIPTION_FIELD_NUMBER: _builtins.int
+ IS_ENABLED_FIELD_NUMBER: _builtins.int
+ ROLLOUT_PERCENTAGE_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ description: _builtins.str
+ is_enabled: _builtins.bool
+ rollout_percentage: _builtins.int
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ description: _builtins.str = ...,
+ is_enabled: _builtins.bool = ...,
+ rollout_percentage: _builtins.int = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["description", b"description", "is_enabled", b"is_enabled", "key", b"key", "rollout_percentage", b"rollout_percentage"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___SaveFlagRequest: _TypeAlias = SaveFlagRequest # noqa: Y015
+
+@_typing.final
+class SetOverrideRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ USER_ID_FIELD_NUMBER: _builtins.int
+ ENABLED_FIELD_NUMBER: _builtins.int
+ CLEAR_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ user_id: _builtins.str
+ enabled: _builtins.bool
+ clear: _builtins.bool
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ user_id: _builtins.str = ...,
+ enabled: _builtins.bool = ...,
+ clear: _builtins.bool = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["clear", b"clear", "enabled", b"enabled", "key", b"key", "user_id", b"user_id"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___SetOverrideRequest: _TypeAlias = SetOverrideRequest # noqa: Y015
diff --git a/src/apps/flags/grpc/flags_pb2_grpc.py b/src/apps/flags/grpc/flags_pb2_grpc.py
new file mode 100644
index 0000000..ee97a1c
--- /dev/null
+++ b/src/apps/flags/grpc/flags_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.flags.grpc import flags_pb2 as apps_dot_flags_dot_grpc_dot_flags__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/flags/grpc/flags_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 FlagControllerStub:
+ """Missing associated documentation comment in .proto file."""
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.DeleteFlag = channel.unary_unary(
+ '/config.flags.FlagController/DeleteFlag',
+ request_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagRequest.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagResult.FromString,
+ _registered_method=True)
+ self.ListFlags = channel.unary_unary(
+ '/config.flags.FlagController/ListFlags',
+ request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagList.FromString,
+ _registered_method=True)
+ self.MyFlags = channel.unary_unary(
+ '/config.flags.FlagController/MyFlags',
+ request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.EvaluatedFlagList.FromString,
+ _registered_method=True)
+ self.SaveFlag = channel.unary_unary(
+ '/config.flags.FlagController/SaveFlag',
+ request_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SaveFlagRequest.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagResult.FromString,
+ _registered_method=True)
+ self.SetOverride = channel.unary_unary(
+ '/config.flags.FlagController/SetOverride',
+ request_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SetOverrideRequest.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.OverrideResult.FromString,
+ _registered_method=True)
+
+
+class FlagControllerServicer:
+ """Missing associated documentation comment in .proto file."""
+
+ def DeleteFlag(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 ListFlags(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 MyFlags(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 SaveFlag(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 SetOverride(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_FlagControllerServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'DeleteFlag': grpc.unary_unary_rpc_method_handler(
+ servicer.DeleteFlag,
+ request_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagRequest.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagResult.SerializeToString,
+ ),
+ 'ListFlags': grpc.unary_unary_rpc_method_handler(
+ servicer.ListFlags,
+ request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagList.SerializeToString,
+ ),
+ 'MyFlags': grpc.unary_unary_rpc_method_handler(
+ servicer.MyFlags,
+ request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.EvaluatedFlagList.SerializeToString,
+ ),
+ 'SaveFlag': grpc.unary_unary_rpc_method_handler(
+ servicer.SaveFlag,
+ request_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SaveFlagRequest.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagResult.SerializeToString,
+ ),
+ 'SetOverride': grpc.unary_unary_rpc_method_handler(
+ servicer.SetOverride,
+ request_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SetOverrideRequest.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.OverrideResult.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'config.flags.FlagController', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+ server.add_registered_method_handlers('config.flags.FlagController', rpc_method_handlers)
+
+
+ # This class is part of an EXPERIMENTAL API.
+class FlagController:
+ """Missing associated documentation comment in .proto file."""
+
+ @staticmethod
+ def DeleteFlag(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.flags.FlagController/DeleteFlag',
+ apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagRequest.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagResult.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def ListFlags(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.flags.FlagController/ListFlags',
+ google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.FlagList.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def MyFlags(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.flags.FlagController/MyFlags',
+ google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.EvaluatedFlagList.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def SaveFlag(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.flags.FlagController/SaveFlag',
+ apps_dot_flags_dot_grpc_dot_flags__pb2.SaveFlagRequest.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.FlagResult.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def SetOverride(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.flags.FlagController/SetOverride',
+ apps_dot_flags_dot_grpc_dot_flags__pb2.SetOverrideRequest.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.OverrideResult.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
diff --git a/src/apps/flags/grpc/flags_pb2_grpc.pyi b/src/apps/flags/grpc/flags_pb2_grpc.pyi
new file mode 100644
index 0000000..a20e792
--- /dev/null
+++ b/src/apps/flags/grpc/flags_pb2_grpc.pyi
@@ -0,0 +1,86 @@
+"""
+@generated by mypy-protobuf. Do not edit manually!
+isort:skip_file
+"""
+
+from apps.flags.grpc import flags_pb2 as _flags_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 FlagControllerStub:
+ @_typing.overload
+ def __new__(cls, channel: _grpc.Channel) -> _Self: ...
+ @_typing.overload
+ def __new__(cls, channel: _aio.Channel) -> FlagControllerAsyncStub: ...
+ DeleteFlag: _grpc.UnaryUnaryMultiCallable[_flags_pb2.DeleteFlagRequest, _flags_pb2.DeleteFlagResult]
+ ListFlags: _grpc.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.FlagList]
+ MyFlags: _grpc.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.EvaluatedFlagList]
+ SaveFlag: _grpc.UnaryUnaryMultiCallable[_flags_pb2.SaveFlagRequest, _flags_pb2.FlagResult]
+ SetOverride: _grpc.UnaryUnaryMultiCallable[_flags_pb2.SetOverrideRequest, _flags_pb2.OverrideResult]
+
+@_typing.type_check_only
+class FlagControllerAsyncStub(FlagControllerStub):
+ def __init__(self, channel: _aio.Channel) -> None: ...
+ DeleteFlag: _aio.UnaryUnaryMultiCallable[_flags_pb2.DeleteFlagRequest, _flags_pb2.DeleteFlagResult] # type: ignore[assignment]
+ ListFlags: _aio.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.FlagList] # type: ignore[assignment]
+ MyFlags: _aio.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.EvaluatedFlagList] # type: ignore[assignment]
+ SaveFlag: _aio.UnaryUnaryMultiCallable[_flags_pb2.SaveFlagRequest, _flags_pb2.FlagResult] # type: ignore[assignment]
+ SetOverride: _aio.UnaryUnaryMultiCallable[_flags_pb2.SetOverrideRequest, _flags_pb2.OverrideResult] # type: ignore[assignment]
+
+class FlagControllerServicer(metaclass=_abc_1.ABCMeta):
+ @_abc_1.abstractmethod
+ def DeleteFlag(
+ self,
+ request: _flags_pb2.DeleteFlagRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.DeleteFlagResult, _abc.Awaitable[_flags_pb2.DeleteFlagResult]]: ...
+
+ @_abc_1.abstractmethod
+ def ListFlags(
+ self,
+ request: _empty_pb2.Empty,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.FlagList, _abc.Awaitable[_flags_pb2.FlagList]]: ...
+
+ @_abc_1.abstractmethod
+ def MyFlags(
+ self,
+ request: _empty_pb2.Empty,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.EvaluatedFlagList, _abc.Awaitable[_flags_pb2.EvaluatedFlagList]]: ...
+
+ @_abc_1.abstractmethod
+ def SaveFlag(
+ self,
+ request: _flags_pb2.SaveFlagRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.FlagResult, _abc.Awaitable[_flags_pb2.FlagResult]]: ...
+
+ @_abc_1.abstractmethod
+ def SetOverride(
+ self,
+ request: _flags_pb2.SetOverrideRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.OverrideResult, _abc.Awaitable[_flags_pb2.OverrideResult]]: ...
+
+def add_FlagControllerServicer_to_server(servicer: FlagControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ...
diff --git a/src/apps/flags/grpc/serializers.py b/src/apps/flags/grpc/serializers.py
new file mode 100644
index 0000000..69e2ada
--- /dev/null
+++ b/src/apps/flags/grpc/serializers.py
@@ -0,0 +1,23 @@
+"""The nested messages the flags service answers with."""
+
+from rest_framework import serializers
+
+
+class EvaluatedFlag(serializers.Serializer[dict[str, object]]):
+ key = serializers.CharField()
+ enabled = serializers.BooleanField()
+
+
+class FlagOverride(serializers.Serializer[dict[str, object]]):
+ user_id = serializers.CharField()
+ is_enabled = serializers.BooleanField()
+
+
+class Flag(serializers.Serializer[dict[str, object]]):
+ """``rollout_percentage`` is -1 on the wire when the flag has none."""
+
+ key = serializers.CharField()
+ description = serializers.CharField()
+ is_enabled = serializers.BooleanField()
+ rollout_percentage = serializers.IntegerField()
+ overrides = FlagOverride(many=True)
diff --git a/src/apps/flags/grpc/services.py b/src/apps/flags/grpc/services.py
new file mode 100644
index 0000000..ba120d2
--- /dev/null
+++ b/src/apps/flags/grpc/services.py
@@ -0,0 +1,138 @@
+"""Feature flags over gRPC. The caller comes from metadata, as on the other doors.
+
+Protobuf has no null for a scalar, so ``rollout_percentage`` is -1 for "none" in
+both directions, and an override is cleared with ``clear`` rather than a null.
+"""
+
+from __future__ import annotations
+
+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.flags import services
+from apps.flags.errors import FlagError
+from apps.flags.grpc.serializers import EvaluatedFlag, Flag
+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
+
+NO_ROLLOUT = -1
+TITLES = {
+ 403: ResponseTitle.FORBIDDEN,
+ 404: ResponseTitle.NOT_FOUND,
+}
+
+
+def _pb2() -> Any:
+ from apps.flags.grpc import flags_pb2
+
+ return flags_pb2
+
+
+async def _run(call: Any, *args: Any, **kwargs: Any) -> Any:
+ try:
+ return await sync_to_async(call)(*args, **kwargs)
+ except FlagError as refusal:
+ raise ApiError(
+ str(refusal),
+ status=refusal.status,
+ title=TITLES.get(refusal.status, ResponseTitle.VALIDATION_ERROR),
+ ) from None
+
+
+def _flag(row: dict[str, Any]) -> Any:
+ pb2 = _pb2()
+ rollout = row["rollout_percentage"]
+ return pb2.Flag(
+ key=row["key"],
+ description=row["description"],
+ is_enabled=row["is_enabled"],
+ rollout_percentage=NO_ROLLOUT if rollout is None else rollout,
+ overrides=[pb2.FlagOverride(**override) for override in row["overrides"]],
+ )
+
+
+class FlagService(generics.GenericService):
+ @grpc_action(
+ request=[],
+ response=[{"name": "flags", "cardinality": "repeated", "type": EvaluatedFlag}],
+ response_name="EvaluatedFlagList",
+ )
+ @action
+ async def MyFlags(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rows = await _run(services.evaluate_all, user)
+ return _pb2().EvaluatedFlagList(flags=[_pb2().EvaluatedFlag(**row) for row in rows])
+
+ @grpc_action(
+ request=[],
+ response=[{"name": "flags", "cardinality": "repeated", "type": Flag}],
+ response_name="FlagList",
+ )
+ @action
+ async def ListFlags(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rows = await _run(services.list_flags, user)
+ return _pb2().FlagList(flags=[_flag(row) for row in rows])
+
+ @grpc_action(
+ request=[
+ {"name": "key", "type": "string"},
+ {"name": "description", "type": "string"},
+ {"name": "is_enabled", "type": "bool"},
+ {"name": "rollout_percentage", "type": "int32"},
+ ],
+ request_name="SaveFlagRequest",
+ response=[{"name": "flag", "type": Flag}],
+ response_name="FlagResult",
+ )
+ @action
+ async def SaveFlag(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rollout = request.rollout_percentage
+ row = await _run(
+ services.save_flag,
+ user,
+ request.key,
+ is_enabled=request.is_enabled,
+ rollout_percentage=None if rollout == NO_ROLLOUT else rollout,
+ description=request.description,
+ )
+ return _pb2().FlagResult(flag=_flag(row))
+
+ @grpc_action(
+ request=[{"name": "key", "type": "string"}],
+ request_name="DeleteFlagRequest",
+ response=[{"name": "deleted", "type": "bool"}],
+ response_name="DeleteFlagResult",
+ )
+ @action
+ async def DeleteFlag(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ await _run(services.delete_flag, user, request.key)
+ return _pb2().DeleteFlagResult(deleted=True)
+
+ @grpc_action(
+ request=[
+ {"name": "key", "type": "string"},
+ {"name": "user_id", "type": "string"},
+ {"name": "enabled", "type": "bool"},
+ {"name": "clear", "type": "bool"},
+ ],
+ request_name="SetOverrideRequest",
+ response=[{"name": "flag", "type": Flag}],
+ response_name="OverrideResult",
+ )
+ @action
+ async def SetOverride(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ enabled = None if request.clear else request.enabled
+ row = await _run(services.set_override, user, request.key, request.user_id, enabled)
+ return _pb2().OverrideResult(flag=_flag(row))
+
+
+GRPC_SERVICES = [FlagService]
diff --git a/src/apps/flags/migrations/0001_initial.py b/src/apps/flags/migrations/0001_initial.py
new file mode 100644
index 0000000..077b743
--- /dev/null
+++ b/src/apps/flags/migrations/0001_initial.py
@@ -0,0 +1,86 @@
+# Generated by Django 6.1.3 on 2026-11-26 14:26
+
+import django.core.validators
+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="Flag",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
+ ),
+ ),
+ ("key", models.SlugField(max_length=100, unique=True)),
+ ("description", models.TextField(blank=True)),
+ ("is_enabled", models.BooleanField(default=False, help_text="The global switch.")),
+ (
+ "rollout_percentage",
+ models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="Empty means everybody once the switch is on; 0-100 admits that share.",
+ null=True,
+ validators=[django.core.validators.MaxValueValidator(100)],
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "ordering": ["key"],
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(("rollout_percentage__lte", 100)),
+ name="flags_rollout_at_most_100",
+ )
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="FlagOverride",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
+ ),
+ ),
+ ("is_enabled", models.BooleanField()),
+ (
+ "flag",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="overrides",
+ to="flags.flag",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="flag_overrides",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("flag", "user"), name="flags_one_override_per_user"
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/src/apps/flags/migrations/__init__.py b/src/apps/flags/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/flags/models.py b/src/apps/flags/models.py
new file mode 100644
index 0000000..f450a06
--- /dev/null
+++ b/src/apps/flags/models.py
@@ -0,0 +1,56 @@
+"""A flag, and the per-account answers that override it."""
+
+from django.conf import settings
+from django.core.validators import MaxValueValidator
+from django.db import models
+
+
+class Flag(models.Model):
+ """One feature switch.
+
+ Evaluated in order: an override for the account wins; otherwise a flag that
+ is off is off; otherwise ``rollout_percentage`` (when set) admits that share
+ of accounts, bucketed by a stable hash of the account and the key.
+ """
+
+ key = models.SlugField(max_length=100, unique=True)
+ description = models.TextField(blank=True)
+ is_enabled = models.BooleanField(default=False, help_text="The global switch.")
+ rollout_percentage = models.PositiveSmallIntegerField(
+ null=True,
+ blank=True,
+ validators=[MaxValueValidator(100)],
+ help_text="Empty means everybody once the switch is on; 0-100 admits that share.",
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ ordering = ["key"]
+ constraints = [
+ models.CheckConstraint(
+ condition=models.Q(rollout_percentage__lte=100),
+ name="flags_rollout_at_most_100",
+ )
+ ]
+
+ def __str__(self) -> str:
+ return self.key
+
+
+class FlagOverride(models.Model):
+ """One account's answer for one flag, whatever the switch and the rollout say."""
+
+ flag = models.ForeignKey(Flag, on_delete=models.CASCADE, related_name="overrides")
+ user = models.ForeignKey(
+ settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="flag_overrides"
+ )
+ is_enabled = models.BooleanField()
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["flag", "user"], name="flags_one_override_per_user")
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.flag.key} for {self.user_id}: {'on' if self.is_enabled else 'off'}"
diff --git a/src/apps/flags/rest/__init__.py b/src/apps/flags/rest/__init__.py
new file mode 100644
index 0000000..f4571c0
--- /dev/null
+++ b/src/apps/flags/rest/__init__.py
@@ -0,0 +1,5 @@
+"""The HTTP transport for the flags app."""
+
+from apps.flags.rest.v1 import router
+
+__all__ = ["router"]
diff --git a/src/apps/flags/rest/schemas.py b/src/apps/flags/rest/schemas.py
new file mode 100644
index 0000000..04c0438
--- /dev/null
+++ b/src/apps/flags/rest/schemas.py
@@ -0,0 +1,37 @@
+"""What the flag routes take and return."""
+
+from ninja import Field, Schema
+
+
+class EvaluatedFlagOut(Schema):
+ key: str
+ enabled: bool
+
+
+class OverrideOut(Schema):
+ user_id: str
+ is_enabled: bool
+
+
+class FlagOut(Schema):
+ key: str
+ description: str
+ is_enabled: bool
+ rollout_percentage: int | None
+ overrides: list[OverrideOut]
+
+
+class FlagIn(Schema):
+ description: str = ""
+ is_enabled: bool = False
+ rollout_percentage: int | None = Field(default=None, ge=0, le=100)
+
+
+class OverrideIn(Schema):
+ """``null`` clears the account's override, so the flag's own rules apply again."""
+
+ enabled: bool | None
+
+
+class DeletedOut(Schema):
+ deleted: bool
diff --git a/src/apps/flags/rest/v1.py b/src/apps/flags/rest/v1.py
new file mode 100644
index 0000000..3754379
--- /dev/null
+++ b/src/apps/flags/rest/v1.py
@@ -0,0 +1,62 @@
+"""Feature flags over HTTP.
+
+``GET /flags/me`` is every flag evaluated for the caller. Everything else is
+staff-only, and refuses anybody else with a 403.
+"""
+
+from typing import Any
+
+from django.http import HttpRequest
+from ninja import Router
+from ninja.errors import HttpError
+
+from apps.flags import services
+from apps.flags.errors import FlagError
+from apps.flags.rest.schemas import DeletedOut, EvaluatedFlagOut, FlagIn, FlagOut, OverrideIn
+
+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)
+
+
+def _run(call: Any, *args: Any, **kwargs: Any) -> Any:
+ try:
+ return call(*args, **kwargs)
+ except FlagError as refusal:
+ raise HttpError(refusal.status, str(refusal)) from None
+
+
+@router.get("/me", response=list[EvaluatedFlagOut], summary="Every flag, evaluated for you")
+def my_flags(request: HttpRequest) -> Any:
+ return services.evaluate_all(request.user)
+
+
+@router.get("/", response=list[FlagOut], summary="Every flag (staff)")
+def list_flags(request: HttpRequest) -> Any:
+ return _run(services.list_flags, request.user)
+
+
+@router.get("/{key}", response=FlagOut, summary="One flag (staff)")
+def get_flag(request: HttpRequest, key: str) -> Any:
+ return _run(services.get_flag, request.user, key)
+
+
+@router.put("/{key}", response=FlagOut, summary="Create or replace a flag (staff)")
+def save_flag(request: HttpRequest, key: str, payload: FlagIn) -> Any:
+ return _run(services.save_flag, request.user, key, **payload.dict())
+
+
+@router.delete("/{key}", response=DeletedOut, summary="Delete a flag (staff)")
+def delete_flag(request: HttpRequest, key: str) -> Any:
+ _run(services.delete_flag, request.user, key)
+ return {"deleted": True}
+
+
+@router.put(
+ "/{key}/overrides/{user_id}", response=FlagOut, summary="Pin a flag for one account (staff)"
+)
+def set_override(request: HttpRequest, key: str, user_id: str, payload: OverrideIn) -> Any:
+ return _run(services.set_override, request.user, key, user_id, payload.enabled)
diff --git a/src/apps/flags/services.py b/src/apps/flags/services.py
new file mode 100644
index 0000000..20412f7
--- /dev/null
+++ b/src/apps/flags/services.py
@@ -0,0 +1,183 @@
+"""Evaluating flags, and the staff operations every transport shares.
+
+A flag's definition -- switch, rollout and overrides -- is cached per key and
+dropped by :mod:`apps.flags.signals` whenever the flag or an override is saved
+or deleted, so evaluation costs one cache read in the steady state.
+"""
+
+import hashlib
+import re
+from typing import Any
+
+from django.contrib.auth import get_user_model
+from django.core.cache import cache
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from apps.flags.errors import FlagError, FlagNotFound, StaffOnly
+from apps.flags.models import Flag, FlagOverride
+
+CACHE_PREFIX = "flags:flag:"
+CACHE_SECONDS = 300
+KEY_PATTERN = re.compile(r"^[-a-zA-Z0-9_]{1,100}$")
+#: What a cache read returns for a key that names no flag, so a missing flag is
+#: cached too and a typo in a hot path does not query the database every call.
+MISSING: dict[str, Any] = {}
+
+
+def _cache_key(key: str) -> str:
+ return f"{CACHE_PREFIX}{key}"
+
+
+def forget(key: str) -> None:
+ """Drop one flag's cached definition."""
+ cache.delete(_cache_key(key))
+
+
+def bucket(key: str, user_id: Any) -> int:
+ """A stable number in 0..99 for one account and one flag.
+
+ Hashed with the key so each flag admits a different slice of accounts, and
+ raising a percentage only ever adds accounts to the ones already admitted.
+ """
+ digest = hashlib.sha256(f"{key}:{user_id}".encode()).digest()
+ return int.from_bytes(digest[:8], "big") % 100
+
+
+def _definition(key: str) -> dict[str, Any]:
+ """The switch, the rollout and every override for one flag, cached.
+
+ ponytail: overrides live in the cached value, so a flag with very many
+ overrides makes a large entry; cache per (key, user) if that ever bites.
+ """
+ found = cache.get(_cache_key(key))
+ if found is not None:
+ return dict(found)
+ flag = Flag.objects.filter(key=key).first()
+ definition: dict[str, Any] = MISSING
+ if flag is not None:
+ definition = {
+ "is_enabled": flag.is_enabled,
+ "rollout_percentage": flag.rollout_percentage,
+ "overrides": dict(flag.overrides.values_list("user_id", "is_enabled")),
+ }
+ cache.set(_cache_key(key), definition, CACHE_SECONDS)
+ return dict(definition)
+
+
+def _evaluate(key: str, definition: dict[str, Any], user: Any) -> bool:
+ if not definition:
+ return False
+ user_id = getattr(user, "pk", None) if getattr(user, "is_authenticated", False) else None
+ if user_id is not None and user_id in definition["overrides"]:
+ return bool(definition["overrides"][user_id])
+ if not definition["is_enabled"]:
+ return False
+ rollout = definition["rollout_percentage"]
+ if rollout is None or rollout >= 100:
+ return True
+ if user_id is None:
+ return False
+ return bucket(key, user_id) < rollout
+
+
+def is_enabled(key: str, user: Any = None) -> bool:
+ """Whether ``key`` is on for ``user``. An unknown key is off.
+
+ Anonymous callers get the switch alone when there is no rollout, and are
+ left out of a partial rollout: there is no stable id to bucket them by.
+ """
+ return _evaluate(key, _definition(key), user)
+
+
+def evaluate_all(user: Any) -> list[dict[str, Any]]:
+ """Every flag, evaluated for ``user``."""
+ keys = Flag.objects.values_list("key", flat=True)
+ return [{"key": key, "enabled": is_enabled(key, user)} for key in keys]
+
+
+def _require_staff(user: Any) -> None:
+ if not getattr(user, "is_staff", False):
+ raise StaffOnly("Only staff manage feature flags.")
+
+
+def _row(flag: Flag) -> dict[str, Any]:
+ return {
+ "key": flag.key,
+ "description": flag.description,
+ "is_enabled": flag.is_enabled,
+ "rollout_percentage": flag.rollout_percentage,
+ "overrides": [
+ {"user_id": str(user_id), "is_enabled": enabled}
+ for user_id, enabled in flag.overrides.order_by("user_id").values_list(
+ "user_id", "is_enabled"
+ )
+ ],
+ }
+
+
+def list_flags(actor: Any) -> list[dict[str, Any]]:
+ _require_staff(actor)
+ return [_row(flag) for flag in Flag.objects.prefetch_related("overrides")]
+
+
+def get_flag(actor: Any, key: str) -> dict[str, Any]:
+ _require_staff(actor)
+ flag = Flag.objects.filter(key=key).first()
+ if flag is None:
+ raise FlagNotFound(f"No flag {key!r}.")
+ return _row(flag)
+
+
+def save_flag(
+ actor: Any,
+ key: str,
+ *,
+ is_enabled: bool,
+ rollout_percentage: int | None = None,
+ description: str = "",
+) -> dict[str, Any]:
+ """Create or replace one flag."""
+ _require_staff(actor)
+ if not KEY_PATTERN.match(key):
+ raise FlagError("A key is 1-100 letters, digits, hyphens or underscores.")
+ if rollout_percentage is not None and not 0 <= rollout_percentage <= 100:
+ raise FlagError("rollout_percentage must be between 0 and 100.")
+ flag, _ = Flag.objects.update_or_create(
+ key=key,
+ defaults={
+ "is_enabled": is_enabled,
+ "rollout_percentage": rollout_percentage,
+ "description": description,
+ },
+ )
+ return _row(flag)
+
+
+def delete_flag(actor: Any, key: str) -> None:
+ _require_staff(actor)
+ deleted, _ = Flag.objects.filter(key=key).delete()
+ if not deleted:
+ raise FlagNotFound(f"No flag {key!r}.")
+
+
+def set_override(actor: Any, key: str, user_id: Any, enabled: bool | None) -> dict[str, Any]:
+ """Pin ``key`` on or off for one account, or clear the pin with ``None``."""
+ _require_staff(actor)
+ flag = Flag.objects.filter(key=key).first()
+ if flag is None:
+ raise FlagNotFound(f"No flag {key!r}.")
+ try:
+ target = get_user_model().objects.filter(pk=user_id).first()
+ except (ValidationError, ValueError):
+ target = None
+ if target is None:
+ raise FlagNotFound(f"No account {user_id!r}.")
+ with transaction.atomic():
+ if enabled is None:
+ FlagOverride.objects.filter(flag=flag, user=target).delete()
+ else:
+ FlagOverride.objects.update_or_create(
+ flag=flag, user=target, defaults={"is_enabled": enabled}
+ )
+ return _row(flag)
diff --git a/src/apps/flags/signals.py b/src/apps/flags/signals.py
new file mode 100644
index 0000000..e21d430
--- /dev/null
+++ b/src/apps/flags/signals.py
@@ -0,0 +1,19 @@
+"""Drop a flag's cached definition whenever it, or one of its overrides, changes."""
+
+from typing import Any
+
+from django.db.models.signals import post_delete, post_save
+from django.dispatch import receiver
+
+from apps.flags.models import Flag, FlagOverride
+from apps.flags.services import forget
+
+
+@receiver([post_save, post_delete], sender=Flag)
+def _flag_changed(sender: Any, instance: Flag, **kwargs: Any) -> None:
+ forget(instance.key)
+
+
+@receiver([post_save, post_delete], sender=FlagOverride)
+def _override_changed(sender: Any, instance: FlagOverride, **kwargs: Any) -> None:
+ forget(Flag.objects.filter(pk=instance.flag_id).values_list("key", flat=True).first() or "")
diff --git a/src/apps/flags/tests/__init__.py b/src/apps/flags/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/apps/flags/tests/conftest.py b/src/apps/flags/tests/conftest.py
new file mode 100644
index 0000000..baa1dbc
--- /dev/null
+++ b/src/apps/flags/tests/conftest.py
@@ -0,0 +1,40 @@
+"""Fixtures for the flags tests. Collection stops when the app is not installed."""
+
+from typing import Any
+
+import pytest
+from django.apps import apps as django_apps
+from django.contrib.auth import get_user_model
+from django.core.cache import cache
+from django.test import RequestFactory
+
+FLAGS_INSTALLED = django_apps.is_installed("apps.flags")
+collect_ignore_glob = [] if FLAGS_INSTALLED else ["*"]
+
+
+def access_token(user: Any) -> str:
+ from infrastructure.auth.core.sessions import issue_credentials
+
+ request = RequestFactory().post("/")
+ return issue_credentials(request, user, method="password").access_token
+
+
+def bearer(user: Any) -> dict[str, str]:
+ return {"HTTP_AUTHORIZATION": f"Bearer {access_token(user)}"}
+
+
+@pytest.fixture(autouse=True)
+def _empty_cache() -> None:
+ cache.clear()
+
+
+@pytest.fixture
+def alice(db: None) -> Any:
+ return get_user_model().objects.create_user(username="alice", email="alice@example.test")
+
+
+@pytest.fixture
+def operator(db: None) -> Any:
+ return get_user_model().objects.create_user(
+ username="operator", email="ops@example.test", is_staff=True
+ )
diff --git a/src/apps/flags/tests/test_admin.py b/src/apps/flags/tests/test_admin.py
new file mode 100644
index 0000000..5d1ec78
--- /dev/null
+++ b/src/apps/flags/tests/test_admin.py
@@ -0,0 +1,17 @@
+from typing import Any
+
+import pytest
+from django.test import Client
+
+from apps.flags.models import Flag
+
+pytestmark = pytest.mark.django_db
+
+
+def test_staff_see_the_flag_admin(admin_user: Any) -> None:
+ Flag.objects.create(key="beta")
+ client = Client()
+ client.force_login(admin_user)
+
+ assert client.get("/admin/flags/flag/").status_code == 200
+ assert client.get("/admin/flags/flag/add/").status_code == 200
diff --git a/src/apps/flags/tests/test_api.py b/src/apps/flags/tests/test_api.py
new file mode 100644
index 0000000..220bf58
--- /dev/null
+++ b/src/apps/flags/tests/test_api.py
@@ -0,0 +1,78 @@
+from typing import Any
+
+import pytest
+from django.test import Client
+
+from apps.flags.models import Flag, FlagOverride
+from apps.flags.tests.conftest import bearer
+
+pytestmark = pytest.mark.django_db
+BASE = "/api/v1/flags"
+
+
+def test_me_is_every_flag_evaluated_for_the_caller(alice: Any) -> None:
+ beta = Flag.objects.create(key="beta", is_enabled=False)
+ Flag.objects.create(key="live", is_enabled=True)
+ FlagOverride.objects.create(flag=beta, user=alice, is_enabled=True)
+
+ response = Client().get(f"{BASE}/me", **bearer(alice))
+
+ assert response.status_code == 200, response.content
+ assert response.json()["data"] == [
+ {"key": "beta", "enabled": True},
+ {"key": "live", "enabled": True},
+ ]
+
+
+def test_me_needs_a_credential() -> None:
+ assert Client().get(f"{BASE}/me").status_code == 401
+
+
+def test_a_member_cannot_manage_flags(alice: Any) -> None:
+ client = Client()
+ assert client.get(f"{BASE}/", **bearer(alice)).status_code == 403
+ response = client.put(
+ f"{BASE}/beta", {"is_enabled": True}, content_type="application/json", **bearer(alice)
+ )
+ assert response.status_code == 403
+ assert not Flag.objects.exists()
+
+
+def test_staff_manage_flags_end_to_end(operator: Any, alice: Any) -> None:
+ client = Client()
+ auth = bearer(operator)
+
+ saved = client.put(
+ f"{BASE}/beta",
+ {"is_enabled": True, "rollout_percentage": 0, "description": "New thing"},
+ content_type="application/json",
+ **auth,
+ )
+ assert saved.status_code == 200, saved.content
+ assert saved.json()["data"]["rollout_percentage"] == 0
+
+ pinned = client.put(
+ f"{BASE}/beta/overrides/{alice.pk}",
+ {"enabled": True},
+ content_type="application/json",
+ **auth,
+ )
+ assert pinned.json()["data"]["overrides"] == [{"user_id": str(alice.pk), "is_enabled": True}]
+ assert client.get(f"{BASE}/me", **bearer(alice)).json()["data"] == [
+ {"key": "beta", "enabled": True}
+ ]
+
+ assert [row["key"] for row in client.get(f"{BASE}/", **auth).json()["data"]] == ["beta"]
+ assert client.get(f"{BASE}/beta", **auth).status_code == 200
+ assert client.delete(f"{BASE}/beta", **auth).json()["data"] == {"deleted": True}
+ assert client.get(f"{BASE}/beta", **auth).status_code == 404
+
+
+def test_a_rollout_over_100_is_refused(operator: Any) -> None:
+ response = Client().put(
+ f"{BASE}/beta",
+ {"is_enabled": True, "rollout_percentage": 150},
+ content_type="application/json",
+ **bearer(operator),
+ )
+ assert response.status_code in (400, 422)
diff --git a/src/apps/flags/tests/test_graph.py b/src/apps/flags/tests/test_graph.py
new file mode 100644
index 0000000..da8b2e9
--- /dev/null
+++ b/src/apps/flags/tests/test_graph.py
@@ -0,0 +1,65 @@
+import json
+from typing import Any
+
+import pytest
+from django.test import Client
+
+from apps.flags.models import Flag
+from apps.flags.tests.conftest import bearer
+
+pytestmark = pytest.mark.django_db
+
+MY_FLAGS = "{ myFlags { key enabled } }"
+FLAGS = "{ flags { key isEnabled rolloutPercentage overrides { userId isEnabled } } }"
+SAVE = """
+mutation($key: String!) {
+ flagSave(key: $key, isEnabled: true, rolloutPercentage: 100) { key rolloutPercentage }
+}
+"""
+OVERRIDE = """
+mutation($key: String!, $userId: String!) {
+ flagOverride(key: $key, userId: $userId, enabled: false) { overrides { userId isEnabled } }
+}
+"""
+DELETE = "mutation($key: String!) { flagDelete(key: $key) }"
+
+
+def graphql(query: str, user: Any = None, **variables: Any) -> dict[str, Any]:
+ headers = bearer(user) if user else {}
+ response = Client().post(
+ "/graphql",
+ json.dumps({"query": query, "variables": variables}),
+ content_type="application/json",
+ **headers,
+ )
+ return response.json()
+
+
+def test_my_flags(alice: Any) -> None:
+ Flag.objects.create(key="live", is_enabled=True)
+ assert graphql(MY_FLAGS, alice)["data"]["myFlags"] == [{"key": "live", "enabled": True}]
+
+
+def test_my_flags_needs_a_caller() -> None:
+ body = graphql(MY_FLAGS)
+ assert body["errors"][0]["extensions"]["status"] == 401
+
+
+def test_members_are_refused_the_staff_fields(alice: Any) -> None:
+ body = graphql(FLAGS, alice)
+ assert body["errors"][0]["extensions"]["status"] == 403
+
+
+def test_staff_round_trip(operator: Any, alice: Any) -> None:
+ assert graphql(SAVE, operator, key="beta")["data"]["flagSave"] == {
+ "key": "beta",
+ "rolloutPercentage": 100,
+ }
+ overridden = graphql(OVERRIDE, operator, key="beta", userId=str(alice.pk))
+ assert overridden["data"]["flagOverride"]["overrides"] == [
+ {"userId": str(alice.pk), "isEnabled": False}
+ ]
+ assert graphql(MY_FLAGS, alice)["data"]["myFlags"] == [{"key": "beta", "enabled": False}]
+ assert len(graphql(FLAGS, operator)["data"]["flags"]) == 1
+ assert graphql(DELETE, operator, key="beta")["data"]["flagDelete"] is True
+ assert not Flag.objects.exists()
diff --git a/src/apps/flags/tests/test_grpc.py b/src/apps/flags/tests/test_grpc.py
new file mode 100644
index 0000000..ee8b6d8
--- /dev/null
+++ b/src/apps/flags/tests/test_grpc.py
@@ -0,0 +1,67 @@
+"""``transactional_db`` throughout: the server answers on its own connection."""
+
+from collections.abc import Callable
+from typing import Any
+
+import grpc
+import pytest
+from google.protobuf.empty_pb2 import Empty
+
+from apps.flags.grpc import flags_pb2, flags_pb2_grpc
+from apps.flags.models import Flag
+from apps.flags.tests.conftest import access_token
+
+Stub = flags_pb2_grpc.FlagControllerStub
+
+
+def test_my_flags(transactional_db: None, alice: Any, grpc_call: Callable[..., Any]) -> None:
+ Flag.objects.create(key="live", is_enabled=True)
+ reply = grpc_call(Stub, "MyFlags", Empty(), token=access_token(alice))
+ assert [(row.key, row.enabled) for row in reply.flags] == [("live", True)]
+
+
+def test_members_cannot_save(
+ transactional_db: None, alice: Any, grpc_call: Callable[..., Any]
+) -> None:
+ with pytest.raises(grpc.RpcError) as refused:
+ grpc_call(
+ Stub,
+ "SaveFlag",
+ flags_pb2.SaveFlagRequest(key="beta", is_enabled=True, rollout_percentage=-1),
+ token=access_token(alice),
+ )
+ assert refused.value.code() == grpc.StatusCode.PERMISSION_DENIED
+
+
+def test_staff_round_trip(
+ transactional_db: None, operator: Any, alice: Any, grpc_call: Callable[..., Any]
+) -> None:
+ token = access_token(operator)
+ saved = grpc_call(
+ Stub,
+ "SaveFlag",
+ flags_pb2.SaveFlagRequest(key="beta", is_enabled=False, rollout_percentage=-1),
+ token=token,
+ )
+ assert saved.flag.rollout_percentage == -1
+ assert Flag.objects.get(key="beta").rollout_percentage is None
+
+ pinned = grpc_call(
+ Stub,
+ "SetOverride",
+ flags_pb2.SetOverrideRequest(key="beta", user_id=str(alice.pk), enabled=True),
+ token=token,
+ )
+ assert [o.user_id for o in pinned.flag.overrides] == [str(alice.pk)]
+ cleared = grpc_call(
+ Stub,
+ "SetOverride",
+ flags_pb2.SetOverrideRequest(key="beta", user_id=str(alice.pk), clear=True),
+ token=token,
+ )
+ assert list(cleared.flag.overrides) == []
+
+ assert [row.key for row in grpc_call(Stub, "ListFlags", Empty(), token=token).flags] == ["beta"]
+ assert grpc_call(
+ Stub, "DeleteFlag", flags_pb2.DeleteFlagRequest(key="beta"), token=token
+ ).deleted
diff --git a/src/apps/flags/tests/test_services.py b/src/apps/flags/tests/test_services.py
new file mode 100644
index 0000000..3797828
--- /dev/null
+++ b/src/apps/flags/tests/test_services.py
@@ -0,0 +1,130 @@
+from typing import Any
+
+import pytest
+from django.contrib.auth import get_user_model
+from django.contrib.auth.models import AnonymousUser
+
+from apps.flags import is_enabled as public_is_enabled
+from apps.flags import services
+from apps.flags.errors import FlagError, FlagNotFound, StaffOnly
+from apps.flags.models import Flag, FlagOverride
+
+pytestmark = pytest.mark.django_db
+
+
+def test_an_unknown_flag_is_off(alice: Any) -> None:
+ assert services.is_enabled("nope", alice) is False
+
+
+def test_the_global_switch(alice: Any) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=True)
+ assert services.is_enabled("beta", alice) is True
+ assert services.is_enabled("beta", AnonymousUser()) is True
+
+ flag.is_enabled = False
+ flag.save()
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_an_override_beats_the_switch_both_ways(alice: Any, operator: Any) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=False)
+ FlagOverride.objects.create(flag=flag, user=alice, is_enabled=True)
+ assert services.is_enabled("beta", alice) is True
+ assert services.is_enabled("beta", operator) is False
+
+ flag.is_enabled = True
+ flag.save()
+ FlagOverride.objects.filter(user=alice).update(is_enabled=False)
+ services.forget("beta") # `.update` sends no signal
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_the_rollout_admits_roughly_its_share_and_is_stable() -> None:
+ Flag.objects.create(key="half", is_enabled=True, rollout_percentage=50)
+ users = [
+ get_user_model().objects.create_user(username=f"u{n}", email=f"u{n}@example.test")
+ for n in range(200)
+ ]
+ admitted = [user for user in users if services.is_enabled("half", user)]
+
+ assert 60 < len(admitted) < 140
+ assert all(services.is_enabled("half", user) for user in admitted)
+
+
+def test_raising_the_rollout_keeps_everybody_already_in() -> None:
+ flag = Flag.objects.create(key="grow", is_enabled=True, rollout_percentage=20)
+ users = [
+ get_user_model().objects.create_user(username=f"u{n}", email=f"u{n}@example.test")
+ for n in range(50)
+ ]
+ before = {user.pk for user in users if services.is_enabled("grow", user)}
+ flag.rollout_percentage = 60
+ flag.save()
+ after = {user.pk for user in users if services.is_enabled("grow", user)}
+
+ assert before <= after
+
+
+def test_a_partial_rollout_leaves_anonymous_callers_out() -> None:
+ Flag.objects.create(key="half", is_enabled=True, rollout_percentage=99)
+ assert services.is_enabled("half", AnonymousUser()) is False
+ assert services.is_enabled("half", None) is False
+
+
+def test_evaluation_is_cached_and_a_save_invalidates(
+ alice: Any, django_assert_num_queries: Any
+) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=True)
+ services.is_enabled("beta", alice)
+ with django_assert_num_queries(0):
+ assert services.is_enabled("beta", alice) is True
+
+ flag.is_enabled = False
+ flag.save()
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_an_override_save_and_delete_invalidate(alice: Any) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=False)
+ assert services.is_enabled("beta", alice) is False
+ override = FlagOverride.objects.create(flag=flag, user=alice, is_enabled=True)
+ assert services.is_enabled("beta", alice) is True
+ override.delete()
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_the_package_level_shortcut(alice: Any) -> None:
+ Flag.objects.create(key="beta", is_enabled=True)
+ assert public_is_enabled("beta", alice) is True
+
+
+def test_staff_operations_refuse_everybody_else(alice: Any) -> None:
+ with pytest.raises(StaffOnly):
+ services.list_flags(alice)
+ with pytest.raises(StaffOnly):
+ services.save_flag(alice, "x", is_enabled=True)
+
+
+def test_staff_save_validates(operator: Any) -> None:
+ with pytest.raises(FlagError):
+ services.save_flag(operator, "bad key!", is_enabled=True)
+ with pytest.raises(FlagError):
+ services.save_flag(operator, "ok", is_enabled=True, rollout_percentage=101)
+
+
+def test_set_override_and_clear(operator: Any, alice: Any) -> None:
+ services.save_flag(operator, "beta", is_enabled=False)
+ row = services.set_override(operator, "beta", str(alice.pk), True)
+ assert row["overrides"] == [{"user_id": str(alice.pk), "is_enabled": True}]
+ assert services.is_enabled("beta", alice) is True
+
+ services.set_override(operator, "beta", str(alice.pk), None)
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_set_override_refuses_unknown_targets(operator: Any) -> None:
+ with pytest.raises(FlagNotFound):
+ services.set_override(operator, "missing", "x", True)
+ services.save_flag(operator, "beta", is_enabled=False)
+ with pytest.raises(FlagNotFound):
+ services.set_override(operator, "beta", "not-a-uuid", True)
diff --git a/src/apps/shop/services.py b/src/apps/shop/services.py
index 8e2e4f2..044e210 100644
--- a/src/apps/shop/services.py
+++ b/src/apps/shop/services.py
@@ -34,6 +34,7 @@
from django.db.models.functions import Greatest
from django.utils import timezone
+from apps.audit.services import record
from apps.shop import options, signals
from apps.shop.attributes import AttributeType, normalize_value
from apps.shop.models import (
@@ -1015,6 +1016,7 @@ def checkout(
OrderEvent.objects.create(
order=order, status=OrderStatus.PENDING, note="Placed.", actor=user
)
+ record(user, "create", order, {"status": [None, str(OrderStatus.PENDING)]})
cart.items.all().delete()
return order
@@ -1087,6 +1089,12 @@ def settle_order(
)
locked.status = OrderStatus.PAID
locked.save(update_fields=["status", "updated_at"])
+ record(
+ actor,
+ "settle",
+ locked,
+ {"status": [str(OrderStatus.PENDING), str(OrderStatus.PAID)]},
+ )
OrderEvent.objects.create(
order=locked,
status=OrderStatus.PAID,
@@ -1185,6 +1193,7 @@ def reject_payment(self, order: Order, *, reason: str = "", actor: Any = None) -
note=f"Payment attempt refused{f': {reason}' if reason else ''}."[:300],
actor=actor,
)
+ record(actor, "reject_payment", locked, {"payment": ["pending", "failed"]})
return locked
def confirm_payment(self, user: Any, number: str, *, reference: str = "") -> Order:
@@ -1227,6 +1236,12 @@ def cancel_order(self, user: Any, number: str) -> Order:
note="Cancelled by the shopper.",
actor=user,
)
+ record(
+ user,
+ "cancel",
+ order,
+ {"status": [str(OrderStatus.PENDING), str(OrderStatus.CANCELLED)]},
+ )
return order
def advance_order(
@@ -1291,8 +1306,10 @@ def advance_order(
locked.tracking_number = tracking_number or locked.tracking_number
locked.tracking_url = tracking_url or locked.tracking_url
changed += ["shipped_at", "carrier", "tracking_number", "tracking_url"]
+ previous = str(locked.status)
locked.status = wanted
locked.save(update_fields=changed)
+ record(actor, "set_status", locked, {"status": [previous, wanted]})
OrderEvent.objects.create(order=locked, status=wanted, note=note[:300], actor=actor)
return locked
diff --git a/src/apps/shop/tests/test_fulfilment.py b/src/apps/shop/tests/test_fulfilment.py
index 80e262c..b287943 100644
--- a/src/apps/shop/tests/test_fulfilment.py
+++ b/src/apps/shop/tests/test_fulfilment.py
@@ -207,3 +207,19 @@ def test_a_pending_order_is_still_the_shopper_s_to_cancel(
def test_the_amount_collected_is_read_off_the_payments(self, paid: Order) -> None:
assert paid.paid_amount == Decimal(str(paid.total))
assert Payment.objects.filter(order=paid, status=PaymentStatus.SUCCEEDED).count() == 1
+
+
+def test_every_status_change_lands_in_the_audit_log(paid: Order) -> None:
+ from apps.audit.models import AuditEntry
+
+ shop_service.start_processing(paid)
+
+ trail = AuditEntry.objects.filter(target_model="shop.order", target_id=str(paid.pk))
+ assert list(trail.order_by("created_at").values_list("action", flat=True)) == [
+ "create",
+ "settle",
+ "set_status",
+ ]
+ assert trail.get(action="set_status").changes == {
+ "status": [str(OrderStatus.PAID), str(OrderStatus.PROCESSING)]
+ }
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/apps/wallet/services.py b/src/apps/wallet/services.py
index 97f9095..911fcd3 100644
--- a/src/apps/wallet/services.py
+++ b/src/apps/wallet/services.py
@@ -61,6 +61,7 @@
from django.db.models import OuterRef, Subquery
from django.utils import timezone
+from apps.audit.services import record
from apps.wallet import gateways, signals
from apps.wallet.balances import Balance, balance_of
from apps.wallet.catalog import Applies, ExchangeRate, PaymentMethod
@@ -875,6 +876,7 @@ def expire_entry(self, entry_id: UUID, *, reason: str = "", by: Any = None) -> d
raise InvalidTransition(
f"A {entry.get_status_display().lower()} entry cannot expire."
)
+ previous = entry.status
entry.status = str(EntryStatus.EXPIRED)
fields = ["status"]
note = {
@@ -885,6 +887,7 @@ def expire_entry(self, entry_id: UUID, *, reason: str = "", by: Any = None) -> d
entry.metadata = {**entry.metadata, **note}
fields.append("metadata")
entry.save(update_fields=fields)
+ record(by, "expire", entry, {"status": [previous, entry.status]})
signals.announce(signals.entry_expired, entry=entry_payload(entry, staff=True))
return entry_payload(entry)
@@ -959,14 +962,24 @@ def adjust(
metadata: dict[str, Any] = {"reason": reason}
if getattr(by, "pk", None):
metadata["adjusted_by"] = str(by.pk)
- return self._record_system(
- user,
- kind=kind,
- amount=amount,
- reference=reference,
- description=reason,
- metadata=metadata,
- )
+ with transaction.atomic():
+ replay = self._existing(self.wallet_for(user), reference) is not None
+ adjusted = self._record_system(
+ user,
+ kind=kind,
+ amount=amount,
+ reference=reference,
+ description=reason,
+ metadata=metadata,
+ )
+ if not replay:
+ record(
+ by,
+ "adjust",
+ WalletEntry.objects.get(pk=adjusted["id"]),
+ {"kind": kind, "amount": str(amount), "reason": reason},
+ )
+ return adjusted
def pay(
self,
@@ -1184,6 +1197,7 @@ def set_wallet_status(
)
locked.status = status
locked.save(update_fields=["status", "updated_at"])
+ record(by, "set_status", locked, {"status": [previous, status]})
change = {
"id": locked.pk,
"status": status,
@@ -1265,6 +1279,7 @@ def approve(self, entry_id: UUID, *, by: Any = None, note: str = "") -> dict[str
entry.reviewed_at = timezone.now()
entry.review_note = note
entry.save(update_fields=["approval", "reviewed_by", "reviewed_at", "review_note"])
+ record(by, "approve", entry, {"approval": ["requested", "approved"]})
signals.announce(signals.entry_approved, entry=entry_payload(entry, staff=True))
rail = entry.payment_method.spec if entry.payment_method_id else None
@@ -1403,6 +1418,7 @@ def reject(self, entry_id: UUID, *, by: Any = None, note: str = "") -> dict[str,
entry.status = str(EntryStatus.CANCELLED)
fields.append("status")
entry.save(update_fields=fields)
+ record(by, "reject", entry, {"approval": ["requested", "rejected"]})
signals.announce(signals.entry_rejected, entry=entry_payload(entry, staff=True))
if cancelled:
signals.announce(signals.entry_cancelled, entry=entry_payload(entry, staff=True))
@@ -1519,9 +1535,11 @@ def _reverse_locked(
metadata=metadata,
counterparty=original,
)
+ previous = original.status
original.status = str(EntryStatus.REVERSED)
original.metadata = {**original.metadata, "reversed_by": str(correction.pk)}
original.save(update_fields=["status", "metadata"])
+ record(by, "reverse", original, {"status": [previous, original.status]})
signals.announce(
signals.entry_reversed,
entry=entry_payload(original, staff=True),
@@ -2011,6 +2029,7 @@ def _transition(
self._check_wallet(locked, entry.direction)
self._check_funds(locked, entry.amount, already_held=entry.amount)
+ previous = entry.status
entry.status = status
fields = ["status"]
if external_reference:
@@ -2021,6 +2040,7 @@ def _transition(
entry.metadata = {**entry.metadata, **note}
fields.append("metadata")
entry.save(update_fields=fields)
+ record(by or user, "set_status", entry, {"status": [previous, status]})
signals.announce(signals.STATUS_SIGNALS[status], entry=entry_payload(entry, staff=True))
return entry_payload(entry)
diff --git a/src/apps/wallet/tests/test_backoffice.py b/src/apps/wallet/tests/test_backoffice.py
index e5bc8cc..1d979f2 100644
--- a/src/apps/wallet/tests/test_backoffice.py
+++ b/src/apps/wallet/tests/test_backoffice.py
@@ -168,3 +168,23 @@ def test_an_empty_wallet_closes_and_stays_closed(alice: Any, cash: PaymentMethod
def test_a_status_that_is_not_one_is_refused(funded: Any) -> None:
with pytest.raises(WalletError, match="not a wallet status"):
wallet_service.set_wallet_status(_wallet(funded).pk, "asleep")
+
+
+def test_back_office_actions_land_in_the_audit_log(funded: Any, operator: Any) -> None:
+ from apps.audit.models import AuditEntry
+
+ for _ in range(2): # the replay is not a second adjustment
+ wallet_service.adjust(
+ funded,
+ kind=str(EntryKind.BONUS),
+ amount=Decimal("10"),
+ reference="adjustment:audited",
+ reason="Goodwill",
+ by=operator,
+ )
+ wallet_service.set_wallet_status(_wallet(funded).pk, str(WalletStatus.FROZEN), by=operator)
+
+ rows = list(AuditEntry.objects.filter(actor=operator).order_by("created_at"))
+ assert [row.action for row in rows] == ["adjust", "set_status"]
+ assert rows[0].target_model == "wallet.walletentry"
+ assert rows[1].changes == {"status": [str(WalletStatus.ACTIVE), str(WalletStatus.FROZEN)]}
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..4e4ba87 100644
--- a/src/config/api.py
+++ b/src/config/api.py
@@ -43,10 +43,13 @@ def build_apis() -> dict[str, NinjaAPI]:
*credential_routes,
*settings.CLUB_ROUTERS,
*settings.CMS_ROUTERS,
+ *settings.FLAGS_ROUTERS,
*settings.NOTIFICATIONS_ROUTERS,
*settings.SHOP_ROUTERS,
*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/api_registry.json b/src/config/api_registry.json
index a1c2f96..e45b84d 100644
--- a/src/config/api_registry.json
+++ b/src/config/api_registry.json
@@ -7,6 +7,13 @@
"router": "infrastructure.common.rest.api.router",
"tag": "Health",
"description": "Liveness and readiness probes, for a load balancer and an orchestrator. Public, so a probe needs no credential."
+ },
+ {
+ "app_config": "apps.audit.apps.AuditConfig",
+ "prefix": "/audit",
+ "router": "apps.audit.rest.router",
+ "tag": "Audit",
+ "description": "Append-only record of who changed what and when. Staff read it; nothing writes it over the API."
}
]
}
diff --git a/src/config/settings/base.py b/src/config/settings/base.py
index f2d8258..262cf9a 100644
--- a/src/config/settings/base.py
+++ b/src/config/settings/base.py
@@ -758,6 +758,30 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]:
CLUB_PAGE_SIZE = int(os.getenv("DJANGO_CLUB_PAGE_SIZE", "50"))
CLUB_MAX_PAGE_SIZE = int(os.getenv("DJANGO_CLUB_MAX_PAGE_SIZE", "200"))
+# The feature flags app. Optional the same way the others are: naming it
+# installs its two tables, its routes and its admin. `apps.flags.is_enabled`
+# answers False in a project that does not name it, so other apps may call it.
+FLAGS_ENABLED = os.getenv("DJANGO_FLAGS_ENABLED", "false").lower() == "true"
+FLAGS_APP = "apps.flags.apps.FlagsConfig"
+FLAGS_INSTALLED_APPS = [FLAGS_APP] if FLAGS_ENABLED else []
+FLAGS_TRANSPORTS = app_transports("flags", ("rest", "graph", "grpc")) if FLAGS_ENABLED else ()
+FLAGS_ROUTERS = (
+ [
+ {
+ "prefix": "/flags",
+ "router": "apps.flags.rest.router",
+ "tag": "Feature flags",
+ "description": (
+ "Feature flags: a global switch, per-account overrides and a "
+ "percentage rollout. `/flags/me` is every flag evaluated for the "
+ "caller; everything else is for staff."
+ ),
+ }
+ ]
+ if "rest" in FLAGS_TRANSPORTS
+ else []
+)
+
# The support app. Optional the same way the CMS, the notifications and the shop
# are: naming it installs its tables, its routes, its admin and its socket, and
# a project that does not name it never imports the package.
@@ -882,6 +906,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"))
@@ -903,6 +955,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 +991,11 @@ 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,
+ "apps.files": FILES_TRANSPORTS,
+ # Always installed, through `api_registry.json`.
+ "apps.audit": ("rest", "graph", "grpc"),
+ "apps.flags": FLAGS_TRANSPORTS,
}
# How often one caller may ask, whichever endpoint they are asking. A correct
@@ -1022,6 +1108,9 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]:
*SUPPORT_INSTALLED_APPS,
*WALLET_INSTALLED_APPS,
*CLUB_INSTALLED_APPS,
+ *WEBHOOKS_INSTALLED_APPS,
+ *FILES_INSTALLED_APPS,
+ *FLAGS_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.
@@ -1158,4 +1247,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 474cdb6..1313bd6 100644
--- a/src/config/settings/test.py
+++ b/src/config/settings/test.py
@@ -6,6 +6,9 @@
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_FILES_ENABLED", "true")
+os.environ.setdefault("DJANGO_FLAGS_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/__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"
diff --git a/src/django_ninja_starter/template/Makefile b/src/django_ninja_starter/template/Makefile
index 642a1a4..639ab52 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 DJANGO_FILES_ENABLED=true DJANGO_FLAGS_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..6b6eb1e 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
@@ -217,6 +231,10 @@ DJANGO_CLUB_ENABLED=false
DJANGO_CLUB_JOIN_ON_SIGNUP=
DJANGO_CLUB_PAGE_SIZE=50
DJANGO_CLUB_MAX_PAGE_SIZE=200
+# Feature flags: a global switch, per-account overrides and a percentage
+# rollout. `apps.flags.is_enabled(key, user)` answers False while this is off.
+DJANGO_FLAGS_ENABLED=false
+# DJANGO_FLAGS_TRANSPORTS=rest,graph,grpc
# The two transports beside REST. These decide which doors are open, never what
# is behind them.
DJANGO_GRAPHQL_ENABLED=true
@@ -267,3 +285,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..3afef85 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), [`files`](files.md), [`flags`](flags.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,9 @@ 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 |
+| [`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 |
+| [`flags`](flags.md) | `DJANGO_FLAGS_ENABLED=true` | Feature flags with a global switch, per-account overrides and a stable percentage rollout; `apps.flags.is_enabled(key, user)` is cached and invalidated on save |
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/docs/flags.md b/src/django_ninja_starter/template/docs/flags.md
new file mode 100644
index 0000000..1719e68
--- /dev/null
+++ b/src/django_ninja_starter/template/docs/flags.md
@@ -0,0 +1,98 @@
+# Feature flags
+
+A flag has a key, a global on/off switch, optional per-account overrides and an
+optional percentage rollout. Optional like every feature app: naming it in
+`DJANGO_FLAGS_ENABLED` installs its two tables, its routes and its admin, and a
+project that does not name it never imports the package.
+
+## Asking whether a flag is on
+
+ from apps.flags import is_enabled
+
+ if is_enabled("new-checkout", request.user):
+ ...
+
+`apps.flags.is_enabled` answers `False` when the app is not installed, so any
+app may call it unconditionally. An unknown key is off.
+
+## How a flag is evaluated
+
+1. An override for the account wins, whether it says on or off.
+2. Otherwise a flag whose switch is off is off.
+3. Otherwise, with no rollout (or 100), it is on for everybody.
+4. Otherwise the account is admitted when a stable hash of its id and the
+ key, reduced to 0-99, is below the rollout percentage. Hashing with the key
+ gives each flag a different slice of accounts, and raising the percentage
+ only ever adds accounts to the ones already in. Anonymous callers have no
+ id to hash, so a partial rollout leaves them out.
+
+Each flag's definition is cached for five minutes in the default cache and
+dropped whenever the flag or one of its overrides is saved or deleted (bulk
+`.update()` sends no signal; call `apps.flags.services.forget(key)` after one).
+
+## Who may do what
+
+Any signed-in account reads `GET /flags/me` (GraphQL `myFlags`, gRPC
+`MyFlags`): every flag, evaluated for itself. Everything else -- listing,
+saving, deleting, pinning an override -- is staff only, over all three
+transports and the admin. Over gRPC, protobuf has no null scalar, so a
+`rollout_percentage` of `-1` means none and an override is cleared with
+`clear: true`.
+
+## Routes
+
+
+| Method | Path | Auth | Purpose |
+| --- | --- | --- | --- |
+| `GET` | `/api/v1/flags/` | Bearer | Every flag (staff) |
+| `GET` | `/api/v1/flags/me` | Bearer | Every flag, evaluated for you |
+| `DELETE` | `/api/v1/flags/{key}` | Bearer | Delete a flag (staff) |
+| `GET` | `/api/v1/flags/{key}` | Bearer | One flag (staff) |
+| `PUT` | `/api/v1/flags/{key}` | Bearer | Create or replace a flag (staff) |
+| `PUT` | `/api/v1/flags/{key}/overrides/{user_id}` | Bearer | Pin a flag for one account (staff) |
+
+
+## Models
+
+
+#### `Flag`
+
+One feature switch.
+
+| Field | Type | Notes |
+| --- | --- | --- |
+| `id` | BigAuto | primary key |
+| `key` | Slug | unique |
+| `description` | Text | |
+| `is_enabled` | Boolean | |
+| `rollout_percentage` | PositiveSmallInteger | nullable |
+| `created_at` | DateTime | not editable |
+| `updated_at` | DateTime | not editable |
+
+#### `FlagOverride`
+
+One account's answer for one flag, whatever the switch and the rollout say.
+
+| Field | Type | Notes |
+| --- | --- | --- |
+| `id` | BigAuto | primary key |
+| `flag` | ForeignKey | → `flags.Flag` |
+| `user` | ForeignKey | → `accounts.User` |
+| `is_enabled` | Boolean | |
+
+
+## Admin
+
+
+| Model | Editable | Actions | Columns |
+| --- | --- | --- | --- |
+| `Flag` | Yes | — | `key`, `is_enabled`, `rollout_percentage`, `updated_at` |
+
+
+## Setup
+
+
+_This app requires no settings of its own._
+
+
+## Usage
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/pyproject.toml b/src/django_ninja_starter/template/pyproject.toml
index 099f87d..17d7c5a 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.
@@ -55,6 +57,10 @@ dev = [
# Type stubs for the generated protobuf messages, so a misspelled field is a
# type error rather than an AttributeError raised while answering a call.
"mypy-protobuf>=3.6",
+ # protoc's output carries its version and `protos --check` compares bytes, so
+ # the committed stubs only match when everyone generates with this release.
+ # Bump it together with a `manage.py protos` run.
+ "grpcio-tools==1.84.0",
"pytest>=8.3",
"pytest-cov>=6.0",
"pytest-django>=4.11",
diff --git a/src/django_ninja_starter/template/src/apps/audit/__init__.py b/src/django_ninja_starter/template/src/apps/audit/__init__.py
new file mode 100644
index 0000000..a7ca09d
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/__init__.py
@@ -0,0 +1 @@
+"""Append-only record of who changed what, and when."""
diff --git a/src/django_ninja_starter/template/src/apps/audit/admin.py b/src/django_ninja_starter/template/src/apps/audit/admin.py
new file mode 100644
index 0000000..07e6c91
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/admin.py
@@ -0,0 +1,14 @@
+from django.contrib import admin
+
+from apps.audit.models import AuditEntry
+from infrastructure.common.admin import ReadOnlyAdmin
+
+
+@admin.register(AuditEntry)
+class AuditEntryAdmin(ReadOnlyAdmin):
+ """Read-only: the log is appended to by code, never typed into."""
+
+ list_display = ("created_at", "actor", "action", "target_model", "target_id", "ip")
+ list_filter = ("action", "target_model")
+ search_fields = ("target_id",)
+ date_hierarchy = "created_at"
diff --git a/src/django_ninja_starter/template/src/apps/audit/apps.py b/src/django_ninja_starter/template/src/apps/audit/apps.py
new file mode 100644
index 0000000..6320d23
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/apps.py
@@ -0,0 +1,8 @@
+from django.apps import AppConfig
+
+
+class AuditConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "apps.audit"
+ label = "audit"
+ verbose_name = "Audit log"
diff --git a/src/django_ninja_starter/template/src/apps/audit/graph/__init__.py b/src/django_ninja_starter/template/src/apps/audit/graph/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/audit/graph/schema.py b/src/django_ninja_starter/template/src/apps/audit/graph/schema.py
new file mode 100644
index 0000000..7549b59
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/graph/schema.py
@@ -0,0 +1,59 @@
+"""The audit log over GraphQL: one staff-only query, no mutation."""
+
+from datetime import datetime
+from typing import Any
+
+import strawberry
+from strawberry.scalars import JSON
+from strawberry.types import Info
+
+from apps.audit.services import entries
+from infrastructure.common.graph.errors import require_caller, resolver
+from infrastructure.common.identity import caller
+
+
+@strawberry.type
+class AuditEntryType:
+ id: str
+ actor_id: str | None
+ action: str
+ target_model: str
+ target_id: str
+ changes: JSON
+ ip: str | None
+ created_at: str
+
+
+@strawberry.type
+class AuditEntryPage:
+ entries: list[AuditEntryType]
+ count: int
+
+
+@strawberry.type
+class Query:
+ @strawberry.field(description="Audit entries, newest first. Staff only.")
+ @resolver
+ def audit_entries(
+ self,
+ info: Info[Any, Any],
+ actor_id: str | None = None,
+ target_model: str | None = None,
+ target_id: str | None = None,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ limit: int | None = None,
+ offset: int = 0,
+ ) -> AuditEntryPage:
+ user = require_caller(caller(info.context.request))
+ rows, count = entries(
+ user,
+ actor_id=actor_id,
+ target_model=target_model,
+ target_id=target_id,
+ since=since,
+ until=until,
+ limit=limit,
+ offset=offset,
+ )
+ return AuditEntryPage(entries=[AuditEntryType(**row) for row in rows], count=count)
diff --git a/src/django_ninja_starter/template/src/apps/audit/grpc/__init__.py b/src/django_ninja_starter/template/src/apps/audit/grpc/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/audit/grpc/audit.proto b/src/django_ninja_starter/template/src/apps/audit/grpc/audit.proto
new file mode 100644
index 0000000..48cdc94
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/grpc/audit.proto
@@ -0,0 +1,36 @@
+syntax = "proto3";
+
+package config.audit;
+
+import "google/protobuf/struct.proto";
+
+service AuditController {
+ rpc ListEntries(ListEntriesRequest) returns (EntryList) {}
+}
+
+message Entry {
+ string id = 1;
+ string actor_id = 2;
+ string action = 3;
+ string target_model = 4;
+ string target_id = 5;
+ google.protobuf.Struct changes = 6;
+ string ip = 7;
+ string created_at = 8;
+}
+
+message EntryList {
+ repeated Entry entries = 1;
+ int32 count = 2;
+}
+
+message ListEntriesRequest {
+ string actor_id = 1;
+ string target_model = 2;
+ string target_id = 3;
+ string since = 4;
+ string until = 5;
+ int32 limit = 6;
+ int32 offset = 7;
+}
+
diff --git a/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2.py b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2.py
new file mode 100644
index 0000000..d219fc0
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: apps/audit/grpc/audit.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/audit/grpc/audit.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1b\x61pps/audit/grpc/audit.proto\x12\x0c\x63onfig.audit\x1a\x1cgoogle/protobuf/struct.proto\"\xa8\x01\n\x05\x45ntry\x12\n\n\x02id\x18\x01 \x01(\t\x12\x10\n\x08\x61\x63tor_id\x18\x02 \x01(\t\x12\x0e\n\x06\x61\x63tion\x18\x03 \x01(\t\x12\x14\n\x0ctarget_model\x18\x04 \x01(\t\x12\x11\n\ttarget_id\x18\x05 \x01(\t\x12(\n\x07\x63hanges\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\n\n\x02ip\x18\x07 \x01(\t\x12\x12\n\ncreated_at\x18\x08 \x01(\t\"@\n\tEntryList\x12$\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x13.config.audit.Entry\x12\r\n\x05\x63ount\x18\x02 \x01(\x05\"\x8c\x01\n\x12ListEntriesRequest\x12\x10\n\x08\x61\x63tor_id\x18\x01 \x01(\t\x12\x14\n\x0ctarget_model\x18\x02 \x01(\t\x12\x11\n\ttarget_id\x18\x03 \x01(\t\x12\r\n\x05since\x18\x04 \x01(\t\x12\r\n\x05until\x18\x05 \x01(\t\x12\r\n\x05limit\x18\x06 \x01(\x05\x12\x0e\n\x06offset\x18\x07 \x01(\x05\x32]\n\x0f\x41uditController\x12J\n\x0bListEntries\x12 .config.audit.ListEntriesRequest\x1a\x17.config.audit.EntryList\"\x00\x62\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.audit.grpc.audit_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ DESCRIPTOR._loaded_options = None
+ _globals['_ENTRY']._serialized_start=76
+ _globals['_ENTRY']._serialized_end=244
+ _globals['_ENTRYLIST']._serialized_start=246
+ _globals['_ENTRYLIST']._serialized_end=310
+ _globals['_LISTENTRIESREQUEST']._serialized_start=313
+ _globals['_LISTENTRIESREQUEST']._serialized_end=453
+ _globals['_AUDITCONTROLLER']._serialized_start=455
+ _globals['_AUDITCONTROLLER']._serialized_end=548
+# @@protoc_insertion_point(module_scope)
diff --git a/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2.pyi b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2.pyi
new file mode 100644
index 0000000..f6912e2
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2.pyi
@@ -0,0 +1,121 @@
+"""
+@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 import struct_pb2 as _struct_pb2
+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 Entry(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ ID_FIELD_NUMBER: _builtins.int
+ ACTOR_ID_FIELD_NUMBER: _builtins.int
+ ACTION_FIELD_NUMBER: _builtins.int
+ TARGET_MODEL_FIELD_NUMBER: _builtins.int
+ TARGET_ID_FIELD_NUMBER: _builtins.int
+ CHANGES_FIELD_NUMBER: _builtins.int
+ IP_FIELD_NUMBER: _builtins.int
+ CREATED_AT_FIELD_NUMBER: _builtins.int
+ id: _builtins.str
+ actor_id: _builtins.str
+ action: _builtins.str
+ target_model: _builtins.str
+ target_id: _builtins.str
+ ip: _builtins.str
+ created_at: _builtins.str
+ @_builtins.property
+ def changes(self) -> _struct_pb2.Struct: ...
+ def __init__(
+ self,
+ *,
+ id: _builtins.str = ...,
+ actor_id: _builtins.str = ...,
+ action: _builtins.str = ...,
+ target_model: _builtins.str = ...,
+ target_id: _builtins.str = ...,
+ changes: _struct_pb2.Struct | None = ...,
+ ip: _builtins.str = ...,
+ created_at: _builtins.str = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _typing.Literal["changes", b"changes"] # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["action", b"action", "actor_id", b"actor_id", "changes", b"changes", "created_at", b"created_at", "id", b"id", "ip", b"ip", "target_id", b"target_id", "target_model", b"target_model"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___Entry: _TypeAlias = Entry # noqa: Y015
+
+@_typing.final
+class EntryList(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ ENTRIES_FIELD_NUMBER: _builtins.int
+ COUNT_FIELD_NUMBER: _builtins.int
+ count: _builtins.int
+ @_builtins.property
+ def entries(self) -> _containers.RepeatedCompositeFieldContainer[Global___Entry]: ...
+ def __init__(
+ self,
+ *,
+ entries: _abc.Iterable[Global___Entry] | None = ...,
+ count: _builtins.int = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["count", b"count", "entries", b"entries"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___EntryList: _TypeAlias = EntryList # noqa: Y015
+
+@_typing.final
+class ListEntriesRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ ACTOR_ID_FIELD_NUMBER: _builtins.int
+ TARGET_MODEL_FIELD_NUMBER: _builtins.int
+ TARGET_ID_FIELD_NUMBER: _builtins.int
+ SINCE_FIELD_NUMBER: _builtins.int
+ UNTIL_FIELD_NUMBER: _builtins.int
+ LIMIT_FIELD_NUMBER: _builtins.int
+ OFFSET_FIELD_NUMBER: _builtins.int
+ actor_id: _builtins.str
+ target_model: _builtins.str
+ target_id: _builtins.str
+ since: _builtins.str
+ until: _builtins.str
+ limit: _builtins.int
+ offset: _builtins.int
+ def __init__(
+ self,
+ *,
+ actor_id: _builtins.str = ...,
+ target_model: _builtins.str = ...,
+ target_id: _builtins.str = ...,
+ since: _builtins.str = ...,
+ until: _builtins.str = ...,
+ limit: _builtins.int = ...,
+ offset: _builtins.int = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["actor_id", b"actor_id", "limit", b"limit", "offset", b"offset", "since", b"since", "target_id", b"target_id", "target_model", b"target_model", "until", b"until"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___ListEntriesRequest: _TypeAlias = ListEntriesRequest # noqa: Y015
diff --git a/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2_grpc.py
new file mode 100644
index 0000000..b513342
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2_grpc.py
@@ -0,0 +1,97 @@
+# 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.audit.grpc import audit_pb2 as apps_dot_audit_dot_grpc_dot_audit__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/audit/grpc/audit_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 AuditControllerStub:
+ """Missing associated documentation comment in .proto file."""
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.ListEntries = channel.unary_unary(
+ '/config.audit.AuditController/ListEntries',
+ request_serializer=apps_dot_audit_dot_grpc_dot_audit__pb2.ListEntriesRequest.SerializeToString,
+ response_deserializer=apps_dot_audit_dot_grpc_dot_audit__pb2.EntryList.FromString,
+ _registered_method=True)
+
+
+class AuditControllerServicer:
+ """Missing associated documentation comment in .proto file."""
+
+ def ListEntries(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_AuditControllerServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'ListEntries': grpc.unary_unary_rpc_method_handler(
+ servicer.ListEntries,
+ request_deserializer=apps_dot_audit_dot_grpc_dot_audit__pb2.ListEntriesRequest.FromString,
+ response_serializer=apps_dot_audit_dot_grpc_dot_audit__pb2.EntryList.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'config.audit.AuditController', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+ server.add_registered_method_handlers('config.audit.AuditController', rpc_method_handlers)
+
+
+ # This class is part of an EXPERIMENTAL API.
+class AuditController:
+ """Missing associated documentation comment in .proto file."""
+
+ @staticmethod
+ def ListEntries(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.audit.AuditController/ListEntries',
+ apps_dot_audit_dot_grpc_dot_audit__pb2.ListEntriesRequest.SerializeToString,
+ apps_dot_audit_dot_grpc_dot_audit__pb2.EntryList.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/audit/grpc/audit_pb2_grpc.pyi b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2_grpc.pyi
new file mode 100644
index 0000000..f4216b0
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/grpc/audit_pb2_grpc.pyi
@@ -0,0 +1,49 @@
+"""
+@generated by mypy-protobuf. Do not edit manually!
+isort:skip_file
+"""
+
+from apps.audit.grpc import audit_pb2 as _audit_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 AuditControllerStub:
+ @_typing.overload
+ def __new__(cls, channel: _grpc.Channel) -> _Self: ...
+ @_typing.overload
+ def __new__(cls, channel: _aio.Channel) -> AuditControllerAsyncStub: ...
+ ListEntries: _grpc.UnaryUnaryMultiCallable[_audit_pb2.ListEntriesRequest, _audit_pb2.EntryList]
+
+@_typing.type_check_only
+class AuditControllerAsyncStub(AuditControllerStub):
+ def __init__(self, channel: _aio.Channel) -> None: ...
+ ListEntries: _aio.UnaryUnaryMultiCallable[_audit_pb2.ListEntriesRequest, _audit_pb2.EntryList] # type: ignore[assignment]
+
+class AuditControllerServicer(metaclass=_abc_1.ABCMeta):
+ @_abc_1.abstractmethod
+ def ListEntries(
+ self,
+ request: _audit_pb2.ListEntriesRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_audit_pb2.EntryList, _abc.Awaitable[_audit_pb2.EntryList]]: ...
+
+def add_AuditControllerServicer_to_server(servicer: AuditControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ...
diff --git a/src/django_ninja_starter/template/src/apps/audit/grpc/serializers.py b/src/django_ninja_starter/template/src/apps/audit/grpc/serializers.py
new file mode 100644
index 0000000..e1dff1b
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/grpc/serializers.py
@@ -0,0 +1,14 @@
+"""The message one audit entry travels as. ``changes`` is a JSON string."""
+
+from rest_framework import serializers
+
+
+class Entry(serializers.Serializer[dict[str, object]]):
+ id = serializers.CharField()
+ actor_id = serializers.CharField(allow_blank=True)
+ action = serializers.CharField()
+ target_model = serializers.CharField()
+ target_id = serializers.CharField()
+ changes = serializers.JSONField()
+ ip = serializers.CharField(allow_blank=True)
+ created_at = serializers.CharField()
diff --git a/src/django_ninja_starter/template/src/apps/audit/grpc/services.py b/src/django_ninja_starter/template/src/apps/audit/grpc/services.py
new file mode 100644
index 0000000..24aafe6
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/grpc/services.py
@@ -0,0 +1,81 @@
+"""The audit log over gRPC: one staff-only listing call, nothing that writes."""
+
+from __future__ import annotations
+
+from datetime import datetime
+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.audit.grpc.serializers import Entry
+from apps.audit.services import entries
+from infrastructure.common.errors import ApiError
+from infrastructure.common.grpc.errors import action, require_caller
+from infrastructure.common.identity import grpc_caller
+
+
+def _pb2() -> Any:
+ from apps.audit.grpc import audit_pb2
+
+ return audit_pb2
+
+
+def _when(value: str) -> datetime | None:
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value)
+ except ValueError:
+ raise ApiError(f"Not an ISO-8601 timestamp: {value!r}", status=400) from None
+
+
+def _entry(row: dict[str, Any]) -> Any:
+ return _pb2().Entry(
+ id=row["id"],
+ actor_id=row["actor_id"] or "",
+ action=row["action"],
+ target_model=row["target_model"],
+ target_id=row["target_id"],
+ changes=row["changes"],
+ ip=row["ip"] or "",
+ created_at=row["created_at"],
+ )
+
+
+class AuditService(generics.GenericService):
+ @grpc_action(
+ request=[
+ {"name": "actor_id", "type": "string"},
+ {"name": "target_model", "type": "string"},
+ {"name": "target_id", "type": "string"},
+ {"name": "since", "type": "string"},
+ {"name": "until", "type": "string"},
+ {"name": "limit", "type": "int32"},
+ {"name": "offset", "type": "int32"},
+ ],
+ request_name="ListEntriesRequest",
+ response=[
+ {"name": "entries", "cardinality": "repeated", "type": Entry},
+ {"name": "count", "type": "int32"},
+ ],
+ response_name="EntryList",
+ )
+ @action
+ async def ListEntries(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rows, count = await sync_to_async(entries)(
+ user,
+ actor_id=request.actor_id or None,
+ target_model=request.target_model or None,
+ target_id=request.target_id or None,
+ since=_when(request.since),
+ until=_when(request.until),
+ limit=request.limit or None,
+ offset=request.offset or 0,
+ )
+ return _pb2().EntryList(entries=[_entry(row) for row in rows], count=count)
+
+
+GRPC_SERVICES = [AuditService]
diff --git a/src/django_ninja_starter/template/src/apps/audit/migrations/0001_initial.py b/src/django_ninja_starter/template/src/apps/audit/migrations/0001_initial.py
new file mode 100644
index 0000000..01053a2
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/migrations/0001_initial.py
@@ -0,0 +1,76 @@
+# Generated by Django 6.1.3 on 2026-11-26 14:25
+
+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="AuditEntry",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=uuid.uuid4, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ (
+ "action",
+ models.CharField(
+ help_text="What was done, e.g. create or update.", max_length=64
+ ),
+ ),
+ (
+ "target_model",
+ models.CharField(help_text="app_label.model of the target.", max_length=128),
+ ),
+ (
+ "target_id",
+ models.CharField(
+ help_text="Primary key of the target, as text.", max_length=64
+ ),
+ ),
+ (
+ "changes",
+ models.JSONField(blank=True, default=dict, help_text="Field -> [old, new]."),
+ ),
+ (
+ "ip",
+ models.GenericIPAddressField(
+ blank=True, help_text="The request's address.", null=True
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
+ (
+ "actor",
+ models.ForeignKey(
+ blank=True,
+ help_text="Who made the change. Empty for the system, or an account since deleted.",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="audit_entries",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "verbose_name_plural": "audit entries",
+ "ordering": ("-created_at",),
+ "indexes": [
+ models.Index(
+ fields=["target_model", "target_id"], name="audit_audit_target__53778f_idx"
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/src/django_ninja_starter/template/src/apps/audit/migrations/__init__.py b/src/django_ninja_starter/template/src/apps/audit/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/audit/models.py b/src/django_ninja_starter/template/src/apps/audit/models.py
new file mode 100644
index 0000000..ab1cce9
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/models.py
@@ -0,0 +1,46 @@
+"""One audit entry: who did what to which object, when, and from where.
+
+Entries are append-only. ``save`` refuses to rewrite a stored row and ``delete``
+refuses outright, so no transport and no admin screen can launder the record.
+Bulk ``QuerySet.update``/``delete`` bypass this; nothing in the project calls them.
+"""
+
+import uuid
+from typing import Any
+
+from django.conf import settings
+from django.db import models
+
+
+class AuditEntry(models.Model):
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ actor = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ null=True,
+ blank=True,
+ on_delete=models.SET_NULL,
+ related_name="audit_entries",
+ help_text="Who made the change. Empty for the system, or an account since deleted.",
+ )
+ action = models.CharField(max_length=64, help_text="What was done, e.g. create or update.")
+ target_model = models.CharField(max_length=128, help_text="app_label.model of the target.")
+ target_id = models.CharField(max_length=64, help_text="Primary key of the target, as text.")
+ changes = models.JSONField(default=dict, blank=True, help_text="Field -> [old, new].")
+ ip = models.GenericIPAddressField(null=True, blank=True, help_text="The request's address.")
+ created_at = models.DateTimeField(auto_now_add=True, db_index=True)
+
+ class Meta:
+ ordering = ("-created_at",)
+ indexes = [models.Index(fields=("target_model", "target_id"))]
+ verbose_name_plural = "audit entries"
+
+ def __str__(self) -> str:
+ return f"{self.action} {self.target_model}:{self.target_id}"
+
+ def save(self, *args: Any, **kwargs: Any) -> None:
+ if not self._state.adding:
+ raise PermissionError("Audit entries are append-only.")
+ super().save(*args, **kwargs)
+
+ def delete(self, *args: Any, **kwargs: Any) -> Any:
+ raise PermissionError("Audit entries are append-only.")
diff --git a/src/django_ninja_starter/template/src/apps/audit/rest/__init__.py b/src/django_ninja_starter/template/src/apps/audit/rest/__init__.py
new file mode 100644
index 0000000..45f9c00
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/rest/__init__.py
@@ -0,0 +1,5 @@
+"""The HTTP transport for the audit app."""
+
+from apps.audit.rest.v1 import router
+
+__all__ = ["router"]
diff --git a/src/django_ninja_starter/template/src/apps/audit/rest/v1.py b/src/django_ninja_starter/template/src/apps/audit/rest/v1.py
new file mode 100644
index 0000000..2b332ee
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/rest/v1.py
@@ -0,0 +1,56 @@
+"""The audit log over HTTP: read-only, staff only. There is no write route."""
+
+from datetime import datetime
+from typing import Any
+
+from django.http import HttpRequest
+from ninja import Router, Schema
+
+from apps.audit.services import entries
+
+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)
+
+
+class EntryOut(Schema):
+ id: str
+ actor_id: str | None
+ action: str
+ target_model: str
+ target_id: str
+ changes: dict[str, Any]
+ ip: str | None
+ created_at: str
+
+
+class EntryPage(Schema):
+ entries: list[EntryOut]
+ count: int
+
+
+@router.get("/entries", response=EntryPage, summary="Audit entries, newest first")
+def list_entries(
+ request: HttpRequest,
+ actor_id: str | None = None,
+ target_model: str | None = None,
+ target_id: str | None = None,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ limit: int | None = None,
+ offset: int = 0,
+) -> Any:
+ rows, count = entries(
+ request.user,
+ actor_id=actor_id,
+ target_model=target_model,
+ target_id=target_id,
+ since=since,
+ until=until,
+ limit=limit,
+ offset=offset,
+ )
+ return {"entries": rows, "count": count}
diff --git a/src/django_ninja_starter/template/src/apps/audit/services.py b/src/django_ninja_starter/template/src/apps/audit/services.py
new file mode 100644
index 0000000..e645472
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/services.py
@@ -0,0 +1,81 @@
+"""Writing and reading the audit log. Every transport goes through here."""
+
+from datetime import datetime
+from typing import Any
+
+from django.db.models import Model
+
+from apps.audit.models import AuditEntry
+from infrastructure.common.errors import ApiError
+from infrastructure.common.responses import ResponseTitle
+
+DEFAULT_PAGE = 50
+MAX_PAGE = 200
+
+
+def request_ip(request: Any) -> str | None:
+ """The peer address. Forwarded headers are client-supplied, so not trusted here."""
+ meta = getattr(request, "META", None) or {}
+ return meta.get("REMOTE_ADDR") or None
+
+
+def record(
+ actor: Any,
+ action: str,
+ target: Model,
+ changes: dict[str, Any] | None = None,
+ *,
+ request: Any = None,
+) -> AuditEntry:
+ """Append one entry. ``actor`` may be ``None`` or anonymous for system changes."""
+ return AuditEntry.objects.create(
+ actor=actor if getattr(actor, "is_authenticated", False) else None,
+ action=action,
+ target_model=target._meta.label_lower,
+ target_id=str(target.pk),
+ changes=changes or {},
+ ip=request_ip(request),
+ )
+
+
+def entry_payload(entry: AuditEntry) -> dict[str, Any]:
+ return {
+ "id": str(entry.id),
+ "actor_id": str(entry.actor_id) if entry.actor_id is not None else None,
+ "action": entry.action,
+ "target_model": entry.target_model,
+ "target_id": entry.target_id,
+ "changes": entry.changes,
+ "ip": entry.ip,
+ "created_at": entry.created_at.isoformat(),
+ }
+
+
+def entries(
+ viewer: Any,
+ *,
+ actor_id: str | None = None,
+ target_model: str | None = None,
+ target_id: str | None = None,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ limit: int | None = None,
+ offset: int = 0,
+) -> tuple[list[dict[str, Any]], int]:
+ """One page of entries, newest first, and the total that matched. Staff only."""
+ if not getattr(viewer, "is_staff", False):
+ raise ApiError("Staff only.", status=403, title=ResponseTitle.FORBIDDEN)
+ rows = AuditEntry.objects.all()
+ if actor_id:
+ rows = rows.filter(actor_id=actor_id)
+ if target_model:
+ rows = rows.filter(target_model=target_model.lower())
+ if target_id:
+ rows = rows.filter(target_id=target_id)
+ if since:
+ rows = rows.filter(created_at__gte=since)
+ if until:
+ rows = rows.filter(created_at__lt=until)
+ page = max(1, min(limit or DEFAULT_PAGE, MAX_PAGE))
+ start = max(0, offset)
+ return [entry_payload(e) for e in rows[start : start + page]], rows.count()
diff --git a/src/django_ninja_starter/template/src/apps/audit/tests/__init__.py b/src/django_ninja_starter/template/src/apps/audit/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/audit/tests/test_audit.py b/src/django_ninja_starter/template/src/apps/audit/tests/test_audit.py
new file mode 100644
index 0000000..df2efc4
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/audit/tests/test_audit.py
@@ -0,0 +1,133 @@
+"""The audit log: append-only, staff-read, same answer on every transport."""
+
+import json
+from collections.abc import Callable
+from datetime import timedelta
+from typing import Any
+
+import grpc
+import pytest
+from django.contrib.auth import get_user_model
+from django.test import Client, RequestFactory
+from django.utils import timezone
+
+from apps.audit.grpc import audit_pb2, audit_pb2_grpc
+from apps.audit.models import AuditEntry
+from apps.audit.services import entries, record
+
+
+def access_token(user: Any) -> str:
+ from infrastructure.auth.core.sessions import issue_credentials
+
+ return issue_credentials(RequestFactory().post("/"), user, method="password").access_token
+
+
+@pytest.fixture
+def alice(db: None) -> Any:
+ return get_user_model().objects.create_user(username="alice", email="alice@example.test")
+
+
+@pytest.fixture
+def staff(db: None) -> Any:
+ return get_user_model().objects.create_user(
+ username="ops", email="ops@example.test", is_staff=True
+ )
+
+
+@pytest.fixture
+def logged(alice: Any, staff: Any) -> list[AuditEntry]:
+ request = RequestFactory().post("/", REMOTE_ADDR="203.0.113.7")
+ return [
+ record(alice, "update", staff, {"email": ["a", "b"]}, request=request),
+ record(staff, "delete", alice),
+ ]
+
+
+def test_record_captures_target_actor_and_ip(logged: list[AuditEntry], alice: Any) -> None:
+ entry = logged[0]
+
+ assert entry.actor == alice
+ assert entry.target_model == entry.actor._meta.label_lower
+ assert entry.ip == "203.0.113.7"
+ assert entry.changes == {"email": ["a", "b"]}
+
+
+def test_entries_cannot_be_rewritten_or_deleted(logged: list[AuditEntry]) -> None:
+ entry = logged[0]
+ entry.action = "forged"
+
+ with pytest.raises(PermissionError):
+ entry.save()
+ with pytest.raises(PermissionError):
+ entry.delete()
+
+
+def test_only_staff_read(logged: list[AuditEntry], alice: Any) -> None:
+ from infrastructure.common.errors import ApiError
+
+ with pytest.raises(ApiError) as refused:
+ entries(alice)
+ assert refused.value.status == 403
+
+
+def test_filters_and_pagination(logged: list[AuditEntry], alice: Any, staff: Any) -> None:
+ by_actor, count = entries(staff, actor_id=str(alice.pk))
+ assert count == 1 and by_actor[0]["action"] == "update"
+
+ by_target, _ = entries(staff, target_id=str(alice.pk))
+ assert [row["action"] for row in by_target] == ["delete"]
+
+ _, future = entries(staff, since=timezone.now() + timedelta(minutes=1))
+ assert future == 0
+
+ page, total = entries(staff, limit=1, offset=1)
+ assert total == 2 and len(page) == 1
+
+
+def test_rest_lists_for_staff_and_refuses_others(
+ logged: list[AuditEntry], alice: Any, staff: Any
+) -> None:
+ client = Client()
+ ok = client.get("/api/v1/audit/entries", HTTP_AUTHORIZATION=f"Bearer {access_token(staff)}")
+ denied = client.get("/api/v1/audit/entries", HTTP_AUTHORIZATION=f"Bearer {access_token(alice)}")
+
+ assert ok.status_code == 200
+ assert ok.json()["data"]["count"] == 2
+ assert denied.status_code == 403
+
+
+def test_rest_has_no_write_route(logged: list[AuditEntry], staff: Any) -> None:
+ response = Client().delete(
+ f"/api/v1/audit/entries/{logged[0].id}",
+ HTTP_AUTHORIZATION=f"Bearer {access_token(staff)}",
+ )
+
+ assert response.status_code in (404, 405)
+
+
+def test_graphql_lists_for_staff(logged: list[AuditEntry], staff: Any) -> None:
+ response = Client().post(
+ "/graphql",
+ json.dumps({"query": "{ auditEntries(limit: 1) { count entries { action ip } } }"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {access_token(staff)}",
+ )
+
+ page = response.json()["data"]["auditEntries"]
+ assert page["count"] == 2 and len(page["entries"]) == 1
+
+
+def test_grpc_lists_for_staff_and_refuses_others(
+ transactional_db: None, alice: Any, staff: Any, grpc_call: Callable[..., Any]
+) -> None:
+ record(alice, "update", staff, {"x": [1, 2]})
+ stub = audit_pb2_grpc.AuditControllerStub
+
+ reply = grpc_call(
+ stub, "ListEntries", audit_pb2.ListEntriesRequest(), token=access_token(staff)
+ )
+ assert reply.count == 1 and reply.entries[0].action == "update"
+
+ with pytest.raises(grpc.RpcError) as refused:
+ grpc_call(stub, "ListEntries", audit_pb2.ListEntriesRequest(), token=access_token(alice))
+ assert refused.value.code() == grpc.StatusCode.PERMISSION_DENIED
diff --git a/src/django_ninja_starter/template/src/apps/club/grpc/club_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/club/grpc/club_pb2_grpc.py
index 856373f..b63e60e 100644
--- a/src/django_ninja_starter/template/src/apps/club/grpc/club_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/apps/club/grpc/club_pb2_grpc.py
@@ -6,7 +6,7 @@
from apps.club.grpc import club_pb2 as apps_dot_club_dot_grpc_dot_club__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/apps/cms/grpc/cms_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/cms/grpc/cms_pb2_grpc.py
index 4f12e19..1a467f7 100644
--- a/src/django_ninja_starter/template/src/apps/cms/grpc/cms_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/apps/cms/grpc/cms_pb2_grpc.py
@@ -6,7 +6,7 @@
from apps.cms.grpc import cms_pb2 as apps_dot_cms_dot_grpc_dot_cms__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
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/flags/__init__.py b/src/django_ninja_starter/template/src/apps/flags/__init__.py
new file mode 100644
index 0000000..b13e848
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/__init__.py
@@ -0,0 +1,23 @@
+"""Feature flags: a global switch, per-user overrides and a percentage rollout.
+
+ from apps.flags import is_enabled
+ if is_enabled("new-checkout", request.user): ...
+
+Imported lazily, as ``apps.club.track`` is, so another app may call this
+unconditionally: it answers ``False`` when the flags app is not installed.
+"""
+
+from typing import Any
+
+__all__ = ["is_enabled"]
+
+
+def is_enabled(key: str, user: Any = None) -> bool:
+ """Whether ``key`` is on for ``user``. See :func:`apps.flags.services.is_enabled`."""
+ from django.apps import apps
+
+ if not apps.is_installed("apps.flags"):
+ return False
+ from apps.flags.services import is_enabled as _is_enabled
+
+ return _is_enabled(key, user)
diff --git a/src/django_ninja_starter/template/src/apps/flags/admin.py b/src/django_ninja_starter/template/src/apps/flags/admin.py
new file mode 100644
index 0000000..54f9f72
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/admin.py
@@ -0,0 +1,20 @@
+"""Staff edit flags and their overrides here; saving clears the cache through signals."""
+
+from django.contrib import admin
+from unfold.admin import ModelAdmin, TabularInline
+
+from apps.flags.models import Flag, FlagOverride
+
+
+class FlagOverrideInline(TabularInline):
+ model = FlagOverride
+ extra = 0
+ autocomplete_fields = ["user"]
+
+
+@admin.register(Flag)
+class FlagAdmin(ModelAdmin):
+ list_display = ["key", "is_enabled", "rollout_percentage", "updated_at"]
+ list_filter = ["is_enabled"]
+ search_fields = ["key", "description"]
+ inlines = [FlagOverrideInline]
diff --git a/src/django_ninja_starter/template/src/apps/flags/apps.py b/src/django_ninja_starter/template/src/apps/flags/apps.py
new file mode 100644
index 0000000..a997f06
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/apps.py
@@ -0,0 +1,13 @@
+"""The flags app. Saving or deleting a flag or an override clears its cache entry."""
+
+from django.apps import AppConfig
+
+
+class FlagsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "apps.flags"
+ label = "flags"
+ verbose_name = "Feature flags"
+
+ def ready(self) -> None:
+ from apps.flags import signals # noqa: F401
diff --git a/src/django_ninja_starter/template/src/apps/flags/errors.py b/src/django_ninja_starter/template/src/apps/flags/errors.py
new file mode 100644
index 0000000..b2044f3
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/errors.py
@@ -0,0 +1,15 @@
+"""Every refusal this app makes, with the HTTP status it carries."""
+
+
+class FlagError(Exception):
+ """Something a caller asked for that this app will not do."""
+
+ status = 400
+
+
+class FlagNotFound(FlagError, LookupError):
+ status = 404
+
+
+class StaffOnly(FlagError):
+ status = 403
diff --git a/src/django_ninja_starter/template/src/apps/flags/graph/__init__.py b/src/django_ninja_starter/template/src/apps/flags/graph/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/flags/graph/schema.py b/src/django_ninja_starter/template/src/apps/flags/graph/schema.py
new file mode 100644
index 0000000..e50bc5f
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/graph/schema.py
@@ -0,0 +1,115 @@
+"""Feature flags over GraphQL. Fields are prefixed ``flag`` so the merge stays quiet."""
+
+from typing import Any
+
+import strawberry
+from strawberry.types import Info
+
+from apps.flags import services
+from apps.flags.errors import FlagError
+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
+
+TITLES = {
+ 403: ResponseTitle.FORBIDDEN,
+ 404: ResponseTitle.NOT_FOUND,
+}
+
+
+def _caller(info: Info[Any, Any]) -> Any:
+ return require_caller(caller(info.context.request))
+
+
+def _run(call: Any, *args: Any, **kwargs: Any) -> Any:
+ try:
+ return call(*args, **kwargs)
+ except FlagError as refusal:
+ raise ApiError(
+ str(refusal),
+ status=refusal.status,
+ title=TITLES.get(refusal.status, ResponseTitle.VALIDATION_ERROR),
+ ) from None
+
+
+@strawberry.type
+class EvaluatedFlagType:
+ key: str
+ enabled: bool
+
+
+@strawberry.type
+class FlagOverrideType:
+ user_id: str
+ is_enabled: bool
+
+
+@strawberry.type
+class FlagType:
+ key: str
+ description: str
+ is_enabled: bool
+ rollout_percentage: int | None
+ overrides: list[FlagOverrideType]
+
+
+def _flag(row: dict[str, Any]) -> FlagType:
+ return FlagType(
+ key=row["key"],
+ description=row["description"],
+ is_enabled=row["is_enabled"],
+ rollout_percentage=row["rollout_percentage"],
+ overrides=[FlagOverrideType(**override) for override in row["overrides"]],
+ )
+
+
+@strawberry.type
+class Query:
+ @strawberry.field(description="Every flag, evaluated for the caller.")
+ @resolver
+ def my_flags(self, info: Info[Any, Any]) -> list[EvaluatedFlagType]:
+ return [EvaluatedFlagType(**row) for row in services.evaluate_all(_caller(info))]
+
+ @strawberry.field(description="Every flag with its rules. Staff only.")
+ @resolver
+ def flags(self, info: Info[Any, Any]) -> list[FlagType]:
+ return [_flag(row) for row in _run(services.list_flags, _caller(info))]
+
+
+@strawberry.type
+class Mutation:
+ @strawberry.mutation(description="Create or replace a flag. Staff only.")
+ @resolver
+ def flag_save(
+ self,
+ info: Info[Any, Any],
+ key: str,
+ is_enabled: bool,
+ rollout_percentage: int | None = None,
+ description: str = "",
+ ) -> FlagType:
+ row = _run(
+ services.save_flag,
+ _caller(info),
+ key,
+ is_enabled=is_enabled,
+ rollout_percentage=rollout_percentage,
+ description=description,
+ )
+ return _flag(row)
+
+ @strawberry.mutation(description="Delete a flag. Staff only.")
+ @resolver
+ def flag_delete(self, info: Info[Any, Any], key: str) -> bool:
+ _run(services.delete_flag, _caller(info), key)
+ return True
+
+ @strawberry.mutation(
+ description="Pin a flag on or off for one account; null clears the pin. Staff only."
+ )
+ @resolver
+ def flag_override(
+ self, info: Info[Any, Any], key: str, user_id: str, enabled: bool | None
+ ) -> FlagType:
+ return _flag(_run(services.set_override, _caller(info), key, user_id, enabled))
diff --git a/src/django_ninja_starter/template/src/apps/flags/grpc/__init__.py b/src/django_ninja_starter/template/src/apps/flags/grpc/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/flags/grpc/flags.proto b/src/django_ninja_starter/template/src/apps/flags/grpc/flags.proto
new file mode 100644
index 0000000..d540116
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/grpc/flags.proto
@@ -0,0 +1,70 @@
+syntax = "proto3";
+
+package config.flags;
+
+import "google/protobuf/empty.proto";
+
+service FlagController {
+ rpc DeleteFlag(DeleteFlagRequest) returns (DeleteFlagResult) {}
+ rpc ListFlags(google.protobuf.Empty) returns (FlagList) {}
+ rpc MyFlags(google.protobuf.Empty) returns (EvaluatedFlagList) {}
+ rpc SaveFlag(SaveFlagRequest) returns (FlagResult) {}
+ rpc SetOverride(SetOverrideRequest) returns (OverrideResult) {}
+}
+
+message DeleteFlagRequest {
+ string key = 1;
+}
+
+message DeleteFlagResult {
+ bool deleted = 1;
+}
+
+message EvaluatedFlag {
+ string key = 1;
+ bool enabled = 2;
+}
+
+message EvaluatedFlagList {
+ repeated EvaluatedFlag flags = 1;
+}
+
+message Flag {
+ string key = 1;
+ string description = 2;
+ bool is_enabled = 3;
+ int32 rollout_percentage = 4;
+ repeated FlagOverride overrides = 5;
+}
+
+message FlagList {
+ repeated Flag flags = 1;
+}
+
+message FlagOverride {
+ string user_id = 1;
+ bool is_enabled = 2;
+}
+
+message FlagResult {
+ Flag flag = 1;
+}
+
+message OverrideResult {
+ Flag flag = 1;
+}
+
+message SaveFlagRequest {
+ string key = 1;
+ string description = 2;
+ bool is_enabled = 3;
+ int32 rollout_percentage = 4;
+}
+
+message SetOverrideRequest {
+ string key = 1;
+ string user_id = 2;
+ bool enabled = 3;
+ bool clear = 4;
+}
+
diff --git a/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2.py b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2.py
new file mode 100644
index 0000000..828f350
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2.py
@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: apps/flags/grpc/flags.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/flags/grpc/flags.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\x1b\x61pps/flags/grpc/flags.proto\x12\x0c\x63onfig.flags\x1a\x1bgoogle/protobuf/empty.proto\" \n\x11\x44\x65leteFlagRequest\x12\x0b\n\x03key\x18\x01 \x01(\t\"#\n\x10\x44\x65leteFlagResult\x12\x0f\n\x07\x64\x65leted\x18\x01 \x01(\x08\"-\n\rEvaluatedFlag\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08\"?\n\x11\x45valuatedFlagList\x12*\n\x05\x66lags\x18\x01 \x03(\x0b\x32\x1b.config.flags.EvaluatedFlag\"\x87\x01\n\x04\x46lag\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x12\n\nis_enabled\x18\x03 \x01(\x08\x12\x1a\n\x12rollout_percentage\x18\x04 \x01(\x05\x12-\n\toverrides\x18\x05 \x03(\x0b\x32\x1a.config.flags.FlagOverride\"-\n\x08\x46lagList\x12!\n\x05\x66lags\x18\x01 \x03(\x0b\x32\x12.config.flags.Flag\"3\n\x0c\x46lagOverride\x12\x0f\n\x07user_id\x18\x01 \x01(\t\x12\x12\n\nis_enabled\x18\x02 \x01(\x08\".\n\nFlagResult\x12 \n\x04\x66lag\x18\x01 \x01(\x0b\x32\x12.config.flags.Flag\"2\n\x0eOverrideResult\x12 \n\x04\x66lag\x18\x01 \x01(\x0b\x32\x12.config.flags.Flag\"c\n\x0fSaveFlagRequest\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x12\n\nis_enabled\x18\x03 \x01(\x08\x12\x1a\n\x12rollout_percentage\x18\x04 \x01(\x05\"R\n\x12SetOverrideRequest\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x0f\n\x07user_id\x18\x02 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x03 \x01(\x08\x12\r\n\x05\x63lear\x18\x04 \x01(\x08\x32\xfe\x02\n\x0e\x46lagController\x12O\n\nDeleteFlag\x12\x1f.config.flags.DeleteFlagRequest\x1a\x1e.config.flags.DeleteFlagResult\"\x00\x12=\n\tListFlags\x12\x16.google.protobuf.Empty\x1a\x16.config.flags.FlagList\"\x00\x12\x44\n\x07MyFlags\x12\x16.google.protobuf.Empty\x1a\x1f.config.flags.EvaluatedFlagList\"\x00\x12\x45\n\x08SaveFlag\x12\x1d.config.flags.SaveFlagRequest\x1a\x18.config.flags.FlagResult\"\x00\x12O\n\x0bSetOverride\x12 .config.flags.SetOverrideRequest\x1a\x1c.config.flags.OverrideResult\"\x00\x62\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'apps.flags.grpc.flags_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ DESCRIPTOR._loaded_options = None
+ _globals['_DELETEFLAGREQUEST']._serialized_start=74
+ _globals['_DELETEFLAGREQUEST']._serialized_end=106
+ _globals['_DELETEFLAGRESULT']._serialized_start=108
+ _globals['_DELETEFLAGRESULT']._serialized_end=143
+ _globals['_EVALUATEDFLAG']._serialized_start=145
+ _globals['_EVALUATEDFLAG']._serialized_end=190
+ _globals['_EVALUATEDFLAGLIST']._serialized_start=192
+ _globals['_EVALUATEDFLAGLIST']._serialized_end=255
+ _globals['_FLAG']._serialized_start=258
+ _globals['_FLAG']._serialized_end=393
+ _globals['_FLAGLIST']._serialized_start=395
+ _globals['_FLAGLIST']._serialized_end=440
+ _globals['_FLAGOVERRIDE']._serialized_start=442
+ _globals['_FLAGOVERRIDE']._serialized_end=493
+ _globals['_FLAGRESULT']._serialized_start=495
+ _globals['_FLAGRESULT']._serialized_end=541
+ _globals['_OVERRIDERESULT']._serialized_start=543
+ _globals['_OVERRIDERESULT']._serialized_end=593
+ _globals['_SAVEFLAGREQUEST']._serialized_start=595
+ _globals['_SAVEFLAGREQUEST']._serialized_end=694
+ _globals['_SETOVERRIDEREQUEST']._serialized_start=696
+ _globals['_SETOVERRIDEREQUEST']._serialized_end=778
+ _globals['_FLAGCONTROLLER']._serialized_start=781
+ _globals['_FLAGCONTROLLER']._serialized_end=1163
+# @@protoc_insertion_point(module_scope)
diff --git a/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2.pyi b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2.pyi
new file mode 100644
index 0000000..c89cdda
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2.pyi
@@ -0,0 +1,269 @@
+"""
+@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 DeleteFlagRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___DeleteFlagRequest: _TypeAlias = DeleteFlagRequest # noqa: Y015
+
+@_typing.final
+class DeleteFlagResult(_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___DeleteFlagResult: _TypeAlias = DeleteFlagResult # noqa: Y015
+
+@_typing.final
+class EvaluatedFlag(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ ENABLED_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ enabled: _builtins.bool
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ enabled: _builtins.bool = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["enabled", b"enabled", "key", b"key"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___EvaluatedFlag: _TypeAlias = EvaluatedFlag # noqa: Y015
+
+@_typing.final
+class EvaluatedFlagList(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAGS_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flags(self) -> _containers.RepeatedCompositeFieldContainer[Global___EvaluatedFlag]: ...
+ def __init__(
+ self,
+ *,
+ flags: _abc.Iterable[Global___EvaluatedFlag] | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flags", b"flags"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___EvaluatedFlagList: _TypeAlias = EvaluatedFlagList # noqa: Y015
+
+@_typing.final
+class Flag(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ DESCRIPTION_FIELD_NUMBER: _builtins.int
+ IS_ENABLED_FIELD_NUMBER: _builtins.int
+ ROLLOUT_PERCENTAGE_FIELD_NUMBER: _builtins.int
+ OVERRIDES_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ description: _builtins.str
+ is_enabled: _builtins.bool
+ rollout_percentage: _builtins.int
+ @_builtins.property
+ def overrides(self) -> _containers.RepeatedCompositeFieldContainer[Global___FlagOverride]: ...
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ description: _builtins.str = ...,
+ is_enabled: _builtins.bool = ...,
+ rollout_percentage: _builtins.int = ...,
+ overrides: _abc.Iterable[Global___FlagOverride] | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["description", b"description", "is_enabled", b"is_enabled", "key", b"key", "overrides", b"overrides", "rollout_percentage", b"rollout_percentage"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___Flag: _TypeAlias = Flag # noqa: Y015
+
+@_typing.final
+class FlagList(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAGS_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flags(self) -> _containers.RepeatedCompositeFieldContainer[Global___Flag]: ...
+ def __init__(
+ self,
+ *,
+ flags: _abc.Iterable[Global___Flag] | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flags", b"flags"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___FlagList: _TypeAlias = FlagList # noqa: Y015
+
+@_typing.final
+class FlagOverride(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ USER_ID_FIELD_NUMBER: _builtins.int
+ IS_ENABLED_FIELD_NUMBER: _builtins.int
+ user_id: _builtins.str
+ is_enabled: _builtins.bool
+ def __init__(
+ self,
+ *,
+ user_id: _builtins.str = ...,
+ is_enabled: _builtins.bool = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["is_enabled", b"is_enabled", "user_id", b"user_id"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___FlagOverride: _TypeAlias = FlagOverride # noqa: Y015
+
+@_typing.final
+class FlagResult(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAG_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flag(self) -> Global___Flag: ...
+ def __init__(
+ self,
+ *,
+ flag: Global___Flag | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___FlagResult: _TypeAlias = FlagResult # noqa: Y015
+
+@_typing.final
+class OverrideResult(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ FLAG_FIELD_NUMBER: _builtins.int
+ @_builtins.property
+ def flag(self) -> Global___Flag: ...
+ def __init__(
+ self,
+ *,
+ flag: Global___Flag | None = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["flag", b"flag"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___OverrideResult: _TypeAlias = OverrideResult # noqa: Y015
+
+@_typing.final
+class SaveFlagRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ DESCRIPTION_FIELD_NUMBER: _builtins.int
+ IS_ENABLED_FIELD_NUMBER: _builtins.int
+ ROLLOUT_PERCENTAGE_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ description: _builtins.str
+ is_enabled: _builtins.bool
+ rollout_percentage: _builtins.int
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ description: _builtins.str = ...,
+ is_enabled: _builtins.bool = ...,
+ rollout_percentage: _builtins.int = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["description", b"description", "is_enabled", b"is_enabled", "key", b"key", "rollout_percentage", b"rollout_percentage"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___SaveFlagRequest: _TypeAlias = SaveFlagRequest # noqa: Y015
+
+@_typing.final
+class SetOverrideRequest(_message.Message):
+ DESCRIPTOR: _descriptor.Descriptor
+
+ KEY_FIELD_NUMBER: _builtins.int
+ USER_ID_FIELD_NUMBER: _builtins.int
+ ENABLED_FIELD_NUMBER: _builtins.int
+ CLEAR_FIELD_NUMBER: _builtins.int
+ key: _builtins.str
+ user_id: _builtins.str
+ enabled: _builtins.bool
+ clear: _builtins.bool
+ def __init__(
+ self,
+ *,
+ key: _builtins.str = ...,
+ user_id: _builtins.str = ...,
+ enabled: _builtins.bool = ...,
+ clear: _builtins.bool = ...,
+ ) -> None: ...
+ _HasFieldArgType: _TypeAlias = _Never # noqa: Y015
+ def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
+ _ClearFieldArgType: _TypeAlias = _typing.Literal["clear", b"clear", "enabled", b"enabled", "key", b"key", "user_id", b"user_id"] # noqa: Y015
+ def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
+ def WhichOneof(self, oneof_group: _Never) -> None: ...
+
+Global___SetOverrideRequest: _TypeAlias = SetOverrideRequest # noqa: Y015
diff --git a/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2_grpc.py
new file mode 100644
index 0000000..ee97a1c
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_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.flags.grpc import flags_pb2 as apps_dot_flags_dot_grpc_dot_flags__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/flags/grpc/flags_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 FlagControllerStub:
+ """Missing associated documentation comment in .proto file."""
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.DeleteFlag = channel.unary_unary(
+ '/config.flags.FlagController/DeleteFlag',
+ request_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagRequest.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagResult.FromString,
+ _registered_method=True)
+ self.ListFlags = channel.unary_unary(
+ '/config.flags.FlagController/ListFlags',
+ request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagList.FromString,
+ _registered_method=True)
+ self.MyFlags = channel.unary_unary(
+ '/config.flags.FlagController/MyFlags',
+ request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.EvaluatedFlagList.FromString,
+ _registered_method=True)
+ self.SaveFlag = channel.unary_unary(
+ '/config.flags.FlagController/SaveFlag',
+ request_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SaveFlagRequest.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagResult.FromString,
+ _registered_method=True)
+ self.SetOverride = channel.unary_unary(
+ '/config.flags.FlagController/SetOverride',
+ request_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SetOverrideRequest.SerializeToString,
+ response_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.OverrideResult.FromString,
+ _registered_method=True)
+
+
+class FlagControllerServicer:
+ """Missing associated documentation comment in .proto file."""
+
+ def DeleteFlag(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 ListFlags(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 MyFlags(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 SaveFlag(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 SetOverride(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_FlagControllerServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'DeleteFlag': grpc.unary_unary_rpc_method_handler(
+ servicer.DeleteFlag,
+ request_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagRequest.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagResult.SerializeToString,
+ ),
+ 'ListFlags': grpc.unary_unary_rpc_method_handler(
+ servicer.ListFlags,
+ request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagList.SerializeToString,
+ ),
+ 'MyFlags': grpc.unary_unary_rpc_method_handler(
+ servicer.MyFlags,
+ request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.EvaluatedFlagList.SerializeToString,
+ ),
+ 'SaveFlag': grpc.unary_unary_rpc_method_handler(
+ servicer.SaveFlag,
+ request_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SaveFlagRequest.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.FlagResult.SerializeToString,
+ ),
+ 'SetOverride': grpc.unary_unary_rpc_method_handler(
+ servicer.SetOverride,
+ request_deserializer=apps_dot_flags_dot_grpc_dot_flags__pb2.SetOverrideRequest.FromString,
+ response_serializer=apps_dot_flags_dot_grpc_dot_flags__pb2.OverrideResult.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'config.flags.FlagController', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+ server.add_registered_method_handlers('config.flags.FlagController', rpc_method_handlers)
+
+
+ # This class is part of an EXPERIMENTAL API.
+class FlagController:
+ """Missing associated documentation comment in .proto file."""
+
+ @staticmethod
+ def DeleteFlag(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.flags.FlagController/DeleteFlag',
+ apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagRequest.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.DeleteFlagResult.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def ListFlags(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.flags.FlagController/ListFlags',
+ google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.FlagList.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def MyFlags(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.flags.FlagController/MyFlags',
+ google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.EvaluatedFlagList.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def SaveFlag(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.flags.FlagController/SaveFlag',
+ apps_dot_flags_dot_grpc_dot_flags__pb2.SaveFlagRequest.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.FlagResult.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def SetOverride(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.flags.FlagController/SetOverride',
+ apps_dot_flags_dot_grpc_dot_flags__pb2.SetOverrideRequest.SerializeToString,
+ apps_dot_flags_dot_grpc_dot_flags__pb2.OverrideResult.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/flags/grpc/flags_pb2_grpc.pyi b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2_grpc.pyi
new file mode 100644
index 0000000..a20e792
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/grpc/flags_pb2_grpc.pyi
@@ -0,0 +1,86 @@
+"""
+@generated by mypy-protobuf. Do not edit manually!
+isort:skip_file
+"""
+
+from apps.flags.grpc import flags_pb2 as _flags_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 FlagControllerStub:
+ @_typing.overload
+ def __new__(cls, channel: _grpc.Channel) -> _Self: ...
+ @_typing.overload
+ def __new__(cls, channel: _aio.Channel) -> FlagControllerAsyncStub: ...
+ DeleteFlag: _grpc.UnaryUnaryMultiCallable[_flags_pb2.DeleteFlagRequest, _flags_pb2.DeleteFlagResult]
+ ListFlags: _grpc.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.FlagList]
+ MyFlags: _grpc.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.EvaluatedFlagList]
+ SaveFlag: _grpc.UnaryUnaryMultiCallable[_flags_pb2.SaveFlagRequest, _flags_pb2.FlagResult]
+ SetOverride: _grpc.UnaryUnaryMultiCallable[_flags_pb2.SetOverrideRequest, _flags_pb2.OverrideResult]
+
+@_typing.type_check_only
+class FlagControllerAsyncStub(FlagControllerStub):
+ def __init__(self, channel: _aio.Channel) -> None: ...
+ DeleteFlag: _aio.UnaryUnaryMultiCallable[_flags_pb2.DeleteFlagRequest, _flags_pb2.DeleteFlagResult] # type: ignore[assignment]
+ ListFlags: _aio.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.FlagList] # type: ignore[assignment]
+ MyFlags: _aio.UnaryUnaryMultiCallable[_empty_pb2.Empty, _flags_pb2.EvaluatedFlagList] # type: ignore[assignment]
+ SaveFlag: _aio.UnaryUnaryMultiCallable[_flags_pb2.SaveFlagRequest, _flags_pb2.FlagResult] # type: ignore[assignment]
+ SetOverride: _aio.UnaryUnaryMultiCallable[_flags_pb2.SetOverrideRequest, _flags_pb2.OverrideResult] # type: ignore[assignment]
+
+class FlagControllerServicer(metaclass=_abc_1.ABCMeta):
+ @_abc_1.abstractmethod
+ def DeleteFlag(
+ self,
+ request: _flags_pb2.DeleteFlagRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.DeleteFlagResult, _abc.Awaitable[_flags_pb2.DeleteFlagResult]]: ...
+
+ @_abc_1.abstractmethod
+ def ListFlags(
+ self,
+ request: _empty_pb2.Empty,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.FlagList, _abc.Awaitable[_flags_pb2.FlagList]]: ...
+
+ @_abc_1.abstractmethod
+ def MyFlags(
+ self,
+ request: _empty_pb2.Empty,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.EvaluatedFlagList, _abc.Awaitable[_flags_pb2.EvaluatedFlagList]]: ...
+
+ @_abc_1.abstractmethod
+ def SaveFlag(
+ self,
+ request: _flags_pb2.SaveFlagRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.FlagResult, _abc.Awaitable[_flags_pb2.FlagResult]]: ...
+
+ @_abc_1.abstractmethod
+ def SetOverride(
+ self,
+ request: _flags_pb2.SetOverrideRequest,
+ context: _ServicerContext,
+ ) -> _typing.Union[_flags_pb2.OverrideResult, _abc.Awaitable[_flags_pb2.OverrideResult]]: ...
+
+def add_FlagControllerServicer_to_server(servicer: FlagControllerServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ...
diff --git a/src/django_ninja_starter/template/src/apps/flags/grpc/serializers.py b/src/django_ninja_starter/template/src/apps/flags/grpc/serializers.py
new file mode 100644
index 0000000..69e2ada
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/grpc/serializers.py
@@ -0,0 +1,23 @@
+"""The nested messages the flags service answers with."""
+
+from rest_framework import serializers
+
+
+class EvaluatedFlag(serializers.Serializer[dict[str, object]]):
+ key = serializers.CharField()
+ enabled = serializers.BooleanField()
+
+
+class FlagOverride(serializers.Serializer[dict[str, object]]):
+ user_id = serializers.CharField()
+ is_enabled = serializers.BooleanField()
+
+
+class Flag(serializers.Serializer[dict[str, object]]):
+ """``rollout_percentage`` is -1 on the wire when the flag has none."""
+
+ key = serializers.CharField()
+ description = serializers.CharField()
+ is_enabled = serializers.BooleanField()
+ rollout_percentage = serializers.IntegerField()
+ overrides = FlagOverride(many=True)
diff --git a/src/django_ninja_starter/template/src/apps/flags/grpc/services.py b/src/django_ninja_starter/template/src/apps/flags/grpc/services.py
new file mode 100644
index 0000000..ba120d2
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/grpc/services.py
@@ -0,0 +1,138 @@
+"""Feature flags over gRPC. The caller comes from metadata, as on the other doors.
+
+Protobuf has no null for a scalar, so ``rollout_percentage`` is -1 for "none" in
+both directions, and an override is cleared with ``clear`` rather than a null.
+"""
+
+from __future__ import annotations
+
+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.flags import services
+from apps.flags.errors import FlagError
+from apps.flags.grpc.serializers import EvaluatedFlag, Flag
+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
+
+NO_ROLLOUT = -1
+TITLES = {
+ 403: ResponseTitle.FORBIDDEN,
+ 404: ResponseTitle.NOT_FOUND,
+}
+
+
+def _pb2() -> Any:
+ from apps.flags.grpc import flags_pb2
+
+ return flags_pb2
+
+
+async def _run(call: Any, *args: Any, **kwargs: Any) -> Any:
+ try:
+ return await sync_to_async(call)(*args, **kwargs)
+ except FlagError as refusal:
+ raise ApiError(
+ str(refusal),
+ status=refusal.status,
+ title=TITLES.get(refusal.status, ResponseTitle.VALIDATION_ERROR),
+ ) from None
+
+
+def _flag(row: dict[str, Any]) -> Any:
+ pb2 = _pb2()
+ rollout = row["rollout_percentage"]
+ return pb2.Flag(
+ key=row["key"],
+ description=row["description"],
+ is_enabled=row["is_enabled"],
+ rollout_percentage=NO_ROLLOUT if rollout is None else rollout,
+ overrides=[pb2.FlagOverride(**override) for override in row["overrides"]],
+ )
+
+
+class FlagService(generics.GenericService):
+ @grpc_action(
+ request=[],
+ response=[{"name": "flags", "cardinality": "repeated", "type": EvaluatedFlag}],
+ response_name="EvaluatedFlagList",
+ )
+ @action
+ async def MyFlags(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rows = await _run(services.evaluate_all, user)
+ return _pb2().EvaluatedFlagList(flags=[_pb2().EvaluatedFlag(**row) for row in rows])
+
+ @grpc_action(
+ request=[],
+ response=[{"name": "flags", "cardinality": "repeated", "type": Flag}],
+ response_name="FlagList",
+ )
+ @action
+ async def ListFlags(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rows = await _run(services.list_flags, user)
+ return _pb2().FlagList(flags=[_flag(row) for row in rows])
+
+ @grpc_action(
+ request=[
+ {"name": "key", "type": "string"},
+ {"name": "description", "type": "string"},
+ {"name": "is_enabled", "type": "bool"},
+ {"name": "rollout_percentage", "type": "int32"},
+ ],
+ request_name="SaveFlagRequest",
+ response=[{"name": "flag", "type": Flag}],
+ response_name="FlagResult",
+ )
+ @action
+ async def SaveFlag(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ rollout = request.rollout_percentage
+ row = await _run(
+ services.save_flag,
+ user,
+ request.key,
+ is_enabled=request.is_enabled,
+ rollout_percentage=None if rollout == NO_ROLLOUT else rollout,
+ description=request.description,
+ )
+ return _pb2().FlagResult(flag=_flag(row))
+
+ @grpc_action(
+ request=[{"name": "key", "type": "string"}],
+ request_name="DeleteFlagRequest",
+ response=[{"name": "deleted", "type": "bool"}],
+ response_name="DeleteFlagResult",
+ )
+ @action
+ async def DeleteFlag(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ await _run(services.delete_flag, user, request.key)
+ return _pb2().DeleteFlagResult(deleted=True)
+
+ @grpc_action(
+ request=[
+ {"name": "key", "type": "string"},
+ {"name": "user_id", "type": "string"},
+ {"name": "enabled", "type": "bool"},
+ {"name": "clear", "type": "bool"},
+ ],
+ request_name="SetOverrideRequest",
+ response=[{"name": "flag", "type": Flag}],
+ response_name="OverrideResult",
+ )
+ @action
+ async def SetOverride(self, request: Any, context: Any) -> Any:
+ user = require_caller(await grpc_caller(context))
+ enabled = None if request.clear else request.enabled
+ row = await _run(services.set_override, user, request.key, request.user_id, enabled)
+ return _pb2().OverrideResult(flag=_flag(row))
+
+
+GRPC_SERVICES = [FlagService]
diff --git a/src/django_ninja_starter/template/src/apps/flags/migrations/0001_initial.py b/src/django_ninja_starter/template/src/apps/flags/migrations/0001_initial.py
new file mode 100644
index 0000000..077b743
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/migrations/0001_initial.py
@@ -0,0 +1,86 @@
+# Generated by Django 6.1.3 on 2026-11-26 14:26
+
+import django.core.validators
+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="Flag",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
+ ),
+ ),
+ ("key", models.SlugField(max_length=100, unique=True)),
+ ("description", models.TextField(blank=True)),
+ ("is_enabled", models.BooleanField(default=False, help_text="The global switch.")),
+ (
+ "rollout_percentage",
+ models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="Empty means everybody once the switch is on; 0-100 admits that share.",
+ null=True,
+ validators=[django.core.validators.MaxValueValidator(100)],
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "ordering": ["key"],
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(("rollout_percentage__lte", 100)),
+ name="flags_rollout_at_most_100",
+ )
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="FlagOverride",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
+ ),
+ ),
+ ("is_enabled", models.BooleanField()),
+ (
+ "flag",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="overrides",
+ to="flags.flag",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="flag_overrides",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("flag", "user"), name="flags_one_override_per_user"
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/src/django_ninja_starter/template/src/apps/flags/migrations/__init__.py b/src/django_ninja_starter/template/src/apps/flags/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/flags/models.py b/src/django_ninja_starter/template/src/apps/flags/models.py
new file mode 100644
index 0000000..f450a06
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/models.py
@@ -0,0 +1,56 @@
+"""A flag, and the per-account answers that override it."""
+
+from django.conf import settings
+from django.core.validators import MaxValueValidator
+from django.db import models
+
+
+class Flag(models.Model):
+ """One feature switch.
+
+ Evaluated in order: an override for the account wins; otherwise a flag that
+ is off is off; otherwise ``rollout_percentage`` (when set) admits that share
+ of accounts, bucketed by a stable hash of the account and the key.
+ """
+
+ key = models.SlugField(max_length=100, unique=True)
+ description = models.TextField(blank=True)
+ is_enabled = models.BooleanField(default=False, help_text="The global switch.")
+ rollout_percentage = models.PositiveSmallIntegerField(
+ null=True,
+ blank=True,
+ validators=[MaxValueValidator(100)],
+ help_text="Empty means everybody once the switch is on; 0-100 admits that share.",
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ ordering = ["key"]
+ constraints = [
+ models.CheckConstraint(
+ condition=models.Q(rollout_percentage__lte=100),
+ name="flags_rollout_at_most_100",
+ )
+ ]
+
+ def __str__(self) -> str:
+ return self.key
+
+
+class FlagOverride(models.Model):
+ """One account's answer for one flag, whatever the switch and the rollout say."""
+
+ flag = models.ForeignKey(Flag, on_delete=models.CASCADE, related_name="overrides")
+ user = models.ForeignKey(
+ settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="flag_overrides"
+ )
+ is_enabled = models.BooleanField()
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["flag", "user"], name="flags_one_override_per_user")
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.flag.key} for {self.user_id}: {'on' if self.is_enabled else 'off'}"
diff --git a/src/django_ninja_starter/template/src/apps/flags/rest/__init__.py b/src/django_ninja_starter/template/src/apps/flags/rest/__init__.py
new file mode 100644
index 0000000..f4571c0
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/rest/__init__.py
@@ -0,0 +1,5 @@
+"""The HTTP transport for the flags app."""
+
+from apps.flags.rest.v1 import router
+
+__all__ = ["router"]
diff --git a/src/django_ninja_starter/template/src/apps/flags/rest/schemas.py b/src/django_ninja_starter/template/src/apps/flags/rest/schemas.py
new file mode 100644
index 0000000..04c0438
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/rest/schemas.py
@@ -0,0 +1,37 @@
+"""What the flag routes take and return."""
+
+from ninja import Field, Schema
+
+
+class EvaluatedFlagOut(Schema):
+ key: str
+ enabled: bool
+
+
+class OverrideOut(Schema):
+ user_id: str
+ is_enabled: bool
+
+
+class FlagOut(Schema):
+ key: str
+ description: str
+ is_enabled: bool
+ rollout_percentage: int | None
+ overrides: list[OverrideOut]
+
+
+class FlagIn(Schema):
+ description: str = ""
+ is_enabled: bool = False
+ rollout_percentage: int | None = Field(default=None, ge=0, le=100)
+
+
+class OverrideIn(Schema):
+ """``null`` clears the account's override, so the flag's own rules apply again."""
+
+ enabled: bool | None
+
+
+class DeletedOut(Schema):
+ deleted: bool
diff --git a/src/django_ninja_starter/template/src/apps/flags/rest/v1.py b/src/django_ninja_starter/template/src/apps/flags/rest/v1.py
new file mode 100644
index 0000000..3754379
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/rest/v1.py
@@ -0,0 +1,62 @@
+"""Feature flags over HTTP.
+
+``GET /flags/me`` is every flag evaluated for the caller. Everything else is
+staff-only, and refuses anybody else with a 403.
+"""
+
+from typing import Any
+
+from django.http import HttpRequest
+from ninja import Router
+from ninja.errors import HttpError
+
+from apps.flags import services
+from apps.flags.errors import FlagError
+from apps.flags.rest.schemas import DeletedOut, EvaluatedFlagOut, FlagIn, FlagOut, OverrideIn
+
+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)
+
+
+def _run(call: Any, *args: Any, **kwargs: Any) -> Any:
+ try:
+ return call(*args, **kwargs)
+ except FlagError as refusal:
+ raise HttpError(refusal.status, str(refusal)) from None
+
+
+@router.get("/me", response=list[EvaluatedFlagOut], summary="Every flag, evaluated for you")
+def my_flags(request: HttpRequest) -> Any:
+ return services.evaluate_all(request.user)
+
+
+@router.get("/", response=list[FlagOut], summary="Every flag (staff)")
+def list_flags(request: HttpRequest) -> Any:
+ return _run(services.list_flags, request.user)
+
+
+@router.get("/{key}", response=FlagOut, summary="One flag (staff)")
+def get_flag(request: HttpRequest, key: str) -> Any:
+ return _run(services.get_flag, request.user, key)
+
+
+@router.put("/{key}", response=FlagOut, summary="Create or replace a flag (staff)")
+def save_flag(request: HttpRequest, key: str, payload: FlagIn) -> Any:
+ return _run(services.save_flag, request.user, key, **payload.dict())
+
+
+@router.delete("/{key}", response=DeletedOut, summary="Delete a flag (staff)")
+def delete_flag(request: HttpRequest, key: str) -> Any:
+ _run(services.delete_flag, request.user, key)
+ return {"deleted": True}
+
+
+@router.put(
+ "/{key}/overrides/{user_id}", response=FlagOut, summary="Pin a flag for one account (staff)"
+)
+def set_override(request: HttpRequest, key: str, user_id: str, payload: OverrideIn) -> Any:
+ return _run(services.set_override, request.user, key, user_id, payload.enabled)
diff --git a/src/django_ninja_starter/template/src/apps/flags/services.py b/src/django_ninja_starter/template/src/apps/flags/services.py
new file mode 100644
index 0000000..20412f7
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/services.py
@@ -0,0 +1,183 @@
+"""Evaluating flags, and the staff operations every transport shares.
+
+A flag's definition -- switch, rollout and overrides -- is cached per key and
+dropped by :mod:`apps.flags.signals` whenever the flag or an override is saved
+or deleted, so evaluation costs one cache read in the steady state.
+"""
+
+import hashlib
+import re
+from typing import Any
+
+from django.contrib.auth import get_user_model
+from django.core.cache import cache
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from apps.flags.errors import FlagError, FlagNotFound, StaffOnly
+from apps.flags.models import Flag, FlagOverride
+
+CACHE_PREFIX = "flags:flag:"
+CACHE_SECONDS = 300
+KEY_PATTERN = re.compile(r"^[-a-zA-Z0-9_]{1,100}$")
+#: What a cache read returns for a key that names no flag, so a missing flag is
+#: cached too and a typo in a hot path does not query the database every call.
+MISSING: dict[str, Any] = {}
+
+
+def _cache_key(key: str) -> str:
+ return f"{CACHE_PREFIX}{key}"
+
+
+def forget(key: str) -> None:
+ """Drop one flag's cached definition."""
+ cache.delete(_cache_key(key))
+
+
+def bucket(key: str, user_id: Any) -> int:
+ """A stable number in 0..99 for one account and one flag.
+
+ Hashed with the key so each flag admits a different slice of accounts, and
+ raising a percentage only ever adds accounts to the ones already admitted.
+ """
+ digest = hashlib.sha256(f"{key}:{user_id}".encode()).digest()
+ return int.from_bytes(digest[:8], "big") % 100
+
+
+def _definition(key: str) -> dict[str, Any]:
+ """The switch, the rollout and every override for one flag, cached.
+
+ ponytail: overrides live in the cached value, so a flag with very many
+ overrides makes a large entry; cache per (key, user) if that ever bites.
+ """
+ found = cache.get(_cache_key(key))
+ if found is not None:
+ return dict(found)
+ flag = Flag.objects.filter(key=key).first()
+ definition: dict[str, Any] = MISSING
+ if flag is not None:
+ definition = {
+ "is_enabled": flag.is_enabled,
+ "rollout_percentage": flag.rollout_percentage,
+ "overrides": dict(flag.overrides.values_list("user_id", "is_enabled")),
+ }
+ cache.set(_cache_key(key), definition, CACHE_SECONDS)
+ return dict(definition)
+
+
+def _evaluate(key: str, definition: dict[str, Any], user: Any) -> bool:
+ if not definition:
+ return False
+ user_id = getattr(user, "pk", None) if getattr(user, "is_authenticated", False) else None
+ if user_id is not None and user_id in definition["overrides"]:
+ return bool(definition["overrides"][user_id])
+ if not definition["is_enabled"]:
+ return False
+ rollout = definition["rollout_percentage"]
+ if rollout is None or rollout >= 100:
+ return True
+ if user_id is None:
+ return False
+ return bucket(key, user_id) < rollout
+
+
+def is_enabled(key: str, user: Any = None) -> bool:
+ """Whether ``key`` is on for ``user``. An unknown key is off.
+
+ Anonymous callers get the switch alone when there is no rollout, and are
+ left out of a partial rollout: there is no stable id to bucket them by.
+ """
+ return _evaluate(key, _definition(key), user)
+
+
+def evaluate_all(user: Any) -> list[dict[str, Any]]:
+ """Every flag, evaluated for ``user``."""
+ keys = Flag.objects.values_list("key", flat=True)
+ return [{"key": key, "enabled": is_enabled(key, user)} for key in keys]
+
+
+def _require_staff(user: Any) -> None:
+ if not getattr(user, "is_staff", False):
+ raise StaffOnly("Only staff manage feature flags.")
+
+
+def _row(flag: Flag) -> dict[str, Any]:
+ return {
+ "key": flag.key,
+ "description": flag.description,
+ "is_enabled": flag.is_enabled,
+ "rollout_percentage": flag.rollout_percentage,
+ "overrides": [
+ {"user_id": str(user_id), "is_enabled": enabled}
+ for user_id, enabled in flag.overrides.order_by("user_id").values_list(
+ "user_id", "is_enabled"
+ )
+ ],
+ }
+
+
+def list_flags(actor: Any) -> list[dict[str, Any]]:
+ _require_staff(actor)
+ return [_row(flag) for flag in Flag.objects.prefetch_related("overrides")]
+
+
+def get_flag(actor: Any, key: str) -> dict[str, Any]:
+ _require_staff(actor)
+ flag = Flag.objects.filter(key=key).first()
+ if flag is None:
+ raise FlagNotFound(f"No flag {key!r}.")
+ return _row(flag)
+
+
+def save_flag(
+ actor: Any,
+ key: str,
+ *,
+ is_enabled: bool,
+ rollout_percentage: int | None = None,
+ description: str = "",
+) -> dict[str, Any]:
+ """Create or replace one flag."""
+ _require_staff(actor)
+ if not KEY_PATTERN.match(key):
+ raise FlagError("A key is 1-100 letters, digits, hyphens or underscores.")
+ if rollout_percentage is not None and not 0 <= rollout_percentage <= 100:
+ raise FlagError("rollout_percentage must be between 0 and 100.")
+ flag, _ = Flag.objects.update_or_create(
+ key=key,
+ defaults={
+ "is_enabled": is_enabled,
+ "rollout_percentage": rollout_percentage,
+ "description": description,
+ },
+ )
+ return _row(flag)
+
+
+def delete_flag(actor: Any, key: str) -> None:
+ _require_staff(actor)
+ deleted, _ = Flag.objects.filter(key=key).delete()
+ if not deleted:
+ raise FlagNotFound(f"No flag {key!r}.")
+
+
+def set_override(actor: Any, key: str, user_id: Any, enabled: bool | None) -> dict[str, Any]:
+ """Pin ``key`` on or off for one account, or clear the pin with ``None``."""
+ _require_staff(actor)
+ flag = Flag.objects.filter(key=key).first()
+ if flag is None:
+ raise FlagNotFound(f"No flag {key!r}.")
+ try:
+ target = get_user_model().objects.filter(pk=user_id).first()
+ except (ValidationError, ValueError):
+ target = None
+ if target is None:
+ raise FlagNotFound(f"No account {user_id!r}.")
+ with transaction.atomic():
+ if enabled is None:
+ FlagOverride.objects.filter(flag=flag, user=target).delete()
+ else:
+ FlagOverride.objects.update_or_create(
+ flag=flag, user=target, defaults={"is_enabled": enabled}
+ )
+ return _row(flag)
diff --git a/src/django_ninja_starter/template/src/apps/flags/signals.py b/src/django_ninja_starter/template/src/apps/flags/signals.py
new file mode 100644
index 0000000..e21d430
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/signals.py
@@ -0,0 +1,19 @@
+"""Drop a flag's cached definition whenever it, or one of its overrides, changes."""
+
+from typing import Any
+
+from django.db.models.signals import post_delete, post_save
+from django.dispatch import receiver
+
+from apps.flags.models import Flag, FlagOverride
+from apps.flags.services import forget
+
+
+@receiver([post_save, post_delete], sender=Flag)
+def _flag_changed(sender: Any, instance: Flag, **kwargs: Any) -> None:
+ forget(instance.key)
+
+
+@receiver([post_save, post_delete], sender=FlagOverride)
+def _override_changed(sender: Any, instance: FlagOverride, **kwargs: Any) -> None:
+ forget(Flag.objects.filter(pk=instance.flag_id).values_list("key", flat=True).first() or "")
diff --git a/src/django_ninja_starter/template/src/apps/flags/tests/__init__.py b/src/django_ninja_starter/template/src/apps/flags/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/django_ninja_starter/template/src/apps/flags/tests/conftest.py b/src/django_ninja_starter/template/src/apps/flags/tests/conftest.py
new file mode 100644
index 0000000..baa1dbc
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/tests/conftest.py
@@ -0,0 +1,40 @@
+"""Fixtures for the flags tests. Collection stops when the app is not installed."""
+
+from typing import Any
+
+import pytest
+from django.apps import apps as django_apps
+from django.contrib.auth import get_user_model
+from django.core.cache import cache
+from django.test import RequestFactory
+
+FLAGS_INSTALLED = django_apps.is_installed("apps.flags")
+collect_ignore_glob = [] if FLAGS_INSTALLED else ["*"]
+
+
+def access_token(user: Any) -> str:
+ from infrastructure.auth.core.sessions import issue_credentials
+
+ request = RequestFactory().post("/")
+ return issue_credentials(request, user, method="password").access_token
+
+
+def bearer(user: Any) -> dict[str, str]:
+ return {"HTTP_AUTHORIZATION": f"Bearer {access_token(user)}"}
+
+
+@pytest.fixture(autouse=True)
+def _empty_cache() -> None:
+ cache.clear()
+
+
+@pytest.fixture
+def alice(db: None) -> Any:
+ return get_user_model().objects.create_user(username="alice", email="alice@example.test")
+
+
+@pytest.fixture
+def operator(db: None) -> Any:
+ return get_user_model().objects.create_user(
+ username="operator", email="ops@example.test", is_staff=True
+ )
diff --git a/src/django_ninja_starter/template/src/apps/flags/tests/test_admin.py b/src/django_ninja_starter/template/src/apps/flags/tests/test_admin.py
new file mode 100644
index 0000000..5d1ec78
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/tests/test_admin.py
@@ -0,0 +1,17 @@
+from typing import Any
+
+import pytest
+from django.test import Client
+
+from apps.flags.models import Flag
+
+pytestmark = pytest.mark.django_db
+
+
+def test_staff_see_the_flag_admin(admin_user: Any) -> None:
+ Flag.objects.create(key="beta")
+ client = Client()
+ client.force_login(admin_user)
+
+ assert client.get("/admin/flags/flag/").status_code == 200
+ assert client.get("/admin/flags/flag/add/").status_code == 200
diff --git a/src/django_ninja_starter/template/src/apps/flags/tests/test_api.py b/src/django_ninja_starter/template/src/apps/flags/tests/test_api.py
new file mode 100644
index 0000000..220bf58
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/tests/test_api.py
@@ -0,0 +1,78 @@
+from typing import Any
+
+import pytest
+from django.test import Client
+
+from apps.flags.models import Flag, FlagOverride
+from apps.flags.tests.conftest import bearer
+
+pytestmark = pytest.mark.django_db
+BASE = "/api/v1/flags"
+
+
+def test_me_is_every_flag_evaluated_for_the_caller(alice: Any) -> None:
+ beta = Flag.objects.create(key="beta", is_enabled=False)
+ Flag.objects.create(key="live", is_enabled=True)
+ FlagOverride.objects.create(flag=beta, user=alice, is_enabled=True)
+
+ response = Client().get(f"{BASE}/me", **bearer(alice))
+
+ assert response.status_code == 200, response.content
+ assert response.json()["data"] == [
+ {"key": "beta", "enabled": True},
+ {"key": "live", "enabled": True},
+ ]
+
+
+def test_me_needs_a_credential() -> None:
+ assert Client().get(f"{BASE}/me").status_code == 401
+
+
+def test_a_member_cannot_manage_flags(alice: Any) -> None:
+ client = Client()
+ assert client.get(f"{BASE}/", **bearer(alice)).status_code == 403
+ response = client.put(
+ f"{BASE}/beta", {"is_enabled": True}, content_type="application/json", **bearer(alice)
+ )
+ assert response.status_code == 403
+ assert not Flag.objects.exists()
+
+
+def test_staff_manage_flags_end_to_end(operator: Any, alice: Any) -> None:
+ client = Client()
+ auth = bearer(operator)
+
+ saved = client.put(
+ f"{BASE}/beta",
+ {"is_enabled": True, "rollout_percentage": 0, "description": "New thing"},
+ content_type="application/json",
+ **auth,
+ )
+ assert saved.status_code == 200, saved.content
+ assert saved.json()["data"]["rollout_percentage"] == 0
+
+ pinned = client.put(
+ f"{BASE}/beta/overrides/{alice.pk}",
+ {"enabled": True},
+ content_type="application/json",
+ **auth,
+ )
+ assert pinned.json()["data"]["overrides"] == [{"user_id": str(alice.pk), "is_enabled": True}]
+ assert client.get(f"{BASE}/me", **bearer(alice)).json()["data"] == [
+ {"key": "beta", "enabled": True}
+ ]
+
+ assert [row["key"] for row in client.get(f"{BASE}/", **auth).json()["data"]] == ["beta"]
+ assert client.get(f"{BASE}/beta", **auth).status_code == 200
+ assert client.delete(f"{BASE}/beta", **auth).json()["data"] == {"deleted": True}
+ assert client.get(f"{BASE}/beta", **auth).status_code == 404
+
+
+def test_a_rollout_over_100_is_refused(operator: Any) -> None:
+ response = Client().put(
+ f"{BASE}/beta",
+ {"is_enabled": True, "rollout_percentage": 150},
+ content_type="application/json",
+ **bearer(operator),
+ )
+ assert response.status_code in (400, 422)
diff --git a/src/django_ninja_starter/template/src/apps/flags/tests/test_graph.py b/src/django_ninja_starter/template/src/apps/flags/tests/test_graph.py
new file mode 100644
index 0000000..da8b2e9
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/tests/test_graph.py
@@ -0,0 +1,65 @@
+import json
+from typing import Any
+
+import pytest
+from django.test import Client
+
+from apps.flags.models import Flag
+from apps.flags.tests.conftest import bearer
+
+pytestmark = pytest.mark.django_db
+
+MY_FLAGS = "{ myFlags { key enabled } }"
+FLAGS = "{ flags { key isEnabled rolloutPercentage overrides { userId isEnabled } } }"
+SAVE = """
+mutation($key: String!) {
+ flagSave(key: $key, isEnabled: true, rolloutPercentage: 100) { key rolloutPercentage }
+}
+"""
+OVERRIDE = """
+mutation($key: String!, $userId: String!) {
+ flagOverride(key: $key, userId: $userId, enabled: false) { overrides { userId isEnabled } }
+}
+"""
+DELETE = "mutation($key: String!) { flagDelete(key: $key) }"
+
+
+def graphql(query: str, user: Any = None, **variables: Any) -> dict[str, Any]:
+ headers = bearer(user) if user else {}
+ response = Client().post(
+ "/graphql",
+ json.dumps({"query": query, "variables": variables}),
+ content_type="application/json",
+ **headers,
+ )
+ return response.json()
+
+
+def test_my_flags(alice: Any) -> None:
+ Flag.objects.create(key="live", is_enabled=True)
+ assert graphql(MY_FLAGS, alice)["data"]["myFlags"] == [{"key": "live", "enabled": True}]
+
+
+def test_my_flags_needs_a_caller() -> None:
+ body = graphql(MY_FLAGS)
+ assert body["errors"][0]["extensions"]["status"] == 401
+
+
+def test_members_are_refused_the_staff_fields(alice: Any) -> None:
+ body = graphql(FLAGS, alice)
+ assert body["errors"][0]["extensions"]["status"] == 403
+
+
+def test_staff_round_trip(operator: Any, alice: Any) -> None:
+ assert graphql(SAVE, operator, key="beta")["data"]["flagSave"] == {
+ "key": "beta",
+ "rolloutPercentage": 100,
+ }
+ overridden = graphql(OVERRIDE, operator, key="beta", userId=str(alice.pk))
+ assert overridden["data"]["flagOverride"]["overrides"] == [
+ {"userId": str(alice.pk), "isEnabled": False}
+ ]
+ assert graphql(MY_FLAGS, alice)["data"]["myFlags"] == [{"key": "beta", "enabled": False}]
+ assert len(graphql(FLAGS, operator)["data"]["flags"]) == 1
+ assert graphql(DELETE, operator, key="beta")["data"]["flagDelete"] is True
+ assert not Flag.objects.exists()
diff --git a/src/django_ninja_starter/template/src/apps/flags/tests/test_grpc.py b/src/django_ninja_starter/template/src/apps/flags/tests/test_grpc.py
new file mode 100644
index 0000000..ee8b6d8
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/tests/test_grpc.py
@@ -0,0 +1,67 @@
+"""``transactional_db`` throughout: the server answers on its own connection."""
+
+from collections.abc import Callable
+from typing import Any
+
+import grpc
+import pytest
+from google.protobuf.empty_pb2 import Empty
+
+from apps.flags.grpc import flags_pb2, flags_pb2_grpc
+from apps.flags.models import Flag
+from apps.flags.tests.conftest import access_token
+
+Stub = flags_pb2_grpc.FlagControllerStub
+
+
+def test_my_flags(transactional_db: None, alice: Any, grpc_call: Callable[..., Any]) -> None:
+ Flag.objects.create(key="live", is_enabled=True)
+ reply = grpc_call(Stub, "MyFlags", Empty(), token=access_token(alice))
+ assert [(row.key, row.enabled) for row in reply.flags] == [("live", True)]
+
+
+def test_members_cannot_save(
+ transactional_db: None, alice: Any, grpc_call: Callable[..., Any]
+) -> None:
+ with pytest.raises(grpc.RpcError) as refused:
+ grpc_call(
+ Stub,
+ "SaveFlag",
+ flags_pb2.SaveFlagRequest(key="beta", is_enabled=True, rollout_percentage=-1),
+ token=access_token(alice),
+ )
+ assert refused.value.code() == grpc.StatusCode.PERMISSION_DENIED
+
+
+def test_staff_round_trip(
+ transactional_db: None, operator: Any, alice: Any, grpc_call: Callable[..., Any]
+) -> None:
+ token = access_token(operator)
+ saved = grpc_call(
+ Stub,
+ "SaveFlag",
+ flags_pb2.SaveFlagRequest(key="beta", is_enabled=False, rollout_percentage=-1),
+ token=token,
+ )
+ assert saved.flag.rollout_percentage == -1
+ assert Flag.objects.get(key="beta").rollout_percentage is None
+
+ pinned = grpc_call(
+ Stub,
+ "SetOverride",
+ flags_pb2.SetOverrideRequest(key="beta", user_id=str(alice.pk), enabled=True),
+ token=token,
+ )
+ assert [o.user_id for o in pinned.flag.overrides] == [str(alice.pk)]
+ cleared = grpc_call(
+ Stub,
+ "SetOverride",
+ flags_pb2.SetOverrideRequest(key="beta", user_id=str(alice.pk), clear=True),
+ token=token,
+ )
+ assert list(cleared.flag.overrides) == []
+
+ assert [row.key for row in grpc_call(Stub, "ListFlags", Empty(), token=token).flags] == ["beta"]
+ assert grpc_call(
+ Stub, "DeleteFlag", flags_pb2.DeleteFlagRequest(key="beta"), token=token
+ ).deleted
diff --git a/src/django_ninja_starter/template/src/apps/flags/tests/test_services.py b/src/django_ninja_starter/template/src/apps/flags/tests/test_services.py
new file mode 100644
index 0000000..3797828
--- /dev/null
+++ b/src/django_ninja_starter/template/src/apps/flags/tests/test_services.py
@@ -0,0 +1,130 @@
+from typing import Any
+
+import pytest
+from django.contrib.auth import get_user_model
+from django.contrib.auth.models import AnonymousUser
+
+from apps.flags import is_enabled as public_is_enabled
+from apps.flags import services
+from apps.flags.errors import FlagError, FlagNotFound, StaffOnly
+from apps.flags.models import Flag, FlagOverride
+
+pytestmark = pytest.mark.django_db
+
+
+def test_an_unknown_flag_is_off(alice: Any) -> None:
+ assert services.is_enabled("nope", alice) is False
+
+
+def test_the_global_switch(alice: Any) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=True)
+ assert services.is_enabled("beta", alice) is True
+ assert services.is_enabled("beta", AnonymousUser()) is True
+
+ flag.is_enabled = False
+ flag.save()
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_an_override_beats_the_switch_both_ways(alice: Any, operator: Any) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=False)
+ FlagOverride.objects.create(flag=flag, user=alice, is_enabled=True)
+ assert services.is_enabled("beta", alice) is True
+ assert services.is_enabled("beta", operator) is False
+
+ flag.is_enabled = True
+ flag.save()
+ FlagOverride.objects.filter(user=alice).update(is_enabled=False)
+ services.forget("beta") # `.update` sends no signal
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_the_rollout_admits_roughly_its_share_and_is_stable() -> None:
+ Flag.objects.create(key="half", is_enabled=True, rollout_percentage=50)
+ users = [
+ get_user_model().objects.create_user(username=f"u{n}", email=f"u{n}@example.test")
+ for n in range(200)
+ ]
+ admitted = [user for user in users if services.is_enabled("half", user)]
+
+ assert 60 < len(admitted) < 140
+ assert all(services.is_enabled("half", user) for user in admitted)
+
+
+def test_raising_the_rollout_keeps_everybody_already_in() -> None:
+ flag = Flag.objects.create(key="grow", is_enabled=True, rollout_percentage=20)
+ users = [
+ get_user_model().objects.create_user(username=f"u{n}", email=f"u{n}@example.test")
+ for n in range(50)
+ ]
+ before = {user.pk for user in users if services.is_enabled("grow", user)}
+ flag.rollout_percentage = 60
+ flag.save()
+ after = {user.pk for user in users if services.is_enabled("grow", user)}
+
+ assert before <= after
+
+
+def test_a_partial_rollout_leaves_anonymous_callers_out() -> None:
+ Flag.objects.create(key="half", is_enabled=True, rollout_percentage=99)
+ assert services.is_enabled("half", AnonymousUser()) is False
+ assert services.is_enabled("half", None) is False
+
+
+def test_evaluation_is_cached_and_a_save_invalidates(
+ alice: Any, django_assert_num_queries: Any
+) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=True)
+ services.is_enabled("beta", alice)
+ with django_assert_num_queries(0):
+ assert services.is_enabled("beta", alice) is True
+
+ flag.is_enabled = False
+ flag.save()
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_an_override_save_and_delete_invalidate(alice: Any) -> None:
+ flag = Flag.objects.create(key="beta", is_enabled=False)
+ assert services.is_enabled("beta", alice) is False
+ override = FlagOverride.objects.create(flag=flag, user=alice, is_enabled=True)
+ assert services.is_enabled("beta", alice) is True
+ override.delete()
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_the_package_level_shortcut(alice: Any) -> None:
+ Flag.objects.create(key="beta", is_enabled=True)
+ assert public_is_enabled("beta", alice) is True
+
+
+def test_staff_operations_refuse_everybody_else(alice: Any) -> None:
+ with pytest.raises(StaffOnly):
+ services.list_flags(alice)
+ with pytest.raises(StaffOnly):
+ services.save_flag(alice, "x", is_enabled=True)
+
+
+def test_staff_save_validates(operator: Any) -> None:
+ with pytest.raises(FlagError):
+ services.save_flag(operator, "bad key!", is_enabled=True)
+ with pytest.raises(FlagError):
+ services.save_flag(operator, "ok", is_enabled=True, rollout_percentage=101)
+
+
+def test_set_override_and_clear(operator: Any, alice: Any) -> None:
+ services.save_flag(operator, "beta", is_enabled=False)
+ row = services.set_override(operator, "beta", str(alice.pk), True)
+ assert row["overrides"] == [{"user_id": str(alice.pk), "is_enabled": True}]
+ assert services.is_enabled("beta", alice) is True
+
+ services.set_override(operator, "beta", str(alice.pk), None)
+ assert services.is_enabled("beta", alice) is False
+
+
+def test_set_override_refuses_unknown_targets(operator: Any) -> None:
+ with pytest.raises(FlagNotFound):
+ services.set_override(operator, "missing", "x", True)
+ services.save_flag(operator, "beta", is_enabled=False)
+ with pytest.raises(FlagNotFound):
+ services.set_override(operator, "beta", "not-a-uuid", True)
diff --git a/src/django_ninja_starter/template/src/apps/notifications/grpc/notifications_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/notifications/grpc/notifications_pb2_grpc.py
index 6552424..ea8a4a7 100644
--- a/src/django_ninja_starter/template/src/apps/notifications/grpc/notifications_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/apps/notifications/grpc/notifications_pb2_grpc.py
@@ -6,7 +6,7 @@
from apps.notifications.grpc import notifications_pb2 as apps_dot_notifications_dot_grpc_dot_notifications__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/apps/shop/grpc/shop_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/shop/grpc/shop_pb2_grpc.py
index f16201a..6397ffa 100644
--- a/src/django_ninja_starter/template/src/apps/shop/grpc/shop_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/apps/shop/grpc/shop_pb2_grpc.py
@@ -6,7 +6,7 @@
from apps.shop.grpc import shop_pb2 as apps_dot_shop_dot_grpc_dot_shop__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/apps/shop/services.py b/src/django_ninja_starter/template/src/apps/shop/services.py
index 8e2e4f2..044e210 100644
--- a/src/django_ninja_starter/template/src/apps/shop/services.py
+++ b/src/django_ninja_starter/template/src/apps/shop/services.py
@@ -34,6 +34,7 @@
from django.db.models.functions import Greatest
from django.utils import timezone
+from apps.audit.services import record
from apps.shop import options, signals
from apps.shop.attributes import AttributeType, normalize_value
from apps.shop.models import (
@@ -1015,6 +1016,7 @@ def checkout(
OrderEvent.objects.create(
order=order, status=OrderStatus.PENDING, note="Placed.", actor=user
)
+ record(user, "create", order, {"status": [None, str(OrderStatus.PENDING)]})
cart.items.all().delete()
return order
@@ -1087,6 +1089,12 @@ def settle_order(
)
locked.status = OrderStatus.PAID
locked.save(update_fields=["status", "updated_at"])
+ record(
+ actor,
+ "settle",
+ locked,
+ {"status": [str(OrderStatus.PENDING), str(OrderStatus.PAID)]},
+ )
OrderEvent.objects.create(
order=locked,
status=OrderStatus.PAID,
@@ -1185,6 +1193,7 @@ def reject_payment(self, order: Order, *, reason: str = "", actor: Any = None) -
note=f"Payment attempt refused{f': {reason}' if reason else ''}."[:300],
actor=actor,
)
+ record(actor, "reject_payment", locked, {"payment": ["pending", "failed"]})
return locked
def confirm_payment(self, user: Any, number: str, *, reference: str = "") -> Order:
@@ -1227,6 +1236,12 @@ def cancel_order(self, user: Any, number: str) -> Order:
note="Cancelled by the shopper.",
actor=user,
)
+ record(
+ user,
+ "cancel",
+ order,
+ {"status": [str(OrderStatus.PENDING), str(OrderStatus.CANCELLED)]},
+ )
return order
def advance_order(
@@ -1291,8 +1306,10 @@ def advance_order(
locked.tracking_number = tracking_number or locked.tracking_number
locked.tracking_url = tracking_url or locked.tracking_url
changed += ["shipped_at", "carrier", "tracking_number", "tracking_url"]
+ previous = str(locked.status)
locked.status = wanted
locked.save(update_fields=changed)
+ record(actor, "set_status", locked, {"status": [previous, wanted]})
OrderEvent.objects.create(order=locked, status=wanted, note=note[:300], actor=actor)
return locked
diff --git a/src/django_ninja_starter/template/src/apps/shop/tests/test_fulfilment.py b/src/django_ninja_starter/template/src/apps/shop/tests/test_fulfilment.py
index 80e262c..b287943 100644
--- a/src/django_ninja_starter/template/src/apps/shop/tests/test_fulfilment.py
+++ b/src/django_ninja_starter/template/src/apps/shop/tests/test_fulfilment.py
@@ -207,3 +207,19 @@ def test_a_pending_order_is_still_the_shopper_s_to_cancel(
def test_the_amount_collected_is_read_off_the_payments(self, paid: Order) -> None:
assert paid.paid_amount == Decimal(str(paid.total))
assert Payment.objects.filter(order=paid, status=PaymentStatus.SUCCEEDED).count() == 1
+
+
+def test_every_status_change_lands_in_the_audit_log(paid: Order) -> None:
+ from apps.audit.models import AuditEntry
+
+ shop_service.start_processing(paid)
+
+ trail = AuditEntry.objects.filter(target_model="shop.order", target_id=str(paid.pk))
+ assert list(trail.order_by("created_at").values_list("action", flat=True)) == [
+ "create",
+ "settle",
+ "set_status",
+ ]
+ assert trail.get(action="set_status").changes == {
+ "status": [str(OrderStatus.PAID), str(OrderStatus.PROCESSING)]
+ }
diff --git a/src/django_ninja_starter/template/src/apps/support/grpc/support_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/support/grpc/support_pb2_grpc.py
index 057d709..c4cb554 100644
--- a/src/django_ninja_starter/template/src/apps/support/grpc/support_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/apps/support/grpc/support_pb2_grpc.py
@@ -6,7 +6,7 @@
from apps.support.grpc import support_pb2 as apps_dot_support_dot_grpc_dot_support__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
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/apps/wallet/grpc/wallet_pb2_grpc.py b/src/django_ninja_starter/template/src/apps/wallet/grpc/wallet_pb2_grpc.py
index c1608f8..e43a9eb 100644
--- a/src/django_ninja_starter/template/src/apps/wallet/grpc/wallet_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/apps/wallet/grpc/wallet_pb2_grpc.py
@@ -6,7 +6,7 @@
from apps.wallet.grpc import wallet_pb2 as apps_dot_wallet_dot_grpc_dot_wallet__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/apps/wallet/services.py b/src/django_ninja_starter/template/src/apps/wallet/services.py
index 97f9095..911fcd3 100644
--- a/src/django_ninja_starter/template/src/apps/wallet/services.py
+++ b/src/django_ninja_starter/template/src/apps/wallet/services.py
@@ -61,6 +61,7 @@
from django.db.models import OuterRef, Subquery
from django.utils import timezone
+from apps.audit.services import record
from apps.wallet import gateways, signals
from apps.wallet.balances import Balance, balance_of
from apps.wallet.catalog import Applies, ExchangeRate, PaymentMethod
@@ -875,6 +876,7 @@ def expire_entry(self, entry_id: UUID, *, reason: str = "", by: Any = None) -> d
raise InvalidTransition(
f"A {entry.get_status_display().lower()} entry cannot expire."
)
+ previous = entry.status
entry.status = str(EntryStatus.EXPIRED)
fields = ["status"]
note = {
@@ -885,6 +887,7 @@ def expire_entry(self, entry_id: UUID, *, reason: str = "", by: Any = None) -> d
entry.metadata = {**entry.metadata, **note}
fields.append("metadata")
entry.save(update_fields=fields)
+ record(by, "expire", entry, {"status": [previous, entry.status]})
signals.announce(signals.entry_expired, entry=entry_payload(entry, staff=True))
return entry_payload(entry)
@@ -959,14 +962,24 @@ def adjust(
metadata: dict[str, Any] = {"reason": reason}
if getattr(by, "pk", None):
metadata["adjusted_by"] = str(by.pk)
- return self._record_system(
- user,
- kind=kind,
- amount=amount,
- reference=reference,
- description=reason,
- metadata=metadata,
- )
+ with transaction.atomic():
+ replay = self._existing(self.wallet_for(user), reference) is not None
+ adjusted = self._record_system(
+ user,
+ kind=kind,
+ amount=amount,
+ reference=reference,
+ description=reason,
+ metadata=metadata,
+ )
+ if not replay:
+ record(
+ by,
+ "adjust",
+ WalletEntry.objects.get(pk=adjusted["id"]),
+ {"kind": kind, "amount": str(amount), "reason": reason},
+ )
+ return adjusted
def pay(
self,
@@ -1184,6 +1197,7 @@ def set_wallet_status(
)
locked.status = status
locked.save(update_fields=["status", "updated_at"])
+ record(by, "set_status", locked, {"status": [previous, status]})
change = {
"id": locked.pk,
"status": status,
@@ -1265,6 +1279,7 @@ def approve(self, entry_id: UUID, *, by: Any = None, note: str = "") -> dict[str
entry.reviewed_at = timezone.now()
entry.review_note = note
entry.save(update_fields=["approval", "reviewed_by", "reviewed_at", "review_note"])
+ record(by, "approve", entry, {"approval": ["requested", "approved"]})
signals.announce(signals.entry_approved, entry=entry_payload(entry, staff=True))
rail = entry.payment_method.spec if entry.payment_method_id else None
@@ -1403,6 +1418,7 @@ def reject(self, entry_id: UUID, *, by: Any = None, note: str = "") -> dict[str,
entry.status = str(EntryStatus.CANCELLED)
fields.append("status")
entry.save(update_fields=fields)
+ record(by, "reject", entry, {"approval": ["requested", "rejected"]})
signals.announce(signals.entry_rejected, entry=entry_payload(entry, staff=True))
if cancelled:
signals.announce(signals.entry_cancelled, entry=entry_payload(entry, staff=True))
@@ -1519,9 +1535,11 @@ def _reverse_locked(
metadata=metadata,
counterparty=original,
)
+ previous = original.status
original.status = str(EntryStatus.REVERSED)
original.metadata = {**original.metadata, "reversed_by": str(correction.pk)}
original.save(update_fields=["status", "metadata"])
+ record(by, "reverse", original, {"status": [previous, original.status]})
signals.announce(
signals.entry_reversed,
entry=entry_payload(original, staff=True),
@@ -2011,6 +2029,7 @@ def _transition(
self._check_wallet(locked, entry.direction)
self._check_funds(locked, entry.amount, already_held=entry.amount)
+ previous = entry.status
entry.status = status
fields = ["status"]
if external_reference:
@@ -2021,6 +2040,7 @@ def _transition(
entry.metadata = {**entry.metadata, **note}
fields.append("metadata")
entry.save(update_fields=fields)
+ record(by or user, "set_status", entry, {"status": [previous, status]})
signals.announce(signals.STATUS_SIGNALS[status], entry=entry_payload(entry, staff=True))
return entry_payload(entry)
diff --git a/src/django_ninja_starter/template/src/apps/wallet/tests/test_backoffice.py b/src/django_ninja_starter/template/src/apps/wallet/tests/test_backoffice.py
index e5bc8cc..1d979f2 100644
--- a/src/django_ninja_starter/template/src/apps/wallet/tests/test_backoffice.py
+++ b/src/django_ninja_starter/template/src/apps/wallet/tests/test_backoffice.py
@@ -168,3 +168,23 @@ def test_an_empty_wallet_closes_and_stays_closed(alice: Any, cash: PaymentMethod
def test_a_status_that_is_not_one_is_refused(funded: Any) -> None:
with pytest.raises(WalletError, match="not a wallet status"):
wallet_service.set_wallet_status(_wallet(funded).pk, "asleep")
+
+
+def test_back_office_actions_land_in_the_audit_log(funded: Any, operator: Any) -> None:
+ from apps.audit.models import AuditEntry
+
+ for _ in range(2): # the replay is not a second adjustment
+ wallet_service.adjust(
+ funded,
+ kind=str(EntryKind.BONUS),
+ amount=Decimal("10"),
+ reference="adjustment:audited",
+ reason="Goodwill",
+ by=operator,
+ )
+ wallet_service.set_wallet_status(_wallet(funded).pk, str(WalletStatus.FROZEN), by=operator)
+
+ rows = list(AuditEntry.objects.filter(actor=operator).order_by("created_at"))
+ assert [row.action for row in rows] == ["adjust", "set_status"]
+ assert rows[0].target_model == "wallet.walletentry"
+ assert rows[1].changes == {"status": [str(WalletStatus.ACTIVE), str(WalletStatus.FROZEN)]}
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..12c536c 100644
--- a/src/django_ninja_starter/template/src/config/api.py
+++ b/src/django_ninja_starter/template/src/config/api.py
@@ -43,10 +43,13 @@ def build_apis() -> dict[str, NinjaAPI]:
*credential_routes,
*settings.CLUB_ROUTERS,
*settings.CMS_ROUTERS,
+ *settings.FLAGS_ROUTERS,
*settings.NOTIFICATIONS_ROUTERS,
*settings.SHOP_ROUTERS,
*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/api_registry.json b/src/django_ninja_starter/template/src/config/api_registry.json
index a1c2f96..e45b84d 100644
--- a/src/django_ninja_starter/template/src/config/api_registry.json
+++ b/src/django_ninja_starter/template/src/config/api_registry.json
@@ -7,6 +7,13 @@
"router": "infrastructure.common.rest.api.router",
"tag": "Health",
"description": "Liveness and readiness probes, for a load balancer and an orchestrator. Public, so a probe needs no credential."
+ },
+ {
+ "app_config": "apps.audit.apps.AuditConfig",
+ "prefix": "/audit",
+ "router": "apps.audit.rest.router",
+ "tag": "Audit",
+ "description": "Append-only record of who changed what and when. Staff read it; nothing writes it over the API."
}
]
}
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..e8af8ef 100644
--- a/src/django_ninja_starter/template/src/config/settings/base.py
+++ b/src/django_ninja_starter/template/src/config/settings/base.py
@@ -758,6 +758,30 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]:
CLUB_PAGE_SIZE = int(os.getenv("DJANGO_CLUB_PAGE_SIZE", "50"))
CLUB_MAX_PAGE_SIZE = int(os.getenv("DJANGO_CLUB_MAX_PAGE_SIZE", "200"))
+# The feature flags app. Optional the same way the others are: naming it
+# installs its two tables, its routes and its admin. `apps.flags.is_enabled`
+# answers False in a project that does not name it, so other apps may call it.
+FLAGS_ENABLED = os.getenv("DJANGO_FLAGS_ENABLED", "false").lower() == "true"
+FLAGS_APP = "apps.flags.apps.FlagsConfig"
+FLAGS_INSTALLED_APPS = [FLAGS_APP] if FLAGS_ENABLED else []
+FLAGS_TRANSPORTS = app_transports("flags", ("rest", "graph", "grpc")) if FLAGS_ENABLED else ()
+FLAGS_ROUTERS = (
+ [
+ {
+ "prefix": "/flags",
+ "router": "apps.flags.rest.router",
+ "tag": "Feature flags",
+ "description": (
+ "Feature flags: a global switch, per-account overrides and a "
+ "percentage rollout. `/flags/me` is every flag evaluated for the "
+ "caller; everything else is for staff."
+ ),
+ }
+ ]
+ if "rest" in FLAGS_TRANSPORTS
+ else []
+)
+
# The support app. Optional the same way the CMS, the notifications and the shop
# are: naming it installs its tables, its routes, its admin and its socket, and
# a project that does not name it never imports the package.
@@ -882,6 +906,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"))
@@ -903,6 +955,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 +991,11 @@ 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,
+ "apps.files": FILES_TRANSPORTS,
+ # Always installed, through `api_registry.json`.
+ "apps.audit": ("rest", "graph", "grpc"),
+ "apps.flags": FLAGS_TRANSPORTS,
}
# How often one caller may ask, whichever endpoint they are asking. A correct
@@ -1022,6 +1108,9 @@ def app_transports(app: str, published: tuple[str, ...]) -> tuple[str, ...]:
*SUPPORT_INSTALLED_APPS,
*WALLET_INSTALLED_APPS,
*CLUB_INSTALLED_APPS,
+ *WEBHOOKS_INSTALLED_APPS,
+ *FILES_INSTALLED_APPS,
+ *FLAGS_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.
@@ -1158,4 +1247,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 474cdb6..1313bd6 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,9 @@
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_FILES_ENABLED", "true")
+os.environ.setdefault("DJANGO_FLAGS_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/accounts/grpc/accounts_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/accounts/grpc/accounts_pb2_grpc.py
index 4152af8..cdbd222 100644
--- a/src/django_ninja_starter/template/src/infrastructure/accounts/grpc/accounts_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/accounts/grpc/accounts_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.accounts.grpc import accounts_pb2 as infrastructure_dot_accounts_dot_grpc_dot_accounts__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/auth/email_code/grpc/auth_email_code_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/auth/email_code/grpc/auth_email_code_pb2_grpc.py
index 7d85fe7..7b16603 100644
--- a/src/django_ninja_starter/template/src/infrastructure/auth/email_code/grpc/auth_email_code_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/auth/email_code/grpc/auth_email_code_pb2_grpc.py
@@ -5,7 +5,7 @@
from infrastructure.auth.email_code.grpc import auth_email_code_pb2 as infrastructure_dot_auth_dot_email__code_dot_grpc_dot_auth__email__code__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/auth/magic_link/grpc/auth_magic_link_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/auth/magic_link/grpc/auth_magic_link_pb2_grpc.py
index b327ecb..83235c5 100644
--- a/src/django_ninja_starter/template/src/infrastructure/auth/magic_link/grpc/auth_magic_link_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/auth/magic_link/grpc/auth_magic_link_pb2_grpc.py
@@ -5,7 +5,7 @@
from infrastructure.auth.magic_link.grpc import auth_magic_link_pb2 as infrastructure_dot_auth_dot_magic__link_dot_grpc_dot_auth__magic__link__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/auth/password/grpc/auth_password_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/auth/password/grpc/auth_password_pb2_grpc.py
index 47510e6..2f9e59d 100644
--- a/src/django_ninja_starter/template/src/infrastructure/auth/password/grpc/auth_password_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/auth/password/grpc/auth_password_pb2_grpc.py
@@ -5,7 +5,7 @@
from infrastructure.auth.password.grpc import auth_password_pb2 as infrastructure_dot_auth_dot_password_dot_grpc_dot_auth__password__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/auth/sms_code/grpc/auth_sms_code_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/auth/sms_code/grpc/auth_sms_code_pb2_grpc.py
index 0576f80..c8551ba 100644
--- a/src/django_ninja_starter/template/src/infrastructure/auth/sms_code/grpc/auth_sms_code_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/auth/sms_code/grpc/auth_sms_code_pb2_grpc.py
@@ -5,7 +5,7 @@
from infrastructure.auth.sms_code.grpc import auth_sms_code_pb2 as infrastructure_dot_auth_dot_sms__code_dot_grpc_dot_auth__sms__code__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/auth/twofactor/grpc/auth_twofactor_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/auth/twofactor/grpc/auth_twofactor_pb2_grpc.py
index 67fa01d..147f906 100644
--- a/src/django_ninja_starter/template/src/infrastructure/auth/twofactor/grpc/auth_twofactor_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/auth/twofactor/grpc/auth_twofactor_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.auth.twofactor.grpc import auth_twofactor_pb2 as infrastructure_dot_auth_dot_twofactor_dot_grpc_dot_auth__twofactor__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/common/grpc/common_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/common/grpc/common_pb2_grpc.py
index 76e7392..820c2f3 100644
--- a/src/django_ninja_starter/template/src/infrastructure/common/grpc/common_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/common/grpc/common_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.common.grpc import common_pb2 as infrastructure_dot_common_dot_grpc_dot_common__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
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..fc4fda2 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,19 @@
# 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",
+ "files",
+ "flags",
+ "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/django_ninja_starter/template/src/infrastructure/oauth/apple/grpc/oauth_apple_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/oauth/apple/grpc/oauth_apple_pb2_grpc.py
index 56e06fa..73e9af3 100644
--- a/src/django_ninja_starter/template/src/infrastructure/oauth/apple/grpc/oauth_apple_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/oauth/apple/grpc/oauth_apple_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.oauth.apple.grpc import oauth_apple_pb2 as infrastructure_dot_oauth_dot_apple_dot_grpc_dot_oauth__apple__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/oauth/github/grpc/oauth_github_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/oauth/github/grpc/oauth_github_pb2_grpc.py
index 50b4994..7669bd0 100644
--- a/src/django_ninja_starter/template/src/infrastructure/oauth/github/grpc/oauth_github_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/oauth/github/grpc/oauth_github_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.oauth.github.grpc import oauth_github_pb2 as infrastructure_dot_oauth_dot_github_dot_grpc_dot_oauth__github__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/oauth/google/grpc/oauth_google_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/oauth/google/grpc/oauth_google_pb2_grpc.py
index b002415..632c49e 100644
--- a/src/django_ninja_starter/template/src/infrastructure/oauth/google/grpc/oauth_google_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/oauth/google/grpc/oauth_google_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.oauth.google.grpc import oauth_google_pb2 as infrastructure_dot_oauth_dot_google_dot_grpc_dot_oauth__google__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/oauth/microsoft/grpc/oauth_microsoft_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/oauth/microsoft/grpc/oauth_microsoft_pb2_grpc.py
index 35166ae..f4a4af9 100644
--- a/src/django_ninja_starter/template/src/infrastructure/oauth/microsoft/grpc/oauth_microsoft_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/oauth/microsoft/grpc/oauth_microsoft_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.oauth.microsoft.grpc import oauth_microsoft_pb2 as infrastructure_dot_oauth_dot_microsoft_dot_grpc_dot_oauth__microsoft__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/oauth/rotation/grpc/oauth_rotation_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/oauth/rotation/grpc/oauth_rotation_pb2_grpc.py
index 4285d71..ea07719 100644
--- a/src/django_ninja_starter/template/src/infrastructure/oauth/rotation/grpc/oauth_rotation_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/oauth/rotation/grpc/oauth_rotation_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.oauth.rotation.grpc import oauth_rotation_pb2 as infrastructure_dot_oauth_dot_rotation_dot_grpc_dot_oauth__rotation__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/oauth/session/grpc/oauth_session_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/oauth/session/grpc/oauth_session_pb2_grpc.py
index 5b1fc37..777ad46 100644
--- a/src/django_ninja_starter/template/src/infrastructure/oauth/session/grpc/oauth_session_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/oauth/session/grpc/oauth_session_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.oauth.session.grpc import oauth_session_pb2 as infrastructure_dot_oauth_dot_session_dot_grpc_dot_oauth__session__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/django_ninja_starter/template/src/infrastructure/oauth/sliding/grpc/oauth_sliding_pb2_grpc.py b/src/django_ninja_starter/template/src/infrastructure/oauth/sliding/grpc/oauth_sliding_pb2_grpc.py
index d34fccb..327939d 100644
--- a/src/django_ninja_starter/template/src/infrastructure/oauth/sliding/grpc/oauth_sliding_pb2_grpc.py
+++ b/src/django_ninja_starter/template/src/infrastructure/oauth/sliding/grpc/oauth_sliding_pb2_grpc.py
@@ -6,7 +6,7 @@
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from infrastructure.oauth.sliding.grpc import oauth_sliding_pb2 as infrastructure_dot_oauth_dot_sliding_dot_grpc_dot_oauth__sliding__pb2
-GRPC_GENERATED_VERSION = '1.83.1'
+GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
diff --git a/src/infrastructure/common/management/commands/authdocs.py b/src/infrastructure/common/management/commands/authdocs.py
index b1f0e18..fc4fda2 100644
--- a/src/infrastructure/common/management/commands/authdocs.py
+++ b/src/infrastructure/common/management/commands/authdocs.py
@@ -43,7 +43,19 @@
# 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",
+ "files",
+ "flags",
+ "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..0472289 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", "flags", "notifications", "shop", "support", "wallet"]
TOKEN_MODES = ["sliding", "session", "rotation"]
PROVIDERS = {
"google": {
@@ -418,6 +418,8 @@ def _admin_page(environment: dict[str, str], database: Path) -> dict[str, list[s
ADMIN_SECTIONS = {
"cms": "Content",
"club": "Club",
+ "files": "Files",
+ "flags": None,
"notifications": "Notifications",
"shop": "Shop",
"support": "Support",
@@ -431,7 +433,7 @@ def test_the_admin_front_page_renders_with_nothing_enabled(tmp_path: Path) -> No
drawn = _admin_page({}, tmp_path / "db.sqlite3")
assert "Overview" in drawn["groups"]
- for section in ADMIN_SECTIONS.values():
+ for section in filter(None, ADMIN_SECTIONS.values()):
assert section not in drawn["sections"], section
@@ -445,7 +447,8 @@ def test_a_feature_app_brings_its_own_admin_and_only_its_own(app: str, tmp_path:
"""
drawn = _admin_page({_enabled(app): "true"}, tmp_path / "db.sqlite3")
- assert ADMIN_SECTIONS[app] in drawn["sections"], f"enabling {app} contributed no section"
+ if ADMIN_SECTIONS[app] is not None:
+ assert ADMIN_SECTIONS[app] in drawn["sections"], f"enabling {app} contributed no section"
for other, section in ADMIN_SECTIONS.items():
- if other != app:
+ if other != app and section is not None:
assert section not in drawn["sections"], f"enabling {app} drew {other}'s section"
diff --git a/tests/test_env_samples.py b/tests/test_env_samples.py
index 31cfc04..596c891 100644
--- a/tests/test_env_samples.py
+++ b/tests/test_env_samples.py
@@ -29,7 +29,17 @@
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",
+ "FILES",
+ "FLAGS",
+)
def flag(sample: Path, app: str) -> str | None:
diff --git a/tests/test_example_project.py b/tests/test_example_project.py
index 9cbda26..efe8c60 100644
--- a/tests/test_example_project.py
+++ b/tests/test_example_project.py
@@ -36,6 +36,7 @@
"support",
"wallet",
"club",
+ "flags",
"socket",
)
@@ -79,6 +80,7 @@ def test_the_example_project_has_every_app_on(example_project: Path) -> None:
assert reported["support"] == "on"
assert reported["wallet"] == "on"
assert reported["club"] == "on"
+ assert reported["flags"] == "on"
assert reported["socket"] == "/ws/notifications,/ws/support"
@@ -98,6 +100,7 @@ def test_the_example_project_has_every_app_on(example_project: Path) -> None:
print("support=" + ("on" if settings.SUPPORT_ENABLED else "off"))
print("wallet=" + ("on" if settings.WALLET_ENABLED else "off"))
print("club=" + ("on" if settings.CLUB_ENABLED else "off"))
+print("flags=" + ("on" if settings.FLAGS_ENABLED else "off"))
print("socket=" + ",".join(path for path, _ in websocket_routes()))
"""
@@ -220,6 +223,9 @@ def test_the_walkthrough_visits_every_app(example_project: Path) -> None:
club = re.search(r"toured (\d+) of (\d+) club endpoints", result.stdout)
assert club is not None, "the club section printed no coverage line"
assert club.group(1) == club.group(2), result.stdout
+ flags = re.search(r"toured (\d+) of (\d+) flags endpoints", result.stdout)
+ assert flags is not None, "the flags section printed no coverage line"
+ assert flags.group(1) == flags.group(2), result.stdout
assert "admin pages opened" in result.stdout, "the admin was not toured"