Authentication and Authorization Domain - Webhook Signature Verification and Auth-Adjacent SDK Support

Overview

This feature area centers on the HMAC-based security model used for inbound webhook handling and the SDK-side helpers that consumers use to validate webhook authenticity before processing payloads. The Node, Python, and Java SDK helpers all implement the same core contract: they require the raw request body plus the X-Lita-Signature value, compute an HMAC-SHA256 digest with the webhook secret, and reject the event immediately when the signature does not match.

The SDK error surfaces intentionally separate webhook-auth failures from ordinary API failures. Signature mismatches raise dedicated webhook signature exceptions, while HTTP/API failures are surfaced through the normal SDK error classes with status, request_id, and retryable metadata. That split lets consumers treat tampered or misconfigured webhook traffic as a terminal authentication problem while still using retry-aware handling for transient API failures.

Architecture Overview

flowchart LR
    Sender[Webhook sender] --> App[Consumer application]

    subgraph ApiRoutes[API webhook routes]
        WebhookRoutes[webhooksRoutes]
        TenantGuard[tenantId guard]
        EndpointList[listWebhookEndpoints]
        DeliveryQueue[enqueueWebhookDelivery]
        WebhookRoutes --> TenantGuard
        WebhookRoutes --> EndpointList
        WebhookRoutes --> DeliveryQueue
    end

    subgraph NodeSdk[Node SDK]
        NodeHelper[constructEvent]
        NodeError[LitaWebhookSignatureError]
        NodeApiError[LitaError]
        NodeHelper --> NodeError
        NodeHelper --> NodeApiError
    end

    subgraph PythonSdk[Python SDK]
        PythonHelper[construct_event]
        PythonError[LitaWebhookSignatureError]
        PythonApiError[LitaError]
        PythonHelper --> PythonError
        PythonHelper --> PythonApiError
    end

    subgraph JavaSdk[Java SDK]
        JavaHelper[Webhooks constructEvent]
        JavaError[LitaWebhookSignatureException]
        JavaApiError[LitaException]
        JavaHelper --> JavaError
        JavaHelper --> JavaApiError
    end

    App --> NodeHelper
    App --> PythonHelper
    App --> JavaHelper

API Integration

Webhook Route Module

apps/api/src/routes/v1/webhooks.ts

The route module registers tenant-scoped webhook management and test delivery endpoints. Each handler checks request.tenantId before calling into the webhook delivery helpers, so the runtime path depends on tenant context being available on the request.

Request Schemas

Schema Property Type Description
endpointSchema url string Destination URL for the webhook endpoint.
endpointSchema events string[] Event names subscribed for the endpoint; at least one value is required.
testSchema eventType string Event name used for the test delivery batch.
testSchema payload Record<string, unknown> Arbitrary payload passed to the test delivery enqueuer.

Create Webhook Endpoint

{
    "title": "Create Webhook Endpoint",
    "description": "Creates a tenant webhook endpoint and stores the subscribed event list",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/endpoints",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"url\": \"https://example.com/lita/webhooks\",\n    \"events\": [\n        \"consent.activated\",\n        \"score.completed\",\n        \"kyc.updated\"\n    ]\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Webhook endpoint created",
            "body": "{\n    \"id\": \"we_01J8A2K6Z4Q9M9V7R1W3B8C2D4\",\n    \"url\": \"https://example.com/lita/webhooks\",\n    \"events\": [\n        \"consent.activated\",\n        \"score.completed\",\n        \"kyc.updated\"\n    ]\n}"
        }
    }
}

List Webhook Endpoints

{
    "title": "List Webhook Endpoints",
    "description": "Returns all webhook endpoints for the current tenant",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/endpoints",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Webhook endpoint list",
            "body": "[\n    {\n        \"id\": \"we_01J8A2K6Z4Q9M9V7R1W3B8C2D4\",\n        \"url\": \"https://example.com/lita/webhooks\",\n        \"events\": [\n            \"consent.activated\",\n            \"score.completed\",\n            \"kyc.updated\"\n        ]\n    }\n]"
        }
    }
}

Test Webhook Delivery

{
    "title": "Test Webhook Delivery",
    "description": "Enqueues a test delivery for every configured endpoint in the tenant",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/test",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"eventType\": \"score.completed\",\n    \"payload\": {\n        \"consent_id\": \"cons_01J8A2K6Z4Q9M9V7R1W3B8C2D4\",\n        \"evidence_ref\": \"evd_01J8A2K6Z4Q9M9V7R1W3B8C2D4\",\n        \"decision\": \"APPROVE\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Count of queued deliveries",
            "body": "{\n    \"queued\": 2\n}"
        }
    }
}

Route Execution Path

  • The handler first relies on request context that includes tenantId.
  • If request.tenantId is missing, the handler throws Error("missing tenant").
  • POST /endpoints creates a tenant endpoint, then records an audit event with the new endpoint ID and URL.
  • GET /endpoints returns the current tenant endpoint list.
  • POST /test fetches the current tenant endpoints, enqueues one delivery per endpoint, and returns the total queued count.

Node.js SDK

sdks/node/src/webhooks.ts

sdks/node/src/errors.ts

sdks/node/src/types.ts

WebhookEventType

consent.activated, consent.expired, consent.revoked, data.updated, features.computed, score.completed, kyc.updated

WebhookEvent

Property Type Description
event_id string Unique identifier for the webhook event.
event_type WebhookEventType Event name emitted by the platform.
created_at string Event creation timestamp.
region Region Region code associated with the event.
data Record<string, unknown> Event payload.

LitaError

Property Type Description
status number HTTP status code returned by the API.
code string Machine-readable API error code.
requestId string Request identifier returned by the API.
retryable boolean Indicates whether the same API request may succeed if retried.

LitaAuthError

Property Type Description
status number Inherited from LitaError.
code string Inherited from LitaError.
requestId string Inherited from LitaError.
retryable boolean Inherited from LitaError.

LitaWebhookSignatureError

Property Type Description
name string Set to LitaWebhookSignatureError.
message string Fixed signature failure message.

constructEvent

Method Description
constructEvent Verifies the webhook signature and parses the event payload into WebhookEvent.

Signature Verification Behavior

  • Accepts rawBody as either Buffer or string.
  • Converts string input to UTF-8 bytes before verification.
  • Computes sha256=<hex digest> using createHmac('sha256', secret).
  • Compares the expected and received signature with timingSafeEqual.
  • Throws LitaWebhookSignatureError on mismatch.
  • Parses JSON only after the signature check succeeds.

Python SDK

[!IMPORTANT] The helper treats signature failure as a hard reject path. It does not retry, back off, or attempt alternate secrets.

sdks/python/lita/webhooks.py

sdks/python/lita/errors.py

sdks/python/lita/types.py

WebhookEventType

consent.activated, consent.expired, consent.revoked, data.updated, features.computed, score.completed, kyc.updated

WebhookEvent

Property Type Description
event_id str Unique identifier for the webhook event.
event_type WebhookEventType Event type emitted by the platform.
created_at str Event creation timestamp.
region Region Region associated with the event.
data Dict[str, Any] Event payload.

LitaError

Property Type Description
status int HTTP status code returned by the API.
code str Machine-readable API error code.
request_id str Request identifier returned by the API.
retryable bool Indicates whether the request may succeed if retried.

LitaWebhookSignatureError

Property Type Description
message str Fixed signature failure message.

construct_event

Method Description
construct_event Verifies the webhook signature and returns a parsed WebhookEvent.

Signature Verification Behavior

  • Accepts raw_body as bytes or str.
  • Converts string input to UTF-8 bytes before verification.
  • Computes the expected signature with hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest().
  • Compares the normalized sha256=<hex digest> value with hmac.compare_digest.
  • Raises LitaWebhookSignatureError when the signature does not match.
  • Builds a WebhookEvent from event_id, event_type, created_at, region, and data after verification.

Java SDK

sdks/java/src/main/java/com/joinlita/Webhooks.java

sdks/java/src/main/java/com/joinlita/LitaWebhookSignatureException.java

sdks/java/src/main/java/com/joinlita/LitaException.java

Webhooks

Property Type Description
MAPPER ObjectMapper Shared JSON parser used to deserialize webhook payloads.

Webhooks Methods

Method Description
constructEvent Verifies a webhook signature from raw bytes and returns the parsed payload as a Map.
constructEvent Convenience overload that accepts the raw body as a UTF-8 string.

LitaWebhookSignatureException

Property Type Description
message String Fixed signature failure message.

LitaException

Property Type Description
statusCode int HTTP status code returned by the API.
errorCode String Machine-readable API error code.
requestId String Request identifier returned by the API.
retryable boolean Indicates whether the request may succeed if retried.

LitaException Methods

Method Description
getStatusCode Returns the HTTP status code.
getErrorCode Returns the machine-readable API error code.
getRequestId Returns the failing request ID.
isRetryable Returns whether the request may succeed on retry.
toString Returns a formatted error summary.

Signature Verification Behavior

  • Accepts rawBody as byte[] or String.
  • Uses Mac.getInstance("HmacSHA256") with the provided secret.
  • Produces the expected signature string as sha256=<hex digest>.
  • Compares expected and received signatures with MessageDigest.isEqual for constant-time comparison.
  • Throws LitaWebhookSignatureException on mismatch.
  • Parses the webhook body into Map<String, Object> only after signature verification succeeds.
  • Wraps HMAC setup failures in RuntimeException("Failed to compute HMAC-SHA256", e).
  • Wraps payload parse failures in RuntimeException("Failed to parse webhook payload", e).

Feature Flows

Inbound Webhook Signature Verification

sequenceDiagram
    participant Sender as Webhook sender
    participant App as Consumer application
    participant Helper as SDK helper
    participant Error as Signature error

    Sender->>App: POST webhook with raw body and X-Lita-Signature
    App->>Helper: constructEvent or construct_event or constructEvent
    Helper->>Helper: Compute HMAC SHA256
    Helper->>Helper: Compare sha256 signature
    alt Signature matches
        Helper-->>App: Parsed webhook payload
        App->>App: Process event data
    else Signature mismatch
        Helper-->>App: Throw webhook signature error
        App->>App: Reject event
    end

The shared flow is identical across Node, Python, and Java:

  1. The application supplies the untouched raw request body.
  2. The helper computes the HMAC with the webhook secret.
  3. The helper normalizes the signature as sha256=<hex digest>.
  4. The helper compares the received header value in constant time.
  5. A mismatch raises a webhook signature exception immediately.
  6. A match returns the parsed payload shape for downstream processing.

Test Delivery Queueing

sequenceDiagram
    participant Client as API client
    participant Route as webhooksRoutes
    participant Store as Endpoint lookup
    participant Queue as Delivery enqueue

    Client->>Route: POST /test
    Route->>Route: Check tenantId
    Route->>Store: listWebhookEndpoints
    Store-->>Route: Endpoint list
    loop For each endpoint
        Route->>Queue: enqueueWebhookDelivery
    end
    Route-->>Client: { queued: count }

The route module's test delivery path is a batch enqueue flow, not a direct send loop. It counts the tenant’s configured endpoints, calls the delivery enqueuer once per endpoint, and returns the number of queued deliveries.

Error Handling and Retry Semantics

Error Surfaces

Surface Behavior
Webhook signature failure Raises LitaWebhookSignatureError in Node and Python, LitaWebhookSignatureException in Java.
API request failure Raises LitaError in Node and Python, LitaException in Java.
API auth failure Node converts 401 and 403 API responses into LitaAuthError.
Java HMAC setup failure Throws RuntimeException("Failed to compute HMAC-SHA256", e).
Java payload parse failure Throws RuntimeException("Failed to parse webhook payload", e).

Retry Semantics

  • Signature failures are terminal and are not marked retryable.
  • API failures carry retry metadata through retryable in the general SDK error classes.
  • The webhook route module’s POST /test handler enqueues deliveries once per endpoint and returns the batch size; no retry policy is implemented in that file.

Testing Considerations

  • Verify that each helper accepts both string and byte-buffer inputs where implemented.
  • Verify that a correct sha256=<hex digest> header value returns the parsed payload.
  • Verify that a tampered header value raises the webhook signature exception for the language in use.
  • Verify that JSON parsing only happens after signature validation.
  • Verify that Node’s LitaError and Java’s LitaException expose requestId and retryable.
  • Verify that POST /test returns the number of queued deliveries for the current tenant.
  • Verify that handlers in apps/api/src/routes/v1/webhooks.ts reject missing tenant context via Error("missing tenant").

Dependencies

  • Node helper crypto: createHmac, timingSafeEqual
  • Python helper crypto and parsing: hashlib, hmac, json
  • Java helper crypto and parsing: Mac, SecretKeySpec, MessageDigest, HexFormat, ObjectMapper
  • API route module: fastify, zod, @lita/webhooks
  • SDK error transport: request_id and retryable fields returned by the API error payload shape

Key Classes Reference

Class Responsibility
webhooks.ts Registers tenant webhook endpoint management and test delivery routes.
webhooks.ts Verifies webhook signatures and parses inbound webhook payloads in Node.
errors.ts Defines Node SDK error surfaces for API failures and webhook signature failures.
webhooks.py Verifies webhook signatures and parses inbound webhook payloads in Python.
errors.py Defines Python SDK error surfaces for API failures and webhook signature failures.
Webhooks.java Verifies webhook signatures and parses inbound webhook payloads in Java.
LitaWebhookSignatureException.java Represents webhook signature verification failure in Java.
LitaException.java Represents API failures with status, code, request ID, and retryability.