Part 1: Quickstart
Deploy the polling Function and the audit event webhook from the example repository.
Part 2: How it works
Read how the components work, including operations, troubleshooting and security.
Part 1: Quickstart
This quickstart helps you to create 2 things:- An Azure Function that polls the Audit Logs API every minute into
FireblocksAudit_CL. - The audit event webhook that sends each event to a second Function, which writes it to
FireblocksWebhook_CL.
az login, and replace each <placeholder> with your value. Most steps end with a check that shows what you should see.
1.1 Send audit events to Sentinel (polling)
Prerequisites
- An Azure subscription, the Azure CLI with Bicep, and Azure Functions Core Tools v4.
- Python 3.13 and OpenSSL.
- A resource group where you are Owner, or Contributor plus User Access Administrator (needed because the template creates role assignments).
- A Log Analytics workspace with Microsoft Sentinel in that resource group. The resource group and the workspace must be in the same region.
- A Fireblocks workspace where you can add an API user.
Steps
1
Clone the repository
Clone the example repository and open the polling folder:
2
Create a key pair and a CSR
Create a key pair and a certificate signing request (CSR) outside the repository:In the Fireblocks Console, go to the Developer center’s API users page, select Add API user, enter a name, select the Auditor role, upload
~/.fireblocks/fireblocks.csr, and select Add user. See Manage API Access.After the approval quorum approves the request, the API key appears in the API User (ID) column. Copy it.
3
Deploy the Azure resources
Deploy the Azure resources. The value of
fireblocksBasePath depends on your environment:- US
- EU
- EU2
- Sandbox
https://api.fireblocks.io/v1The output contains
"provisioningState": "Succeeded".4
Store the secrets in Key Vault
Store the API key and the private key in Key Vault. The values stay in the vault, and the Function reads them through Key Vault references. If the first
az keyvault secret set command returns Forbidden, wait a few minutes for the role assignment to take effect and run it again.az keyvault secret list --vault-name "$KV" -o table lists fireblocks-api-key and fireblocks-secret-key.5
Publish the Function
The command publishes from the
function folder, and the parentheses keep your terminal in the folder where you started.az functionapp function list -g <resource-group> -n "$FUNC" --query "[].name" -o tsv lists poll_audit_logs. Within a few minutes, this query in the Logs page returns the line Fetched N events, uploaded M:6
Confirm the events
Confirm the events in the Logs page of the workspace:
The query returns rows. The first rows can take several minutes to appear, because the new role assignment must propagate before Azure Monitor accepts uploads. A workspace with no recent activity produces no rows, so change a setting in a Sandbox workspace to generate an event.
1.2 Add the audit event webhook
Section 1.2 continues from 1.1 and uses the same resource group, workspace, and<api-base-path> values. The webhook stack has its own name prefix, table, and deployment name, so both stacks share the one resource group and workspace.
Prerequisites
- The prerequisites of 1.1.
- A Fireblocks Console administrator who can add an audit log webhook subscription.
Steps
1
Open the webhook folder
2
Deploy the webhook resources
Deploy the Azure resources. The template uses
jwt authentication and 1 always-ready receiver. To restrict the endpoint to the source addresses of Fireblocks deliveries for your region, add allowedSourceIps='["<allowed-address>"]' to the parameters and replace <allowed-address> with those addresses.The output contains
"provisioningState": "Succeeded".3
Store the webhook secret
Generate a random webhook secret of 32 bytes and store it in Key Vault, then restart the Function app so that it resolves the Key Vault reference. If the Copy the secret to your clipboard with the command for your system, and keep the variable set until step 5 is done.
az keyvault secret set command returns Forbidden, wait a few minutes for the role assignment to take effect and run it again.- macOS
- Linux
- Windows (Git Bash or WSL)
az keyvault secret show --vault-name "$KV" -n fireblocks-webhook-secret --query name -o tsv prints fireblocks-webhook-secret.4
Publish the Functions
The command publishes from the
function folder, and the parentheses keep your terminal in the folder where you started.The output lists
audit_webhook, process_webhook_event, and poll_audit_logs.5
Create the subscription
In the Fireblocks Console, go to Settings > Audit log > Manage subscriptions > Webhooks and add a webhook. Enter a name, select the categories whose events you want (the sample rules use Then run
Administration, Policies, and Transactions), enter the output of the following command as the URL, and paste the secret from your clipboard as the secret key. See the Audit Event webhooks article.unset WEBHOOK_SECRET.The secret key field accepts the pasted value, and the Console shows the webhook in the subscription list.
6
Confirm the webhook events
Trigger an event in one of the selected categories, for example by changing a setting in a Sandbox workspace, and confirm it in the Logs page:
The query returns a row with
Channel set to webhook. The first rows can take a few minutes to appear.Part 2: How it works
The sections below explain the components of the 2 stacks, the Sentinel table, the template parameters, the poller and the receiver, the detection rules, operations and troubleshooting, security, and the example repository.Architecture
Polling architecture
The Function authenticates to Fireblocks with a read-only API user, queries a time window that overlaps the previous one, removes events it has already uploaded, and sends the rest to Sentinel through the Logs Ingestion API. It keeps its position in Azure Table Storage, so a failed upload is retried on the next run and no event is lost. The polling stack has these components.
The Audit Logs API accepts the Admin, Non-Signing Admin, Auditor, Security Admin, and Security Auditor roles and returns
403 Forbidden for any other role. The poller only reads audit logs, so the Auditor role is the narrowest fit. See Audit Logs API.
Webhook architecture
The Console sends an HTTPPOST to the Function’s URL for every event in the categories you select. The receiving Function validates a signed token in the x-webhook-secret header, wraps the request in an envelope, and returns 200, and the Functions host writes the envelope to a Storage Queue. A second Function reads the queue, maps the event to a table row, and uploads the row through the Logs Ingestion API. A message that fails 5 times moves to a poison queue, so nothing that the receiver accepted is silently discarded.
The webhook stack has these components.
Fireblocks sends one HTTP
POST request per event and waits up to 10 seconds for a 2xx response. The receiver therefore returns 200, the Functions host writes the delivery to the queue, and the queue Function processes it afterwards. The template runs the receiver on an always-ready instance, so the first delivery after an idle period is answered without a cold start. The template parameter alwaysReadyReceivers sets the number of instances.
Sentinel table and data collection rule
Each stack creates a custom table and a Direct data collection rule. The table holds the events, and the rule is the endpoint that the Functions and the test generator send them to. A Direct rule exposes its own Logs Ingestion endpoint, so you do not need a separate data collection endpoint. See Logs Ingestion API in Azure Monitor. The table has these columns.Raw is a dynamic column so that every field of the original event stays queryable (for example Raw.timestamp) even when it has no column of its own.
The tenant ID is stored as
FbTenantId because Azure Monitor reserves TenantId and several other column names. See supported tables in the Azure Monitor documentation.source and rows pass through unchanged. Each Function’s system-assigned managed identity receives the Monitoring Metrics Publisher role on its rule, which is the role the Logs Ingestion API requires, and the deploying user receives the same role when you pass adminPrincipalId.
Configuration
Template parameters
Both templates take these parameters.
The allow rules apply to the Function app site that serves the webhook URL. The platform answers a request from an address outside
allowedSourceIps with 403 before the Function runs, so the request does not appear in the Function logs. The deployment site that func azure functionapp publish uses is not restricted by address, so publishing works from any machine.
The deployment name webhook keeps the webhook stack’s deployment record apart from the polling stack’s record named main, which a deployment under the same name would overwrite.
Publish the code and store the webhook secret before you create the Console subscription.
To run the second poller, store the Fireblocks credentials in the webhook stack’s Key Vault, then run the deployment command of step 2 in 1.2 again with -p enableReconcile=true added and the same other parameters, including allowedSourceIps. The second poller reads the API base path from fireblocksBasePath.
Deployment outputs
The polling deployment outputsfunctionAppName, keyVaultName, workspaceName, dcrEndpoint, dcrImmutableId, streamName, and stateAccountUrl. The webhook deployment outputs the same values plus webhookUrl, webhookQueueName, and webhookPoisonQueueName. Read one with az deployment group show -g <resource-group> -n <main-or-webhook> --query properties.outputs.<name>.value -o tsv.
Where the numbers come from
Each figure below is set in the example code. The table says what it controls and why it has this value, so you can decide whether to change it.How the code works
How the poller works
function_app.py registers one function that runs run_once() on a timer. The 6-field schedule 0 * * * * * fires at second 0 of every minute.
Settings.from_env() in poller.py reads every value from environment variables, which are the Function app settings in Azure. The private key comes from FIREBLOCKS_SECRET_KEY, which is a Key Vault reference in Azure, and load_secret_key() falls back to the file named by FIREBLOCKS_SECRET_KEY_PATH for local tools. The Function reaches Azure Monitor and Table Storage with DefaultAzureCredential, which resolves to the Function’s managed identity in Azure and to your az login session on your computer, so no Azure client secret exists anywhere.
Constants at the top of poller.py set the polling behavior:
-
Read the position.
TableStatestores the position (next_start_ms) and a list of recently seen event IDs in one row of a Table Storage table namedfbstate. The position is stored as text because Table Storage integers default to 32 bits, which cannot hold an epoch time in milliseconds. On the first run, when no position exists, the poller starts 1 hour in the past. -
Fetch.
fetch_eventsqueries from the stored position to the current time, oldest events first, 500 events per page, and follows thenextcursor until the response has none. It stops after 50 pages, so a very large backlog cannot run indefinitely. -
Remove duplicates and upload. The window overlaps the previous one, so the poller drops the events whose IDs are in the seen list and uploads the rest.
- Advance. After a complete run, the next start is the current time minus 2 minutes, and the seen list is pruned to events inside the new window. The list holds at most 500 entries and at most 30,000 serialized characters, and the oldest IDs are dropped first. The poller saves the position last, so an upload that raises an error leaves the stored position unchanged and the next run repeats the same window.
AUDIT_POLL_CAP_HIT, so a backlog is visible.
The next start time is the newest event timestamp minus the overlap. When that value is not later than the previous start time, the next start time is the newest event timestamp, or 1 millisecond after the previous start time when that is later. If none of the fetched events has a readable timestamp, the poller keeps its position unchanged and logs the same error on every run.
to_row() maps an event to the table columns and keeps the whole event in Raw. The poller converts timestamp to epoch milliseconds. A timestamp outside 1970 to 2100 is treated as missing. An event with an unreadable timestamp does not raise an error. It is uploaded with the time of the run, so one malformed event cannot block every later run.
Limits of the poller
The poller has these limits.- An event that becomes queryable more than 2 minutes after its timestamp can be missed. Each run queries from 2 minutes before the end of the previous window by event timestamp, so an event that appears in the API only after its timestamp has fallen outside every later window is never returned. Raise
OVERLAP_MSinpoller.pyto widen the window, then publish again. - Delivery is at least once. The overlap re-queries events on every run, and the seen list removes most repeats, but an event can be stored more than once. Events inside the overlap that exceed the seen list limits are uploaded again as duplicates and are not dropped, and a restart or a failed save of the position repeats a window. Write rules that tolerate a repeated row, as the sample rules do by grouping alerts into one incident per user.
How the receiver works
The audit event webhook sends a token in thex-webhook-secret header, signed with the secret key you entered in the Console. The Audit Event webhooks article describes the webhook. In jwt mode the receiver accepts a token signed with HS256 using the secret, compares the signature in constant time, and requires an exp claim in the future.
handle_delivery in webhook.py runs its checks in a fixed order and answers with one of these responses.
The body size and the declared length are checked in every mode, before the credential and before any parsing. The receiver never logs header values or request bodies, and it logs one line for each delivery with the mode, the status, the body size, and the outcome.
After the credential check, the receiver wraps the delivery in an envelope that holds the raw body and a short allowlist of headers (content type, content length, user agent, forwarding headers, and trace headers), so the secret header is never queued.
process_webhook_event reads each queued envelope and calls process_message. Each delivery is one JSON event, and process_message parses the body, maps the event to one row with Channel set to webhook, and uploads it. The processor sets EventId to the event id when the payload has one and otherwise to a hash of the event, prefixed h-, and it takes TimeGenerated from createdAt. FbTenantId is filled when the payload carries a tenantId, and the whole event stays in Raw.
A body that is not valid JSON or has no recognizable event fields raises an error, so the queue retries it and then moves it to the poison queue. host.json sets the queue retry behavior. A failed message becomes visible again after 30 seconds and is attempted at most 5 times in total. The processor reads the app setting WEBHOOK_MAX_DEQUEUE (5 in the template) to recognize the last attempt, and the setting must equal maxDequeueCount in host.json.
WEBHOOK_POISON:, and the Functions host moves the message to fb-audit-webhook-poison, which the host creates.
The poison queue holds the complete envelope of each failed message, which is the body and the selected headers. To inspect a poisoned message, peek at the poison queue, which needs a Storage Queue Data role on the storage account that the template does not assign to the deploying user. After you fix the cause, copy the message back to fb-audit-webhook to process it again.
Detection rules
The 3 sample analytics rules query each table. Each one is a KQL query that you paste into a Sentinel scheduled query rule. For the rule wizard, see Create scheduled analytics rules in Microsoft Sentinel. In each rule:- Set Generate alert when number of query results to Is greater than
0, because the queries return rows only when something matches. - Group alerts into one incident per user, so that a row seen twice produces one incident.
Rules for the polling table
The rules forFireblocksAudit_CL filter on ingestion_time(), the time a row reached the table, so a row that arrives some time after its event is still evaluated. Each accordion below shows one rule file.
kql/off_hours_admin_change.kql
kql/off_hours_admin_change.kql
kql/policy_change.kql
kql/policy_change.kql
kql/rejection_burst.kql
kql/rejection_burst.kql
The 1-day query period lets the rule see rows whose event time is older than the filter window. The event names come from the Audit Log Events reference.
The 3 rules do the following.
- User, role, or IP allowlist change outside business hours alerts on user, role, and IP allowlist changes in the
Administrationcategory outside 07:00 to 19:59 UTC. Adjust the hour range to your time zone. - Policy change alerts on any event in the
Policiescategory. To alert only when a change becomes live, narrowEventtoPublished policyandPut policy into effect. - Burst of rejected transactions alerts when one user has 5 or more rejected or policy-blocked transactions in the 10 minutes before a run. The window slides with each run, so a burst that crosses a clock boundary is still counted once.
Rules for the webhook table
The rules for the webhook stack query theFireblocksWebhookDedup function, which reads FireblocksWebhook_CL. The function returns one row for each EventId, which is the copy that arrived first, together with IngestedAt, the time that copy was ingested.
Queue processing is at least once, so the function keeps a message that was processed twice from raising 2 alerts, and a rule that filters on IngestedAt alerts once when an event first appears. Keep the query period at 1 day or more for rules that filter on IngestedAt, so that a repeated copy is matched with its first copy.
The webhook rules use the same schedules, query periods, and thresholds as the table above, and the template deploys the function from FireblocksWebhookDedup.kql. The accordions below show the saved function and the webhook version of each rule.
kql/FireblocksWebhookDedup.kql
kql/FireblocksWebhookDedup.kql
kql/off_hours_admin_change.kql
kql/off_hours_admin_change.kql
kql/policy_change.kql
kql/policy_change.kql
kql/rejection_burst.kql
kql/rejection_burst.kql
Test the rules with the generator
To test the rules,generate.py sends events through the same rule, flags them with Synthetic = true, and reads the settings that you export. Each scenario matches one rule. Run it from the folder of the stack that you test, with the values from that stack’s deployment outputs. The generator authenticates with your az login identity, which holds the Monitoring Metrics Publisher role on the rule when you passed adminPrincipalId.
dcrEndpoint and dcrImmutableId from the deployment named main in the polling folder and from the deployment named webhook in the webhook folder. The .env.example file in each folder sets DCR_STREAM_NAME for that stack, which is Custom-FireblocksAudit_CL in polling and Custom-FireblocksWebhook_CL in webhook. In the webhook folder the generator sets Channel to synthetic.
The following 3 behaviors affect how you test.
- The
off-hours-adminscenario stamps its events at 03:15 UTC on the most recent day when that time has already passed, so the events are up to 24 hours old. The rule’s 1-day query period includes them, and its ingestion-time filter selects them while the rows are new. - The
rejection-burstscenario sends 8 events 20 seconds apart, which fall inside one 10-minute window and exceed the threshold of 5. - Each scenario sends events with new IDs, so repeating one creates new rows rather than duplicates.
tools/generate.py replay <file>, where the file holds a JSON list of audit events as the Audit Logs API returns them. Replay shifts the events so that the newest one lands at the current time and marks every row as synthetic.
Operations and troubleshooting
Confirm ingestion
Open the Logs page of the workspace and run the following queries for the stack that you want to check.- Polling stack
- Webhook stack
Show recent polled rows, including the full event in Summarize the real events by category, subject, and event:Check whether any polled event was stored more than once. Polling delivery is at least once, so rows can appear, for example after the seen list overflows, as Limits of the poller describes:Measure the delay between an event and its row in the table:
Raw:Read the Function logs
Each Function app writes its logs to Application Insights, which the template points at the same workspace as Sentinel, so the logs appear in theAppTraces table.
The Function’s
host.json samples Application Insights telemetry but excludes requests, traces, and exceptions from sampling ("excludedTypes": "Request;Trace;Exception"), so an AUDIT_POLL_CAP_HIT entry is never sampled away. See the host.json reference. When the message appears, the poller has already uploaded the events it fetched and moved its position forward, so the next runs drain the rest of the backlog. If the message repeats on every run and mentions events without a usable timestamp, the poller is not advancing, so inspect the Raw column of recent rows and the timestamp format of the events.
Troubleshoot the poller
Troubleshoot the webhook
Inspect deliveries in capture mode
To inspect what your endpoint receives, run the deployment command of step 2 in 1.2 again with-p webhookAuthMode=capture and the same other parameters, including allowedSourceIps, trigger an event, and print the records from the webhook folder.
Set STATE_ACCOUNT_URL in .env to the stateAccountUrl output first. tools/show_capture.py needs the Storage Table Data Reader role on the storage account, and --delete needs Storage Table Data Contributor. The template does not assign these roles to the deploying user.
fbcapture, answers 200 with the body captured, and queues nothing. The record lists the header names, the content type, the first word of an Authorization header, the body with sensitive values redacted, and a one-line body_shape.
Redaction is by key name: a value is replaced with [redacted] when its key contains, in any letter case, one of secret, signature, password, token, authorization, private, apikey, api_key, credential, passphrase, seed, mnemonic, otp, or cookie.
The secret_header block describes the x-webhook-secret header without its value: has_three_dot_separated_base64url_parts is true for a JWT-shaped value, and hs256_signature_valid_with_configured_secret is true when the token is signed with the secret in Key Vault.
The table keeps at most 10 records and removes records older than 7 days when it writes the next record. Run .venv/bin/python tools/show_capture.py --delete to delete the table, and run the deployment command again with webhookAuthMode=jwt and the same other parameters, including allowedSourceIps, to forward events.
Rotate the API key
Fireblocks API users authenticate with a CSR and key pair, so you rotate credentials by creating a new API user. See Rotating secrets.- Generate a new key pair and CSR, and create a new API user with the Auditor role, as in step 2 of 1.1.
-
Store the new API key and private key in Key Vault with the same
az keyvault secret setcommands. Each command creates a new secret version, and the Key Vault references in the Function app use the latest version. -
Restart the Function app so that it resolves the new secret versions:
-
Confirm that the next run logs
Fetched N events, uploaded Mwithout errors, and then delete the old API user in the Console.
Rotate the webhook secret
- Generate a new value, and store it in Key Vault under the same secret name with the commands in step 3 of 1.2. Each command creates a new secret version.
- Restart the Function app so that the reference resolves the new version.
- Update the secret key in the Console webhook.
Run the 3 steps back to back. Deliveries that arrive between steps 2 and 3 carry a token signed with the old secret, and the receiver answers them with
401.Remove the resources
Delete the webhook subscription in the Console first, so that Fireblocks stops sending deliveries. Then delete the resources that each template created. The names below assume the defaultnamePrefix values, fbsent for polling and fbhook for the webhook.
Each Key Vault has purge protection enabled, so a deleted vault name stays reserved for 7 days. To deploy into the same resource group sooner, use a different
namePrefix.Security considerations
- Least-privilege API key. The polling API user holds the Auditor role and is used for nothing else. Create a separate API user for every integration so that you can revoke one without affecting another.
- Managed identity. Each Function reaches Azure with a system-assigned managed identity, so no Azure client secret exists. The identity receives Monitoring Metrics Publisher on its data collection rule, Key Vault Secrets User on its vault, and Storage Blob Data Owner, Storage Table Data Contributor, and Storage Queue Data Contributor on its storage account.
- Secrets. The Fireblocks credentials and the webhook secret are Key Vault secrets that the app settings reference, and the app settings hold no Fireblocks or webhook secret values. The Function identity can read every secret in its vault, and the webhook app settings reference the Fireblocks API key and the private key only when
enableReconcileistrue. Keep local copies of the private key outside the repository, and out of app settings text and build logs. - Signed token. The receiver validates the HS256 signature against the configured secret in constant time and requires
expto be a number in the future. It returns the sameunauthorizedresponse for every credential failure, and it checks the body size before the credential. The token is not bound to the request body, so a valid token authorizes any body until itsexp. Anyone who holds the webhook secret can create valid tokens and write arbitrary rows into the table. Use a webhook secret that you generate for this webhook and use nowhere else. - Address restriction. The webhook endpoint uses anonymous authorization, and the receiver authenticates each request with the signed token.
allowedSourceIpstakes single IPv4 addresses, and the template adds/32to each. With an empty list the endpoint accepts requests from any address and the signed token is the only access control. Every request, including an unauthenticated one, invokes the Function (maximumInstanceCountis 2), and the platform buffers the body before the receiver checks its size. - Capture mode. The receiver answers requests without authentication in
capturemode, applies the same body-size limits as injwtmode, and stores a sanitized record of each one infbcapture. A record holds the redacted event body,x-forwarded-for, anduser-agent, which can include user names, user IDs, and client addresses. Any caller can add records until the 10 are used, and records older than 7 days are purged when the next capture request writes. Thesecret_headerreport never stores the header value or the signature, and it stores the decoded token header and payload with values under sensitive key names redacted. Usecapturemode for short setup sessions withallowedSourceIpsset, and runtools/show_capture.py --deleteto remove the table. - Poison queue.
fb-audit-webhook-poisonholds the complete envelope of every message that failed, which is the body and the selected headers, until you delete it. - Storage and Function apps. Each storage account disables shared-key access and public blob access and requires TLS 1.2. Each Function app accepts HTTPS only, disables FTPS, and requires TLS 1.2.
- Key Vault. Each vault uses Azure role-based access control with purge protection and a 7-day soft-delete retention, so the name of a deleted vault stays reserved for 7 days.
- Diagnostics. No diagnostic settings are configured on Key Vault or on the storage account.
- Public endpoints. Key Vault, the storage account, and the data collection rule endpoint use public endpoints that Microsoft Entra authentication and role assignments protect. The templates configure no storage or Key Vault firewall rules and no private endpoints.
- Remove deployer access after setup. The
adminPrincipalIdparameter grants your user Key Vault Secrets Officer and Monitoring Metrics Publisher. Remove both role assignments when you no longer need to store secrets or run the generator. - Sensitive data. Audit events contain user names and IDs, so restrict who can read
FireblocksAudit_CLandFireblocksWebhook_CLwith workspace access controls. Application Insights writes to the same Log Analytics workspace as Sentinel, which mixes Function telemetry with security data. Use a separate workspace for telemetry if that does not fit your policy. - Dependencies.
requirements.txtpins every dependency and is resolved fromrequirements.in. Runpip-audit -r function/requirements.txtto check the pinned versions, and again after any change.
Example repository
The example repository holds the complete source for both stacks in thepolling/ and webhook/ folders, and the excerpts in this guide quote it. The tree below shows the layout of both folders.
polling
.env.example
README.md
function
function_app.py
host.json
poller.py
requirements.in
requirements.txt
infra
main.bicep
kql
off_hours_admin_change.kql
policy_change.kql
rejection_burst.kql
tests
test_poller.py
tools
capture_sample.py
generate.py
webhook
.env.example
README.md
function
function_app.py
host.json
poller.py
webhook.py
requirements.in
requirements.txt
infra
main.bicep
kql
FireblocksWebhookDedup.kql
off_hours_admin_change.kql
policy_change.kql
rejection_burst.kql
tests
test_poller.py
test_webhook.py
tools
capture_sample.py
generate.py
show_capture.py
.venv/bin/python -m unittest discover -s tests -v.
Related
- Audit Event webhooks in the Help Center for the audit event webhook.
- Audit Logs API for filters, paging, and errors.
- Manage API Access for API users, key pairs, and rotation.
- Audit Log Events for the categories, subjects, and events that appear in the tables.