Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Webhooks: signed send time (Speakr-Signature-V2), rotation grace, recording.updated from every write path, updated_at and occurred_at (mailr spec W1 to W4)

Murtaza Nasir0c7c81697b5a
diff --git a/config/env.asr.example b/config/env.asr.example
index fda16b5b..394acd4b 100644
--- a/config/env.asr.example
+++ b/config/env.asr.example
@@ -394,6 +394,10 @@ MAX_CONCURRENT_UPLOADS=3
# the changes feed (/api/v1/recordings/changes). Default: 90.
# RECORDING_TOMBSTONE_DAYS=90
+# How long the previous webhook secret still signs Speakr-Signature-V2 after
+# a rotation, in hours. Default: 24.
+# WEBHOOK_SECRET_GRACE_HOURS=24
+
# --- Server-Side Recording Sessions (optional) ---
# Opt-in: in-app recordings stream audio chunks to the server as they record,
# instead of buffering the entire recording in browser RAM. This enables
diff --git a/config/env.transcription.example b/config/env.transcription.example
index ba899b22..451a301e 100644
--- a/config/env.transcription.example
+++ b/config/env.transcription.example
@@ -552,6 +552,10 @@ MAX_CONCURRENT_UPLOADS=3
# the changes feed (/api/v1/recordings/changes). Default: 90.
# RECORDING_TOMBSTONE_DAYS=90
+# How long the previous webhook secret still signs Speakr-Signature-V2 after
+# a rotation, in hours. Default: 24.
+# WEBHOOK_SECRET_GRACE_HOURS=24
+
# =============================================================================
# SERVER-SIDE RECORDING SESSIONS (optional)
# =============================================================================
diff --git a/config/env.whisper.example b/config/env.whisper.example
index 55db544e..20f4fcab 100644
--- a/config/env.whisper.example
+++ b/config/env.whisper.example
@@ -390,6 +390,10 @@ MAX_CONCURRENT_UPLOADS=3
# the changes feed (/api/v1/recordings/changes). Default: 90.
# RECORDING_TOMBSTONE_DAYS=90
+# How long the previous webhook secret still signs Speakr-Signature-V2 after
+# a rotation, in hours. Default: 24.
+# WEBHOOK_SECRET_GRACE_HOURS=24
+
# --- Server-Side Recording Sessions (optional) ---
# Opt-in: in-app recordings stream audio chunks to the server as they record,
# instead of buffering the entire recording in browser RAM. This enables
diff --git a/config/env.whisperx.example b/config/env.whisperx.example
index 42d144ba..e43978bf 100644
--- a/config/env.whisperx.example
+++ b/config/env.whisperx.example
@@ -308,6 +308,10 @@ MAX_CONCURRENT_UPLOADS=3
# the changes feed (/api/v1/recordings/changes). Default: 90.
# RECORDING_TOMBSTONE_DAYS=90
+# How long the previous webhook secret still signs Speakr-Signature-V2 after
+# a rotation, in hours. Default: 24.
+# WEBHOOK_SECRET_GRACE_HOURS=24
+
# --- Background Processing Queues ---
# Separate queues for transcription (slow) and summary (fast) jobs
# This prevents slow ASR jobs from blocking quick summary generation
diff --git a/docs/admin-guide/webhooks.md b/docs/admin-guide/webhooks.md
index 58d0825e..7c8cccc3 100644
--- a/docs/admin-guide/webhooks.md
+++ b/docs/admin-guide/webhooks.md
@@ -19,7 +19,7 @@ or programmatically via the `/api/v1/webhooks` API.
| `recording.summary.completed` | Summary generated successfully | `recording_id`, `title`, `summarization_duration_seconds` |
| `recording.summary.failed` | Summary failed permanently | `recording_id`, `title`, `error` |
| `recording.events.extracted` | Calendar event extraction finished and produced at least one event | `recording_id`, `title`, `events_count` |
-| `recording.updated` | Title, participants, notes, summary, meeting_date, is_inbox, is_highlighted, or folder_id changed via `PATCH /api/v1/recordings/{id}` | `recording_id`, `title`, `fields_changed` (list of strings) |
+| `recording.updated` | A change a user can see, from the web app or the API (see below) | `recording_id`, `title`, `fields_changed` (list of strings), `updated_at` |
| `recording.deleted` | Recording removed | `recording_id`, `title` |
| `webhook.test` | Synthetic event from the **Test** button or `POST /api/v1/webhooks/{id}/test` | `reason`, `webhook_id` |
@@ -29,11 +29,30 @@ file's existence on disk is confirmed, so subscribers don't see
misleading started→failed sequences for jobs that abort immediately
(e.g. the audio file was deleted between upload and worker pickup).
-The `recording.updated` event is **not currently debounced**. Rapid
-edits (e.g. notes autosave, drag-drop tag changes) emit one event per
-mutation. Receivers that want to coalesce can deduplicate on
-`(recording_id, fields_changed)` within a short window. A built-in
-debounce is planned for a later release (see `docs/roadmap.md`).
+`recording.updated` fires once per saved change, whether the change was made in the web
+app, through API v1 or by a speaker rename or merge. `fields_changed` uses these words:
+
+| Word | Changed |
+|---|---|
+| `title`, `participants`, `notes`, `summary`, `meeting_date`, `folder_id` | that field |
+| `transcript` | the transcript text or its speaker names |
+| `speakers` | which name each diarization label shows |
+| `tags` | a tag was added, removed or reordered |
+| `events` | extracted calendar events changed |
+| `is_inbox`, `is_highlighted`, `is_archived` | the owner's flags |
+| `audio` | the audio was removed |
+| `deletion_exempt`, `prompt_variables` | that setting |
+
+Status changes during processing fire no `recording.updated`; the lifecycle events above
+cover them. Changes a user who received a shared recording makes to their own flags fire
+nothing for the owner.
+
+Bursts are merged: a `recording.updated` with the same `recording_id` and `fields_changed`
+as a delivery that has not been attempted yet replaces that delivery's `data`, so a notes
+autosave sends one delivery with the latest state.
+
+Since v0.10.11-alpha, edits made in the web app fire `recording.updated` too. Before, only
+`PATCH /api/v1/recordings/{id}` did, so receivers subscribed to this event get more of them.
## Envelope
@@ -43,18 +62,28 @@ Every delivery is a `POST` with a JSON body shaped like:
{
"id": "f4e6a4e1-3b9b-4a04-9d4f-0e7a5d8b3c10",
"type": "recording.transcription.completed",
- "timestamp": "2026-06-04T15:23:11.124Z",
+ "timestamp": "2026-06-04T15:23:11.124000Z",
+ "occurred_at": "2026-06-04T15:23:11.124000Z",
"user_id": 42,
"data": {
"recording_id": 9173,
"title": "Q3 planning",
"language": "en",
"audio_duration_seconds": 3624.7,
- "transcription_duration_seconds": 212
+ "transcription_duration_seconds": 212,
+ "updated_at": "2026-06-04T15:23:10.981233Z"
}
}
```
+- `id` is one UUID per event; every webhook that receives the event gets the same `id`.
+- `timestamp` and `occurred_at` are the time the event happened (UTC, microseconds). They do
+ not change on retries: the body is stored once and every attempt sends the same bytes.
+- `data` of every `recording.*` event carries `updated_at`, the recording's last change as
+ in the API (absent for `recording.deleted`).
+- The body is `json.dumps(envelope, separators=(',', ':'), ensure_ascii=False)` in UTF-8.
+ Verify the signature over the raw bytes you received, never over re-serialised JSON.
+
`language` is the language the transcription service reported for that recording,
as an ISO 639-1 code. It reflects what was detected or used for that audio, not the
user's current transcription-language preference. Fields are omitted when Speakr does
@@ -68,18 +97,62 @@ Headers:
|---|---|
| `Content-Type: application/json` | Body format |
| `User-Agent: Speakr-Webhook/1.0` | Identifies Speakr to receivers |
-| `Speakr-Event` | The event type — useful for routing without parsing the body |
-| `Speakr-Delivery-Id` | UUID echo of `data.id` — receivers use it for idempotency |
-| `Speakr-Timestamp` | ISO-8601 UTC of dispatch — receivers may reject stale deliveries |
-| `Speakr-Signature` | `sha256=<hex>` HMAC of the raw body with the webhook's secret |
+| `Speakr-Event` | The event type, for routing without parsing the body |
+| `Speakr-Delivery-Id` | The envelope `id`; use it for idempotency |
+| `Speakr-Signature-V2` | `t=<send time, Unix seconds>,v1=<hex>`: HMAC-SHA256 of `"<t>." + raw body`. Verify this one when it is present. |
+| `Speakr-Signature` | `sha256=<hex>`: HMAC-SHA256 of the raw body |
+| `Speakr-Attempt` | `1` for the first attempt, `2` for the first retry, and so on |
+| `Speakr-Timestamp` | ISO 8601 UTC send time. **Not signed**: do not use it for freshness checks. |
## Signature verification
-Every receiver must verify the `Speakr-Signature` header before
-trusting the body. Failure to verify means anyone who guesses the URL
-can forge events.
+Every receiver must verify a signature before trusting the body. Without it, anyone who
+guesses the URL can forge events.
+
+Verify `Speakr-Signature-V2` when it is present. Its signature covers the send time `t`, so
+a receiver can refuse old deliveries (for example `|now - t| > 300` seconds) while every
+retry still passes: each attempt is signed with its own send time over the same body.
+During a secret rotation the header carries two `v1=` values; accept a match with either.
-### Python
+### Python (V2)
+
+```python
+import hmac
+import hashlib
+import time
+
+def verify_speakr_v2(secret: str, raw_body: bytes, header: str, window: int = 300) -> bool:
+ parts = [p.split('=', 1) for p in header.split(',') if '=' in p]
+ try:
+ t = int(next(v for k, v in parts if k == 't'))
+ except (StopIteration, ValueError):
+ return False
+ if abs(time.time() - t) > window:
+ return False
+ expected = hmac.new(secret.encode(), f'{t}.'.encode() + raw_body, hashlib.sha256).hexdigest()
+ return any(hmac.compare_digest(expected, v) for k, v in parts if k == 'v1')
+```
+
+### Node.js (V2)
+
+```js
+const crypto = require('crypto');
+
+function verifySpeakrV2(secret, rawBody, header, windowSeconds = 300) {
+ if (!header) return false;
+ const parts = header.split(',').map(p => p.split('='));
+ const t = Number((parts.find(([k]) => k === 't') || [])[1]);
+ if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > windowSeconds) return false;
+ const expected = crypto.createHmac('sha256', secret)
+ .update(Buffer.concat([Buffer.from(`${t}.`), rawBody])).digest();
+ return parts.filter(([k]) => k === 'v1').some(([, v]) => {
+ const given = Buffer.from(v || '', 'hex');
+ return given.length === expected.length && crypto.timingSafeEqual(expected, given);
+ });
+}
+```
+
+### Python (V1, `Speakr-Signature`)
```python
import hmac
@@ -93,7 +166,7 @@ def verify_speakr(secret: str, raw_body: bytes, signature_header: str) -> bool:
return hmac.compare_digest(expected, given)
```
-### Node.js
+### Node.js (V1)
```js
const crypto = require('crypto');
@@ -118,6 +191,21 @@ echo -n "$RAW_BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print "sha256
Compare the output against the `Speakr-Signature` header value.
+### Idempotency
+
+Answer `2xx` to a `Speakr-Delivery-Id` you have already processed. Any other `4xx` counts as
+a permanent failure, so refusing a repeat with `409` would stop the retries of a delivery
+you never finished.
+
+### Secret rotation
+
+`POST /api/v1/webhooks/{id}/rotate-secret` returns the new secret once. The previous secret
+stays valid for `WEBHOOK_SECRET_GRACE_HOURS` (default 24): until then `Speakr-Signature-V2`
+carries a second `v1=` value signed with it, so a receiver can switch to the new secret
+without missing deliveries. `Speakr-Signature` uses the new secret at once. The webhook's
+`previous_secret_valid_until` shows when the grace ends; the old secret itself is never
+returned.
+
## Retry policy
Delivery attempts use the following backoff schedule:
@@ -132,8 +220,14 @@ Delivery attempts use the following backoff schedule:
After attempt 5, status flips to `permanent_failure` and the webhook's
`consecutive_failures` counter increments. When it reaches
-`WEBHOOK_AUTOPAUSE_FAILURES` (default 10) the webhook is auto-paused; the
-user must manually re-enable it.
+`WEBHOOK_AUTOPAUSE_FAILURES` (default 10) the webhook is auto-paused. An
+auto-paused webhook gets one trial delivery every
+`WEBHOOK_TRIAL_INTERVAL_SECONDS` (default 3600); a successful trial resumes it.
+Re-enabling it by hand also clears the pause.
+
+A replay (`POST /api/v1/webhooks/{id}/deliveries/{did}/replay`) is a new
+delivery: a new `id`, a new `timestamp` and `occurred_at`, and `replayed_from`
+with the old `id`.
**Retryable HTTP responses:** 408, 429, 5xx, plus network errors and
timeouts.
@@ -170,6 +264,8 @@ payloads.
| `WEBHOOK_AUTOPAUSE_FAILURES` | `10` | Consecutive failures before auto-pause. |
| `WEBHOOK_DISPATCHER_INTERVAL_SECONDS` | `5` | How often the dispatcher polls for due deliveries. |
| `WEBHOOK_INTRANET_HOST_ALLOWLIST` | empty | Regex of allowed private hosts. Empty = SSRF block always applies. |
+| `WEBHOOK_TRIAL_INTERVAL_SECONDS` | `3600` | Trial delivery interval for an auto-paused webhook; `0` disables trials. |
+| `WEBHOOK_SECRET_GRACE_HOURS` | `24` | How long the previous secret still signs `Speakr-Signature-V2` after a rotation; `0` ends it at once. |
## API surface
@@ -183,7 +279,7 @@ or an API token. The OpenAPI schema documents every field.
| GET | `/api/v1/webhooks/{id}` | Read one. Secret is never returned. |
| PATCH | `/api/v1/webhooks/{id}` | Update name / url / events / enabled / allow_http. |
| DELETE | `/api/v1/webhooks/{id}` | Delete (cascades to deliveries). |
-| POST | `/api/v1/webhooks/{id}/rotate-secret` | Generate a fresh HMAC secret. Returned once. |
+| POST | `/api/v1/webhooks/{id}/rotate-secret` | Generate a fresh HMAC secret. Returned once; the previous one stays valid for the grace period. |
| POST | `/api/v1/webhooks/{id}/test` | Queue a synthetic `webhook.test` delivery. |
| GET | `/api/v1/webhooks/{id}/deliveries` | Recent deliveries (default 50, max 200). |
| GET | `/api/v1/webhooks/{id}/deliveries/{did}` | Full delivery record including the original payload. |
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.md
index a2c441e6..81080c3a 100644
--- a/docs/user-guide/api-reference.md
+++ b/docs/user-guide/api-reference.md
@@ -1398,7 +1398,7 @@ Returns the active transcription connector, the optional fields it accepts, the
Webhooks deliver event notifications to an external URL when things happen to your recordings. Each webhook is owned by the user who creates it. The number of webhooks per user is capped (default 10, configurable by the administrator via `WEBHOOK_MAX_PER_USER`).
!!! info "Delivery security and reliability"
- Each delivery is signed with an HMAC-SHA256 signature sent in the `Speakr-Signature` header (formatted as `sha256=<hex>`), computed over the raw request body using the webhook's secret. Deliveries also carry `Speakr-Delivery-Id` (a UUID for idempotency), `Speakr-Event` (the event type), and `Speakr-Timestamp` headers. Failed deliveries are retried automatically; after a configurable number of consecutive failures (`WEBHOOK_AUTOPAUSE_FAILURES`, default 10) the webhook is auto-paused (`auto_paused: true`, `enabled: false`). Re-enabling it manually clears the auto-pause flag.
+ Each delivery is signed twice with the webhook's secret: `Speakr-Signature-V2` (`t=<send time>,v1=<hex>`, HMAC-SHA256 of `"<t>." + raw body`; verify this one when present) and `Speakr-Signature` (`sha256=<hex>` of the raw body). Deliveries also carry `Speakr-Delivery-Id` (a UUID for idempotency; answer `2xx` to a repeat), `Speakr-Event`, `Speakr-Attempt`, and `Speakr-Timestamp` (not signed). `recording.updated` fires for every visible change, from the web app or the API. Failed deliveries are retried automatically; after a configurable number of consecutive failures (`WEBHOOK_AUTOPAUSE_FAILURES`, default 10) the webhook is auto-paused (`auto_paused: true`, `enabled: false`). Re-enabling it manually clears the auto-pause flag.
For administrator-level configuration and receiver setup, see the [Webhooks admin guide](../admin-guide/webhooks.md).
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 82b9ec78..e48ed744 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -890,6 +890,7 @@ CAPABILITY_FEATURES = {
'token_scopes': True,
'changes_feed': True,
'etags': True,
+ 'webhook_signature_v2': True,
}
@@ -1513,27 +1514,17 @@ def update_recording(recording_id):
'error': 'keep_audio_only is set at upload time and cannot be changed afterwards.'
}), 400
- # Track which fields actually changed so the webhook payload tells
- # subscribers what was touched (recording.updated event, #275).
- # Compared against the incoming key set, not the prior value, so an
- # explicit no-op write still surfaces as an intentional update.
- changed_fields = []
-
# Update fields if provided
if 'title' in data:
if data['title'] != recording.title:
recording.title_source = 'user'
recording.title = data['title']
- changed_fields.append('title')
if 'participants' in data:
recording.participants = data['participants']
- changed_fields.append('participants')
if 'notes' in data:
recording.notes = data['notes']
- changed_fields.append('notes')
if 'summary' in data:
recording.summary = data['summary']
- changed_fields.append('summary')
if 'meeting_date' in data:
try:
if data['meeting_date']:
@@ -1542,15 +1533,12 @@ def update_recording(recording_id):
recording.meeting_date = to_utc_naive(datetime.fromisoformat(data['meeting_date'].replace('Z', '+00:00')))
else:
recording.meeting_date = None
- changed_fields.append('meeting_date')
except ValueError:
return jsonify({'error': 'Invalid meeting_date format'}), 400
if 'is_inbox' in data:
recording.is_inbox = bool(data['is_inbox'])
- changed_fields.append('is_inbox')
if 'is_highlighted' in data:
recording.is_highlighted = bool(data['is_highlighted'])
- changed_fields.append('is_highlighted')
if 'is_archived' in data:
archived = parse_archived_flag(data['is_archived'])
if archived is None:
@@ -1558,7 +1546,6 @@ def update_recording(recording_id):
# Per user, like the web app: a shared editor archives it for
# themselves only (#394).
set_user_archived(recording, current_user, archived, commit=False)
- changed_fields.append('is_archived')
if 'folder_id' in data:
new_folder_id = data['folder_id']
if new_folder_id is None:
@@ -1579,28 +1566,11 @@ def update_recording(recording_id):
if not membership:
return jsonify({'error': 'No access to target folder'}), 403
recording.folder_id = new_folder_id
- changed_fields.append('folder_id')
db.session.commit()
- # Webhook fan-out (#275) for `recording.updated`. Best-effort: a
- # webhook failure must not roll back the legitimate mutation that
- # already committed. Debouncing across rapid edits is a future
- # improvement; for now every PATCH fires once.
- if changed_fields:
- try:
- from src.services.webhook_dispatch import emit_webhook_event
- emit_webhook_event(
- user_id=recording.user_id,
- event_type='recording.updated',
- data={
- 'recording_id': recording.id,
- 'title': recording.title,
- 'fields_changed': changed_fields,
- },
- )
- except Exception as e:
- current_app.logger.warning(f"Webhook emit (recording.updated) failed for recording {recording_id}: {e}")
+ # recording.updated goes out from the change listener after the commit
+ # (src/services/recording_changes.py), the same for every write path.
return jsonify({
'success': True,
diff --git a/src/api/webhooks.py b/src/api/webhooks.py
index 1c8d60df..a9fd5459 100644
--- a/src/api/webhooks.py
+++ b/src/api/webhooks.py
@@ -196,6 +196,20 @@ def rotate_secret(webhook_id):
wh, err = _load_owned(webhook_id)
if err:
return err
+ # The old secret stays valid for WEBHOOK_SECRET_GRACE_HOURS: Speakr-Signature-V2
+ # carries a second v1= value signed with it until then (spec W2).
+ import os as _os
+ from datetime import timedelta
+ try:
+ grace_hours = float(_os.environ.get('WEBHOOK_SECRET_GRACE_HOURS', '24'))
+ except ValueError:
+ grace_hours = 24.0
+ if grace_hours > 0:
+ wh.previous_secret = wh.secret
+ wh.previous_secret_expires_at = datetime.utcnow() + timedelta(hours=grace_hours)
+ else:
+ wh.previous_secret = None
+ wh.previous_secret_expires_at = None
wh.secret = generate_webhook_secret()
db.session.commit()
return jsonify(wh.to_dict(include_secret=True))
@@ -302,6 +316,7 @@ def replay_delivery(webhook_id, delivery_id):
envelope = _json.loads(src.payload)
envelope['id'] = new_event_id
envelope['timestamp'] = datetime.utcnow().isoformat() + 'Z'
+ envelope['occurred_at'] = envelope['timestamp']
envelope['replayed_from'] = src.event_id
new_payload = serialize_envelope(envelope)
except Exception:
diff --git a/src/init_db.py b/src/init_db.py
index 3a2d13de..15c0ef92 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -708,6 +708,13 @@ def _run_migrations(app, engine):
app.logger.warning(f"Error during meeting_date migration: {e}")
app.logger.warning("New recordings will work correctly, but existing dates may need manual migration")
+ with _migration_section(app, failures, "webhook secret rotation grace"):
+ # mailr spec W2: the previous secret signs a second V2 value for a while.
+ if add_column_if_not_exists(engine, 'webhook', 'previous_secret', 'VARCHAR(120)'):
+ app.logger.info("Added previous_secret column to webhook table")
+ if add_column_if_not_exists(engine, 'webhook', 'previous_secret_expires_at', 'DATETIME'):
+ app.logger.info("Added previous_secret_expires_at column to webhook table")
+
with _migration_section(app, failures, "notifications"):
# The table itself comes from create_all(); these cover a database
# that already had an earlier version of it. Columns are added
diff --git a/src/models/webhook.py b/src/models/webhook.py
index b4090cc5..256a07ff 100644
--- a/src/models/webhook.py
+++ b/src/models/webhook.py
@@ -78,6 +78,10 @@ class Webhook(db.Model):
# responses, surface to the user only on creation, allow rotation
# via a dedicated endpoint.
secret = db.Column(db.String(120), nullable=False, default=generate_webhook_secret)
+ # The secret before the last rotation, accepted until previous_secret_expires_at
+ # (WEBHOOK_SECRET_GRACE_HOURS). Never returned by the API.
+ previous_secret = db.Column(db.String(120), nullable=True)
+ previous_secret_expires_at = db.Column(db.DateTime, nullable=True)
# JSON array of event type strings the endpoint is subscribed to.
# Validated against WEBHOOK_EVENT_TYPES on write.
@@ -158,6 +162,10 @@ class Webhook(db.Model):
'created_at': self.created_at.isoformat() if self.created_at else None,
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
'last_delivery_at': self.last_delivery_at.isoformat() if self.last_delivery_at else None,
+ 'previous_secret_valid_until': (
+ self.previous_secret_expires_at.isoformat() + 'Z'
+ if self.previous_secret and self.previous_secret_expires_at
+ and self.previous_secret_expires_at > datetime.utcnow() else None),
}
if include_secret:
payload['secret'] = self.secret
diff --git a/src/services/recording_changes.py b/src/services/recording_changes.py
index 65b08ebb..bd3018f8 100644
--- a/src/services/recording_changes.py
+++ b/src/services/recording_changes.py
@@ -13,6 +13,11 @@ tombstone for that user. The changes feed reads updated_at and the
tombstones in one order, (changed_at, kind, id), and pages with an opaque
cursor.
+The same listener collects what changed per recording; after the commit one
+recording.updated webhook goes out per recording (spec W3), so an edit from
+the web app fires the same event as an API PATCH. Status changes during
+processing fire none: the lifecycle events cover them.
+
Bulk Query.update() bypasses ORM events; tests/test_recording_changes.py fails
if one is added for the recording table.
"""
@@ -34,6 +39,17 @@ TRACKED_FIELDS = (
'error_message', 'speaker_label_map', 'deletion_exempt', 'prompt_variables',
)
+# Column -> the word in recording.updated fields_changed. Columns not listed
+# (status, completed_at, error_message) move updated_at but fire no
+# recording.updated; the lifecycle events cover them.
+WEBHOOK_FIELD_NAMES = {
+ 'title': 'title', 'participants': 'participants', 'notes': 'notes', 'summary': 'summary',
+ 'transcription': 'transcript', 'meeting_date': 'meeting_date', 'folder_id': 'folder_id',
+ 'is_inbox': 'is_inbox', 'is_highlighted': 'is_highlighted', 'is_archived': 'is_archived',
+ 'speaker_label_map': 'speakers', 'audio_deleted_at': 'audio', 'deletion_exempt': 'deletion_exempt',
+ 'prompt_variables': 'prompt_variables',
+}
+
SETTLE_SECONDS = 2
TOMBSTONE_DAYS = int(os.environ.get('RECORDING_TOMBSTONE_DAYS', '90') or 90)
FEED_SINCE_KEY = 'changes_feed_since'
@@ -59,20 +75,28 @@ def effective_updated_at(recording):
# ---------------------------------------------------------------- listener
def _child_recording_ids(session):
- """Recording ids touched through a row that belongs to a recording."""
+ """{recording id: webhook field or None} for rows that belong to a recording.
+
+ Tags, events and external references are part of the owner's view
+ (fields tags, events, external_refs). Shares and a recipient's own state
+ move updated_at but fire no recording.updated for the owner (None).
+ """
from src.models import Event, InternalShare, RecordingTag, SharedRecordingState
- child_types = (RecordingTag, Event, InternalShare, SharedRecordingState)
+ kinds = [(RecordingTag, 'tags'), (Event, 'events'), (InternalShare, None), (SharedRecordingState, None)]
try:
from src.models import RecordingExternalRef # G8
- child_types = child_types + (RecordingExternalRef,)
+ kinds.append((RecordingExternalRef, 'external_refs'))
except ImportError:
pass
- ids = set()
+ ids = {}
for obj in list(session.new) + list(session.dirty) + list(session.deleted):
- if isinstance(obj, child_types):
- rid = getattr(obj, 'recording_id', None)
- if rid is not None:
- ids.add(rid)
+ for model, field in kinds:
+ if isinstance(obj, model):
+ rid = getattr(obj, 'recording_id', None)
+ if rid is not None:
+ fields = ids.setdefault(rid, set())
+ if field:
+ fields.add(field)
return ids
@@ -104,11 +128,13 @@ def _before_flush(session, flush_context, instances):
deleted_recordings = {obj.id for obj in session.deleted if isinstance(obj, Recording)}
with session.no_autoflush:
- for rid in _child_recording_ids(session) - deleted_recordings:
+ for rid, fields in _child_recording_ids(session).items():
+ if rid in deleted_recordings:
+ continue
rec = session.get(Recording, rid)
if rec is not None and rec not in session.new:
rec.updated_at = now
- changes.setdefault(rid, set()).add('related')
+ changes.setdefault(rid, set()).update(fields)
for obj in session.deleted:
if isinstance(obj, Recording):
@@ -135,12 +161,60 @@ def _add_tombstone(session, recording_id, user_id, now, reason):
session.add(RecordingTombstone(recording_id=recording_id, user_id=user_id, deleted_at=now, reason=reason))
+def _after_flush(session, flush_context):
+ """Remember owner, title and updated_at while the rows are loaded; after
+ the commit the objects are expired and the session cannot query."""
+ from sqlalchemy.orm.util import identity_key
+ from src.models import Recording
+ changes = session.info.get('recording_changes')
+ if not changes:
+ return
+ facts = session.info.setdefault('recording_change_facts', {})
+ for rid in changes:
+ rec = session.identity_map.get(identity_key(Recording, rid))
+ if rec is not None:
+ facts[rid] = (rec.user_id, rec.title, iso_z(rec.updated_at or rec.created_at))
+
+
+def _after_commit(session):
+ changes = session.info.pop('recording_changes', None) or {}
+ facts = session.info.pop('recording_change_facts', None) or {}
+ events = []
+ for rid, columns in changes.items():
+ fields = sorted({WEBHOOK_FIELD_NAMES.get(c, c) for c in columns
+ if c in WEBHOOK_FIELD_NAMES or c in ('tags', 'events', 'external_refs')})
+ if fields and rid in facts:
+ user_id, title, updated_at = facts[rid]
+ events.append((user_id, {'recording_id': rid, 'title': title, 'fields_changed': fields,
+ 'updated_at': updated_at}))
+ if not events:
+ return
+ try:
+ from src.services.webhook_dispatch import _global_enabled, enqueue_event
+ if not _global_enabled():
+ return
+ with Session(bind=session.get_bind()) as webhook_session:
+ for user_id, data in events:
+ enqueue_event(webhook_session, user_id, 'recording.updated', data)
+ except Exception as e: # webhooks never undo or fail the change itself
+ import logging
+ logging.getLogger(__name__).warning(f"recording.updated webhook not queued: {e}")
+
+
+def _after_rollback(session):
+ session.info.pop('recording_changes', None)
+ session.info.pop('recording_change_facts', None)
+
+
def register_change_tracking():
- """Register the listener once, for every session."""
+ """Register the listeners once, for every session."""
global _registered
if _registered:
return
event.listen(Session, 'before_flush', _before_flush)
+ event.listen(Session, 'after_flush', _after_flush)
+ event.listen(Session, 'after_commit', _after_commit)
+ event.listen(Session, 'after_soft_rollback', lambda session, previous_transaction: _after_rollback(session))
_registered = True
diff --git a/src/services/speaker_merge.py b/src/services/speaker_merge.py
index ca184c37..3c8e13f1 100644
--- a/src/services/speaker_merge.py
+++ b/src/services/speaker_merge.py
@@ -190,19 +190,15 @@ def rename_speaker_in_recordings(user_id, old_name, new_name):
def refresh_renamed_recordings(changed):
"""After names change in committed recordings: rebuild their Inquire
chunks (the chunk text holds the names), rewrite their auto-exports and
- send recording.updated for each. changed: {recording id: fields}."""
+ recording.updated goes out from the change listener on commit.
+ changed: {recording id: fields}."""
if not changed:
return
from flask import current_app
from src.api import recordings as recordings_api
from src.file_exporter import ENABLE_AUTO_EXPORT, export_recording
- from src.models import Recording
- from src.services.webhook_dispatch import emit_recording_updated
for rid in sorted(changed):
recordings_api.reindex_recording_chunks_async(rid)
- recording = db.session.get(Recording, rid)
- if recording is not None:
- emit_recording_updated(recording, sorted(changed[rid]))
if ENABLE_AUTO_EXPORT:
try:
export_recording(rid)
diff --git a/src/services/webhook_dispatch.py b/src/services/webhook_dispatch.py
index 55fd4598..cc90cd7c 100644
--- a/src/services/webhook_dispatch.py
+++ b/src/services/webhook_dispatch.py
@@ -334,11 +334,33 @@ def sign_payload(secret: str, body: bytes) -> str:
return f'sha256={mac.hexdigest()}'
+def sign_payload_v2(secret: str, t: int, body: bytes) -> str:
+ """One v1= value of Speakr-Signature-V2: HMAC-SHA256 over "<t>." + body.
+
+ The send time t is inside the signature, so a receiver can check
+ freshness on every attempt while the body stays byte-identical.
+ """
+ mac = hmac.new(secret.encode('utf-8'), f'{t}.'.encode('utf-8') + body, hashlib.sha256)
+ return mac.hexdigest()
+
+
+def signature_v2_header(webhook, t: int, body: bytes) -> str:
+ """t=<unix seconds>,v1=<new secret>[,v1=<previous secret during the rotation grace>]."""
+ parts = [f't={t}', f'v1={sign_payload_v2(webhook.secret, t, body)}']
+ previous = getattr(webhook, 'previous_secret', None)
+ expires = getattr(webhook, 'previous_secret_expires_at', None)
+ if isinstance(previous, str) and previous and isinstance(expires, datetime) and expires > datetime.utcnow():
+ parts.append(f'v1={sign_payload_v2(previous, t, body)}')
+ return ','.join(parts)
+
+
def _build_envelope(event_id: str, event_type: str, user_id: int, data: dict):
+ now = datetime.utcnow().isoformat() + 'Z'
return {
'id': event_id,
'type': event_type,
- 'timestamp': datetime.utcnow().isoformat() + 'Z',
+ 'timestamp': now,
+ 'occurred_at': now,
'user_id': user_id,
'data': data or {},
}
@@ -377,34 +399,7 @@ def emit_webhook_event(user_id: int, event_type: str, data: dict, *, app=None) -
return 0
def _do_enqueue():
- # Find enabled, non-paused webhooks for the user that subscribe to this event.
- subscriptions = (
- Webhook.query
- .filter_by(user_id=user_id, enabled=True)
- .all()
- )
- matched = [w for w in subscriptions if event_type in w.event_list]
- if not matched:
- return 0
-
- event_id = str(uuid.uuid4())
- first_attempt_at = datetime.utcnow()
- created = 0
- for wh in matched:
- envelope = _build_envelope(event_id, event_type, user_id, data)
- delivery = WebhookDelivery(
- webhook_id=wh.id,
- event_id=event_id,
- event_type=event_type,
- payload=serialize_envelope(envelope),
- status='pending',
- next_retry_at=first_attempt_at,
- )
- db.session.add(delivery)
- created += 1
- if created:
- db.session.commit()
- return created
+ return enqueue_event(db.session, user_id, event_type, data)
if app is not None:
with app.app_context():
@@ -412,6 +407,69 @@ def emit_webhook_event(user_id: int, event_type: str, data: dict, *, app=None) -
return _do_enqueue()
+def _with_updated_at(session, event_type, data):
+ """data of a recording.* event carries the recording's updated_at (spec W4)."""
+ data = dict(data or {})
+ if event_type.startswith('recording.') and 'updated_at' not in data and data.get('recording_id'):
+ from src.models import Recording
+ rec = session.get(Recording, data['recording_id'])
+ if rec is not None:
+ data['updated_at'] = rec.updated_at_z()
+ return data
+
+
+def _merge_pending_update(session, webhook_id, data):
+ """Fold a recording.updated into a not-yet-attempted delivery for the same
+ recording and fields (autosave bursts give one delivery). Returns True when
+ merged."""
+ candidates = (session.query(WebhookDelivery)
+ .filter_by(webhook_id=webhook_id, event_type='recording.updated',
+ status='pending', attempt_count=0)
+ .order_by(WebhookDelivery.id.desc()).limit(20).all())
+ for delivery in candidates:
+ try:
+ envelope = json.loads(delivery.payload)
+ except (TypeError, ValueError):
+ continue
+ old = envelope.get('data') or {}
+ if (old.get('recording_id') == data.get('recording_id')
+ and sorted(old.get('fields_changed') or []) == sorted(data.get('fields_changed') or [])):
+ envelope['data'] = data
+ delivery.payload = serialize_envelope(envelope)
+ return True
+ return False
+
+
+def enqueue_event(session, user_id, event_type, data):
+ """Write one pending delivery per subscribed webhook through ``session``
+ and commit it. Returns the number of deliveries written or merged."""
+ subscriptions = session.query(Webhook).filter_by(user_id=user_id, enabled=True).all()
+ matched = [w for w in subscriptions if event_type in w.event_list]
+ if not matched:
+ return 0
+ data = _with_updated_at(session, event_type, data)
+ event_id = str(uuid.uuid4())
+ first_attempt_at = datetime.utcnow()
+ created = 0
+ for wh in matched:
+ if event_type == 'recording.updated' and _merge_pending_update(session, wh.id, data):
+ created += 1
+ continue
+ envelope = _build_envelope(event_id, event_type, user_id, data)
+ session.add(WebhookDelivery(
+ webhook_id=wh.id,
+ event_id=event_id,
+ event_type=event_type,
+ payload=serialize_envelope(envelope),
+ status='pending',
+ next_retry_at=first_attempt_at,
+ ))
+ created += 1
+ if created:
+ session.commit()
+ return created
+
+
# ---- Dispatcher: one pass over due deliveries -----------------------------
def _post_delivery(delivery: WebhookDelivery, webhook: Webhook) -> tuple:
@@ -435,10 +493,14 @@ def _post_delivery(delivery: WebhookDelivery, webhook: Webhook) -> tuple:
return None, None, f'blocked at delivery: {reason}'[:500]
signature = sign_payload(webhook.secret, body_bytes)
+ import time as _time
+ sent_at = int(_time.time())
headers = {
'Content-Type': 'application/json',
'User-Agent': f'Speakr-Webhook/1.0',
'Speakr-Signature': signature,
+ 'Speakr-Signature-V2': signature_v2_header(webhook, sent_at, body_bytes),
+ 'Speakr-Attempt': str((delivery.attempt_count or 0) + 1),
'Speakr-Delivery-Id': delivery.event_id,
'Speakr-Event': delivery.event_type,
'Speakr-Timestamp': datetime.utcnow().isoformat() + 'Z',
@@ -681,25 +743,6 @@ def start_dispatcher_thread(app):
app.logger.info("✅ Webhook dispatcher thread initialized")
-def emit_recording_updated(recording, fields_changed):
- """recording.updated for a change made outside PATCH /recordings/{id}.
-
- Same payload as the PATCH route. Best-effort: never raises.
- """
- try:
- emit_webhook_event(
- user_id=recording.user_id,
- event_type='recording.updated',
- data={
- 'recording_id': recording.id,
- 'title': recording.title,
- 'fields_changed': list(fields_changed),
- },
- )
- except Exception as e:
- logger.warning(f"Webhook emit (recording.updated) failed for {getattr(recording, 'id', None)}: {e}")
-
-
def emit_recording_created(recording):
"""recording.created, from every path that creates a recording (#412 audit P11).
diff --git a/tests/test_speaker_merge_renames.py b/tests/test_speaker_merge_renames.py
index 6c2e710f..940fad38 100644
--- a/tests/test_speaker_merge_renames.py
+++ b/tests/test_speaker_merge_renames.py
@@ -23,7 +23,7 @@ from flask.testing import FlaskClient
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.app import app, db
-from src.models import Recording, Speaker, TranscriptChunk, User
+from src.models import Recording, Speaker, TranscriptChunk, User, Webhook, WebhookDelivery
app.config["WTF_CSRF_ENABLED"] = False
@@ -99,17 +99,28 @@ def _speakers(rid):
def test_a_merge_renames_the_merged_speaker_in_every_recording(world):
+ with app.app_context():
+ hook = Webhook(user_id=world["me"], name="t", url="https://example.com/h", secret="s" * 32,
+ events=json.dumps(["recording.updated"]))
+ db.session.add(hook)
+ db.session.commit()
+ hook_id = hook.id
reindex, flag, export = _effects()
- with reindex as m_reindex, flag, export as m_export, \
- patch("src.services.webhook_dispatch.emit_webhook_event") as emit:
+ with reindex as m_reindex, flag, export as m_export:
resp = _client(world["me"]).post("/speakers/merge",
json={"target_id": world["keep"], "source_ids": [world["old"]]})
assert resp.status_code == 200, resp.get_json()
assert resp.get_json()["recordings_updated"] == 2
- updates = {c.kwargs["data"]["recording_id"]: c.kwargs["data"]["fields_changed"]
- for c in emit.call_args_list if c.kwargs["event_type"] == "recording.updated"}
- assert updates == {world["only_old"]: ["participants", "speaker_label_map", "transcription"],
- world["both"]: ["participants", "transcription"]}
+ with app.app_context():
+ updates = {}
+ for d in WebhookDelivery.query.filter_by(webhook_id=hook_id, event_type="recording.updated"):
+ data = json.loads(d.payload)["data"]
+ updates[data["recording_id"]] = data["fields_changed"]
+ WebhookDelivery.query.filter_by(webhook_id=hook_id).delete()
+ db.session.delete(db.session.get(Webhook, hook_id))
+ db.session.commit()
+ assert updates == {world["only_old"]: ["participants", "speakers", "transcript"],
+ world["both"]: ["participants", "transcript"]}
with app.app_context():
segs, parts, label_map = _speakers(world["only_old"])
assert segs == ["Murtaza", "Bob"] and parts == "Bob, Murtaza"
diff --git a/tests/test_upgrade_mailr_api.py b/tests/test_upgrade_mailr_api.py
index 0a83f717..409c10dc 100644
--- a/tests/test_upgrade_mailr_api.py
+++ b/tests/test_upgrade_mailr_api.py
@@ -107,3 +107,33 @@ def test_recording_updated_at_and_tombstones(tmp_path, fixture):
assert {"ix_recording_updated_at", "ix_recording_user_updated"} <= indexes
assert "recording_tombstone" in tables
assert ledger == 1 and since and since[0].endswith("Z")
+
+
[email protected]("fixture", FIXTURES, ids=[f[:-4] for f in FIXTURES])
+def test_webhook_rotation_grace_columns(tmp_path, fixture):
+ """W2: previous_secret columns arrive empty; the current secret is untouched."""
+ db_path, con = _load(tmp_path, fixture)
+ if "webhook" not in {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}:
+ con.close()
+ pytest.skip("webhook table not in this release")
+ con.execute('INSERT INTO "user" (id, username, email, password) VALUES (1, ?, ?, ?)',
+ ("u", "[email protected]", "hash"))
+ cols = _columns(con, "webhook")
+ values = {"id": 3, "user_id": 1, "name": "n8n", "url": "https://example.com/h", "secret": "s" * 40,
+ "events": "[]", "enabled": 1, "auto_paused": 0, "consecutive_failures": 0,
+ "created_at": "2026-01-01 00:00:00", "updated_at": "2026-01-01 00:00:00", "allow_http": 0}
+ values = {k: v for k, v in values.items() if k in cols}
+ con.execute(f"INSERT INTO webhook ({', '.join(values)}) VALUES ({', '.join('?' for _ in values)})",
+ tuple(values.values()))
+ con.commit()
+ con.close()
+
+ _upgrade(db_path)
+ _upgrade(db_path)
+
+ con = sqlite3.connect(db_path)
+ assert {"previous_secret", "previous_secret_expires_at"} <= _columns(con, "webhook")
+ row = con.execute("SELECT secret, previous_secret, previous_secret_expires_at FROM webhook WHERE id = 3").fetchone()
+ con.close()
+ assert row == ("s" * 40, None, None)
+
diff --git a/tests/test_webhooks_v2.py b/tests/test_webhooks_v2.py
new file mode 100644
index 00000000..3f8c17cf
--- /dev/null
+++ b/tests/test_webhooks_v2.py
@@ -0,0 +1,230 @@
+"""Webhook signature V2, rotation grace and recording.updated from every path
+(mailr spec section 5: W1 to W4).
+
+SHARED-DB: users, tokens, tags, webhooks, deliveries and the recording are
+removed afterwards.
+"""
+
+import hashlib
+import hmac
+import json
+import os
+import secrets
+import sys
+from datetime import datetime, timedelta
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import g, has_app_context
+from flask.testing import FlaskClient
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import (APIToken, Recording, RecordingTag, Speaker, Tag, User, Webhook,
+ WebhookDelivery)
+from src.services import webhook_dispatch as wd
+from src.utils.token_auth import hash_token
+
+app.config["WTF_CSRF_ENABLED"] = False
+SEGMENTS = [{"speaker": "SPEAKER_00", "sentence": "Launch moves to Q3.", "start_time": 0.0, "end_time": 2.0}]
+
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ if has_app_context():
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+
+def world():
+ with app.app_context():
+ s = secrets.token_hex(4)
+ me = User(username=f"wh_{s}", email=f"wh_{s}@local.test", password="x")
+ db.session.add(me)
+ db.session.commit()
+ rec = Recording(user_id=me.id, title="Sync", status="COMPLETED", original_filename="s.wav",
+ transcription=json.dumps(SEGMENTS))
+ tag = Tag(name=f"t-{s}", user_id=me.id)
+ hook = Webhook(user_id=me.id, name="mailr", url="https://example.com/hook", secret="a" * 40,
+ events=json.dumps(["recording.updated", "recording.transcription.completed"]))
+ plain = f"tok-{secrets.token_urlsafe(16)}"
+ db.session.add_all([rec, tag, hook, APIToken(user_id=me.id, token_hash=hash_token(plain), name="wh")])
+ db.session.commit()
+ ids = dict(me=me.id, rec=rec.id, tag=tag.id, hook=hook.id, token=plain)
+ yield ids
+ with app.app_context():
+ db.session.rollback()
+ WebhookDelivery.query.filter_by(webhook_id=ids["hook"]).delete()
+ Webhook.query.filter_by(user_id=ids["me"]).delete()
+ RecordingTag.query.filter_by(recording_id=ids["rec"]).delete()
+ Recording.query.filter_by(user_id=ids["me"]).delete()
+ Tag.query.filter_by(user_id=ids["me"]).delete()
+ Speaker.query.filter_by(user_id=ids["me"]).delete()
+ APIToken.query.filter_by(user_id=ids["me"]).delete()
+ User.query.filter_by(id=ids["me"]).delete()
+ db.session.commit()
+
+
+def _updates(world):
+ with app.app_context():
+ rows = (WebhookDelivery.query.filter_by(webhook_id=world["hook"], event_type="recording.updated")
+ .order_by(WebhookDelivery.id).all())
+ return [json.loads(d.payload) for d in rows]
+
+
+def _session(uid):
+ c = _Client(app, app.response_class, use_cookies=True)
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(uid)
+ return c
+
+
+def _verify_v2(header, secret, body, now, window=300):
+ parts = [p.split("=", 1) for p in header.split(",")]
+ t = int(next(v for k, v in parts if k == "t"))
+ sigs = [v for k, v in parts if k == "v1"]
+ expected = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
+ return abs(now - t) <= window and any(hmac.compare_digest(expected, s) for s in sigs)
+
+
+# ------------------------------------------------------------ W1, W2
+
+def _send(world, delivery_id, at):
+ sent = {}
+
+ def fake_post(url, data=None, headers=None, **kw):
+ sent.update(body=data, headers=headers)
+ return MagicMock(status_code=200, text="ok")
+
+ with app.app_context(), patch.object(wd, "_http_post", side_effect=fake_post), \
+ patch.object(wd, "is_url_safe_for_webhook", return_value=(True, "")), patch("time.time", return_value=at):
+ d = db.session.get(WebhookDelivery, delivery_id)
+ wd._post_delivery(d, db.session.get(Webhook, world["hook"]))
+ return sent
+
+
+def _test_fire(world):
+ resp = _session(world["me"]).post(f"/api/v1/webhooks/{world['hook']}/test")
+ assert resp.status_code == 202
+ return resp.get_json()["id"]
+
+
+def test_v2_signs_the_wire_bytes_and_the_send_time(world):
+ delivery_id = _test_fire(world)
+ first = _send(world, delivery_id, 1_790_000_000)
+ with app.app_context():
+ d = db.session.get(WebhookDelivery, delivery_id)
+ d.attempt_count = 2
+ db.session.commit()
+ third = _send(world, delivery_id, 1_790_000_600)
+ assert first["body"] == third["body"] # same bytes every attempt
+ assert first["headers"]["Speakr-Signature-V2"].startswith("t=1790000000,")
+ assert third["headers"]["Speakr-Signature-V2"].startswith("t=1790000600,")
+ assert third["headers"]["Speakr-Attempt"] == "3"
+ for sent, at in ((first, 1_790_000_000), (third, 1_790_000_600)):
+ assert _verify_v2(sent["headers"]["Speakr-Signature-V2"], "a" * 40, sent["body"], at)
+ assert not _verify_v2(sent["headers"]["Speakr-Signature-V2"], "a" * 40, sent["body"], at + 301)
+ v1 = "sha256=" + hmac.new(("a" * 40).encode(), first["body"], hashlib.sha256).hexdigest()
+ assert first["headers"]["Speakr-Signature"] == v1 # unchanged scheme
+ envelope = json.loads(first["body"])
+ assert envelope["occurred_at"] == envelope["timestamp"]
+
+
+def test_replay_carries_v2(world):
+ original = _test_fire(world)
+ resp = _session(world["me"]).post(f"/api/v1/webhooks/{world['hook']}/deliveries/{original}/replay")
+ assert resp.status_code == 202
+ sent = _send(world, resp.get_json()["id"], 1_790_000_000)
+ assert _verify_v2(sent["headers"]["Speakr-Signature-V2"], "a" * 40, sent["body"], 1_790_000_000)
+ envelope = json.loads(sent["body"])
+ assert envelope["replayed_from"] and envelope["occurred_at"] == envelope["timestamp"]
+
+
+def test_rotation_keeps_the_old_secret_for_the_grace_period(world):
+ resp = _session(world["me"]).post(f"/api/v1/webhooks/{world['hook']}/rotate-secret")
+ assert resp.status_code == 200
+ new_secret = resp.get_json()["secret"]
+ assert new_secret != "a" * 40 and resp.get_json()["previous_secret_valid_until"]
+ assert "previous_secret" not in resp.get_json()
+ delivery_id = _test_fire(world)
+ sent = _send(world, delivery_id, 1_790_000_000)
+ header = sent["headers"]["Speakr-Signature-V2"]
+ assert header.count("v1=") == 2
+ assert _verify_v2(header, new_secret, sent["body"], 1_790_000_000)
+ assert _verify_v2(header, "a" * 40, sent["body"], 1_790_000_000)
+ assert sent["headers"]["Speakr-Signature"] == "sha256=" + hmac.new(
+ new_secret.encode(), sent["body"], hashlib.sha256).hexdigest()
+
+ with app.app_context():
+ hook = db.session.get(Webhook, world["hook"])
+ hook.previous_secret_expires_at = datetime.utcnow() - timedelta(seconds=1)
+ db.session.commit()
+ after = _send(world, delivery_id, 1_790_000_000)["headers"]["Speakr-Signature-V2"]
+ assert after.count("v1=") == 1
+
+
+# ------------------------------------------------------------ W3, W4
+
+def _api(world):
+ return {"Authorization": f"Bearer {world['token']}"}
+
+
[email protected]("action,fields", [
+ ("save_title", ["title"]),
+ ("tag_add", ["tags"]),
+ ("put_notes", ["notes"]),
+ ("speaker_rename", ["participants", "transcript"]), # voice profiles stubbed: no label map
+ ("v1_patch", ["title"]),
+])
+def test_each_edit_fires_one_recording_updated(world, action, fields):
+ c = _session(world["me"])
+ with patch("src.api.recordings.reindex_recording_chunks_async"), patch("src.file_exporter.export_recording"), \
+ patch("src.services.speaker.update_voice_profiles", return_value=(0, 0)):
+ if action == "save_title":
+ resp = c.post("/save", json={"id": world["rec"], "title": "Saved"})
+ elif action == "tag_add":
+ resp = c.post(f"/api/recordings/{world['rec']}/tags", json={"tag_id": world["tag"]})
+ elif action == "put_notes":
+ resp = c.put(f"/api/v1/recordings/{world['rec']}/notes", json={"notes": "n"}, headers=_api(world))
+ elif action == "speaker_rename":
+ resp = c.post(f"/recording/{world['rec']}/update_speakers",
+ json={"speaker_map": {"SPEAKER_00": {"name": "Jane", "isMe": False}}})
+ else:
+ resp = c.patch(f"/api/v1/recordings/{world['rec']}", json={"title": "Patched"}, headers=_api(world))
+ assert resp.status_code in (200, 201), resp.get_data(as_text=True)[:300]
+ updates = _updates(world)
+ assert len(updates) == 1, [u["data"] for u in updates]
+ data = updates[0]["data"]
+ assert data["recording_id"] == world["rec"] and data["fields_changed"] == fields
+ assert data["updated_at"].endswith("Z")
+
+
+def test_processing_status_changes_fire_no_update(world):
+ with app.app_context():
+ r = db.session.get(Recording, world["rec"])
+ r.status = "SUMMARIZING"
+ db.session.commit()
+ r.status = "COMPLETED"
+ r.completed_at = datetime.utcnow()
+ db.session.commit()
+ assert _updates(world) == []
+
+
+def test_quick_note_saves_merge_into_one_delivery(world):
+ c = app.test_client()
+ for text in ("first", "second", "third"):
+ assert c.put(f"/api/v1/recordings/{world['rec']}/notes", json={"notes": text},
+ headers=_api(world)).status_code == 200
+ updates = _updates(world)
+ assert len(updates) == 1 and updates[0]["data"]["fields_changed"] == ["notes"]
+
+
+def test_lifecycle_events_carry_updated_at(world):
+ with app.app_context():
+ wd.emit_webhook_event(user_id=world["me"], event_type="recording.transcription.completed",
+ data={"recording_id": world["rec"], "title": "Sync"})
+ d = WebhookDelivery.query.filter_by(webhook_id=world["hook"],
+ event_type="recording.transcription.completed").one()
+ assert json.loads(d.payload)["data"]["updated_at"].endswith("Z")