Audit Action Message Bus Handler Guide (Beta)

Overview

The Audit Action Message Bus Handler is a specialized extension type in the Q2 SDK that allows you to process audit events asynchronously through the message bus system. This handler automatically receives audit records when specific audit actions occur in the Q2 platform and allows you to implement custom business logic in response to these events.

Key Features

  • Asynchronous Processing: Handle audit events without blocking the main application flow

  • Selective Subscription: Subscribe only to specific audit actions you care about

  • Structured Data: Receive rich, structured audit record data

  • Type Safety: Built-in dataclass support for audit records

  • Automatic Filtering: Framework automatically filters subscribed vs unsubscribed actions

Architecture

The audit action message bus handler follows this flow:

  1. Q2 Platform generates an audit event (e.g., user login, transaction)

  2. Message Bus receives the audit record and routes it to subscribed handlers

  3. Your Handler receives the structured audit record and processes it

  4. Custom Logic executes your business-specific code

Core Components

AuditRecord Dataclass

The AuditRecord dataclass represents a structured audit event with the following fields:

Required Fields:

Note: All fields except audit_action(Audit action name) are defaulted to some default value

customer_key: str        # Customer identifier
audit_uuid: str         # Unique audit event ID
audit_action: str       # Type of action (LOGIN, LOGOUT, TRANSFER, etc.)
session_id: str         # User session identifier
version: str            # Application version
git_rev: str           # Git revision
protobuf_type: str     # Record type
envstack: str          # Environment stack
app_source: str        # Source application
cryptokey: str         # Encryption key

Optional Fields:

audit_id: Optional[int]               # Numeric audit ID
global_id: Optional[str]              # Global identifier
start_timestamp: Optional[datetime]   # Event start time
timestamp: Optional[datetime]         # Event timestamp
end_timestamp: Optional[datetime]     # Event end time
action_id: Optional[int]              # Action identifier
audit_description: Optional[str]      # Human-readable description
workstation: Optional[str]            # Workstation identifier
legacy_details: Optional[LegacyDetails]      # Legacy audit details
execution_context: Optional[ExecutionContext] # Execution context
is_reservation: Optional[bool]        # Reservation flag
hmac: Optional[bytes]                 # HMAC signature
zone_id: Optional[int]                # Zone identifier
entity_changes: list[EntityChange]    # List of entity changes
end_of_frame: bool                    # End of frame flag

Creating an Audit Action Message Bus Extension

Step 1: Generate the Extension

Use the Q2 CLI to create a new audit action message bus extension:

q2 create_extension

New Extension Name: MyAuditActionMsgBus
What type of extension are you creating?

    1) Online (default)
    2) SSO (Third Party Integration)
    3) Ardent (API)
    4) Q2Console (Backoffice)
    5) Central (Legacy Backoffice)
    6) Adapter
    7) Audit Action <---------
    8) Custom Health Check
    9) Message Bus
    10) Caliper API Custom Endpoint
    11) Q2Config Extensions (Client Side Rendered)
    12) Base Extension

Please make a selection and press Return [1]: 7
Audit Action
Select Audit Action type to generate

    1) Audit Action (Message Bus style (beta))  <---------
    2) Audit Action

Please make a selection and press Return: 1
Audit Action (Message Bus style (beta))

This has registered as an endpoint. If you do NOT want this endpoint exposed, remove it from the INSTALLED_EXTENSIONS in /Users/hfaraaz/q2dev/repos/extension_testing/configuration/settings.py

Provide audit actions you would like to handle (comma-separated if multiple). Use tab completion to verify options: "LOGIN", "LOGOUT", "TRANSFER"

writing rendered jinja template to MyAuditActionMsgBus/extension.py
writing rendered jinja template to MyAuditActionMsgBus/urls.py

Step 2: Implement Your Handler

The generated extension will create a handler class that looks like this:

from q2_sdk.core.http_handlers.audit_action_msg_bus_handler import (
    AuditActionMsgBusHandler,
    AuditRecord
)

class MyAuditProcessorHandler(AuditActionMsgBusHandler):
    # Specify which audit actions this handler subscribes to
    SUBSCRIBED_AUDIT_ACTIONS = ["LOGIN", "LOGOUT", "TRANSFER"]
    async def handle_audit_record(self, audit_record: AuditRecord) -> AuditRecord:
        """
        This is the hook where you can put your handling logic.

        message.text contains the message body posted from the bus.
        """
        self.logger.info(
            f"received subscribed audit action :- {audit_record.audit_action} on {self.extension_name}"
        )

Handler Base Class

The AuditActionMsgBusHandler base class provides:

Core Attributes

MESSAGE_TYPE = ["q2msg.shared.AuditRecord"]
SUBSCRIBED_AUDIT_ACTIONS = []  # Selected Audit actions at the time of creation will be populated here

Core Methods

handle(message: Message) -> Any

Framework entry point. Converts message to AuditRecord and routes to your handler.

handle_audit_record(audit_record: AuditRecord) -> Any

Override this method - Your custom business logic goes here.

Filtering Behavior

The handler automatically filters audit actions:

  • Subscribed Actions: Actions in SUBSCRIBED_AUDIT_ACTIONS are processed

  • Unsubscribed Actions: Other actions are logged as warnings and ignored

# This handler only processes LOGIN and LOGOUT events
SUBSCRIBED_AUDIT_ACTIONS = ["LOGIN", "LOGOUT"]

Troubleshooting

Common Issues

Handler not receiving messages: - Verify SUBSCRIBED_AUDIT_ACTIONS contains the correct action names - Check message bus connectivity - Review deployment logs

Data parsing errors: - Verify audit record field access - Check for None values in optional fields - Review audit record structure changes

Testing

Use q2 send_msg_to_bus to test an audit action message bus extension locally. Start your extension with q2 run in one terminal window, then send a test message from another terminal window.

The audit_record command builds a q2msg.v2.shared.AuditRecord and publishes it with message type q2msg.shared.AuditRecord so it is compatible with the current Audit Action Message Bus handler. For local HQ-style emulation, the CLI sends a framed AuditRecord payload, Snappy-compresses and encrypts only legacy_details.detail, and recalculates the final AuditRecord HMAC from the encrypted detail.

Minimal AuditRecord example:

q2 send_msg_to_bus audit_record --audit-action "sdk_OAuthRefreshToken"

Most fields are defaulted for quick local testing. --audit-action is the only required AuditRecord option.

Important AuditRecord options:

  • Scalar fields: --customer-key, --audit-uuid, --audit-action, --session-id, --version, --git-rev, --protobuf_type, --envstack, --app-source, --cryptokey

  • Optional metadata: --audit-id, --global-id, --action-id, --audit-description, --workstation, --zone-id

  • ISO timestamp fields: --start-timestamp, --timestamp, --end-timestamp

  • JSON fields: --legacy-details, --execution-context, --entity-changes

  • Base64 bytes field: --hmac

  • Boolean flags: --is-reservation, --end-of-frame

--legacy-details must be a JSON object. Its detail value is base64-encoded plaintext bytes. The message bus helper encrypts this field before sending it.

--hmac is accepted to populate the AuditRecord before publishing, but the final sent message uses the HMAC recalculated after legacy_details.detail is encrypted.

HQ-style AuditRecord example:

q2 send_msg_to_bus audit_record \
  --customer-key "A14C52D9-7B83-4E2A-9F15-6D08B347AC21" \
  --audit-uuid "f761b6c4-0f62-4f74-a8db-209a56c7e136" \
  --audit-action "SessionEnd" \
  --session-id "local-session-4f8c2a91" \
  --version "2.4.1-local" \
  --git-rev "f3c9a2b" \
  --protobuf_type "q2msg.shared.AuditRecord" \
  --envstack "example-stg" \
  --app-source "HQ" \
  --cryptokey "example-key-2026-06-23" \
  --action-id "401" \
  --workstation "workstation-2e5f91c0" \
  --legacy-details '{"detail":"c3ludGhldGljLWF1ZGl0LWRldGFpbA==","hydraIdName":"example-hydra-node:https://example.internal/hq/OnlineBanking.ashx"}' \
  --execution-context '{"errorReturnCode":0,"uiSourceId":1,"uiSource":"OnlineBanking","actor":{"clientAddress":"127.0.0.1"},"target":{}}' \
  --end-of-frame

HQ Payload Shape

HQ publishes AuditRecord data with camelCase field names. The Audit Action Message Bus handler exposes that data as a snake_case AuditRecord dataclass. The values below are synthetic, but they show the rough shape of the payload and the transformed object your handler receives.

An HQ-style payload resembles:

{
    "customerKey": "A14C52D9-7B83-4E2A-9F15-6D08B347AC21",
    "auditId": "987654321",
    "auditUuid": "f761b6c4-0f62-4f74-a8db-209a56c7e136",
    "startTimestamp": "2026-04-18T09:15:30.123456Z",
    "timestamp": "2026-04-18T09:15:31.234567Z",
    "actionId": 401,
    "auditAction": "SessionEnd",
    "workstation": "workstation-2e5f91c0",
    "legacyDetails": {
        "detail": "c3ludGhldGljLWF1ZGl0LWRldGFpbA==",
        "hydraIdName": "example-hydra-node:https://example.internal/hq/OnlineBanking.ashx",
    },
    "executionContext": {
        "uiSourceId": 1,
        "uiSource": "OnlineBanking",
        "actor": {"clientAddress": "127.0.0.1"},
        "target": {},
    },
    "isReservation": True,
    "sessionId": "local-session-4f8c2a91",
    "version": "2.4.1-local",
    "gitRev": "f3c9a2b",
    "type": "q2msg.shared.AuditRecord",
    "envstack": "example-stg",
    "appSource": "HQ",
    "hmac": "c3ludGhldGljLWhtYWM=",
    "cyptokey": "example-key-2026-06-23",
}

After the SDK converts it, your handler receives a value shaped like:

AuditRecord(
    customer_key="A14C52D9-7B83-4E2A-9F15-6D08B347AC21",
    audit_uuid="f761b6c4-0f62-4f74-a8db-209a56c7e136",
    audit_action="SessionEnd",
    session_id="local-session-4f8c2a91",
    version="2.4.1-local",
    git_rev="f3c9a2b",
    protobuf_type="q2msg.shared.AuditRecord",
    envstack="example-stg",
    app_source="HQ",
    cryptokey="example-key-2026-06-23",
    audit_id="xxx-xx-4321",
    global_id=None,
    start_timestamp="2026-04-18T09:15:30.123456Z",
    timestamp="2026-04-18T09:15:31.234567Z",
    end_timestamp=None,
    action_id=401,
    audit_description=None,
    workstation="workstation-2e5f91c0",
    legacy_details={
        "detail": "c3ludGhldGljLWF1ZGl0LWRldGFpbA==",
        "hydraIdName": "example-hydra-node:https://example.internal/hq/OnlineBanking.ashx",
    },
    execution_context={
        "uiSourceId": 1,
        "uiSource": "OnlineBanking",
        "actor": {"clientAddress": "127.0.0.1"},
        "target": {},
    },
    is_reservation=True,
    hmac="c3ludGhldGljLWhtYWM=",
    zone_id=None,
    entity_changes=[],
    end_of_frame=False,
)

Full AuditRecord option example:

q2 send_msg_to_bus audit_record \
  --customer-key "A14C52D9-7B83-4E2A-9F15-6D08B347AC21" \
  --audit-uuid "f761b6c4-0f62-4f74-a8db-209a56c7e136" \
  --audit-action "SessionEnd" \
  --session-id "local-session-4f8c2a91" \
  --version "2.4.1-local" \
  --git-rev "f3c9a2b" \
  --protobuf_type "q2msg.shared.AuditRecord" \
  --envstack "example-stg" \
  --app-source "HQ" \
  --cryptokey "example-key-2026-06-23" \
  --audit-id "1042" \
  --global-id "global-example-7d2f" \
  --start-timestamp "2026-04-18T09:15:30.123456Z" \
  --timestamp "2026-04-18T09:15:31.234567Z" \
  --end-timestamp "2026-04-18T09:15:32.345678Z" \
  --action-id "401" \
  --audit-description "Session ended from local CLI test" \
  --workstation "workstation-2e5f91c0" \
  --legacy-details '{"detail":"c3ludGhldGljLWF1ZGl0LWRldGFpbA==","hydraIdName":"example-hydra-node:https://example.internal/hq/OnlineBanking.ashx"}' \
  --execution-context '{"errorReturnCode":0,"uiSourceId":1,"uiSource":"OnlineBanking","actor":{"clientAddress":"127.0.0.1"},"target":{}}' \
  --is-reservation \
  --hmac "c3ludGhldGljLWhtYWM=" \
  --zone-id "17" \
  --entity-changes '[{"before":"YmVmb3JlLWV4YW1wbGU=","after":"YWZ0ZXItZXhhbXBsZQ==","context":"Session","contextId":"session-example-5a31","beforeHmac":"YmVmb3JlLWhtYWM=","afterHmac":"YWZ0ZXItaG1hYw=="}]' \
  --end-of-frame

When running this from an IDE or Python run/debug configuration, each JSON value must be passed as one argument. If the IDE strips shell quotes, configure the JSON value as a single literal argument or escape the double quotes inside the JSON string.

You can also send a normal string message:

q2 send_msg_to_bus string_message "hello world" "Lowercase"

Local Artemis Auto-Deployment (local development only)

Artemis is the consumer of audit action messages. The Q2 SDK can automatically create a temporary Artemis Kafka consumer for local development when q2 run starts an audit-consuming extension.

This feature is intended for local development and testing only. It is not intended for production use.

Prerequisites

Run:

q2 sandbox q2msg generate_keys

This generates the sandbox HMAC/crypto keys used by the local Artemis consumer. The keys are stored in the local development environment.

Auto-deployment starts only when all of the following are true:

  • Q2SDK_LOCAL_DEV=True

  • Q2SDK_ARTEMIS_AUTODEPLOY=True (the default)

  • STACKNAME is set to the sandbox stack name

  • DEV_SOCKET_URL is configured for the local development socket

  • The extension has an AuditActionMsgBusHandler with at least one action in SUBSCRIBED_AUDIT_ACTIONS

  • The developer is logged in and can obtain a Developer Portal access token

For example:

export STACKNAME="my-sandbox-stack"
q2 login
q2 run

Job Lifecycle

The SDK runs Artemis provisioning asynchronously as part of q2 run. It does not block server startup and does not call Nomad directly.

The SDK sends the current configuration to the Q2 Developer Portal. The Portal owns Artemis job creation and lifecycle and creates or replaces the developer’s audit consumer using the supplied stack, callback URL, action filter, and TTL.

When subscribed actions, the stack, callback URL, or TTL changes, restart q2 run so the SDK sends the updated configuration to the Portal.

Portal Request

The SDK makes an authenticated asynchronous POST request to:

https://q2developer.com/api/v1.0/sandbox/audit-consumers

The request uses the SDK q2_requests HTTP interface and contains:

{
  "stackName": "my-sandbox-stack",
  "callbackUrl": "https://local-dev-api.q2developer.com/proxy/user@example.com-repo/q2msg.shared.AuditRecord",
  "actionFilter": "LOGIN,LOGOUT",
  "ttlMinutes": 60
}

The fields are derived as follows:

  • stackName comes from STACKNAME.

  • callbackUrl defaults to https://{host}/proxy/{email}-{repo}/q2msg.shared.AuditRecord and can be overridden with Q2SDK_ARTEMIS_CALLBACK_URL.

  • actionFilter contains the unique, comma-separated subscribed audit actions.

  • ttlMinutes is the validated integer value from Q2SDK_ARTEMIS_TTL.

TTL Configuration

Q2SDK_ARTEMIS_TTL accepts an integer number of minutes from 5 through 1440. The default is 720 minutes:

export Q2SDK_ARTEMIS_TTL="60"
export Q2SDK_ARTEMIS_TTL="30"
export Q2SDK_ARTEMIS_TTL="1400"

Hour or minute suffixes and combined duration formats are not supported. Values outside 5 through 1440 are rejected without stopping q2 run.

Callback URL Override

Set Q2SDK_ARTEMIS_CALLBACK_URL to use a callback URL other than the SDK-generated local proxy URL:

export Q2SDK_ARTEMIS_CALLBACK_URL="https://{host}/proxy/{email}-{repo}/q2msg.shared.AuditRecord"

Disabling Auto-Deployment

Disable local consumer setup with:

export Q2SDK_ARTEMIS_AUTODEPLOY=false

Troubleshooting

  • Consumer is not created: verify STACKNAME, DEV_SOCKET_URL, local-dev settings, and SUBSCRIBED_AUDIT_ACTIONS.

  • 401 Unauthorized: run q2 login again and verify the Developer Portal account can access sandbox consumers.

  • Invalid TTL: use an integer from 5 through 1440 minutes, such as 30 or 720.

  • Messages are not received: verify the callback URL, stack name, and audit action names.

Auto-deployment is intentionally best-effort. Authentication, network, validation, or Portal failures are logged as warnings and never stop q2 run.

API Reference

AuditActionMsgBusHandler Extension