ContentsClose contents
Pre-release
Chapter 52 · Webhooks and reliable external integrationsCHAPTER 52

Complete six-part pre-release for review. One development package: standardwebhooks, for the receiver and tests. A new app, integrations. Admin edits now go through Event.edit() (a declared change to Chapter 33's admin). Checked end to end with a real receiver on the same computer; a partner over TLS was not.

Working towards: API and integrations (Chapter 54). Another program can list published events through an API and receive signed notifications when an event changes. All milestones

CHAPTER FIFTY-TWO

Webhooks and reliable external integrations

Stage 6: APIs and real-time updates (Chapters 47 to 54)

Prerequisites: Chapters 9 to 51, including the Chapter 51 project with its 734 passing tests, Chapter 44’s background tasks and delivery rows, the model methods of Chapters 48 and 49 (edit(), publish_by(), cancel_by()), the public event as the API shows it, and the httpx client of Chapter 51

What you’ll build: an integrations app that tells partners’ servers when an event is published, changed, or cancelled: endpoints managed by administrators on a Webhooks page, each message signed as Standard Webhooks describes, queued in the change’s transaction and sent after commit, retried for about 17 hours, and sent only to public addresses checked at save and before every send; admin edits that now go through Event.edit(); and a partner’s receiver that verifies each message with the specification’s own library

Why This Matters

The library’s site copies Otahque’s events every night, as Chapter 51 showed. On Thursday at noon Raj cancels the Python clinic. Until midnight, the library’s calendar still shows it, and three people turn up at a locked room. Asking every five minutes would shorten the gap and multiply the traffic by three hundred. What the library wants is to be told.

A webhook tells it: when something happens, Otahque sends an HTTP request to an address the partner chose. It sounds like one line of code, httpx.post(url, json=event), and every part of that line goes wrong in production. The partner’s server is down for an hour, so the message must be sent again, without sending it twice as two different changes. Someone could forge a message that cancels an event, so the partner must be able to prove it came from Otahque. And the address is typed into Otahque by a person, so it could point at Otahque’s own database, its cloud’s secrets, or an admin page on localhost, and Otahque would call it obediently.

This chapter builds webhooks that survive all of that, with one more change that closes a door left open since Chapter 33: an administrator’s edit in the admin now goes through the same Event.edit() as every other edit, so it is recorded, it promotes waiting members, it emails holders, and it tells partners.

By the end of the chapter, you will be able to:

  • explain what a webhook is, and what can go wrong with one: late, twice, forged, or never;
  • sign a message with HMAC as Standard Webhooks describes, and verify it on the other side;
  • queue messages in the change’s transaction and send them after commit, with retries and a final state;
  • stop a webhook from becoming a way into your own network (SSRF), at save and before every send;
  • write a receiver that refuses forged and replayed messages and ignores duplicates and stale versions;
  • rotate a secret without losing a message.

Out of scope: receiving other services’ webhooks into Otahque (the same checks, reversed, come back for billing in Chapter 69), an outbound proxy that only lets public addresses out (Chapter 63), encrypting endpoint secrets in the database (an open question for Chapter 59), and a Send test button on the Webhooks page, which Chapter 53 adds as an async view that waits for the partner's answer.

PAGE 001

What You Need to Know

Polling and pushing

Until now partners poll: they ask on a timer whether anything changed. Polling is simple and safe, and the answer is mostly “no”. A webhook turns it around: the server pushes a message to the partner when something changes. The partner registers an address (an endpoint), and the server sends a POST to it for each event it cares about. The message is small and arrives within seconds. In exchange, the sender takes on four problems that polling never had: the message may be late, duplicated, forged, or lost.

New Concept: a webhook

What problem exists? A partner needs to know about a change soon after it happens, without asking all day.

What did people do before? Poll on a timer, or exchange files overnight; both are late by design.

What is it? A webhook is an HTTP request a service sends to an address someone registered with it, when something happens. The body describes what happened; headers prove who sent it. The receiver answers 2xx to say “got it”; anything else means “send it again later”.

Why use it? Changes arrive in seconds, and nobody asks when nothing has changed.

Now let’s use it. Steps 3 to 7 build Otahque’s sending side; Step 10 writes a partner’s receiving side.

One message, from the change that causes it to the partner’s answer, is traced in Figure 52.1.

Six numbered cards in order. 1, a change commits: edit(), publish_by(), or cancel_by() writes one WebhookDelivery per endpoint in the change’s own transaction. 2, after commit a task is enqueued; a rolled-back change or a dry run sends nothing. 3, the address is checked again: the name is resolved, any inner address refused, and the connection made to the address checked. 4, sign and send: webhook-id, webhook-timestamp, and webhook-signature headers, the body exactly as stored, 15 seconds at most. 5, a 2xx answer: sent, and the endpoint’s failure count goes back to 0. 6, anything else: retry after 5 seconds, 5 and 30 minutes, then 2, 5, and 10 hours; 410 stops the endpoint; after seven failed tries the message is failed.
Figure 52.1 — A webhook’s journey.

One format, not our own

Every service that sends webhooks once invented its own headers and signature format, so every receiver needed custom code. Standard Webhooks is an open specification that fixes one: three headers, webhook-id, webhook-timestamp, and webhook-signature, and a body shaped as {"type": ..., "timestamp": ..., "data": {...}}. It publishes libraries in several languages that verify those headers. Otahque follows it (D52.3): the partner’s developer can use the library instead of reading Otahque’s code.

Under the Hood: what an HMAC signature proves

Otahque and the partner share a secret, a random key that only the two of them hold. To sign, Otahque joins the message id, the timestamp, and the body exactly as it will be sent, id.timestamp.body, and computes an HMAC, a keyed hash, with SHA-256 and the secret. The result, in base64 after v1,, goes in webhook-signature. The receiver does the same computation on the bytes it received. If the results match, the message was made by someone holding the secret and was not changed on the way: one changed byte gives a completely different HMAC. Signing the id and the timestamp too means an attacker who records a genuine message cannot send it again later as new: the receiver refuses a timestamp more than five minutes away. HMAC proves who and what, not when it arrived or whether it was seen before; those are the receiver’s checks of Figure 52.2.

Otahque signs with its own few lines of Python’s hmac module, so every step is visible; the tests, and the partner’s receiver in Step 10, verify with the specification’s library, standardwebhooks 1.3.0 (N52.6). When the library accepts what Otahque signed, the two agree.

What a message carries

Each message carries one of three types, event.published, event.changed, or event.cancelled, and in data, the event exactly as GET /api/v1/events/{id}/ shows it, plus its version (D52.4). A partner can update its calendar from the message alone. Messages can arrive out of order: a retry from yesterday may land after today’s change. So the partner keeps the highest version it has seen for each event and ignores anything older. The public API itself stays without version; it is a field for this ordering only. Drafts are never sent, and nothing about members ever is.

Retries, and at least once

A partner’s server may be down, slow, or redeploying. Otahque keeps each message as a row, WebhookDelivery, and tries again on a schedule close to the specification’s (N52.7): at once, then after 5 seconds, 5 and 30 minutes, and 2, 5, and 10 hours, about 17 hours in all. Only a 2xx answer counts as delivered. A redirect counts as a failure and is never followed. 410 Gone means the partner removed the address, and the endpoint is turned off; so is one whose last 20 messages all failed. A Retry-After header is honoured.

Retrying has a consequence. If a try reaches the partner, who applies it, but the answer is lost on the way back, Otahque sees a timeout and sends it again. So delivery is at least once: every retry carries the same webhook-id, and a careful receiver applies each id once (Figure 52.2).

Five numbered cards in order, the receiver’s checks. 1, signature: the HMAC-SHA256 of id.timestamp.body with the secret; any of the signatures may match; otherwise 400. 2, timestamp: within five minutes of now, so an old message replayed is refused. 3, webhook-id: seen before means answer 200 and do nothing again. 4, version: not newer than the one kept for this event means answer 200 and ignore it. 5, apply it: the newest event, once.
Figure 52.2 — What a receiver checks.

When the address is the attack

New Concept: server-side request forgery (SSRF)

What problem exists? A feature that fetches or posts to an address someone typed makes the server send a request on that person’s behalf, from inside its own network, where it can reach things the person cannot.

What did people do before? Accept any address, perhaps refusing the word localhost, which is easy to get around.

What is it? Server-side request forgery is making a server send a request it should not. An endpoint of http://169.254.169.254/ would ask a cloud machine for its own credentials; http://127.0.0.1:5432/ would poke its database; a name that resolves to 10.0.0.5 reaches the private network. OWASP keeps a cheat sheet on preventing it, which this chapter follows.

Why does it matter here? Webhook addresses are exactly such addresses, typed by a person, called by Otahque.

Now let’s use it. Step 5 writes the checks of Figure 52.3.

The checks (D52.5): https:// only outside development; no name or password in the address; resolve the name and refuse it if any address it gives is private, loopback, link-local, shared, reserved, multicast, or an IPv4 address hidden in IPv6; then connect to the very address that was checked, keeping the name for the Host header and for TLS, so the certificate is still checked against it. A name can be pointed elsewhere after it was checked (DNS rebinding), so the check runs at save and again before every send, and redirects are never followed. While developing, loopback addresses are allowed, so a receiver on your own computer can be tried; nothing else is.

Top, a zone titled refused, at save and before each send, with four red cards: 127.0.0.1 and ::1, this server; 10.0.0.5 and 192.168.x, the private network; 169.254.169.254, a cloud’s metadata; ::ffff:10.0.0.1, an inner address in disguise. Below, a green card: partner.example resolves to a public address; connect to that address, with the name kept in Host and TLS, and no redirects. An arrow leads to a grey card: later, an outbound proxy in Chapter 63, so only public addresses leave the network whatever the code does.
Figure 52.3 — Where a typed address could lead, and where it is stopped.

In practice: a partner’s calendar

Situation. The library adds an endpoint for event.published and event.cancelled only; it does not care about edits.

Application. Raj cancels at noon; the message is sent within seconds of the commit; the library’s receiver checks the signature, finds the event by id, and marks it cancelled. If its server is restarting, the message arrives five seconds later instead.

Consideration. The library still runs its nightly sync from Chapter 51, less often: a webhook is a fast path, not the only one, because a message that failed for 17 hours is gone. Its receiver must answer within 15 seconds, so it should store the message and do slow work later.

Secrets: shown once, rotated with overlap

An endpoint’s secret looks like whsec_ and 44 characters of base64. Unlike Chapter 50’s tokens, it cannot be stored as a hash, because signing needs the key itself; it is kept as written, so anyone who can read the table could sign as Otahque until the secret is rotated. Chapter 59, which encrypts two-factor secrets in the database, encrypts endpoint secrets too. The Webhooks page shows it once, when the endpoint is added or its secret rotated. Rotation makes a new secret while the old one keeps signing for 24 hours, so both signatures travel in one header, separated by a space, and the partner can switch at their own pace without refusing a message.

PAGE 002

How We Build It

Start from Chapter 51, in the folder containing manage.py, with Otahque on PostgreSQL 18, 734 passing tests, and the work committed (the last commit is “Page, filter, and limit the API; add docs”). One development package is added, standardwebhooks 1.3.0, for the receiver and the tests. A new app, integrations, holds the endpoint and delivery models, signing, the address checks, the task that sends, the Webhooks page, and six test modules. Three migrations are new: two in integrations (one written by hand, granting the page to Administrators) and one in audit. The events models and admin, the settings, the project’s addresses, the menu, the roles, the audit actions, the stylesheet, the contract, two design notes, and one earlier test module change; ADR-009, a shared status badge, and examples/receiver.py are new. The visible result: administrators add a partner’s endpoint and copy its secret once; a publish or a cancel reaches the partner within seconds, signed; and each endpoint’s page lists its recent messages with their status in words. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

The webhook most tutorials start from is one line in a view:

httpx.post(partner_url, json=event_data(event))

Run inside the request, it makes Raj wait for the library’s server, and if that server is down, the message is simply lost. Run inside the transaction, it can announce a change that then rolls back. Nothing signs it, so anyone who learns the address can send fake cancellations. json= lets httpx choose the exact bytes, so a signature computed elsewhere may not match. And partner_url is whatever someone typed, so Otahque will call its own database port if asked. This illustration is not added to the project.

The Django Way

The Django Way builds on what Otahque already has: a row per message written in the change’s transaction, as Chapter 44’s emails are; a task, enqueued after commit, that sends it; the model methods of Chapters 48 and 49 as the one place every change goes through; and a page with the same access rules as the other administrators’ pages.

Step 1: Check the starting point

uv run python manage.py test --parallel
Found 734 test(s).
Creating test database for alias 'default'...
...
Ran 734 tests in ...s

OK
git status --short
git log --oneline -1
... Page, filter, and limit the API; add docs

Step 2: The receiver’s library, for development

uv add --dev standardwebhooks==1.3.0
Resolved 63 packages in ...
Installed 1 package in ...
 + standardwebhooks==1.3.0

--dev puts it in the development group: Otahque itself never needs it, only its tests and the example receiver.

Step 3: The app and its models

uv run python manage.py startapp integrations

As for the API in Chapter 47, the tests go in a package. Replace the file startapp made:

Remove-Item integrations\tests.py
New-Item -ItemType Directory integrations\tests | Out-Null
New-Item integrations\tests\__init__.py | Out-Null
rm integrations/tests.py
mkdir integrations/tests
touch integrations/tests/__init__.py

Give integrations/apps.py its docstrings:

"""Configuration Django reads to load the integrations app."""
from django.apps import AppConfig


class IntegrationsConfig(AppConfig):
    """Webhooks to partners' servers (Chapter 52)."""

    name = 'integrations'

and add it to INSTALLED_APPS in config/settings.py, which now ends:

    'drf_spectacular_sidecar',
    # Chapter 52: webhooks to partners' servers.
    'integrations.apps.IntegrationsConfig',

integrations/models.py holds three parts. Its top: the secrets, the message ids, and the three kinds of message:

"""Webhooks: partners' addresses, and each message sent."""
import base64
import secrets
import uuid
from datetime import timedelta

from django.conf import settings
from django.db import models
from django.utils import timezone

# How long the old secret still signs after a rotation, so
# a partner can change secrets without missing a message.
OVERLAP = timedelta(hours=24)
# An endpoint is turned off after this many messages in a
# row have failed every attempt.
MOST_FAILURES = 20


def new_secret():
    """Return a secret as Standard Webhooks writes them.

    whsec_, then 32 random bytes in base64: the key itself,
    not a hash of it, because signing needs the key.
    """
    key = base64.b64encode(secrets.token_bytes(32)).decode()
    return f'whsec_{key}'


def new_message_id():
    """Return a message id, the same for every attempt."""
    return f'msg_{uuid.uuid4().hex}'


class Kind(models.TextChoices):
    """What happened to an event, as a message's type."""

    PUBLISHED = 'event.published', 'Published'
    CHANGED = 'event.changed', 'Changed'
    CANCELLED = 'event.cancelled', 'Cancelled'

after two blank lines, the endpoint:

class WebhookEndpoint(models.Model):
    """A partner's address, told when events change.

    Administrators add, rotate, and turn endpoints off on
    the Webhooks page. The secret is kept as written, since
    every message is signed with it.
    """

    url = models.URLField(max_length=500)
    description = models.CharField(max_length=100)
    kinds = models.JSONField(default=list)
    secret = models.CharField(max_length=60,
                              default=new_secret)
    previous_secret = models.CharField(max_length=60,
                                       blank=True)
    previous_until = models.DateTimeField(null=True,
                                          blank=True)
    active = models.BooleanField(default=True)
    failures_in_a_row = models.PositiveIntegerField(default=0)
    stopped_because = models.CharField(max_length=200,
                                       blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
        related_name='+',
    )
    created_at = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['description', 'id']
        permissions = [
            ('manage_webhooks', 'Manage webhook endpoints'),
        ]

    def __str__(self):
        return self.description

    def wants(self, kind):
        """Return whether this endpoint hears about kind."""
        return self.active and kind in self.kinds

    def secrets_now(self):
        """Return the secrets to sign with: new, then old."""
        found = [self.secret]
        if (self.previous_secret and self.previous_until
                and self.previous_until > timezone.now()):
            found.append(self.previous_secret)
        return found

    def rotate(self):
        """Make a new secret; the old one signs for a day."""
        self.previous_secret = self.secret
        self.previous_until = timezone.now() + OVERLAP
        self.secret = new_secret()
        self.save(update_fields=['secret', 'previous_secret',
                                 'previous_until'])

    def stop(self, because):
        """Turn the endpoint off, saying why."""
        self.active = False
        self.stopped_because = because
        self.save(update_fields=['active', 'stopped_because'])

    def start(self):
        """Turn the endpoint on again, with a clean count."""
        self.active = True
        self.stopped_because = ''
        self.failures_in_a_row = 0
        self.save(update_fields=['active', 'stopped_because',
                                 'failures_in_a_row'])

and after two more, one delivery:

class WebhookDelivery(models.Model):
    """One message to one endpoint, and how sending went.

    The body is kept exactly as signed and sent, so every
    attempt sends the same bytes under the same id.
    """

    class Status(models.TextChoices):
        """Where the message is."""

        QUEUED = 'queued', 'Queued'
        SENT = 'sent', 'Sent'
        FAILED = 'failed', 'Failed'
        SKIPPED = 'skipped', 'Skipped'

    endpoint = models.ForeignKey(
        WebhookEndpoint, on_delete=models.CASCADE,
        related_name='deliveries',
    )
    message_id = models.CharField(
        max_length=40, unique=True, default=new_message_id,
    )
    kind = models.CharField(max_length=30, choices=Kind)
    body = models.TextField()
    status = models.CharField(max_length=10, choices=Status,
                              default=Status.QUEUED)
    attempts = models.PositiveIntegerField(default=0)
    due_at = models.DateTimeField(default=timezone.now)
    last_code = models.PositiveIntegerField(null=True,
                                            blank=True)
    last_error = models.CharField(max_length=200, blank=True)
    created_at = models.DateTimeField(default=timezone.now)
    sent_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-created_at', '-id']
        verbose_name_plural = 'webhook deliveries'

    def __str__(self):
        return f'{self.kind} to {self.endpoint}'

kinds is a list in a JSONField, filtered in Python by wants(): SQLite cannot search inside JSON lists the way PostgreSQL can, and an Otahque has a handful of endpoints. The body is stored as text, exactly as it will be signed, so a retry tomorrow sends the same bytes under the same message_id. manage_webhooks is the permission the page will check, in Step 9.

uv run python manage.py makemigrations integrations
uv run python manage.py migrate
Migrations for 'integrations':
  integrations\migrations\0001_initial.py
    + Create model WebhookEndpoint
    + Create model WebhookDelivery
Operations to perform:
  Apply all migrations: account, accounts, admin, api, audit,
    auth, contenttypes, django_tasks_database, events,
    integrations, mfa, registrations, sessions, socialaccount
Running migrations:
  Applying integrations.0001_initial... OK

Step 4: Signing

The tests come first, with a helper module the others share. Create integrations/tests/helpers.py:

"""What the integrations tests share (Chapter 52).

Not a test module: its name does not start with "test".
"""
import ipaddress
from unittest import mock

from config.helpers import in_group
from integrations.models import Kind, WebhookEndpoint

# A public address, as a partner's name might resolve to.
PUBLIC = ipaddress.ip_address('93.184.215.14')


def resolving_to(*ips):
    """Patch name lookups to answer ips, in a with block."""
    return mock.patch(
        'integrations.addresses.resolve',
        return_value=[ipaddress.ip_address(ip) for ip in ips])


def endpoint(**changes):
    """Save the library's endpoint, wanting every kind."""
    admin = in_group(f'admin{WebhookEndpoint.objects.count()}'
                     '@example.org', 'Administrators')
    fields = {'url': 'https://library.example/hooks/',
              'description': 'Library', 'kinds': Kind.values,
              'created_by': admin}
    return WebhookEndpoint.objects.create(**(fields | changes))

resolving_to() replaces name lookups during a test, so no test touches the real DNS. Then integrations/tests/test_signing.py:

"""Otahque signs as Standard Webhooks says (Chapter 52).

Otahque signs with its own few lines of hmac; the checks
use the specification's published library, so a pass means
the two agree.
"""
import time

from django.test import TestCase
from standardwebhooks.webhooks import (
    Webhook, WebhookVerificationError,
)

from integrations import signing
from integrations.models import WebhookDelivery
from integrations.tests.helpers import endpoint


class SigningTests(TestCase):
    """Signatures a receiver's library accepts, or not."""

    def setUp(self):
        self.hook = endpoint()
        self.delivery = WebhookDelivery.objects.create(
            endpoint=self.hook, kind='event.published',
            body='{"type":"event.published"}')

    def sent(self, timestamp=None):
        """Return the headers of an attempt made now."""
        stamp = timestamp or int(time.time())
        return signing.headers(self.hook, self.delivery, stamp)

    def test_the_library_accepts_it(self):
        message = Webhook(self.hook.secret).verify(
            self.delivery.body, self.sent())
        self.assertEqual(message['type'], 'event.published')

    def test_a_changed_body_is_refused(self):
        with self.assertRaises(WebhookVerificationError):
            Webhook(self.hook.secret).verify(
                '{"type":"event.cancelled"}', self.sent())

    def test_an_old_message_is_refused(self):
        ten_minutes_ago = int(time.time()) - 600
        with self.assertRaises(WebhookVerificationError):
            Webhook(self.hook.secret).verify(
                self.delivery.body, self.sent(ten_minutes_ago))

    def test_both_secrets_sign_during_a_rotation(self):
        old = self.hook.secret
        self.hook.rotate()
        headers = self.sent()
        self.assertEqual(
            len(headers['webhook-signature'].split()), 2)
        for secret in (old, self.hook.secret):
            Webhook(secret).verify(self.delivery.body, headers)

    def test_every_attempt_has_the_same_id(self):
        first = self.sent()
        later = self.sent(int(time.time()) + 60)
        self.assertEqual(first['webhook-id'],
                         later['webhook-id'])
        self.assertNotEqual(first['webhook-signature'],
                            later['webhook-signature'])

Every check is made by the standardwebhooks library, not by Otahque’s code.

uv run python manage.py test integrations.tests.test_signing
Found 1 test(s).
ERROR: test_signing
    (unittest.loader._FailedTest.test_signing)
ImportError: Failed to import test module: test_signing
ImportError: cannot import name 'signing' from 'integrations'
    (...\integrations\__init__.py)
Ran 1 test in ...s

FAILED (errors=1)

Create integrations/signing.py:

"""Signing webhooks, as Standard Webhooks v1 describes.

The receiver recomputes the signature with the shared
secret; a match proves the message came from Otahque and
was not changed. The id and time are signed with the body,
so an old message cannot be sent again as new.
"""
import base64
import hashlib
import hmac


def sign(secret, message_id, timestamp, body):
    """Return one signature: v1, then HMAC-SHA256 in base64.

    What is signed is "id.timestamp.body", the body exactly
    as sent, byte for byte.
    """
    key = base64.b64decode(secret.removeprefix('whsec_'))
    signed = f'{message_id}.{timestamp}.{body}'.encode()
    digest = hmac.new(key, signed, hashlib.sha256).digest()
    return 'v1,' + base64.b64encode(digest).decode()


def headers(endpoint, delivery, timestamp):
    """Return the headers for one attempt at a delivery.

    During a rotation both secrets sign, separated by a
    space, so receivers with either secret accept it.
    """
    signatures = [sign(secret, delivery.message_id,
                       timestamp, delivery.body)
                  for secret in endpoint.secrets_now()]
    return {
        'webhook-id': delivery.message_id,
        'webhook-timestamp': str(timestamp),
        'webhook-signature': ' '.join(signatures),
        'content-type': 'application/json',
        'user-agent': 'Otahque-Webhooks/1.0',
    }

The secret’s base64 is decoded to the key’s bytes before use, as the specification says; body is the stored text, never re-encoded from data.

uv run python manage.py test integrations.tests.test_signing
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Step 5: Which addresses may be called

The tests, in integrations/tests/test_addresses.py:

"""Which addresses webhooks may go to (Chapter 52)."""
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase, override_settings

from integrations import addresses
from integrations.tests.helpers import resolving_to

HOOK = 'https://partner.example/hooks/'


class AddressTests(SimpleTestCase):
    """Public addresses only, checked after resolving."""

    def test_a_public_address_is_used_by_number(self):
        with resolving_to('93.184.215.14'):
            target = addresses.check(HOOK)
        self.assertEqual(target.url,
                         'https://93.184.215.14:443/hooks/')
        self.assertEqual((target.host, target.netloc),
                         ('partner.example', 'partner.example'))

    def test_inner_addresses_are_refused(self):
        for ip in ('127.0.0.1', '10.0.0.5', '192.168.1.2',
                   '169.254.169.254', '100.64.0.1', '::1',
                   'fc00::1', '::ffff:10.0.0.1', '224.0.0.1',
                   '0.0.0.0'):
            with self.subTest(ip), resolving_to(ip):
                with self.assertRaises(ValidationError):
                    addresses.check(HOOK)

    def test_one_inner_address_among_public_ones(self):
        with resolving_to('93.184.215.14', '10.0.0.5'):
            with self.assertRaises(ValidationError):
                addresses.check(HOOK)

    def test_http_and_passwords_are_refused(self):
        for url in ('http://partner.example/hooks/',
                    'https://me:pw@partner.example/hooks/',
                    'ftp://partner.example/'):
            with self.subTest(url):
                with resolving_to('93.184.215.14'):
                    with self.assertRaises(ValidationError):
                        addresses.check(url)

    @override_settings(DEBUG=True)
    def test_developing_allows_this_computer_only(self):
        with resolving_to('127.0.0.1'):
            target = addresses.check('http://localhost:8001/')
        self.assertEqual(target.url, 'http://127.0.0.1:8001/')
        with resolving_to('10.0.0.5'):
            with self.assertRaises(ValidationError):
                addresses.check('http://intranet:8001/')

test_inner_addresses_are_refused lists one address of each kind Figure 52.3 shows, and a few more: shared address space (100.64.0.1), IPv6 unique-local (fc00::1), multicast, and 0.0.0.0.

uv run python manage.py test integrations.tests.test_addresses
Found 1 test(s).
ERROR: test_addresses
    (unittest.loader._FailedTest.test_addresses)
ImportError: Failed to import test module: test_addresses
ImportError: cannot import name 'addresses' from
    'integrations' (...\integrations\__init__.py)
Ran 1 test in ...s

FAILED (errors=1)

Create integrations/addresses.py:

"""Which addresses Otahque may send webhooks to (Chapter 52).

A webhook makes Otahque's server call an address someone
typed in. Unchecked, that someone could point it at the
server's own network: a database, a cloud's metadata
service, an admin page on localhost. This is server-side
request forgery (SSRF). Every address is checked when it
is saved and again before each send, after the name is
resolved, and the send connects to the address checked.
"""
import ipaddress
import socket
from dataclasses import dataclass
from urllib.parse import urlsplit

from django.conf import settings
from django.core.exceptions import ValidationError


@dataclass
class Target:
    """Where to connect, and the name to say we called.

    url has the checked address in place of the name; the
    name goes in the Host header (netloc) and in TLS, so the
    certificate is still checked against it.
    """

    url: str
    host: str
    netloc: str


def resolve(host, port):
    """Return every address host has, as ip_address objects."""
    found = socket.getaddrinfo(host, port,
                               type=socket.SOCK_STREAM)
    return [ipaddress.ip_address(info[4][0]) for info in found]


def allowed(ip):
    """Return whether Otahque may connect to ip.

    Only public unicast addresses: no private, loopback,
    link-local, shared, reserved, or multicast ones. An
    IPv6 address that carries an IPv4 one is judged by it.
    While developing, loopback is allowed, for a receiver
    on this computer.
    """
    if ip.version == 6 and ip.ipv4_mapped:
        ip = ip.ipv4_mapped
    if settings.DEBUG and ip.is_loopback:
        return True
    return ip.is_global and not ip.is_multicast


def check(url):
    """Return the Target for url, or raise ValidationError."""
    parts = urlsplit(url)
    schemes = ['https'] + (['http'] if settings.DEBUG else [])
    if parts.scheme not in schemes:
        raise ValidationError('Use an https:// address.')
    if parts.username or parts.password:
        raise ValidationError(
            'Put no name or password in the address.')
    host = parts.hostname
    if not host:
        raise ValidationError('The address has no host.')
    port = parts.port or (443 if parts.scheme == 'https'
                          else 80)
    try:
        ips = resolve(host, port)
    except (OSError, UnicodeError):
        raise ValidationError(
            f'{host} could not be found.') from None
    refused = [str(ip) for ip in ips if not allowed(ip)]
    if refused or not ips:
        raise ValidationError(
            f'{host} leads to an address Otahque may not '
            f'call: {", ".join(refused)}.')
    ip = ips[0]
    shown = f'[{ip}]' if ip.version == 6 else str(ip)
    to_ip = parts._replace(netloc=f'{shown}:{port}')
    return Target(to_ip.geturl(), host, parts.netloc)

ip.is_global is Python’s own judgement from the IANA registries of special addresses, so the code lists no ranges by hand. Every address a name resolves to must pass, not just the first: a name with one public and one private address would otherwise be checked on one and connected on the other. Target.url replaces the name with the checked address, so the connection cannot be redirected by a second lookup.

uv run python manage.py test integrations.tests.test_addresses
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Common Error: checking the address only when it is saved

A partner’s name can resolve to a public address on Monday, when the endpoint is saved, and to 10.0.0.5 on Tuesday, whether by mistake or by design. A check at save alone then protects nothing. Check before every send, connect to the address you checked, and never follow a redirect, which would be a new, unchecked address.

Step 6: Queue after commit, and send

The tests, in integrations/tests/test_messages.py; Step 8 adds one more class at the end:

"""Which changes queue a webhook, and what it says (52)."""
import json

from django.test import TestCase, override_settings

from api.serializers import EventSerializer
from api.tests.test_mine import ready
from config.helpers import admin_url, event_form, in_group
from events.models import Event
from events.tests.test_tasks import QUEUE_ONLY, enqueued
from integrations.models import WebhookDelivery
from integrations.tests.helpers import endpoint


def retitle(title):
    """Return an edit's change(): set the title."""
    def change(locked):
        """Set the new title on the locked copy."""
        locked.title = title
        return []
    return change


def bodies():
    """Return every queued message's body, oldest first."""
    return [json.loads(d.body) for d in
            WebhookDelivery.objects.order_by('id')]


@override_settings(TASKS=QUEUE_ONLY)
class MessageTests(TestCase):
    """Publish, change, and cancel each queue one message."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', 'Organizers')

    def setUp(self):
        self.hook = endpoint()
        self.event = ready(title='Clinic')
        self.event.add_organizer(self.sam)

    def test_publish_change_and_cancel(self):
        event = self.event
        event.publish_by(self.sam)
        event.edit(self.sam, event.version, retitle('Clinic 2'))
        event.refresh_from_db()
        event.cancel_by(self.sam)
        self.assertEqual([b['type'] for b in bodies()], [
            'event.published', 'event.changed',
            'event.cancelled'])
        versions = [b['data']['version'] for b in bodies()]
        self.assertEqual(versions, sorted(set(versions)))

    def test_the_data_is_the_public_event_and_version(self):
        self.event.publish_by(self.sam)
        data = bodies()[0]['data']
        self.assertEqual(set(data),
                         set(EventSerializer().fields)
                         | {'version'})
        self.assertNotIn('@', json.dumps(data))

    def test_drafts_and_dry_runs_send_nothing(self):
        event = self.event
        event.edit(self.sam, event.version, retitle('Draft'))
        event.publish_by(self.sam, dry_run=True)
        self.assertFalse(WebhookDelivery.objects.exists())

    def test_only_endpoints_that_want_it_are_told(self):
        endpoint(kinds=['event.cancelled'])
        endpoint(active=False)
        self.event.publish_by(self.sam)
        self.assertEqual(
            list(WebhookDelivery.objects.values_list(
                'endpoint', flat=True)), [self.hook.pk])

    def test_sending_waits_for_the_commit(self):
        before = len(enqueued())
        with self.captureOnCommitCallbacks(execute=True):
            self.event.publish_by(self.sam)
            self.assertEqual(len(enqueued()), before)
        self.assertEqual(len(enqueued()), before + 1)

test_sending_waits_for_the_commit uses captureOnCommitCallbacks(): inside the transaction nothing has been enqueued; after it, one task has. test_drafts_and_dry_runs_send_nothing holds decision N52.9.

uv run python manage.py test integrations.tests.test_messages
Found 5 test(s).
Creating test database for alias 'default'...
ERROR: test_the_data_is_the_public_event_and_version
IndexError: list index out of range
FAIL: test_only_endpoints_that_want_it_are_told
AssertionError: Lists differ: [] != [2]
FAIL: test_publish_change_and_cancel
AssertionError: Lists differ: [] != ['event.published',
    'event.changed', 'event.cancelled']
... (1 more like these)
Ran 5 tests in ...s

FAILED (failures=3, errors=1)

Create integrations/tasks.py. Its top:

"""Queueing and sending webhooks (Chapter 52).

A change to an event queues one WebhookDelivery per
endpoint that wants it, in the change's own transaction;
a task sends each one after commit. As for Chapter 44's
emails, the row is the outbox: nothing is sent for a
change that rolled back, and nothing queued is lost.
"""
import json
from datetime import timedelta

import httpx
from django.core.exceptions import ValidationError
from django.db import transaction
from django.tasks import task
from django.utils import timezone

from . import addresses, signing
from .models import (
    MOST_FAILURES, WebhookDelivery, WebhookEndpoint,
)

# Seconds before each retry: Standard Webhooks' schedule,
# about 17 hours in all. After the seventh try, failed.
RETRIES = [5, 5 * 60, 30 * 60, 2 * 3600, 5 * 3600, 10 * 3600]
# How long one try may take, connecting included.
TIMEOUT = httpx.Timeout(15.0)
# Tests put an httpx.MockTransport here instead of the
# network.
transport = None

queueing, after two blank lines:

def announce(event, kind):
    """Queue a message about event for every endpoint.

    Call it inside the change's transaction: the rows commit
    with the change, and the sends start after. The body is
    the event as the public API shows it, with its version,
    so a receiver can keep the newest. Drafts are never
    announced.
    """
    from api.representation import listed
    from api.serializers import EventSerializer

    endpoints = [e for e in WebhookEndpoint.objects.all()
                 if e.wants(kind)]
    if not endpoints or event.status == event.Status.DRAFT:
        return
    data = EventSerializer(listed().get(pk=event.pk)).data
    body = json.dumps({
        'type': kind,
        'timestamp': timezone.now().isoformat(),
        'data': {**data, 'version': event.version},
    }, separators=(',', ':'))
    for endpoint in endpoints:
        delivery = WebhookDelivery.objects.create(
            endpoint=endpoint, kind=kind, body=body)
        transaction.on_commit(
            lambda pk=delivery.pk: enqueue(pk))


def enqueue(delivery_id, run_after=None):
    """Enqueue the task that sends a delivery, as 44 does."""
    send = send_webhook
    if run_after and send.get_backend().supports_defer:
        send = send.using(run_after=run_after)
    send.enqueue(delivery_id)

and sending, after two more:

def post(endpoint, delivery):
    """Send one try; return the response.

    The address is checked again now: a name can resolve
    elsewhere since it was saved. Redirects are never
    followed, and the checked address is the one used.
    """
    target = addresses.check(endpoint.url)
    stamp = int(timezone.now().timestamp())
    sent = signing.headers(endpoint, delivery, stamp)
    with httpx.Client(timeout=TIMEOUT, transport=transport,
                      follow_redirects=False) as client:
        return client.post(
            target.url, content=delivery.body,
            headers={**sent, 'host': target.netloc},
            extensions={'sni_hostname': target.host})


@task
def send_webhook(delivery_id):
    """Try to send one delivery; retry, finish, or give up.

    2xx is success. 410 Gone means the partner removed the
    address: the endpoint is stopped. Anything else, 3xx
    included, and any network error, is a failure, retried
    on RETRIES, sooner if the answer's Retry-After says so.
    The row is locked while it is sent, so two workers never
    send the same try.
    """
    with transaction.atomic():
        delivery = WebhookDelivery.objects.select_for_update(
            of=('self',)).select_related('endpoint').get(
            pk=delivery_id)
        endpoint = delivery.endpoint
        if delivery.status != WebhookDelivery.Status.QUEUED:
            return delivery.status
        if not endpoint.active:
            delivery.status = WebhookDelivery.Status.SKIPPED
            delivery.save()
            return delivery.status
        delivery.attempts += 1
        wait = None
        try:
            answer = post(endpoint, delivery)
        except ValidationError as error:
            delivery.last_error = error.messages[0][:200]
        except httpx.HTTPError as error:
            delivery.last_error = (
                f'{type(error).__name__}: {error}')[:200]
        else:
            delivery.last_code = answer.status_code
            delivery.last_error = ''
            if answer.is_success:
                delivery.status = WebhookDelivery.Status.SENT
                delivery.sent_at = timezone.now()
                endpoint.failures_in_a_row = 0
                endpoint.save(update_fields=[
                    'failures_in_a_row'])
            elif answer.status_code == 410:
                delivery.status = WebhookDelivery.Status.FAILED
                endpoint.stop('The partner answered 410 Gone.')
            given = answer.headers.get('retry-after', '')
            wait = int(given) if given.isdigit() else None
        if delivery.status == WebhookDelivery.Status.QUEUED:
            retry(delivery, wait)
        delivery.save()
    return delivery.status


def retry(delivery, wait=None):
    """Schedule the next try, or mark the delivery failed.

    A delivery that fails every try counts against its
    endpoint; MOST_FAILURES in a row stop it.
    """
    if delivery.attempts > len(RETRIES):
        delivery.status = WebhookDelivery.Status.FAILED
        endpoint = delivery.endpoint
        endpoint.failures_in_a_row += 1
        endpoint.save(update_fields=['failures_in_a_row'])
        if endpoint.failures_in_a_row >= MOST_FAILURES:
            endpoint.stop(f'{MOST_FAILURES} messages in a row '
                          'failed.')
        return
    seconds = min(wait or RETRIES[delivery.attempts - 1],
                  RETRIES[-1])
    delivery.due_at = timezone.now() + timedelta(
        seconds=seconds)
    transaction.on_commit(
        lambda: enqueue(delivery.pk, delivery.due_at))

announce() reads the event back through listed(), inside the change’s transaction, so the body holds the committed-to-be values, places left and organizers included, serialized once with separators=(',', ':') for compact bytes. send_webhook() follows Chapter 44’s send_delivery(): it locks the row, so two workers never send the same try, and it counts the try before sending. extensions={'sni_hostname': ...} tells httpx which name to present in TLS while connecting to the checked address.

Now the model methods announce their changes. In events/models.py, the end of edit()’s docstring and its imports become:

        place (43). The edit page and the API both call it
        (Chapter 48); since Chapter 52, the admin too, and
        partners' webhooks hear of the change. A dry run does
        it all, then undoes it.
        """
        # Imported here: emails imports tasks, which imports
        # this module; so does integrations.tasks.
        from integrations.tasks import announce

        from . import emails

and after the line that counts the emails queued, queued = event.deliveries.count() - queued, add:

            announce(event, 'event.changed')

publish_by() becomes, down to its dry run:

        The page and the API both publish here (Chapter 49);
        publish() raises ValidationError if it is not ready.
        Webhooks are queued with it (Chapter 52).
        """
        from integrations.tasks import announce

        with transaction.atomic():
            self.publish()
            record(by, AuditEvent.Action.PUBLISH_EVENT, self)
            announce(self, 'event.published')

and cancel_by():

        Recorded, and every member holding a place is told,
        in one transaction (Chapters 43 and 49); webhooks too
        (Chapter 52).
        """
        from integrations.tasks import announce

        from . import emails
        with transaction.atomic():
            self.cancel()
            record(by, AuditEvent.Action.CANCEL_EVENT, self)
            queued = self.deliveries.count()
            emails.event_cancelled(self)
            queued = self.deliveries.count() - queued
            announce(self, 'event.cancelled')

The import is inside each method for the same reason emails is: integrations.tasks imports the API’s serializer, which imports this module.

uv run python manage.py test integrations.tests.test_messages
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Common Error: sending inside the transaction

Calling the partner from inside transaction.atomic() announces a change before it is saved. If the transaction then rolls back, perhaps because the lock timed out, the partner believes in a cancellation that never happened. Write the row inside the transaction and send after commit, as transaction.on_commit() does here.

Step 7: What a failure does

send_webhook() already holds every rule of Figure 52.1. Pin each one with a test, in integrations/tests/test_sending.py; httpx’s MockTransport plays the partner, as it played the API in Chapter 51:

"""Sending a webhook: success, retries, and stopping (52)."""
from unittest import mock

import httpx
from django.test import TestCase, override_settings

from events.tests.test_tasks import QUEUE_ONLY
from integrations import tasks
from integrations.models import MOST_FAILURES, WebhookDelivery
from integrations.tasks import RETRIES, send_webhook
from integrations.tests.helpers import endpoint, resolving_to

Status = WebhookDelivery.Status


@override_settings(TASKS=QUEUE_ONLY)
class SendingTests(TestCase):
    """One try at a time, against a partner the test plays."""

    def setUp(self):
        self.hook = endpoint()
        self.delivery = WebhookDelivery.objects.create(
            endpoint=self.hook, kind='event.published',
            body='{"type":"event.published"}')
        self.sent = []

    def answering(self, *answers):
        """Play the partner: give answers in turn, record."""
        queue = list(answers)

        def handle(request):
            """Record the request; give the next answer."""
            self.sent.append(request)
            answer = queue.pop(0)
            if isinstance(answer, Exception):
                raise answer
            return answer

        transport = httpx.MockTransport(handle)
        patch = mock.patch.object(tasks, 'transport', transport)
        patch.start()
        self.addCleanup(patch.stop)

    def send(self, ip='93.184.215.14'):
        """Run one try; return the delivery as saved."""
        with resolving_to(ip):
            send_webhook.call(self.delivery.pk)
        self.delivery.refresh_from_db()
        return self.delivery

    def waited(self, delivery):
        """Return the seconds until the next try."""
        due = delivery.due_at - delivery.created_at
        return due.total_seconds()

    def test_2xx_is_sent_to_the_checked_address(self):
        self.answering(httpx.Response(204))
        self.assertEqual(self.send().status, Status.SENT)
        request = self.sent[0]
        self.assertEqual(request.url.host, '93.184.215.14')
        self.assertEqual(request.headers['host'],
                         'library.example')
        self.assertEqual(request.extensions['sni_hostname'],
                         'library.example')
        self.assertEqual(request.content,
                         self.delivery.body.encode())

    def test_a_failure_waits_as_scheduled(self):
        self.answering(httpx.Response(500))
        delivery = self.send()
        self.assertEqual((delivery.status, delivery.attempts,
                          delivery.last_code),
                         (Status.QUEUED, 1, 500))
        self.assertAlmostEqual(self.waited(delivery),
                               RETRIES[0], delta=2)

    def test_a_redirect_is_a_failure_not_followed(self):
        self.answering(httpx.Response(
            302, headers={'location': 'http://10.0.0.5/'}))
        self.assertEqual(self.send().status, Status.QUEUED)
        self.assertEqual(len(self.sent), 1)

    def test_retry_after_is_honoured(self):
        self.answering(httpx.Response(
            503, headers={'retry-after': '120'}))
        self.assertAlmostEqual(self.waited(self.send()), 120,
                               delta=2)

    def test_a_timeout_is_a_failure(self):
        self.answering(httpx.ConnectTimeout('slow'))
        self.assertIn('ConnectTimeout',
                      self.send().last_error)

    def test_gone_stops_the_endpoint(self):
        self.answering(httpx.Response(410))
        self.assertEqual(self.send().status, Status.FAILED)
        self.hook.refresh_from_db()
        self.assertFalse(self.hook.active)

    def test_failed_after_seven_tries(self):
        self.answering(*[httpx.Response(500)] * 7)
        for _ in range(7):
            delivery = self.send()
        self.assertEqual((delivery.status, delivery.attempts),
                         (Status.FAILED, 7))
        self.hook.refresh_from_db()
        self.assertEqual(self.hook.failures_in_a_row, 1)

    def test_twenty_failed_messages_stop_the_endpoint(self):
        self.hook.failures_in_a_row = MOST_FAILURES - 1
        self.hook.save()
        self.delivery.attempts = len(RETRIES)
        self.delivery.save()
        self.answering(httpx.Response(500))
        self.send()
        self.hook.refresh_from_db()
        self.assertFalse(self.hook.active)

    def test_an_inner_address_now_is_never_called(self):
        self.answering(httpx.Response(204))
        delivery = self.send(ip='10.0.0.5')
        self.assertEqual(self.sent, [])
        self.assertIn('may not call', delivery.last_error)

    def test_a_stopped_endpoint_is_skipped(self):
        self.hook.stop('Test.')
        self.answering()
        self.assertEqual(self.send().status, Status.SKIPPED)

test_2xx_is_sent_to_the_checked_address checks the request itself: sent to the number, with the partner’s name in Host and for TLS, and the body byte for byte. test_an_inner_address_now_is_never_called is DNS rebinding: the endpoint was fine when saved, and now resolves inside.

uv run python manage.py test integrations.tests.test_sending
Found 10 test(s).
Creating test database for alias 'default'...
...
Ran 10 tests in ...s

OK

Step 8: Admin edits, through edit()

Since Chapter 33 the admin saved an event with its own save_model(), counting a new version and nothing more. An administrator who moved the clinic’s start time there recorded nothing, emailed nobody, and now would tell no partner (N52.8). Add the test to the end of test_messages.py:

@override_settings(TASKS=QUEUE_ONLY)
class AdminEditTests(TestCase):
    """An admin edit is an edit like any other (N52.8)."""

    def test_it_is_recorded_and_announced(self):
        root = in_group('root@example.org', 'Administrators',
                        is_staff=True, is_superuser=True)
        hook = endpoint()
        event = ready(title='Clinic',
                      status=Event.Status.PUBLISHED)
        self.client.force_login(root)
        self.client.post(admin_url(Event, 'change', event.pk),
                         event_form(event, title='Renamed'))
        event.refresh_from_db()
        self.assertEqual((event.title, event.version),
                         ('Renamed', 2))
        self.assertTrue(root.audit_events.filter(
            action='edit_event').exists())
        message = hook.deliveries.get()
        self.assertEqual(message.kind, 'event.changed')
uv run python manage.py test integrations.tests.test_messages
Found 6 test(s).
Creating test database for alias 'default'...
FAIL: test_it_is_recorded_and_announced
AssertionError: False is not true
Ran 6 tests in ...s

FAILED (failures=1)

In events/admin.py, EventAdmin.save_model() becomes:

    def save_model(self, request, obj, form, change):
        """Save a change through Event.edit(), as the site does.

        Chapter 52: until now an admin edit only counted a new
        version. Through edit() it is also recorded, gives
        waiting members new places, tells holders of a new
        time or place, and sends webhooks. A new event is
        saved as before.
        """
        if not change:
            super().save_model(request, obj, form, change)
            return

        def copy(locked):
            """Copy the form's changes onto the locked event."""
            for name in form.changed_data:
                setattr(locked, name, getattr(obj, name))
            return []

        obj.version = obj.edit(request.user, obj.version,
                               copy).event.version

form.changed_data names exactly the fields the administrator changed, so only those are copied onto the locked copy; edit() does the rest, as for the edit page and the API. This changes Chapter 33’s admin on purpose, and docs/design/admin.md says so in Step 11.

uv run python manage.py test integrations.tests.test_messages
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK

Step 9: The Webhooks page

The tests, in integrations/tests/test_pages.py:

"""The Webhooks page, for administrators (Chapter 52)."""
from django.test import TestCase
from django.urls import reverse

from audit.models import AuditEvent
from config.helpers import SAI_PASSWORD, in_group
from integrations.models import WebhookEndpoint
from integrations.tests.helpers import endpoint, resolving_to


class PageTests(TestCase):
    """Who may open it, and what each form does."""

    @classmethod
    def setUpTestData(cls):
        cls.ann = in_group('ann@example.org', 'Administrators')
        cls.sam = in_group('sam@example.org', 'Organizers')

    def setUp(self):
        self.url = reverse('integrations:endpoints')

    def confirm(self, user):
        """Sign in, then give the password again."""
        self.client.force_login(user)
        self.client.post(reverse('account_reauthenticate'),
                         {'password': SAI_PASSWORD})

    def add(self, url='https://library.example/hooks/'):
        """Send the Add an endpoint form; return the answer."""
        return self.client.post(self.url, {
            'url': url, 'description': 'Library',
            'kinds': ['event.published', 'event.cancelled']})

    def test_organizers_get_403_recorded(self):
        self.client.force_login(self.sam)
        self.assertEqual(self.client.get(self.url).status_code,
                         403)
        refused = AuditEvent.objects.filter(
            action='manage_webhooks', outcome='refused')
        self.assertTrue(refused.exists())

    def test_the_password_is_asked_first(self):
        self.client.force_login(self.ann)
        page = self.client.get(self.url)
        self.assertTrue(page.url.startswith(
            reverse('account_reauthenticate')))

    def test_adding_shows_the_secret_once(self):
        self.confirm(self.ann)
        with resolving_to('93.184.215.14'):
            page = self.add()
        hook = WebhookEndpoint.objects.get()
        self.assertContains(page, hook.secret)
        self.assertIn('no-store', page['Cache-Control'])
        self.assertEqual(hook.kinds, ['event.published',
                                      'event.cancelled'])
        self.assertNotContains(self.client.get(self.url),
                               hook.secret)

    def test_an_inner_address_is_refused_at_save(self):
        self.confirm(self.ann)
        with resolving_to('10.0.0.5'):
            page = self.add('https://intranet.example/')
        self.assertContains(page, 'may not call')
        self.assertFalse(WebhookEndpoint.objects.exists())

    def test_rotating_shows_the_new_secret(self):
        hook = endpoint()
        old = hook.secret
        self.confirm(self.ann)
        page = self.client.post(
            reverse('integrations:rotate', args=[hook.pk]))
        hook.refresh_from_db()
        self.assertContains(page, hook.secret)
        self.assertEqual(hook.secrets_now(), [hook.secret, old])

    def test_the_log_says_each_status_in_words(self):
        hook = endpoint()
        hook.deliveries.create(kind='event.published',
                               body='{}', status='failed')
        self.client.force_login(self.ann)
        page = self.client.get(
            reverse('integrations:endpoint', args=[hook.pk]))
        self.assertContains(page, 'Failed')
        self.assertContains(page, 'data-label="Status"')

    def test_turning_off_asks_the_password_recorded(self):
        hook = endpoint()
        self.client.force_login(self.ann)
        switch = reverse('integrations:switch', args=[hook.pk])
        self.assertTrue(self.client.post(switch).url.startswith(
            reverse('account_reauthenticate')))
        hook.refresh_from_db()
        self.assertTrue(hook.active)
        self.confirm(self.ann)
        self.client.post(switch)
        hook.refresh_from_db()
        self.assertFalse(hook.active)
        self.client.post(switch)
        hook.refresh_from_db()
        self.assertTrue(hook.active)
        self.assertEqual(AuditEvent.objects.filter(
            action='manage_webhooks').count(), 2)

Chapter 39’s guard must see the new pages too. In config/tests/test_public.py, the apps it reads become:

    for app in ('accounts', 'events', 'registrations', 'api',
                'integrations'):
uv run python manage.py test integrations.tests.test_pages
Found 7 test(s).
Creating test database for alias 'default'...
ERROR: test_adding_shows_the_secret_once
django.urls.exceptions.NoReverseMatch: 'integrations' is not
    a registered namespace
ERROR: test_an_inner_address_is_refused_at_save
django.urls.exceptions.NoReverseMatch: 'integrations' is not
    a registered namespace
ERROR: test_organizers_get_403_recorded
django.urls.exceptions.NoReverseMatch: 'integrations' is not
    a registered namespace
... (4 more like these)
Ran 7 tests in ...s

FAILED (errors=7)

Administrators get the permission. In accounts/roles.py, their list ends:

        'registrations.view_registrationquestion',
        # Chapter 52: partners' webhook endpoints.
        'integrations.manage_webhooks',
    ],
}

the audit trail gains an action, after REVOKE_TOKEN in audit/models.py:

        # Chapter 52: partners' webhook endpoints.
        MANAGE_WEBHOOKS = 'manage_webhooks', 'Manage webhooks'

and a migration gives the permission to the existing group, written by hand as Chapter 38’s was. Create integrations/migrations/0002_administrators.py:

"""Administrators manage webhook endpoints (Chapter 52)."""
from django.contrib.auth.management import create_permissions
from django.db import migrations

APP, CODENAME = 'integrations', 'manage_webhooks'


def grant(apps, schema_editor):
    """Let Administrators manage webhook endpoints."""
    # A new model's permissions are made after the last
    # migration, so make them first, as registrations 0005
    # does.
    config = apps.get_app_config(APP)
    config.models_module = True
    create_permissions(config, apps=apps, verbosity=0)
    config.models_module = None
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    group = Group.objects.filter(name='Administrators')
    if group.exists():
        group.get().permissions.add(Permission.objects.get(
            content_type__app_label=APP, codename=CODENAME,
        ))


def revoke(apps, schema_editor):
    """Take the permission away again."""
    Group = apps.get_model('auth', 'Group')
    for group in Group.objects.filter(name='Administrators'):
        group.permissions.remove(*group.permissions.filter(
            content_type__app_label=APP, codename=CODENAME,
        ))


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0008_opt_out'),
        ('integrations', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(grant, revoke),
    ]

Then make the audit migration and apply both:

uv run python manage.py makemigrations audit -n webhook_action
uv run python manage.py migrate
Migrations for 'audit':
  audit\migrations\0008_webhook_action.py
    ~ Alter field action on auditevent
Operations to perform:
  Apply all migrations: account, accounts, admin, api, audit,
    auth, contenttypes, django_tasks_database, events,
    integrations, mfa, registrations, sessions, socialaccount
Running migrations:
  Applying audit.0008_webhook_action... OK
  Applying integrations.0002_administrators... OK

The form, integrations/forms.py, checks the address when it is saved:

"""The form for a partner's webhook endpoint (Chapter 52)."""
from django import forms

from . import addresses
from .models import Kind, WebhookEndpoint


class EndpointForm(forms.ModelForm):
    """An address, what it is for, and what it hears about."""

    kinds = forms.MultipleChoiceField(
        label='Send', choices=Kind.choices,
        widget=forms.CheckboxSelectMultiple,
        initial=Kind.values)

    class Meta:
        model = WebhookEndpoint
        fields = ['url', 'description', 'kinds']
        labels = {'url': 'Address',
                  'description': 'Partner'}
        help_texts = {
            'url': 'https:// only; it must lead to a public '
                   'address.',
        }

    def clean_url(self):
        """Refuse an address Otahque may not call."""
        url = self.cleaned_data['url']
        addresses.check(url)
        return url

The views, integrations/views.py, follow the tokens page of Chapter 50: refused attempts recorded, the password asked again before any change to an endpoint, and never_cache on those answers:

"""The Webhooks page, for administrators (Chapter 52)."""
from functools import wraps

from allauth.account.decorators import (
    reauthentication_required,
)
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import (
    require_http_methods, require_POST,
)

from audit.models import AuditEvent, record
from events.views import deny

from .forms import EndpointForm
from .models import WebhookEndpoint

Action = AuditEvent.Action


def webhooks_access(view):
    """Allow holders of manage_webhooks; refuse the rest.

    A refusal is 403 and recorded, as on Chapter 30's pages.
    """
    @wraps(view)
    def wrapper(request, *args, **kwargs):
        if not request.user.has_perm(
                'integrations.manage_webhooks'):
            deny(request, Action.MANAGE_WEBHOOKS)
        return view(request, *args, **kwargs)
    return wrapper


@require_http_methods(['GET', 'POST'])
@webhooks_access
@reauthentication_required
@never_cache
def endpoints(request):
    """List the endpoints; add one, showing its secret once."""
    form = EndpointForm(request.POST or None)
    new = None
    if form.is_valid():
        form.instance.created_by = request.user
        new = form.save()
        record(request.user, Action.MANAGE_WEBHOOKS, new,
               did='added', url=new.url)
        form = EndpointForm()
    return render(request, 'integrations/endpoints.html', {
        'form': form, 'new': new,
        'endpoints': WebhookEndpoint.objects.all(),
    })


@require_http_methods(['GET', 'HEAD'])
@webhooks_access
def endpoint(request, endpoint_id):
    """Show one endpoint and its last 50 deliveries."""
    found = get_object_or_404(WebhookEndpoint, pk=endpoint_id)
    return render(request, 'integrations/endpoint.html', {
        'endpoint': found,
        'deliveries': found.deliveries.all()[:50],
    })


@require_POST
@webhooks_access
@reauthentication_required
@never_cache
def rotate(request, endpoint_id):
    """Give an endpoint a new secret, shown once."""
    found = get_object_or_404(WebhookEndpoint, pk=endpoint_id)
    found.rotate()
    record(request.user, Action.MANAGE_WEBHOOKS, found,
           did='rotated')
    return render(request, 'integrations/endpoint.html', {
        'endpoint': found, 'rotated': True,
        'deliveries': found.deliveries.all()[:50],
    })


@require_POST
@webhooks_access
@reauthentication_required
def switch(request, endpoint_id):
    """Turn an endpoint off, or on again."""
    found = get_object_or_404(WebhookEndpoint, pk=endpoint_id)
    if found.active:
        found.stop(f'Turned off by {request.user.display_name}.')
        did = 'stopped'
    else:
        found.start()
        did = 'started'
    record(request.user, Action.MANAGE_WEBHOOKS, found, did=did)
    messages.success(request, f'{found} {did}.')
    return redirect('integrations:endpoint', found.pk)

The addresses, integrations/urls.py:

"""Addresses of the Webhooks page (Chapter 52)."""
from django.urls import path

from . import views

app_name = 'integrations'

urlpatterns = [
    path('webhooks/', views.endpoints, name='endpoints'),
    path('webhooks/<int:endpoint_id>/', views.endpoint,
         name='endpoint'),
    path('webhooks/<int:endpoint_id>/rotate/', views.rotate,
         name='rotate'),
    path('webhooks/<int:endpoint_id>/switch/', views.switch,
         name='switch'),
]

and, in config/urls.py, after the registrations line:

    path('', include('registrations.urls')),
    path('', include('integrations.urls')),

The list page, integrations/templates/integrations/endpoints.html, reuses the token page’s cards:

{% extends "base.html" %}

{% block title %}Webhooks | Otahque{% endblock %}

{% block content %}
  <h1>Webhooks</h1>
  <p>Partners' servers that Otahque tells when an event is
    published, changed, or cancelled. Each message is
    signed with the endpoint's secret.</p>

  {% if new %}
    <section class="token-card token-new" role="status"
             aria-labelledby="new-heading">
      <h2 id="new-heading">Give {{ new }} this secret</h2>
      <p>It is shown only now. Send it to the partner by a
        safe route; they verify every message with it.</p>
      <p class="copy-field">
        <code id="new-secret">{{ new.secret }}</code>
        <button type="button" class="btn btn-primary btn-sm
                needs-js" data-copy="new-secret"
                data-copied="Secret copied.">Copy secret</button>
      </p>
    </section>
  {% endif %}

  <div class="token-layout">
    <section class="token-card" aria-labelledby="add">
      <h2 id="add">Add an endpoint</h2>
      <form method="post" class="space-y-4">
        {% csrf_token %}
        {% include "includes/error_summary.html" %}
        <div class="form-grid">{{ form }}</div>
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">
            Add endpoint</button>
        </div>
      </form>
    </section>

    <section aria-labelledby="list">
      <h2 id="list" class="list-heading">Endpoints</h2>
      <ul class="token-list">
        {% for endpoint in endpoints %}
          <li class="token-card">
            {% url 'integrations:endpoint' endpoint.pk as page %}
            <p class="token-head">
              <a class="font-semibold" href="{{ page }}">
                {{ endpoint }}</a>
              {% with status=endpoint.active|yesno:"on,off" %}
                {% include "includes/status_badge.html" %}
              {% endwith %}
            </p>
            <p class="text-sm break-all">{{ endpoint.url }}</p>
            <p class="scope-badges">
              {% for kind in endpoint.kinds %}
                <span class="badge badge-ghost">
                  {{ kind }}</span>
              {% endfor %}
            </p>
          </li>
        {% empty %}
          <li class="token-card">No endpoints yet.</li>
        {% endfor %}
      </ul>
    </section>
  </div>
{% endblock %}

and one endpoint’s page, integrations/templates/integrations/endpoint.html, shows its recent messages:

{% extends "base.html" %}

{% block title %}{{ endpoint }}: webhooks | Otahque{% endblock %}

{% block content %}
  <p><a href="{% url 'integrations:endpoints' %}">
    All webhooks</a></p>
  <h1 class="token-head">{{ endpoint }}
    {% with status=endpoint.active|yesno:"on,off" %}
      {% include "includes/status_badge.html" %}
    {% endwith %}</h1>
  <p class="break-all">{{ endpoint.url }}</p>
  {% if endpoint.stopped_because %}
    <p class="notice-card">
      Off: {{ endpoint.stopped_because }}</p>
  {% endif %}

  {% if rotated %}
    <section class="token-card token-new" role="status"
             aria-labelledby="new-heading">
      <h2 id="new-heading">The new secret</h2>
      <p>The old one also signs for 24 hours, so the partner
        can switch without missing a message.</p>
      <p class="copy-field">
        <code id="new-secret">{{ endpoint.secret }}</code>
        <button type="button" class="btn btn-primary btn-sm
                needs-js" data-copy="new-secret"
                data-copied="Secret copied.">Copy secret</button>
      </p>
    </section>
  {% endif %}

  <div class="action-bar flex flex-wrap gap-3">
    <form method="post"
          action="{% url 'integrations:rotate' endpoint.pk %}">
      {% csrf_token %}
      <button type="submit" class="btn btn-sm">
        Rotate secret</button>
    </form>
    <form method="post"
          action="{% url 'integrations:switch' endpoint.pk %}">
      {% csrf_token %}
      <button type="submit" class="btn btn-sm">
        {% if endpoint.active %}Turn off{% else %}Turn on
        {% endif %}</button>
    </form>
  </div>

  <h2 class="list-heading mt-6">Recent messages</h2>
  <table class="stack-table">
    <thead>
      <tr><th>Message</th><th>Status</th><th>Tries</th>
        <th>Last answer</th><th>Created</th></tr>
    </thead>
    <tbody>
      {% for delivery in deliveries %}
        <tr>
          <td data-label="Message">{{ delivery.kind }}
            <code class="block text-xs">
              {{ delivery.message_id }}</code></td>
          <td data-label="Status">
            {% with status=delivery.status %}
              {% include "includes/status_badge.html" %}
            {% endwith %}</td>
          <td data-label="Tries">{{ delivery.attempts }}</td>
          <td data-label="Last answer">
            {{ delivery.last_code|default:"" }}
            {{ delivery.last_error }}</td>
          <td data-label="Created">
            {{ delivery.created_at|date:"j M Y, H:i" }}</td>
        </tr>
      {% empty %}
        <tr><td colspan="5">No messages yet.</td></tr>
      {% endfor %}
    </tbody>
  </table>
{% endblock %}

The UI increment is that delivery log, readable on a phone. Two shared improvements make it. A status badge that says its status in words, so colour is never the only signal, in templates/includes/status_badge.html:

{# Chapter 52: a status as a badge that says it in words, #}
{# so colour is never the only signal (WCAG 1.4.1). Give #}
{# it status: sent, failed, queued, skipped, on, or off. #}
<span class="badge badge-status
  {% if status == 'sent' or status == 'on' %}badge-success
  {% elif status == 'failed' or status == 'off' %}badge-error
  {% else %}badge-outline{% endif %}">
  {{ status|capfirst }}</span>

and a table that turns into one card per row on a narrow screen, each cell led by its column’s name from data-label, in static/otahque/source.css, above .form-actions:

  /* Chapter 52: a table that becomes a card per row on a
     phone, each cell led by its column's name (data-label);
     for any page with a log or list in a table. */
  .stack-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.875rem;
  }
  .stack-table th,
  .stack-table td {
    padding: 0.5rem 0.75rem;
    border-bottom: 1px solid var(--color-base-300);
    text-align: left;
    vertical-align: top;
  }
  @media (width < 40rem) {
    .stack-table thead {
      display: none;
    }
    .stack-table tr {
      display: grid;
      gap: 0.25rem;
      margin-bottom: 0.75rem;
      padding: 0.75rem;
      border: 1px solid var(--color-base-300);
      border-radius: var(--radius-box);
      background-color: var(--color-base-100);
    }
    .stack-table td {
      padding: 0;
      border: 0;
    }
    .stack-table td[data-label]::before {
      content: attr(data-label) ": ";
      font-weight: 600;
    }
  }
  .badge-status {
    font-weight: 600;
  }

Tailwind builds only the classes it finds in the folders source.css names, so the new app’s templates must be named too. Its @source lines become:

@source "../../api/templates";
@source "../../integrations/templates";

In templates/includes/site_nav.html, administrators get a link:

  {% if perms.events.manage_organizers %}
    <a href="{% url 'events:organizer_events' %}">
      Organizer access</a>
  {% endif %}
  {% if perms.integrations.manage_webhooks %}
    <a href="{% url 'integrations:endpoints' %}">Webhooks</a>
  {% endif %}
npm run build
uv run python manage.py test integrations.tests.test_pages
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s

OK
uv run python manage.py test config.tests.test_public
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK

Common Error: classes that never reach site.css

A new app’s template uses gap-3, and the buttons still touch. Tailwind reads only the folders named by @source in source.css, and integrations/templates was not one of them, so the class was never built. Add the folder and run npm run build again.

Step 10: A partner’s receiver

The tests feed messages signed by Otahque to the receiver, as the network would, in integrations/tests/test_receiver.py:

"""The partner's receiver, fed by Otahque's signer (52).

The receiver, examples/receiver.py, checks messages with
the standardwebhooks library; Otahque signs them with its
own code. Each test signs a real message and hands it to
the receiver, as the network would.
"""
import json
import time

from django.test import TestCase

from examples.receiver import Receiver
from integrations import signing
from integrations.models import WebhookDelivery
from integrations.tests.helpers import endpoint


class ReceiverTests(TestCase):
    """What a careful partner accepts, and ignores."""

    def setUp(self):
        self.hook = endpoint()
        self.receiver = Receiver(self.hook.secret)

    def message(self, version, stamp=None):
        """Return headers and body of a signed message."""
        body = json.dumps({'type': 'event.changed',
                           'timestamp': '2027-01-01T09:00:00Z',
                           'data': {'id': 7, 'title': 'Clinic',
                                    'version': version}})
        delivery = WebhookDelivery.objects.create(
            endpoint=self.hook, kind='event.changed', body=body)
        headers = signing.headers(
            self.hook, delivery, stamp or int(time.time()))
        return headers, body.encode()

    def test_a_signed_message_is_applied(self):
        status, said = self.receiver.handle(*self.message(3))
        self.assertEqual(status, 200)
        self.assertEqual(said,
                         'event.changed: Clinic, version 3')

    def test_a_wrong_secret_is_refused(self):
        other = Receiver(endpoint().secret)
        status, said = other.handle(*self.message(3))
        self.assertEqual(status, 400)
        self.assertIn('refused', said)

    def test_an_old_message_is_refused(self):
        stamp = int(time.time()) - 600
        status, _ = self.receiver.handle(*self.message(3, stamp))
        self.assertEqual(status, 400)

    def test_the_same_message_twice_is_applied_once(self):
        headers, body = self.message(3)
        self.receiver.handle(headers, body)
        status, said = self.receiver.handle(headers, body)
        self.assertEqual((status, said),
                         (200, 'seen before; ignored'))

    def test_an_older_version_is_ignored(self):
        self.receiver.handle(*self.message(4))
        status, said = self.receiver.handle(*self.message(3))
        self.assertEqual((status, said),
                         (200, 'older than version 4; ignored'))
uv run python manage.py test integrations.tests.test_receiver
Found 1 test(s).
ERROR: test_receiver
    (unittest.loader._FailedTest.test_receiver)
ImportError: Failed to import test module: test_receiver
ModuleNotFoundError: No module named 'examples.receiver'
Ran 1 test in ...s

FAILED (errors=1)

Create examples/receiver.py. Its checks:

"""A partner's receiver for Otahque's webhooks (Chapter 52).

Run it beside Otahque while developing, with the
endpoint's secret in OTAHQUE_WEBHOOK_SECRET:

    uv run python examples/receiver.py

It listens on http://127.0.0.1:8001/. Each message is
checked with the standardwebhooks library, the code the
specification publishes, so a message it accepts proves
Otahque signs as the specification says.
"""
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

from standardwebhooks.webhooks import (
    Webhook, WebhookVerificationError,
)


class Receiver:
    """What a partner keeps: ids seen, and newest versions."""

    def __init__(self, secret):
        """Remember the secret; nothing seen yet."""
        self.webhook = Webhook(secret)
        self.seen = set()
        self.versions = {}

    def handle(self, headers, body):
        """Return a status and what happened, for a message.

        A bad signature, or a time more than five minutes off,
        is refused with 400. A message seen before, or older
        than one already applied, is answered 200, so Otahque
        stops sending it, and otherwise ignored.
        """
        try:
            message = self.webhook.verify(body, headers)
        except WebhookVerificationError as error:
            return 400, f'refused: {error}'
        message_id = headers['webhook-id']
        if message_id in self.seen:
            return 200, 'seen before; ignored'
        self.seen.add(message_id)
        data = message['data']
        newest = self.versions.get(data['id'], 0)
        if data['version'] <= newest:
            return 200, f'older than version {newest}; ignored'
        self.versions[data['id']] = data['version']
        return 200, (f"{message['type']}: {data['title']}, "
                     f"version {data['version']}")

and, after two blank lines, a small server from Python’s standard library that hands each POST to them:

class Handler(BaseHTTPRequestHandler):
    """Hand each POST to the server's Receiver."""

    def do_POST(self):
        """Read the body as sent; answer; say what happened."""
        size = int(self.headers.get('content-length', 0))
        body = self.rfile.read(size)
        headers = {k.lower(): v for k, v in self.headers.items()}
        status, said = self.server.receiver.handle(headers, body)
        print(said, flush=True)
        self.send_response(status)
        self.end_headers()

    def log_message(self, *args):
        """Print only what handle() says."""


def main():
    """Listen on port 8001 until stopped with Ctrl+C."""
    server = HTTPServer(('127.0.0.1', 8001), Handler)
    server.receiver = Receiver(
        os.environ['OTAHQUE_WEBHOOK_SECRET'])
    print('Listening on http://127.0.0.1:8001/', flush=True)
    server.serve_forever()


if __name__ == '__main__':
    main()

A duplicate or an older version is answered 200, not refused: the message was received, and a 4xx would only make Otahque send it again for 17 hours. Only a bad signature or an old timestamp is refused.

uv run python manage.py test integrations.tests.test_receiver
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Step 11: The records

At the end of docs/api/contract.md:

## Webhooks (Chapter 52)

A partner can be told when an event changes, instead of
asking every few minutes. An Otahque administrator adds
the partner's https:// address on the Webhooks page and
gives them its secret. Otahque then sends a POST for each
of these, after the change is saved:

| type | When |
|---|---|
| `event.published` | A draft is published |
| `event.changed` | A published or cancelled event is edited |
| `event.cancelled` | A published event is cancelled |

The body follows Standard Webhooks: `{"type": ...,
"timestamp": ..., "data": {...}}`. `data` is the event as
`GET /api/v1/events/{id}/` shows it, plus `version`.
Messages may arrive late, out of order, or more than
once: keep the highest `version` seen for each event, and
ignore the rest. Drafts and members are never sent.

Each message has three headers: `webhook-id` (the same on
every retry), `webhook-timestamp` (seconds since 1970),
and `webhook-signature`: `v1,` and the base64
HMAC-SHA256 of `id.timestamp.body` with the secret.
Verify it on the body exactly as received, and refuse a
timestamp more than five minutes away. While a secret is
being replaced, two signatures come, separated by a
space; either may match.

Answer 2xx quickly. Anything else, a redirect included,
or no answer within 15 seconds, is retried after 5
seconds, 5 and 30 minutes, then 2, 5, and 10 hours: seven
tries in all. 410 Gone turns the address off; so do 20
messages in a row that fail every try.

Record the decision as docs/adr/ADR-009-webhooks.md:

# ADR-009: Webhooks to partners

## Status

Proposed, December 2026 (Chapter 52). The choices follow
the user's decisions of 30 November 2026 (D52.1-D52.5,
N52.6-N52.9); this record is not yet reviewed or accepted.

## Context

Partners such as a library's site copy Otahque's events
and poll for changes, so a cancellation can show on their
site for hours. They want to be told. A message must be
provably from Otahque, delivered again when their server
is down, recognisable when it comes twice, and must never
let an address someone typed make Otahque call into its
own network.

## Options

- A: outbound webhooks in the Standard Webhooks format,
  signed with HMAC-SHA256, queued after commit, retried
  over about 17 hours, to checked public addresses.
- B: a custom header and format of our own.
- C: no push: partners poll the paged list (Chapter 51).

## Decision

A, in the integrations app.

- Administrators manage endpoints on the Webhooks page;
  organizers do not.
- The body is the public event, plus its version, in the
  type/timestamp/data shape; published and cancelled
  events only; no member data.
- Otahque signs with its own few lines of hmac; tests
  verify with the specification's standardwebhooks
  library, so the two are proved to agree.
- One WebhookDelivery per message and endpoint, written in
  the change's transaction by edit(), publish_by(), and
  cancel_by(), and sent by a task after commit; dry runs
  send nothing. Admin edits go through edit() too.
- 2xx is success; 3xx and other codes fail; 410 turns the
  endpoint off, as do 20 failed messages in a row;
  Retry-After is honoured; 15-second timeout.
- https:// only outside development. The name is resolved
  at save and at each send; any private, loopback,
  link-local, shared, reserved, multicast, or IPv4-mapped
  inner address refuses it. The send connects to the
  checked address, with the name kept for the Host header
  and TLS, and follows no redirects.

## Consequences

- The secret is stored as written: signing needs it.
  Anyone who reads the table can sign as Otahque until the
  secret is rotated. Chapter 59 encrypts two-factor
  secrets; it encrypts these too (user decision).
- Delivery is at least once: receivers must ignore a
  webhook-id they have seen.
- The address checks cannot see a proxy's or a cloud's own
  rules; Chapter 63 adds an outbound proxy that allows
  only public addresses, as the specification and OWASP
  advise.
- A slow partner holds a worker for up to 15 seconds per
  try.

In docs/design/admin.md, the list of what the admin shows ends:

- Log entries: view only. The audit log of admin saves.
- Chapter 52: a change to an event saved here goes
  through Event.edit(), as the site's pages and the API
  do: a new version, an AuditEvent, places for waiting
  members, emails to holders of a new time or place, and
  webhooks. Until then an admin save only counted a new
  version.

and in docs/design/permissions.md, above “Organizer access”:

## Webhooks (Chapter 52)

Only holders of integrations.manage_webhooks, the
Administrators group, open the Webhooks page; anyone else
gets 403, recorded as manage_webhooks refused. Adding an
endpoint, rotating its secret, and turning it off or on
ask for the password again, and each is recorded.
Organizers do not manage endpoints (D52.2).

Step 12: Try it end to end

This step needs four terminals in the project folder. In the first, run the server:

uv run python manage.py runserver

Sign in as an administrator, open Webhooks, and add an endpoint for “Library” at http://127.0.0.1:8001/, which development allows, with all three kinds. Copy the secret shown. In the second terminal, start the receiver with it.

PowerShell:

$env:OTAHQUE_WEBHOOK_SECRET = 'whsec_...'
uv run python examples/receiver.py

macOS, Linux, or WSL:

export OTAHQUE_WEBHOOK_SECRET='whsec_...'
uv run python examples/receiver.py

In the third, run Chapter 44’s worker, which sends the queued messages:

uv run python manage.py db_worker

In the fourth, or in the browser as Sam, publish a draft and then cancel it. Within seconds the receiver prints:

Listening on http://127.0.0.1:8001/
event.published: Webhook clinic, version 2
event.cancelled: Webhook clinic, version 3

Open the endpoint on the Webhooks page: both messages are listed as Sent, with the answer 200. Figure 52.4 shows the log on a phone and on a wide screen.

Two screenshots of the Library endpoint’s page. Left, on a phone, 390 pixels wide: the name Library with an On badge, its address, Rotate secret and Turn off buttons, then Recent messages as cards, each listing Message, event.cancelled or event.published with its msg_ id, Status with a green Sent badge, Tries 1, Last answer 200, and Created. Right, at 1280 pixels, the same page with the messages as a table with the columns Message, Status, Tries, Last answer, and Created.
Figure 52.4 — An endpoint’s recent messages, on a phone and on a wide screen.

Stop the receiver, the worker, and the server with Ctrl+C.

Step 13: The checks, and the commit

uv run python check.py
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
No changes detected
== python manage.py test --parallel
Found 772 test(s).
System check identified no issues (0 silenced).
Ran 772 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Tell partners of changes with webhooks"
M  accounts/roles.py
A  audit/migrations/0008_webhook_action.py
M  audit/models.py
M  config/settings.py
M  config/tests/test_public.py
M  config/urls.py
A  docs/adr/ADR-009-webhooks.md
M  docs/api/contract.md
M  docs/design/admin.md
M  docs/design/permissions.md
M  events/admin.py
M  events/models.py
A  examples/receiver.py
A  integrations/__init__.py
A  integrations/addresses.py
A  integrations/admin.py
A  integrations/apps.py
A  integrations/forms.py
A  integrations/migrations/0001_initial.py
A  integrations/migrations/0002_administrators.py
A  integrations/migrations/__init__.py
A  integrations/models.py
A  integrations/signing.py
A  integrations/tasks.py
A  integrations/templates/integrations/endpoint.html
A  integrations/templates/integrations/endpoints.html
A  integrations/tests/__init__.py
A  integrations/tests/helpers.py
A  integrations/tests/test_addresses.py
A  integrations/tests/test_messages.py
A  integrations/tests/test_pages.py
A  integrations/tests/test_receiver.py
A  integrations/tests/test_sending.py
A  integrations/tests/test_signing.py
A  integrations/urls.py
A  integrations/views.py
M  pyproject.toml
M  static/otahque/site.css
M  static/otahque/source.css
M  templates/includes/site_nav.html
A  templates/includes/status_badge.html
M  uv.lock
[main 1a2b3c4] Tell partners of changes with webhooks
 42 files changed, 1763 insertions(+), 8 deletions(-)
 create mode 100644 audit/migrations/0008_webhook_action.py
 create mode 100644 docs/adr/ADR-009-webhooks.md
 create mode 100644 examples/receiver.py
 create mode 100644 integrations/__init__.py
 create mode 100644 integrations/addresses.py
 create mode 100644 integrations/admin.py
 create mode 100644 integrations/apps.py
 create mode 100644 integrations/forms.py
 create mode 100644 integrations/migrations/0001_initial.py
 create mode 100644
    integrations/migrations/0002_administrators.py
 create mode 100644 integrations/migrations/__init__.py
 create mode 100644 integrations/models.py
 create mode 100644 integrations/signing.py
 create mode 100644 integrations/tasks.py
 create mode 100644
    integrations/templates/integrations/endpoint.html
 create mode 100644
    integrations/templates/integrations/endpoints.html
 create mode 100644 integrations/tests/__init__.py
 create mode 100644 integrations/tests/helpers.py
 create mode 100644 integrations/tests/test_addresses.py
 create mode 100644 integrations/tests/test_messages.py
 create mode 100644 integrations/tests/test_pages.py
 create mode 100644 integrations/tests/test_receiver.py
 create mode 100644 integrations/tests/test_sending.py
 create mode 100644 integrations/tests/test_signing.py
 create mode 100644 integrations/urls.py
 create mode 100644 integrations/views.py
 create mode 100644 templates/includes/status_badge.html

If something goes wrong

Table 52.1 — Recovery for Chapter 52
What you see Likely cause What to do
The receiver says No matching signature found Another endpoint's secret, or the body changed on the way Use this endpoint's secret; verify the raw body
Message timestamp too old The two clocks differ by over five minutes Set both computers' clocks by network time
Nothing arrives at the receiver No worker running Run db_worker; the rows wait as Queued
leads to an address Otahque may not call The name resolves inside the network Use the partner's public address; loopback only while developing
Use an https:// address http:// with DEBUG off Give the partner's https:// address
403 on the Webhooks page Not in Administrators Ask an administrator; or check accounts/roles.py and the 0002 migration
Buttons touch, or a badge has no colour integrations/templates not in @source Add it to source.css; npm run build
An admin edit sends no webhook save_model() not changed Route it through Event.edit(), as Step 8 does
PAGE 003

Verify Your Work

Work through Table 52.2 from the folder that holds manage.py, with Otahque on PostgreSQL.

Table 52.2 — Verification checklist for Chapter 52
Check Command or action Expected result
Starting point test --parallel Found 734 test(s); OK
The app startapp; makemigrations integrations; migrate integrations.0001_initial applied
Signing test ...test_signing ImportError first; then 5 tests OK
Addresses test ...test_addresses ImportError first; then 5 tests OK
Queue after commit test ...test_messages Red first; then 5 tests OK
Failures test ...test_sending 10 tests OK
Admin edits test ...test_messages Red first; then 6 tests OK
The Webhooks page test ...test_pages; test_public Errors first; then 7 tests OK; OK
The receiver test ...test_receiver ImportError first; then 5 tests OK
End to end page, receiver, worker, publish and cancel Two messages applied; both Sent at 390 and 1280 px
All checks uv run python check.py == all checks passed; Ran 772 tests
Commit git log --oneline -1 Tell partners of changes with webhooks
Not verified A real partner over TLS to a public address; DNS rebinding against a live resolver; macOS and Linux shells Covered by tests with stand-ins

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 51 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. Step 12 ran for real: in Microsoft Edge, signed in as an administrator with the password check recorded as just given, a Playwright script added the endpoint http://127.0.0.1:8001/, copied its secret from the clipboard, and started examples/receiver.py with it; the Django shell then made a draft of Sam’s, published it, and cancelled it; db_worker --batch sent the two messages over HTTP; and the receiver, verifying with the standardwebhooks library, applied both. The endpoint’s page then showed both as Sent, as a table at 1280 pixels and as cards at 390, with no sideways scroll and every control named. The draft, the endpoint, and its messages stay in the reader’s database, as a reader’s would.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 Why is a webhook’s row written inside the change’s transaction, but sent only after commit?

Flip to check your answerFold answer back

Answer. The row commits with the change, so nothing is lost if the process stops; sending after commit means a change that rolls back, or a dry run, is never announced.

Que. 2 What does webhook-signature prove, and what does it not?

Flip to check your answerFold answer back

Answer. That the message was made by someone holding the shared secret and that the id, timestamp, and body were not changed. Not that it is new or unseen: the receiver checks the timestamp and remembers ids for that.

Que. 3 A partner’s server applied a message, but its answer was lost. What happens next, and what should the partner do?

Flip to check your answerFold answer back

Answer. Otahque sees a failure and sends it again later with the same webhook-id. The partner recognises the id, answers 200, and does not apply it twice.

Que. 4 Why is an endpoint’s address checked again before every send?

Flip to check your answerFold answer back

Answer. A name can be pointed at another address after it was saved, such as an inner one; checking then and connecting to the checked address closes that gap.

Que. 5 Why does the receiver answer 200 to an older version instead of refusing it?

Flip to check your answerFold answer back

Answer. It received the message correctly; refusing it would make Otahque retry it for hours. It is simply not applied.

Mini-Challenge

A draft is never announced, so deleting one should tell no partner either. Write a test, in integrations/tests/test_no_draft.py, that deletes a draft through delete_by() with an endpoint in place, and checks that no message was queued.

Hint: endpoint() in integrations/tests/helpers.py adds the library’s endpoint; ready() in api/tests/test_mine.py saves a draft.

Model answer:

"""Deleting a draft tells no partner (Chapter 52 challenge)."""
from django.test import TestCase

from api.tests.test_mine import ready
from config.helpers import in_group
from integrations.models import WebhookDelivery
from integrations.tests.helpers import endpoint


class DraftDeleteTests(TestCase):
    """A draft was never announced, so nor is its end."""

    def test_deleting_a_draft_sends_nothing(self):
        sam = in_group('sam@example.org', 'Organizers')
        endpoint()
        draft = ready(title='Never shown')
        draft.add_organizer(sam)
        draft.delete_by(sam)
        self.assertFalse(WebhookDelivery.objects.exists())
uv run python manage.py test integrations.tests.test_no_draft
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

delete_by() calls no announce(), and the test keeps it that way: a later change that announced deletions would also announce drafts nobody was ever shown. The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • A webhook pushes a change to a partner; it can be late, duplicated, forged, or lost, and each needs its own answer.
  • Standard Webhooks fixes the headers and the body’s shape, so partners can verify with a published library.
  • An HMAC over id.timestamp.body proves who sent it and that nothing changed; the timestamp limits replays.
  • A row in the change’s transaction, sent after commit, is an outbox: nothing announced that did not happen, nothing lost that did.
  • Retries make delivery at least once; receivers apply each webhook-id once and keep the newest version.
  • A typed address is an attack surface: resolve, refuse inner addresses, connect to what was checked, follow no redirects, and check again before every send.
  • Every change to an event, from the site, the API, or the admin, goes through Event.edit().

Key terms

Use Table 52.3 to explain this chapter’s ideas in your own words.

Table 52.3 — Key terms from Chapter 52
Term Meaning
Webhook An HTTP request sent to a registered address when something happens.
Endpoint The address a partner registered.
Polling Asking on a timer whether anything changed.
HMAC A hash keyed with a shared secret.
Replay Sending a recorded genuine message again.
At least once Every message arrives, perhaps more than once.
Idempotent receiver One that applies each message id once.
Outbox Rows written with the change, sent after commit.
SSRF Making a server send a request it should not.
DNS rebinding A name that resolves elsewhere after it was checked.
Secret rotation A new secret, with the old one valid for an overlap.

Readiness checkpoint: you are ready for Chapter 53 when uv run python check.py ends with “all checks passed” and 772 tests, a publish and a cancel reach examples/receiver.py and show as Sent on the Webhooks page, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 52 work was committed once, in Step 13, as “Tell partners of changes with webhooks”: the integrations app with its models, migrations, signing, address checks, tasks, page, templates, and tests; the events models and admin; the settings, addresses, menu, roles, audit actions and their migration; the status badge, the stylesheet and compiled CSS; pyproject.toml and uv.lock; the receiver; the contract, ADR-009, and two design notes; and the changed guard test. If you kept the Mini-Challenge, commit it on its own:

git add integrations/tests/test_no_draft.py
git commit -m "Check that deleting a draft tells nobody"
PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a signature broken by a proxy and to defending the address rules. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.

L1 (Junior): What is a webhook, and when would you use one instead of polling?

What the interviewer is testing: Can you describe push and pull, and the trade between them?

Flip to check your answerFold answer back

Perfect answer: A webhook is an HTTP request a service sends to an address you registered, when something happens; polling is you asking on a timer. Use a webhook when the change matters soon and happens rarely compared with how often you would ask, as a cancellation does for the library’s calendar. Keep polling, less often, as a safety net, because a message that failed every retry is gone. In Otahque, publish, change, and cancel each queue one message per endpoint, sent after the change commits.

Table 52.4 — Polling and webhooks
Question Polling Webhook
Who starts it The partner Otahque
How late Up to one interval Seconds
Cost when nothing changes Every request Nothing
What can go wrong Late; load Lost, twice, forged

Behind the scenes:

cancel_by()  ->  WebhookDelivery (queued)
commit       ->  send_webhook task
POST https://library.example/hooks/  ->  200

Code proof: the tests of which changes are announced:

Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK

Common mistakes:

  • Treating a webhook as guaranteed, with no polling fallback.
  • Sending from inside the request, so the user waits for the partner.

Follow-up the interviewer might ask:

  • What does the partner answer, and how fast? (2xx within 15 seconds; slow work goes in its own queue.)

L2 (Mid-Level): A try times out, but the partner did get it. Predict what happens next

What the interviewer is testing: Can you reason about at-least-once delivery, from both sides?

Flip to check your answerFold answer back

Perfect answer: Otahque cannot tell “lost on the way there” from “lost on the way back”, so it counts a failure and sends the same message again after the next wait: same webhook-id, same body, a new timestamp and so a new signature. The partner has already applied it. If it applies it again, a “changed” message is harmless, but a “cancelled” one might send its own emails twice. A careful receiver remembers ids it has seen, answers 200 to a repeat so Otahque stops, and does nothing more. The proof sends one message twice to the example receiver.

A numbered flow of five cards. 1, try 1 reaches the partner and is applied. 2, the answer is lost: Otahque sees a timeout. 3, try 2: the same webhook-id and the same body. 4, the partner has seen the id. 5, it answers 200 and does nothing again.
Figure 52.5 — The same message, twice.

Behind the scenes:

try 1  webhook-id msg_9f...  applied
try 2  webhook-id msg_9f...  seen before: 200

Code proof: one message, delivered twice, to the receiver, made and rolled back:

"""A retry of a message that already arrived (52, L2)."""
import json
import time

from django.db import transaction

from accounts.models import User
from examples.receiver import Receiver
from integrations import signing
from integrations.models import WebhookEndpoint

sam = User.objects.get(email='sam@example.org')
with transaction.atomic():
    hook = WebhookEndpoint.objects.create(
        url='https://library.example/hooks/',
        description='Proof', kinds=['event.changed'],
        created_by=sam)
    body = json.dumps({'type': 'event.changed',
                       'timestamp': '2027-01-01T09:00:00Z',
                       'data': {'id': 7, 'title': 'Clinic',
                                'version': 3}})
    delivery = hook.deliveries.create(kind='event.changed',
                                      body=body)
    partner = Receiver(hook.secret)
    ids = []
    for attempt in (1, 2):
        stamp = int(time.time()) + attempt
        headers = signing.headers(hook, delivery, stamp)
        ids.append(headers['webhook-id'])
        status, said = partner.handle(headers, body.encode())
        print(f'try {attempt}:', status, said)
    print('one webhook-id for both tries:', ids[0] == ids[1])
    transaction.set_rollback(True)
try 1: 200 event.changed: Clinic, version 3
try 2: 200 seen before; ignored
one webhook-id for both tries: True

Common mistakes:

  • Answering a repeat with 409, which makes the sender retry for hours.
  • Deduplicating by body, which differs when the timestamp header does not matter but the data does.

Follow-up the interviewer might ask:

  • How long should the receiver remember ids? (Longer than the sender retries: here, more than 17 hours.)

L3 (Senior): Defend sending the whole public event with its version

What the interviewer is testing: Can you weigh payload designs against what the receiver must do?

Flip to check your answerFold answer back

Perfect answer: There are two common shapes. A thin message carries only the id and a link, and the receiver fetches the event through the API; it can never be stale, but every message costs a read, and a flood of messages becomes a flood of reads. A full message carries the event, so the receiver updates from it alone, but messages can arrive out of order, so an older one could overwrite a newer one. Otahque sends the public event, exactly the fields the API already publishes, never member data, plus its version, and the contract tells receivers to keep the highest version per event. That gives the partner what it needs in one message and a simple rule for order. The proof publishes a draft and prints what the partner would be sent.

A numbered flow of five cards. 1, need: a partner shows the right event. 2, thin: an id only, then a read per message. 3, full: the public event, plus version. 4, public fields only, no member data. 5, keep the highest version, ignore the rest.
Figure 52.6 — What a message carries.

Behind the scenes:

{"type": "event.published",
 "timestamp": "2026-12-...",
 "data": {...the public event..., "version": 2}}

Code proof: a draft published with an endpoint listening, made and rolled back:

"""What a partner is sent when an event is published (L3)."""
import json
from datetime import timedelta

from django.db import transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event
from integrations.models import WebhookEndpoint

sam = User.objects.get(email='sam@example.org')
start = timezone.now() + timedelta(days=30)
with transaction.atomic():
    hook = WebhookEndpoint.objects.create(
        url='https://library.example/hooks/',
        description='Proof', kinds=['event.published'],
        created_by=sam)
    event = Event(title='Proof clinic', description='Hi.',
                  starts_at=start,
                  ends_at=start + timedelta(hours=2),
                  timezone='Europe/London', location='Leeds',
                  capacity=10, registration_closes_at=start,
                  cancellation_deadline=start)
    event.save_draft(sam)
    event.publish_by(sam)
    message = json.loads(hook.deliveries.get().body)
    print('type:', message['type'])
    print('data:', ', '.join(sorted(message['data'])))
    print('version:', message['data']['version'])
    transaction.set_rollback(True)
type: event.published
data: cancellation_deadline, capacity, cover, description,
    ends_at, id, location, organizers, places_left,
    registration_closes_at, registration_opens_at, starts_at,
    status, timezone, title, url, version
version: 2

Common mistakes:

  • Putting private fields in a webhook “because the partner is trusted”; the payload goes to their logs too.
  • Ordering by the message’s timestamp, which is when it was made, not which change is newer.

Follow-up the interviewer might ask:

  • When would you switch to thin messages? (If payloads grew large or sensitive, or partners needed fields the public API does not show.)

L4 (Senior): Every signature fails after a partner adds a proxy. Diagnose it

What the interviewer is testing: Do you know what a signature is computed over?

Flip to check your answerFold answer back

Perfect answer: A signature is over bytes, not meaning. If anything between Otahque and the receiver parses the JSON and writes it out again, with different spacing, key order, or escaping, the bytes change and no signature matches, though the data is the same. I would capture the body as the receiver gets it and compare it with what Otahque stored in WebhookDelivery.body; a difference in whitespace confirms it. The fix is on the receiving side: pass the body through unchanged, and verify the raw bytes before any framework parses them. The same mistake happens in code: a receiver that verifies json.dumps(request.json) instead of the request body fails every time. The proof verifies a body as sent, then the same data re-encoded.

A numbered flow of five cards. 1, symptom: every signature fails. 2, compare the bytes sent and received. 3, a proxy re-encoded the JSON. 4, verify the raw body, before parsing. 5, pass bodies through unchanged.
Figure 52.7 — Diagnosing failing signatures.

Behind the scenes:

sent      {"type":"event.changed","data":{"id":7}}
received  {
           "type": "event.changed", ...
same data, different bytes, different HMAC

Code proof: one body, verified as sent and re-encoded:

"""A body re-encoded on the way breaks its signature (L4)."""
import json
import time

from standardwebhooks.webhooks import (
    Webhook, WebhookVerificationError,
)

from integrations import signing
from integrations.models import new_secret


class Sent:
    """Just enough of a delivery to sign."""

    message_id = 'msg_proof'
    body = '{"type":"event.changed","data":{"id":7}}'


class Hook:
    """Just enough of an endpoint to sign."""

    secret = new_secret()

    def secrets_now(self):
        """Return the one secret."""
        return [self.secret]


headers = signing.headers(Hook(), Sent(), int(time.time()))
check = Webhook(Hook.secret)
print('as sent:', check.verify(Sent.body, headers)['type'])
pretty = json.dumps(json.loads(Sent.body), indent=1)
try:
    check.verify(pretty, headers)
except WebhookVerificationError as error:
    print('re-encoded:', error)
as sent: event.changed
re-encoded: No matching signature found

Common mistakes:

  • Signing parsed data on the sending side, so every attempt’s bytes may differ.
  • Disabling verification “temporarily” to get messages flowing.

Follow-up the interviewer might ask:

  • Why does Otahque store the body as text, not as JSON? (So every try sends, and signs, the identical bytes.)

L5 (Lead): Defend the outbound address rules to a team that wants “just a URL field”

What the interviewer is testing: Can you explain a security boundary, its cost, and its layers?

Flip to check your answerFold answer back

Perfect answer: A URL field that the server calls is a request the server makes on someone else’s behalf, from inside our network. Without rules, an administrator’s typo or an attacker with a stolen admin session can make Otahque read a cloud’s metadata service or poke a database port, which is SSRF. The rules cost little: https:// only, no inner addresses after resolving, checked when saved and again before each send because names can change, connecting to the address checked, and no redirects. They are tested address by address. I would also say what they do not cover: a resolver we do not control, or a cloud rule we cannot see, which is why Chapter 63 adds a second layer, an outbound proxy that only lets public addresses out, as the specification and OWASP advise. The decision and its limits are in ADR-009.

A numbered flow of five cards. 1, need: typed addresses must not reach inside. 2, checked at save only fails, because names change. 3, resolve and check before each send. 4, connect to the checked address, with no redirects. 5, an outbound proxy as a second wall, Chapter 63.
Figure 52.8 — Layers against SSRF.

Behind the scenes:

save   resolve, check every address
send   resolve, check again, connect to the IP
TLS    name kept for SNI and the certificate
63     outbound proxy: public addresses only

Code proof: the address tests:

Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Common mistakes:

  • Blocking the word localhost and calling it done; 127.1, [::1], or a name that resolves to them pass.
  • Checking the address, then letting the HTTP library resolve it again and follow redirects.

Follow-up the interviewer might ask:

  • Why allow loopback while developing? (So a receiver on the same computer can be tried; DEBUG is off in production, and the tests run with it off.)

Next: Chapter 53, Async Django, ASGI, and sync/async boundaries, looks at what async changes in Django, and where it does and does not help Otahque, starting with a Send test button on the Webhooks page.

PAGE 006