Verify KoBoToolbox webhooks

KoboToolbox doesn't sign REST Service requests, so there's no signature to check. A service sends no credentials by default, but once you choose basic authentication, each request carries your username and password in an Authorization: Basic header, which you decode and compare in constant time. That shows the sender knows the credentials, but it doesn't cover the body or stop a replayed request.

The facts

Signature header
None (unsigned)
What to build
Decode the Basic header, then compare username and password
Key
shared secret

KoBoToolbox webhook secret

KoboToolbox doesn't issue a secret. You choose a username and password and enter them on the REST Service, and it sends them as HTTP Basic credentials. Keep it in an environment variable, not in source code.

  • A service defaults to no_auth, so it sends no Authorization header until you choose basic authentication.
  • Credentials belong to one REST Service, so each project's service can have its own pair.
  • No rotation process is documented.
  • Custom headers can carry a static value too, set in settings.custom_headers on the service.

Source: KoBoToolbox docs ↗

Code

express/src/index.js
javascript
// Generated with: kobotoolbox-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

/**
 * Constant-time comparison of two byte strings. Hashing both sides first gives
 * equal-length buffers, so timingSafeEqual never throws and length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(a).digest();
  const hb = crypto.createHash('sha256').update(b).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * Parse "Authorization: Basic base64(username:password)". The scheme is
 * case-insensitive and the credentials split on the FIRST colon (passwords may
 * contain colons). Returns null if the header is missing or malformed.
 */
function parseBasicAuth(header) {
  if (typeof header !== 'string') return null;
  const match = /^basic +([A-Za-z0-9+/]+=*)\s*$/i.exec(header);
  if (!match) return null;
  const decoded = Buffer.from(match[1], 'base64');
  const colon = decoded.indexOf(0x3a);
  if (colon < 0) return null;
  return { username: decoded.subarray(0, colon), password: decoded.subarray(colon + 1) };
}

/**
 * KoboToolbox REST Services do not sign requests. They send HTTP Basic auth on
 * every request; a static credential, so it authenticates the sender, not the body.
 * Both comparisons run before deciding (no short-circuit).
 */
function verifyKoboRequest(
  headers,
  username = process.env.KOBOTOOLBOX_WEBHOOK_USERNAME,
  password = process.env.KOBOTOOLBOX_WEBHOOK_PASSWORD
) {
  if (!username || !password) return false; // never accept when unconfigured
  const creds = parseBasicAuth(headers.authorization);
  if (!creds) return false;
  const userOk = safeEqual(creds.username, Buffer.from(username, 'utf8'));
  const passOk = safeEqual(creds.password, Buffer.from(password, 'utf8'));
  return userOk && passOk;
}

/**
 * A REST Service fires once per new submission. There is no event type: the body
 * is the submission (JSON or XML, optionally a subset of fields or a custom wrapper).
 */
function handleSubmission(body, format) {
  if (format === 'json' && body && typeof body === 'object' && !Array.isArray(body)) {
    console.log(`New submission ${body._id} (${body._xform_id_string}) at ${body._submission_time}`);
    // Your code: store the submission; use body._uuid or body._id to deduplicate retries
  } else {
    console.log(`New submission (${format}, ${String(body).length} chars)`);
    // Your code: parse the XML submission (or your custom wrapper) with your XML library
  }
}

// Read the body raw (any content type) so the request is authenticated before parsing.
app.post('/webhooks/kobotoolbox', express.raw({ type: '*/*' }), (req, res) => {
  if (!verifyKoboRequest(req.headers)) {
    res.set('WWW-Authenticate', 'Basic realm="kobotoolbox"');
    return res.status(401).json({ error: 'Invalid or missing Basic credentials' });
  }

  const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';

  // JSON when it parses as JSON; otherwise keep the raw text (XML format).
  let body = raw;
  let format = 'xml/text';
  try {
    body = JSON.parse(raw);
    format = 'json';
  } catch {
    /* not JSON: leave as raw text */
  }

  try {
    handleSubmission(body, format);
  } catch (err) {
    console.error('Error handling KoboToolbox submission:', err);
    return res.status(500).json({ error: 'Handler error' });
  }

  res.status(200).json({ received: true });
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = app;
module.exports.verifyKoboRequest = verifyKoboRequest;
module.exports.parseBasicAuth = parseBasicAuth;

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/kobotoolbox`);
  });
}
nextjs/app/webhooks/kobotoolbox/route.ts
typescript
// Generated with: kobotoolbox-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyKoboRequest } from '../../../lib/verify-kobotoolbox';

// A REST Service fires once per new submission. There is no event type: the body
// is the submission (JSON or XML, optionally a subset of fields or a custom wrapper).
function handleSubmission(body: unknown, format: 'json' | 'xml/text'): void {
  if (format === 'json' && body && typeof body === 'object' && !Array.isArray(body)) {
    const s = body as Record<string, unknown>;
    console.log(`New submission ${s._id} (${s._xform_id_string}) at ${s._submission_time}`);
    // Your code: store the submission; use s._uuid or s._id to deduplicate retries
  } else {
    console.log(`New submission (${format}, ${String(body).length} chars)`);
    // Your code: parse the XML submission (or your custom wrapper) with your XML library
  }
}

export async function POST(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyKoboRequest(request.headers)) {
    return NextResponse.json(
      { error: 'Invalid or missing Basic credentials' },
      { status: 401, headers: { 'WWW-Authenticate': 'Basic realm="kobotoolbox"' } }
    );
  }

  // Read as text so any content type is accepted.
  const raw = await request.text();

  // JSON when it parses as JSON; otherwise keep the raw text (XML format).
  let body: unknown = raw;
  let format: 'json' | 'xml/text' = 'xml/text';
  try {
    body = JSON.parse(raw);
    format = 'json';
  } catch {
    // not JSON: leave as raw text
  }

  try {
    handleSubmission(body, format);
  } catch (err) {
    console.error('Error handling KoboToolbox submission:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: kobotoolbox-webhooks skill
# https://github.com/hookdeck/webhook-skills
import base64
import binascii
import hashlib
import hmac
import json
import os
import re

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

_BASIC_RE = re.compile(r"^basic +([A-Za-z0-9+/]+=*)\s*$", re.IGNORECASE)


def safe_equal(a: bytes, b: bytes) -> bool:
    """Constant-time comparison of two byte strings (compare_digest on equal-length digests).

    Always pass bytes: hmac.compare_digest raises TypeError on non-ASCII str.
    """
    return hmac.compare_digest(hashlib.sha256(a).digest(), hashlib.sha256(b).digest())


def parse_basic_auth(header):
    """Parse "Authorization: Basic base64(username:password)".

    The scheme is case-insensitive and the credentials split on the FIRST colon
    (passwords may contain colons). Returns (username, password) bytes or None.
    """
    if not header:
        return None
    match = _BASIC_RE.match(header)
    if not match:
        return None
    try:
        decoded = base64.b64decode(match.group(1), validate=True)
    except (binascii.Error, ValueError):
        return None
    username, sep, password = decoded.partition(b":")
    if not sep:
        return None
    return username, password


def verify_kobotoolbox_request(headers, username=None, password=None) -> bool:
    """KoboToolbox REST Services do not sign requests. They send HTTP Basic auth on
    every request; a static credential, so it authenticates the sender, not the body.
    Both comparisons run before deciding (no short-circuit).
    """
    username = username if username is not None else os.environ.get("KOBOTOOLBOX_WEBHOOK_USERNAME")
    password = password if password is not None else os.environ.get("KOBOTOOLBOX_WEBHOOK_PASSWORD")
    if not username or not password:
        return False  # never accept when unconfigured
    creds = parse_basic_auth(headers.get("authorization"))
    if creds is None:
        return False
    user_ok = safe_equal(creds[0], username.encode("utf-8"))
    pass_ok = safe_equal(creds[1], password.encode("utf-8"))
    return user_ok and pass_ok


async def require_basic_auth(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is read."""
    if not verify_kobotoolbox_request(request.headers):
        raise HTTPException(
            status_code=401,
            detail="Invalid or missing Basic credentials",
            headers={"WWW-Authenticate": 'Basic realm="kobotoolbox"'},
        )


def handle_submission(body, fmt: str) -> None:
    """A REST Service fires once per new submission. There is no event type: the body
    is the submission (JSON or XML, optionally a subset of fields or a custom wrapper).
    """
    if fmt == "json" and isinstance(body, dict):
        print(f"New submission {body.get('_id')} ({body.get('_xform_id_string')}) at {body.get('_submission_time')}")
        # Your code: store the submission; use body["_uuid"] or body["_id"] to deduplicate retries
    else:
        print(f"New submission ({fmt}, {len(str(body))} chars)")
        # Your code: parse the XML submission (or your custom wrapper) with your XML library


@app.post("/webhooks/kobotoolbox", dependencies=[Depends(require_basic_auth)])
async def kobotoolbox_webhook(request: Request):
    # Read the raw body so any content type is accepted.
    raw = (await request.body()).decode("utf-8", errors="replace")

    # JSON when it parses as JSON; otherwise keep the raw text (XML format).
    try:
        body, fmt = json.loads(raw), "json"
    except json.JSONDecodeError:
        body, fmt = raw, "xml/text"

    try:
        handle_submission(body, fmt)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling KoboToolbox submission: {err}")
        raise HTTPException(status_code=500, detail="Handler error")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

From hookdeck/webhook-skills ↗

Or install the KoBoToolbox webhooks skill:

npx skills add hookdeck/webhook-skills --skill kobotoolbox-webhooks

Common failures

The service has no credentials

A REST Service defaults to no authentication, so no Authorization header arrives. Set Security to Basic Authorization on the service.

The password contains a colon

The decoded header is username:password. Split it on the first colon only, because a password can contain more.

The body is parsed before the check

An XML service sends application/xml, so a handler that parses JSON before it authenticates rejects a legitimate request.

Deliveries failed while the credentials differed

The kpi sender doesn't retry a 401, so those submissions stay failed after you fix the password. Retry them from the service's log.

From Hookdeck's KoBoToolbox guide

Let Event Gateway check KoboToolbox credentials.

Event Gateway checks the Basic username and password on each KoboToolbox request, and a request that doesn't match never reaches your service. It queues the rest and retries failures on your schedule.

Not affiliated with KoBoToolbox. Facts are compiled from public sources and linked inline.