# Verify Signed Webhooks Before Running Mac Jobs

Canonical: https://figment.so/blog/mac-agent-signed-webhooks

Sign each request as timestamp.raw_body with HMAC-SHA256, reject anything older than 300 seconds, and compare in constant time before the Mac runs a job. A Figment Intel Mac VM ($25 a month) can host the listener.

Verify every webhook before the Mac runs a job: sign the string `{timestamp}.{raw_body}` with HMAC-SHA256, reject any request whose timestamp is more than 300 seconds off, and compare signatures in constant time. If your Mac launches a job for each webhook it receives, one captured request becomes an unlimited replay. The signature stops forgery and the timestamp window stops replay. A Figment Intel Mac VM ($25 a month) can run the listener and light jobs.

## Which Figment Mac should run the listener?

Choose by what the webhook triggers, because the listener itself is tiny: it parses headers, recomputes an HMAC and dispatches.

| The webhook triggers | Plan | Price |
| --- | --- | --- |
| Scripting, packaging, Intel-compatible builds, or outbound CI runner work (Xcode 26.0 to 26.3 on macOS Sequoia) | [Intel Mac VM](/mac-hosting#intel-vm), 4 shared vCPUs, 4GB, 80GB | $25 a month, $2 a day, $0.15 an hour |
| arm64-only tools, Xcode 26.4 or later, or visionOS | [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm), 4 shared vCPUs, 4GB, 65GB | $39 a month, $6 a day, $0.40 an hour |
| Heavy builds or jobs you want isolated on a whole Mac | [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro), M4 Pro, 48GB, 512GB | $349 a month ($299 on a 12-month term) |

If the triggered job needs Apple silicon, put the listener on the same Apple silicon Mac that runs the work, and skip an extra hop through an Intel VM. Plans include SSH, encrypted remote desktop and browser access. A tunnel such as `cloudflared` can give the sender a public URL that forwards to the listener, and that is the approach this guide uses. Figment runs the Mac and network layer. The listener, the tunnel and the secret are yours to manage.

## What is the signed-string contract?

The signed string is `{timestamp}.{raw_request_body_bytes}`. Agree on it, and version it, before you write code. Sender and receiver must recompute the identical byte sequence.

| Header | Value |
|---|---|
| `X-Timestamp` | Unix timestamp, integer seconds, UTC |
| `X-Signature` | `sha256=<lowercase hex HMAC-SHA256>` |

The receiver does six things:

1. Read `X-Timestamp` and `X-Signature`.
2. Reject if `abs(now - timestamp) > 300` seconds.
3. Rebuild the signed string from the **raw request body bytes**, not re-parsed JSON.
4. Compute `HMAC-SHA256(secret, signed_string)`.
5. Compare with `hmac.compare_digest` (constant-time, per the Python [`hmac` module documentation](https://docs.python.org/3/library/hmac.html)).
6. Reject on any mismatch.

Any JSON reformat, such as a key reorder, a whitespace change or number normalization, produces different bytes and a different HMAC. Read the body once into a `bytes` buffer and sign that exact buffer on the sender.

## How do I generate test vectors?

Use a fixed vector set, which catches almost every integration bug (wrong key encoding, missing separator, hex versus base64, a re-serialized body). Run this on any machine with `openssl`:

```bash
#!/usr/bin/env bash
set -euo pipefail

SECRET="test-secret-01"
TIMESTAMP="1731240000"
BODY='{"event":"build","ref":"main"}'
SIGNED_STRING="${TIMESTAMP}.${BODY}"

SIG=$(printf '%s' "${SIGNED_STRING}" \
  | openssl dgst -sha256 -hmac "${SECRET}" \
  | awk '{print "sha256=" $2}')

printf 'Secret:        %s\n' "${SECRET}"
printf 'Timestamp:     %s\n' "${TIMESTAMP}"
printf 'Body:          %s\n' "${BODY}"
printf 'Signed string: %s\n' "${SIGNED_STRING}"
printf 'Signature:     %s\n' "${SIG}"
```

Treat the printed signature as an untested example. Record whatever your own run produces and pin that as the golden value in your tests. Build at least these cases:

| Vector | Change | Expected result |
|---|---|---|
| Baseline | None | accept |
| Wrong secret | secret flipped | reject |
| Body edited after signing | extra whitespace in JSON | reject |
| Stale timestamp | 10 minutes old | reject |
| Missing `X-Signature` | header dropped | reject |

## How do I run the listener under launchd?

Use a Python listener with only the standard library. `hmac.compare_digest` is constant-time, and `hmac.new(key, msg, digestmod='sha256')` matches the documented signature in the Python [`hmac` module](https://docs.python.org/3/library/hmac.html).

```python
#!/usr/bin/env python3
"""webhook-listener.py — verify signed webhooks before dispatching Mac jobs."""

import hashlib, hmac, http.server, json, os, subprocess, time

WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "")
REPLAY_WINDOW_SECONDS = 300
JOB_SCRIPT = os.environ.get("JOB_SCRIPT", "/usr/local/bin/run-mac-job.sh")
LISTEN_PORT = int(os.environ.get("LISTEN_PORT", "8765"))

if not WEBHOOK_SECRET:
    raise RuntimeError("WEBHOOK_SECRET is required")


def verify(raw_body: bytes, ts_str: str, received_sig: str) -> bool:
    try:
        ts = int(ts_str)
    except (ValueError, TypeError):
        return False
    if abs(time.time() - ts) > REPLAY_WINDOW_SECONDS:
        return False
    signed = f"{ts}.".encode() + raw_body
    expected = "sha256=" + hmac.new(
        WEBHOOK_SECRET.encode(), signed, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, received_sig or "")


class Handler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        raw = self.rfile.read(length)
        ts = self.headers.get("X-Timestamp", "")
        sig = self.headers.get("X-Signature", "")

        if not verify(raw, ts, sig):
            self.send_response(401); self.end_headers(); return

        try:
            payload = json.loads(raw)
        except json.JSONDecodeError:
            self.send_response(400); self.end_headers(); return

        event = payload.get("event", "unknown")
        log_path = (
            f"/tmp/job-{int(time.time())}-{os.getpid()}-"
            f"{os.urandom(4).hex()}.log"
        )
        with open(log_path, "w") as fh:
            subprocess.Popen(
                [JOB_SCRIPT, event], stdout=fh,
                stderr=subprocess.STDOUT, close_fds=True,
            )

        self.send_response(202)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps({"accepted": True, "event": event}).encode())


if __name__ == "__main__":
    http.server.HTTPServer(("127.0.0.1", LISTEN_PORT), Handler).serve_forever()
```

Keep `WEBHOOK_SECRET` in the Keychain or your CI secret manager and fetch it at launchd startup. Do not commit the plist with a real secret, and do not dump the whole environment to disk. This minimal user agent uses plist keys documented in Apple's [launchd jobs reference](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html):

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>            <string>com.example.webhook-listener</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/sh</string>
    <string>-c</string>
    <string>WEBHOOK_SECRET="$(security find-generic-password -a agent -s webhook-secret -w)" exec /usr/bin/python3 /usr/local/bin/webhook-listener.py</string>
  </array>
  <key>KeepAlive</key>        <true/>
  <key>StandardOutPath</key>  <string>/Users/agent/Library/Logs/webhook.log</string>
  <key>StandardErrorPath</key><string>/Users/agent/Library/Logs/webhook.err</string>
</dict>
</plist>
```

The listener binds to `127.0.0.1`. Your tunnel (`cloudflared`, `ngrok`) or reverse proxy forwards the public URL to it.

## What should I check when verification fails?

Start with these four cases:

- **Everything returns 401.** Run the test-vector script, `curl` the listener with the printed values, and compare the first 64 bytes of `raw_body` on both sides. The usual cause is a sender that re-serialized the JSON after signing.
- **Timestamp drift.** If senders have unreliable clocks, widen the window to 600 seconds and add a nonce cache (a SQLite table keyed on signature, with TTL equal to the window) so duplicates inside the window do not re-trigger jobs.
- **Secret rotation.** Accept two secrets during a rollover window. Verify against both and log which one matched.
- **Job stampedes.** Each dispatch writes to a unique log path (`time.pid.random`), so collisions within a second are safe. If the job itself is not idempotent, deduplicate on the webhook's own event ID before `Popen`.

## How do I start on Figment?

Most webhook-driven automations fit the Intel Mac VM, where the listener and the dispatched job run together. Move to an Apple silicon plan when the triggered job needs arm64-only tools or Xcode 26.4 or later. Compare the options on the [Mac hosting plans](/mac-hosting), then install the plist, start the tunnel and send the test vectors before you accept real traffic.

---

**Related guides:** [Job checkpoints on a hosted Mac](/blog/mac-agent-job-checkpoints) · [Download completion detection on a hosted Mac](/blog/mac-agent-download-completion) · [GitHub Actions self-hosted runner on Mac](/blog/mac-github-actions-self-hosted-runner)
