KDPika Licensing Sign inStart free
API v1
Show all languages
Browse documentation

Choose a page in the navigation drawer.

KDPika Licensing · API v1 Advanced

Python webhook signature verifier

Run the complete Python raw-byte notification verifier with authenticated event and environment checks.

On this page
Updated 2026-10-18 UTCDownload Markdown

Authenticate KDPika Licensing notification bytes with the complete Python verifier.

What you will learn

  • Install and execute this exact sample.
  • Verify raw bytes, event metadata and the pinned environment.
  • Identify the boundary between authentication and durable business processing.

Prerequisites

Prepare a request

  1. Work inside the extracted webhooks directory, which contains contract.json.
  2. Set KDP_WEBHOOK_SECRET through your private process environment.
  3. Set KDP_WEBHOOK_ENVIRONMENT to sandbox.
  4. Use Python 3.11+ to create a fresh private synthetic request.
bashbash
python3 make-test.py events/test-ping.json private/request-1

Expected output: Created private test request files. Use a new directory for each generated request; existing files are not overwritten. The helper signs a captured synthetic body, not a real payment or license authorization. Keep contract.json in place: it supplies the shared event list, 300-second receiver freshness policy and 1 MiB receiver body cap.

Build and run

bashbash
python3 verify.py private/request-1/body.json private/request-1/headers.json

Expected result: exit 0 with verified=true, event_id=evt_ffa11b785e0ede73d9e69801, event=test.ping and environment=sandbox. Property order is not significant. This source was executed in the recorded macOS contract suite; native Windows and Linux execution are not claimed.

Complete source

verify.pypython
#!/usr/bin/env python3
"""Verify a notification, not license validity. Python 3.11+, standard library.
Run: KDP_WEBHOOK_SECRET=YOUR_WEBHOOK_SECRET KDP_WEBHOOK_ENVIRONMENT=SANDBOX python3 verify.py body.json headers.json
Expected: JSON verified=true for valid bytes; verified=false and exit 1 otherwise.
"""
import hashlib
import hmac
import json
import os
from pathlib import Path
import re
import sys
import time


def verify(body: bytes, headers: dict, secret: str, environment: str, now: int) -> dict:
    contract = json.loads(Path(__file__).with_name('contract.json').read_text())
    if not secret or environment not in contract['environments'] or len(body) > contract['body_limit']:
        raise ValueError('Invalid configuration or body size')
    signature = headers.get('x-lmp-signature')
    if not isinstance(signature, str):
        raise ValueError('Missing signature')
    match = re.fullmatch(r't=([1-9][0-9]{0,10}),v1=([0-9a-f]{64})', signature)
    if not match or abs(now - int(match[1])) > contract['tolerance_seconds']:
        raise ValueError('Invalid or stale signature')
    message = match[1].encode('ascii') + b'.' + body
    digest = hmac.new(secret.encode('utf-8'), message, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(digest, match[2]):
        raise ValueError('Signature mismatch')
    event = json.loads(body.decode('utf-8', errors='strict'))
    if not isinstance(event, dict) or not isinstance(event.get('id'), str):
        raise ValueError('Invalid event')
    if not re.fullmatch(r'evt_[A-Za-z0-9_-]{1,100}', event['id']):
        raise ValueError('Invalid event ID')
    if event.get('event') not in contract['events'] or event.get('environment') != environment:
        raise ValueError('Wrong event or environment')
    if event['id'] != headers.get('x-lmp-event-id') or event['event'] != headers.get('x-lmp-event'):
        raise ValueError('Header and body mismatch')
    if not isinstance(event.get('data'), dict) or not isinstance(event.get('created_at'), str) or not event['created_at']:
        raise ValueError('Invalid event envelope')
    return event


def main() -> int:
    try:
        if len(sys.argv) != 3:
            raise ValueError('Two file paths required')
        with open(sys.argv[1], 'rb') as stream:
            body = stream.read(1048577)
        with open(sys.argv[2], 'rb') as stream:
            raw_headers = stream.read(32769)
        if len(raw_headers) > 32768:
            raise ValueError('Headers too large')
        headers = json.loads(raw_headers.decode('utf-8', errors='strict'))
        if not isinstance(headers, dict):
            raise ValueError('Invalid headers')
        event = verify(body, headers, os.environ.get('KDP_WEBHOOK_SECRET', ''),
                       os.environ.get('KDP_WEBHOOK_ENVIRONMENT', '').lower(), int(time.time()))
        print(json.dumps({'verified': True, 'event_id': event['id'], 'event': event['event'],
                          'environment': event['environment']}))
        return 0
    except (OSError, ValueError, TypeError, KeyError, OverflowError):
        print('{"verified":false}')
        return 1


if __name__ == '__main__':
    raise SystemExit(main())

Connect to an HTTP adapter

  1. Read a bounded raw HTTP body before JSON middleware changes it.
  2. Reject duplicate signature, event-ID and event-name header fields.
  3. Normalize header names to lowercase without changing their values.
  4. Pass the exact raw body, headers, configured endpoint secret and expected environment to the verifier.
  5. Atomically persist the verified event ID and work item before sending a 2xx response.

Expected result: only authenticated recent notifications reach your inbox. The CLI tool does not start an HTTP listener, save deduplication records, call licensing APIs, send email or unlock an application. Use the local inbox example to test the durable acknowledgement boundary.

Expected result

All captured event types pass when signed with the right current secret and pinned environment. Changed raw bytes, a wrong secret, stale/future attempt timestamp, malformed envelope or wrong environment print exactly {"verified":false} and exit 1. The shared suite exercises positive events, negative input and size boundaries against the exact file above.

Common mistakes

  • Reading contract.json from a different working directory or copying only one source without its companion files.
  • Re-encoding JSON before HMAC verification.
  • Reusing an expired test signature instead of generating a current one.
  • Assuming successful authentication deduplicates an additive renewal.

Security notes

Never print the secret or full signature in logs. Use the endpoint's plaintext HMAC secret, not a developer API key or an Ed25519 public key. A verified notification is not an authoritative license-validity response. Timestamp filtering does not stop duplicate delivery inside its window; use a durable authenticated event-ID ledger and an independent business-operation key.

Troubleshooting

SymptomCauseFix
verified=false for an unchanged fixtureTimestamp expired, wrong secret or wrong environmentRegenerate the private request using the intended Sandbox configuration
Companion file cannot be foundWorking directory or extraction incompleteRestore the complete source archive and work inside webhooks
The same ID verifies againVerifier only authenticates bytesCommit a unique inbox record before applying an effect

Next steps

Run the local HTTP, replay and storage-failure tests.

Was this page helpful?

Choose an answer

Do not include personal data, license keys or credentials. Retained for up to 30 days. This is not a support inbox.

Search documentation

Arrow keys to move, Enter to open, Escape to close. Search stays in your browser.

Cookie settings