> ## Documentation Index
> Fetch the complete documentation index at: https://developers.fireblocks.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Stream Audit Logs to Microsoft Sentinel

> Send Fireblocks audit events to Microsoft Sentinel with an Azure Function that polls the Audit Logs API, and add the audit event webhook.

This guide shows you how to ingest Fireblocks audit log data into Microsoft Sentinel. It uses polling and the audit event webhook together for maximum redundancy.

The events are written to custom tables in your Log Analytics workspace, where Sentinel analytics rules can alert on administrative, policy, and transaction activity.

The guide consists of 2 parts. The [example repository](https://github.com/fireblocks/sentinel-siem-integration-example) holds the source code for both.

> [card] [Part 1: Quickstart](#part-1-quickstart)
>
> Deploy the polling Function and the audit event webhook from the example repository.

> [card] [Part 2: How it works](#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:

1. An Azure Function that polls the [Audit Logs API](https://developers.fireblocks.com/docs/audit-logs-api.md) every minute into `FireblocksAudit_CL`.
2. The [audit event webhook](https://support.fireblocks.io/hc/en-us/articles/21630746432284-Audit-Event-webhooks-notifications) that sends each event to a second Function, which writes it to `FireblocksWebhook_CL`.

Run the commands in a terminal that is signed in with `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](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) with [Bicep](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/install), and [Azure Functions Core Tools](https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local) 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:

```bash theme={"system"}
git clone https://github.com/fireblocks/sentinel-siem-integration-example.git
cd sentinel-siem-integration-example/polling
```

**2. Create a key pair and a CSR**

Create a key pair and a certificate signing request (CSR) outside the repository:

```bash theme={"system"}
mkdir -p ~/.fireblocks
(umask 077; openssl req -new -newkey rsa:4096 -nodes \
  -keyout ~/.fireblocks/fireblocks_secret.key -out ~/.fireblocks/fireblocks.csr \
  -subj '/O=<your-organization>')
```

In the Fireblocks Console, go to the [Developer center's API users page](https://console.fireblocks.io/v2/developer/api-users), select **Add API user**, enter a name, select the **Auditor** role, upload `~/.fireblocks/fireblocks.csr`, and select **Add user**. See [Manage API Access](https://developers.fireblocks.com/docs/manage-api-keys.md).

> [!TIP]
>
> 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:

> [tab] US
>
> `https://api.fireblocks.io/v1`

> [tab] EU
>
> `https://eu-api.fireblocks.io/v1`

> [tab] EU2
>
> `https://eu2-api.fireblocks.io/v1`

> [tab] Sandbox
>
> `https://sandbox-api.fireblocks.io/v1`

```bash theme={"system"}
az account set --subscription <subscription-id>

az deployment group create -g <resource-group> -n main -f infra/main.bicep \
  -p workspaceName=<workspace-name> \
     fireblocksBasePath=<api-base-path> \
     adminPrincipalId=$(az ad signed-in-user show --query id -o tsv)
```

> [!TIP]
>
> The 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.

```bash theme={"system"}
KV=$(az deployment group show -g <resource-group> -n main --query properties.outputs.keyVaultName.value -o tsv)
FUNC=$(az deployment group show -g <resource-group> -n main --query properties.outputs.functionAppName.value -o tsv)

read -rs FIREBLOCKS_API_KEY   # paste the API key, then press Return
az keyvault secret set --vault-name "$KV" -n fireblocks-api-key \
  --file <(printf %s "$FIREBLOCKS_API_KEY") >/dev/null
az keyvault secret set --vault-name "$KV" -n fireblocks-secret-key \
  --file ~/.fireblocks/fireblocks_secret.key >/dev/null
unset FIREBLOCKS_API_KEY
```

> [!TIP]
>
> `az keyvault secret list --vault-name "$KV" -o table` lists `fireblocks-api-key` and `fireblocks-secret-key`.

> [!WARNING]
>
> Move `~/.fireblocks/fireblocks_secret.key` to your password manager and delete the local copy.

**5. Publish the Function**

The command publishes from the `function` folder, and the parentheses keep your terminal in the folder where you started.

```bash theme={"system"}
(cd function && func azure functionapp publish "$FUNC")
```

> [!TIP]
>
> `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`:
>
> ```kql theme={"system"}
> AppTraces | where Message has "Fetched" | take 5
> ```

**6. Confirm the events**

Confirm the events in the **Logs** page of the workspace:

```kql theme={"system"}
FireblocksAudit_CL | take 10
```

> [!TIP]
>
> 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.

The 3 sample detection rules are ready to paste into Sentinel. See [Detection rules](#detection-rules).

### 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](#1-1-send-audit-events-to-sentinel-polling).
* A Fireblocks Console administrator who can add an audit log webhook subscription.

#### Steps

**1. Open the webhook folder**

```bash theme={"system"}
cd ../webhook
```

**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.

> [!WARNING]
>
> Without the `allowedSourceIps` parameter, no address restriction applies and the signed token is the only access control.

```bash theme={"system"}
az deployment group create -g <resource-group> -n webhook -f infra/main.bicep \
  -p workspaceName=<workspace-name> \
     fireblocksBasePath=<api-base-path> \
     adminPrincipalId=$(az ad signed-in-user show --query id -o tsv)
```

> [!TIP]
>
> 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 `az keyvault secret set` command returns `Forbidden`, wait a few minutes for the role assignment to take effect and run it again.

```bash theme={"system"}
KV=$(az deployment group show -g <resource-group> -n webhook --query properties.outputs.keyVaultName.value -o tsv)
FUNC=$(az deployment group show -g <resource-group> -n webhook --query properties.outputs.functionAppName.value -o tsv)

WEBHOOK_SECRET=$(openssl rand -hex 32)
az keyvault secret set --vault-name "$KV" -n fireblocks-webhook-secret \
  --file <(printf %s "$WEBHOOK_SECRET") >/dev/null

az functionapp restart -g <resource-group> -n "$FUNC"
```

Copy the secret to your clipboard with the command for your system, and keep the variable set until step 5 is done.

> [tab] macOS
>
> ```bash theme={"system"}
> printf %s "$WEBHOOK_SECRET" | pbcopy
> ```

> [tab] Linux
>
> ```bash theme={"system"}
> printf %s "$WEBHOOK_SECRET" | xclip -selection clipboard
> ```

> [tab] Windows (Git Bash or WSL)
>
> ```bash theme={"system"}
> printf %s "$WEBHOOK_SECRET" | clip
> ```

> [!TIP]
>
> `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.

```bash theme={"system"}
(cd function && func azure functionapp publish "$FUNC")
```

> [!TIP]
>
> 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 `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](https://support.fireblocks.io/hc/en-us/articles/21630746432284-Audit-Event-webhooks-notifications).

```bash theme={"system"}
az deployment group show -g <resource-group> -n webhook --query properties.outputs.webhookUrl.value -o tsv
```

Then run `unset WEBHOOK_SECRET`.

> [!TIP]
>
> 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:

```kql theme={"system"}
FireblocksWebhook_CL | take 10
```

> [!TIP]
>
> 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.

```mermaid theme={"system"}
%%{init: {"theme": "base", "themeVariables": {"fontFamily": "Figtree, Inter, system-ui, sans-serif", "fontSize": "15px", "lineColor": "#678BFF", "textColor": "#212647", "edgeLabelBackground": "#FFFFFF", "clusterBkg": "#F4F5F7", "clusterBorder": "#678BFF", "titleColor": "#212647"}, "flowchart": {"curve": "basis", "padding": 28, "nodeSpacing": 56, "rankSpacing": 64, "diagramPadding": 16, "subGraphTitleMargin": {"top": 12, "bottom": 12}}}}%%
flowchart TD
  subgraph FBS["Fireblocks"]
    FB(["Fireblocks workspace<br/>GET /v1/management/audit_logs"])
  end
  subgraph POLL["Polling stack"]
    direction LR
    KV("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Key Vault&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
    FN("Azure Function<br/>(managed identity)")
    TS[("&nbsp;&nbsp;Table Storage&nbsp;&nbsp;")]
  end
  subgraph MON["Azure Monitor and Sentinel"]
    direction LR
    DCR("Data collection rule (DCR)")
    T[("FireblocksAudit_CL")]
    R("Sentinel analytics rules")
  end

  FBS -->|"&nbsp;every minute,<br/>overlapping window&nbsp;"| POLL
  KV -.->|"&nbsp;API credentials&nbsp;"| FN
  FN <-->|"&nbsp;position and seen IDs&nbsp;"| TS
  POLL -->|"&nbsp;Logs Ingestion API&nbsp;"| MON
  DCR --> T
  T --> R

  classDef fireblocks fill:#678BFF,stroke:#4568F3,stroke-width:2px,color:#FFFFFF,font-weight:bold
  classDef func fill:#212647,stroke:#678BFF,stroke-width:3px,color:#FFFFFF,font-weight:bold
  classDef store fill:#2C365F,stroke:#678BFF,stroke-width:2px,color:#FFFFFF
  classDef azure fill:#FFFFFF,stroke:#678BFF,stroke-width:2px,color:#212647
  class FB fireblocks
  class FN func
  class KV,TS store
  class DCR,T,R azure
  style FBS fill:#F4F5F7,stroke:#678BFF,stroke-width:2px,rx:12,ry:12
  style POLL fill:#F4F5F7,stroke:#678BFF,stroke-width:2px,rx:12,ry:12
  style MON fill:#F4F5F7,stroke:#678BFF,stroke-width:2px,rx:12,ry:12
  linkStyle default stroke:#678BFF,stroke-width:2px
  linkStyle 1 stroke:#4568F3,stroke-width:2px,stroke-dasharray:6 4
```

The polling stack has these components.

| Component | Role |
| :- | :- |
| Azure Function (Python 3.13, Flex Consumption) | Runs the poller on a timer trigger. |
| Managed identity | Authenticates the Function to Azure Monitor, Key Vault, and Table Storage without an Azure secret. |
| Key Vault | Holds the Fireblocks API key and private key, which the Function reads through Key Vault references. |
| Table Storage | Stores the poller's position and its list of recently seen event IDs. The code creates the table `fbstate` at run time. |
| Data collection rule (DCR) | Receives uploads and routes them to the custom table. |
| `FireblocksAudit_CL` | The Sentinel table that holds the audit events. |
| `generate.py` | Sends synthetic events so you can test detections without real activity. |

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](https://developers.fireblocks.com/docs/audit-logs-api.md#permissions).

#### Webhook architecture

The Console sends an HTTP `POST` 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.

```mermaid theme={"system"}
%%{init: {"theme": "base", "themeVariables": {"fontFamily": "Figtree, Inter, system-ui, sans-serif", "fontSize": "15px", "lineColor": "#678BFF", "textColor": "#212647", "edgeLabelBackground": "#FFFFFF", "clusterBkg": "#F4F5F7", "clusterBorder": "#678BFF", "titleColor": "#212647"}, "flowchart": {"curve": "basis", "padding": 16, "nodeSpacing": 28, "rankSpacing": 36}}}%%
flowchart TD
  subgraph CANVAS[" "]
    direction TB
    subgraph FBS["Fireblocks"]
      FB(["Fireblocks Console<br/>audit event webhook"])
    end
    subgraph HOOK["Webhook stack"]
      KV("Key Vault")
      RX("audit_webhook<br/>HTTP trigger")
      Q[("Storage Queue<br/>fb-audit-webhook")]
      PQ[("Poison queue")]
      PR("process_webhook_event<br/>queue trigger")
    end
    subgraph MON["Azure Monitor and Sentinel"]
      DCR("Direct data collection rule")
      T[("FireblocksWebhook_CL table")]
      D("FireblocksWebhookDedup function")
      R("Sentinel analytics rules")
    end
    G("generate.py<br/>synthetic events")
  end

  FB -->|"POST, header x-webhook-secret"| RX
  KV -.->|"webhook secret"| RX
  RX -->|"envelope"| Q
  Q --> PR
  Q -.->|"5 failed attempts"| PQ
  PR -->|"Logs Ingestion API"| DCR
  G -->|"Logs Ingestion API"| DCR
  DCR --> T
  T --> D
  D --> R

  classDef fireblocks fill:#678BFF,stroke:#4568F3,stroke-width:2px,color:#FFFFFF,font-weight:bold
  classDef func fill:#212647,stroke:#678BFF,stroke-width:3px,color:#FFFFFF,font-weight:bold
  classDef store fill:#2C365F,stroke:#678BFF,stroke-width:2px,color:#FFFFFF
  classDef azure fill:#FFFFFF,stroke:#678BFF,stroke-width:2px,color:#212647
  classDef test fill:#E4E9F2,stroke:#212647,stroke-width:2px,stroke-dasharray:6 4,color:#212647
  class FB fireblocks
  class RX,PR func
  class KV,Q,PQ store
  class DCR,T,D,R azure
  class G test
  style CANVAS fill:#FFFFFF,stroke:#E4E9F2,stroke-width:2px,rx:20,ry:20
  style FBS fill:#F4F5F7,stroke:#678BFF,stroke-width:2px,rx:12,ry:12
  style HOOK fill:#F4F5F7,stroke:#678BFF,stroke-width:2px,rx:12,ry:12
  style MON fill:#F4F5F7,stroke:#678BFF,stroke-width:2px,rx:12,ry:12
  linkStyle default stroke:#678BFF,stroke-width:2px
  linkStyle 1,4 stroke:#4568F3,stroke-width:2px,stroke-dasharray:6 4
```

The webhook stack has these components.

| Component | Role |
| :- | :- |
| `audit_webhook` (HTTP trigger) | Checks the delivery, wraps it in an envelope, queues it, and answers the Console. |
| `process_webhook_event` (queue trigger) | Parses the queued delivery and uploads one row per event. |
| `poll_audit_logs` (timer trigger) | An optional second poller inside this stack. It is off by default. |
| Storage Queue `fb-audit-webhook` | Holds accepted deliveries until the processor writes them. The Functions host creates the poison queue `fb-audit-webhook-poison`. |
| Key Vault | Holds the webhook secret. |
| `FireblocksWebhook_CL` | The Sentinel table that holds the webhook events. |
| `FireblocksWebhookDedup` | A saved function that returns one row for each event ID. The sample rules read it. |

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](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview).

The table has these columns.

| Column | Type | Content |
| :- | :- | :- |
| `TimeGenerated` | datetime | The event's own timestamp. Falls back to the time of the run, or of the delivery, when an event has no readable timestamp or a timestamp outside 1970 to 2100. |
| `EventId` | string | The event `id`. When `id` is missing, a hash of the event, prefixed `h-`. |
| `Category` | string | The event `category`, for example `Administration`. |
| `Subject` | string | The event `subject`, for example `User`. |
| `Event` | string | The event type, for example `Changed role`. |
| `UserName` | string | The `user` that triggered the event. |
| `UserId` | string | The `userId` that triggered the event. |
| `FbTenantId` | string | The Fireblocks `tenantId`, when the event carries one. |
| `Synthetic` | boolean | `true` for rows sent by the test generator. |
| `Channel` | string | `FireblocksWebhook_CL` only: `webhook` for rows from the receiver, `poll` for rows from the optional second poller, and `synthetic` for generated events. |
| `Raw` | dynamic | The complete event as JSON. |

`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.

> [!NOTE]
>
> The tenant ID is stored as `FbTenantId` because Azure Monitor reserves `TenantId` and several other column names. See [supported tables](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview#supported-tables) in the Azure Monitor documentation.

The same column list defines the table and the rule's input stream, so the transformation is `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.

| Parameter | Stack | Default | Description |
| :- | :- | :- | :- |
| `workspaceName` | Both | Required | The existing Log Analytics workspace in the resource group. |
| `fireblocksBasePath` | Both | Required | The API base path for your environment. Only the polling stack and the optional second poller use it. |
| `adminPrincipalId` | Both | Empty | The object ID of the person deploying. Grants Key Vault Secrets Officer on the vault (to store secrets) and Monitoring Metrics Publisher on the rule (to run the generator). |
| `location` | Both | The resource group location | The region of the resources, which must match the region of the workspace. |
| `namePrefix` | Both | `fbsent` and `fbhook` | A short lowercase prefix for resource names, 3 to 10 characters. Keep the 2 prefixes different. |
| `webhookAuthMode` | Webhook | `jwt` | How the receiver treats a delivery: `jwt` verifies the HS256 token in the `x-webhook-secret` header and queues the delivery, and `capture` stores a sanitized record of the delivery in a table named `fbcapture`, which the code creates at run time, for inspection and queues nothing. |
| `allowedSourceIps` | Webhook | `[]` | A list of single IPv4 addresses that may reach the Function app. Each address becomes an allow rule for that address, and the platform denies any other address. An empty list applies no address restriction, and the signed token is then the only access control. |
| `alwaysReadyReceivers` | Webhook | `1` | The number of always-ready instances for the receiver, from 0 to 2. Set `0` to let the app scale to zero. |
| `enableReconcile` | Webhook | `false` | Runs a second poller inside the webhook stack, which reads the Audit Logs API on a schedule and uploads the events it reads. It needs the Fireblocks API key and private key in the webhook stack's Key Vault as `fireblocks-api-key` and `fireblocks-secret-key`, stored as in the commands below. When `true`, the Function app also references these 2 secrets. |
| `reconcileSchedule` | Webhook | `0 */10 * * * *` | The schedule of the second poller, which is every 10 minutes. |
| `reconcileOverlapMs` | Webhook | `120000` | The overlap that each run of the second poller re-queries, which is 2 minutes. |

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.

> [!WARNING]
>
> Repeat the other parameters, including `allowedSourceIps`, in every later deployment, because the template sets the restriction from that parameter.

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](#1-2-add-the-audit-event-webhook) again with `-p enableReconcile=true` added and the same other parameters, including `allowedSourceIps`. The second poller reads the API base path from `fireblocksBasePath`.

```bash theme={"system"}
KV=$(az deployment group show -g <resource-group> -n webhook --query properties.outputs.keyVaultName.value -o tsv)
read -rs FIREBLOCKS_API_KEY   # paste the API key, then press Return
FIREBLOCKS_SECRET_KEY_PATH=~/.fireblocks/fireblocks_secret.key
az keyvault secret set --vault-name "$KV" -n fireblocks-api-key --file <(printf %s "$FIREBLOCKS_API_KEY") >/dev/null
az keyvault secret set --vault-name "$KV" -n fireblocks-secret-key --file "$FIREBLOCKS_SECRET_KEY_PATH" >/dev/null
unset FIREBLOCKS_API_KEY
```

#### Deployment outputs

The polling deployment outputs `functionAppName`, `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.

| Number | What it controls | Why this value |
| :- | :- | :- |
| Poll interval: 1 minute | This dictates how often your integration checks Fireblocks for new events to send to Sentinel. It is a 6-field [NCRONTAB expression](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer#ncrontab-expressions), `0 * * * * *`, that fires on the first second of every minute. | An example default. A longer interval delays alerts by up to that interval. |
| First-run lookback: 60 minutes | When you first deploy the integration, it needs to know how far back in time to look for events in Fireblocks. `FIRST_RUN_LOOKBACK_MS` is 3,600,000 milliseconds, which is 60 minutes. | An example default that loads the last hour of events. Raise it to load older events, up to 1 year back, which is the farthest the Audit Logs API allows. |
| Page cap: 25,000 events per run | Fireblocks returns events in pages, and each run of the integration reads a limited number of pages so that it always finishes. A page holds up to 500 events (`PAGE_SIZE`) and a run reads up to 50 pages (`MAX_PAGES`), so 50 x 500 = 25,000 events per run. | 500 is the most the [Audit Logs API](https://developers.fireblocks.com/docs/audit-logs-api.md#sorting-and-pagination) returns per page and 50 is an example default. When there are more events than the cap, the next run carries on from where this one stopped, so a large backlog loads over several runs. |
| Overlap: 2 minutes | Some events appear in Fireblocks a little after they happen, so each run starts slightly before the previous run ended to catch them. `OVERLAP_MS` is 120,000 milliseconds, which is 2 minutes. Events that were already sent are skipped, so nothing is duplicated. | An example default of 2 poll intervals. The second poller in the webhook stack reads the same value from `reconcileOverlapMs`. |
| Delivery attempts: 5 tries, 30 seconds apart | When the webhook receiver cannot process an event, it tries again. `maxDequeueCount` is how many tries it makes and `visibilityTimeout` is how long it waits between tries. After the last try the event moves to a poison queue, where you can look at it. | Example defaults. `WEBHOOK_MAX_DEQUEUE` in `main.bicep` is set to the same 5. |
| Body limits: 32 KiB request, 45,000-character queue message | The receiver refuses webhook requests that are too large before it spends any effort on them. `WEBHOOK_MAX_BODY_BYTES` is the largest request, 32,768 bytes (32 KiB), and `WEBHOOK_MAX_ENVELOPE_CHARS` is the largest message it puts on the queue, 45,000 characters. | An Azure queue message can be at most 64 KiB (65,536 bytes) and Functions base64-encode it, so 45,000 characters become 45,000 x 4 / 3 = 60,000 bytes, which fits. 32 KiB is an example default. |
| Maximum instances: 2 | Azure starts more copies of the webhook Function app when many requests arrive. `maximumInstanceCount` is the most copies it runs at the same time, which keeps cost and load down if someone floods your endpoint with requests. | An example default, and the largest value of `alwaysReadyReceivers`. |
| Reconcile schedule: every 10 minutes | Fireblocks sends each webhook event only once, so an event can be missed. The optional second poller fixes that by reading Fireblocks on a schedule and sending any event that the webhook did not deliver. `0 */10 * * * *` fires on the first second of every 10th minute. | An example default. A shorter interval closes gaps sooner but makes more Audit Logs API calls. |
| Rule schedules and thresholds | Each detection rule runs on a schedule and looks back over a period of time. The rules also set the business hours (07:00 to 19:59 UTC) and how many rejections raise an alert (5 within 10 minutes). All of these are in the rule files in [Detection rules](#detection-rules). | The hours and the threshold are examples, so set them to match your own policy. Sentinel requires a run interval from 5 minutes to 14 days and a lookback at least as long as the interval ([Create scheduled analytics rules](https://learn.microsoft.com/en-us/azure/sentinel/create-analytics-rules)). |
| Rule windows: 20 and 10 minutes | How far back each rule looks when it runs: 20 minutes for the off-hours rule and 10 minutes for the policy rule. | Each is the run interval plus 5 minutes of slack (15 + 5 = 20 and 5 + 5 = 10), so a row that reaches Sentinel a little late is still checked. |
| Key Vault retention: 7 days | If someone deletes the Key Vault that holds your secrets, Azure keeps it for a while so that you can recover it. `softDeleteRetentionInDays` is how long, and purge protection (`enablePurgeProtection`) stops anyone from removing it sooner, as described in [Azure Key Vault soft-delete overview](https://learn.microsoft.com/en-us/azure/key-vault/general/soft-delete-overview). | 7 days is the shortest retention that Key Vault allows. |

### 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.

```python theme={"system"}
@app.timer_trigger(
    schedule="0 * * * * *", arg_name="timer", run_on_startup=False, use_monitor=True
)
def poll_audit_logs(timer: func.TimerRequest) -> None:
    """Pull new Fireblocks audit events once a minute and send them to Sentinel."""
    if timer.past_due:
        logging.warning("Timer is past due; running now.")
    run_once()
```

`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:

```python theme={"system"}
OVERLAP_MS = 120_000
FIRST_RUN_LOOKBACK_MS = 3_600_000
PAGE_SIZE = 500
MAX_PAGES = 50
MAX_SEEN = 500
# Table Storage rejects string properties longer than 32K characters.
MAX_SEEN_CHARS = 30_000
# Timestamps outside 1970 to 2100 are treated as unreadable.
MAX_EVENT_MS = 4_102_444_800_000
```

Each run works through these steps.

1. **Read the position.** `TableState` stores the position (`next_start_ms`) and a list of recently seen event IDs in one row of a Table Storage table named `fbstate`. 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.

2. **Fetch.** `fetch_events` queries from the stored position to the current time, oldest events first, 500 events per page, and follows the `next` cursor until the response has none. It stops after 50 pages, so a very large backlog cannot run indefinitely.

3. **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.

   ```python theme={"system"}
       events, complete = fetch_events(client, start_ms, end_ms)
       fresh = [e for e in events if event_id(e) not in seen]
       if fresh:
           uploader([to_row(e, now_ms=end_ms) for e in fresh])
   ```

4. **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.

If more events are waiting than one run can fetch (50 pages of 500, which is 25,000 events), the poller uploads what it fetched and sets the next start time as described below, and it logs an error that contains `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_MS` in `poller.py` to 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 the `x-webhook-secret` header, signed with the secret key you entered in the Console. The [Audit Event webhooks article](https://support.fireblocks.io/hc/en-us/articles/21630746432284-Audit-Event-webhooks-notifications) 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.

| Status | Response text | When |
| :- | :- | :- |
| `200` | `ok` | The delivery passed every check and was handed to the queue. |
| `200` | `captured` | The mode is `capture` and a sanitized record was stored. In this mode the receiver answers without checking the token. |
| `400` | `body is not UTF-8` | The body cannot be decoded as UTF-8. |
| `401` | `unauthorized` | The `x-webhook-secret` header is missing, does not validate, or has expired. Every credential failure returns the same response. |
| `413` | `payload too large` | The body or the declared `Content-Length` is above 32 KiB in any mode, or the envelope is above 45,000 characters. |
| `500` | `capture failed` | The mode is `capture` and the record could not be stored. |
| `503` | `not configured` | The mode is not one of the allowed values, the secret is empty or an unresolved Key Vault reference, or the mode is `capture` and no capture store is available. |
| `503` | `enqueue failed` | The call that writes to the queue raised an error. |

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`.

```json theme={"system"}
  "extensions": {
    "queues": {
      "maxDequeueCount": 5,
      "visibilityTimeout": "00:00:30"
    }
  },
```

On the last attempt the processor logs an error that starts with `WEBHOOK_POISON:`, and the Functions host moves the message to `fb-audit-webhook-poison`, which the host creates.

> [!TIP]
>
> Create a scheduled query alert that runs every 5 minutes and fires when this query returns a count above 0:
>
> ```kql theme={"system"}
> AppTraces
> | where Message startswith "WEBHOOK_POISON:"
> | summarize Poisoned = count() by bin(TimeGenerated, 5m)
> ```

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.

```bash theme={"system"}
az storage message peek --queue-name fb-audit-webhook-poison \
  --account-name <storage-account-name> --auth-mode login
```

### 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](https://learn.microsoft.com/en-us/azure/sentinel/create-analytics-rules). 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 for `FireblocksAudit_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.

> [accordion] kql/off\_hours\_admin\_change.kql
>
> ```kql theme={"system"}
> // Analytics rule: user, role or IP allowlist change outside business hours.
> // Schedule: run every 15 minutes with a query period of 1 day.
> // The ingestion_time() filter selects rows that arrived in the last 20 minutes (the 15 minute
> // interval plus 5 minutes of slack), so rows that reach Sentinel late are still evaluated. The
> // 1 day query period stops the rule's own time filter from hiding events whose event time is
> // older than the interval, which is the case for the generator's off-hours test event. The
> // slack means a row can be seen by two runs, so group alerts into one incident per user.
> // Business hours here are 07:00 to 19:59 UTC; adjust them to your time zone.
> FireblocksAudit_CL
> | where ingestion_time() >= ago(20m)
> | where Category == "Administration"
> | where Subject in ("User", "New user", "Edit user", "Whitelisted IP")
> | where Event in ("Changed role", "Deactivated", "Deleted", "Approved", "Submitted request", "List updated")
> | where hourofday(TimeGenerated) !between (7 .. 19)
> | summarize Events = count(), Actions = make_set(strcat(Subject, " / ", Event), 10), FirstSeen = min(TimeGenerated) by UserName, UserId
> ```

> [accordion] kql/policy\_change.kql
>
> ```kql theme={"system"}
> // Analytics rule: any change to the transaction authorization policy.
> // Schedule: run every 5 minutes with a query period of 1 day.
> // The ingestion_time() filter selects rows that arrived in the last 10 minutes (the 5 minute
> // interval plus 5 minutes of slack), so rows that reach Sentinel after the event time are still
> // evaluated. The 1 day query period stops the rule's own time filter from hiding them. The slack
> // means a row can be seen by two runs, so group alerts into one incident per user.
> // The Policies category covers every change to a policy, up to and including a policy
> // going into effect. Narrow Event to "Published policy" and "Put policy into effect" to
> // alert only when a change becomes live.
> FireblocksAudit_CL
> | where ingestion_time() >= ago(10m)
> | where Category == "Policies"
> | project TimeGenerated, UserName, UserId, Subject, Event, Synthetic
> ```

> [accordion] kql/rejection\_burst.kql
>
> ```kql theme={"system"}
> // Analytics rule: five or more rejected or policy-blocked transactions by one user in 10 minutes.
> // Schedule: run every 5 minutes with a query period of 10 minutes.
> // The count covers the 10 minutes before each run instead of fixed clock-aligned time buckets,
> // so a burst that straddles a bucket boundary is still counted once. Consecutive runs overlap,
> // so group alerts into one incident per user.
> // Event names come from the Fireblocks Audit Log Events reference (https://developers.fireblocks.com/reference/audit-log-events).
> FireblocksAudit_CL
> | where TimeGenerated >= ago(10m)
> | where Category == "Transactions" and Subject == "Transaction"
> | where Event in ("Rejected", "Rejected by AML", "Blocked by TAP")
> | summarize Rejections = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by UserName, UserId
> | where Rejections >= 5
> ```

The table below lists the schedule of each rule.

| Rule | Run query every | Lookup data from the last (query period) | Time filter in the query |
| :- | :- | :- | :- |
| User, role, or IP allowlist change outside business hours | 15 minutes | 1 day | Rows ingested in the last 20 minutes |
| Policy change | 5 minutes | 1 day | Rows ingested in the last 10 minutes |
| Burst of rejected transactions | 5 minutes | 10 minutes | Events from the last 10 minutes |

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](https://developers.fireblocks.com/reference/audit-log-events.md) reference.

> [!TIP]
>
> The schedules, the business hours of 07:00 to 19:59 UTC, and the threshold of 5 rejections in 10 minutes are starting values to tune.

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 `Administration` category outside 07:00 to 19:59 UTC. Adjust the hour range to your time zone.
* **Policy change** alerts on any event in the `Policies` category. To alert only when a change becomes live, narrow `Event` to `Published policy` and `Put 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 the `FireblocksWebhookDedup` 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.

> [accordion] kql/FireblocksWebhookDedup.kql
>
> ```kql theme={"system"}
> // Saved function FireblocksWebhookDedup (deployed by infra/main.bicep, alias FireblocksWebhookDedup).
> // FireblocksWebhook_CL can hold several rows with the same EventId when a queue message is processed
> // more than once. This function returns one row per EventId: the copy that arrived first.
> // IngestedAt is the ingestion time of that first copy, so a rule that filters on IngestedAt alerts
> // once when an event first appears and is not triggered again by a repeated copy.
> // EventId is the id of the event when the payload has one, and otherwise a hash of the event prefixed h-.
> // Rules must read this function, not the table.
> // A duplicate that arrives after the rule's query period has ended can no longer be matched
> // with its first copy, so keep the period at 1 day or more for rules that filter on IngestedAt.
> FireblocksWebhook_CL
> | extend IngestedAt = ingestion_time()
> | summarize arg_min(IngestedAt, *) by EventId
> ```

> [accordion] kql/off\_hours\_admin\_change.kql
>
> ```kql theme={"system"}
> // Analytics rule: user, role or IP allowlist change outside business hours.
> // Reads the FireblocksWebhookDedup function (kql/FireblocksWebhookDedup.kql), which returns one row per EventId.
> // Schedule: run every 15 minutes with a query period of 1 day.
> // The IngestedAt filter selects events that first arrived in the last 20 minutes (the 15 minute
> // interval plus 5 minutes of slack), so rows that reach Sentinel late are still evaluated. The
> // 1 day query period stops the rule's own time filter from hiding events whose event time is
> // older than the interval, which is the case for the generator's off-hours test event. The
> // slack means a row can be seen by two runs, so group alerts into one incident per user.
> // Business hours here are 07:00 to 19:59 UTC; adjust them to your time zone.
> FireblocksWebhookDedup
> | where IngestedAt >= ago(20m)
> | where Category == "Administration"
> | where Subject in ("User", "New user", "Edit user", "Whitelisted IP")
> | where Event in ("Changed role", "Deactivated", "Deleted", "Approved", "Submitted request", "List updated")
> | where hourofday(TimeGenerated) !between (7 .. 19)
> | summarize Events = count(), Actions = make_set(strcat(Subject, " / ", Event), 10), FirstSeen = min(TimeGenerated) by UserName, UserId
> ```

> [accordion] kql/policy\_change.kql
>
> ```kql theme={"system"}
> // Analytics rule: any change to the transaction authorization policy.
> // Reads the FireblocksWebhookDedup function (kql/FireblocksWebhookDedup.kql), which returns one row per EventId.
> // Schedule: run every 5 minutes with a query period of 1 day.
> // The IngestedAt filter selects events that first arrived in the last 10 minutes (the 5 minute
> // interval plus 5 minutes of slack), so rows that reach Sentinel after the event time are still
> // evaluated. The 1 day query period stops the rule's own time filter from hiding them. The slack
> // means a row can be seen by two runs, so group alerts into one incident per user.
> // The Policies category covers every change to a policy, up to and including a policy
> // going into effect. Narrow Event to "Published policy" and "Put policy into effect" to
> // alert only when a change becomes live.
> FireblocksWebhookDedup
> | where IngestedAt >= ago(10m)
> | where Category == "Policies"
> | project TimeGenerated, UserName, UserId, Subject, Event, Synthetic
> ```

> [accordion] kql/rejection\_burst.kql
>
> ```kql theme={"system"}
> // Analytics rule: five or more rejected or policy-blocked transactions by one user in 10 minutes.
> // Reads the FireblocksWebhookDedup function (kql/FireblocksWebhookDedup.kql), which returns one row per EventId.
> // Schedule: run every 5 minutes with a query period of 10 minutes.
> // The count covers the 10 minutes before each run instead of fixed clock-aligned time buckets,
> // so a burst that straddles a bucket boundary is still counted once. Consecutive runs overlap,
> // so group alerts into one incident per user.
> // Event names come from the Fireblocks Audit Log Events reference (https://developers.fireblocks.com/reference/audit-log-events).
> FireblocksWebhookDedup
> | where TimeGenerated >= ago(10m)
> | where Category == "Transactions" and Subject == "Transaction"
> | where Event in ("Rejected", "Rejected by AML", "Blocked by TAP")
> | summarize Rejections = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by UserName, UserId
> | where Rejections >= 5
> ```

#### 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`.

```bash theme={"system"}
python3.13 -m venv .venv
.venv/bin/pip install -r function/requirements.txt
cp .env.example .env   # set DCR_ENDPOINT and DCR_IMMUTABLE_ID from the deployment outputs
set -a; source .env; set +a

.venv/bin/python tools/generate.py scenario off-hours-admin
.venv/bin/python tools/generate.py scenario policy-change
.venv/bin/python tools/generate.py scenario rejection-burst
```

Read `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-admin` scenario 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-burst` scenario 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.

To replay your own events, run `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.

> [tab] Polling stack
>
> Show recent polled rows, including the full event in `Raw`:
>
> ```kql theme={"system"}
> FireblocksAudit_CL
> | where TimeGenerated > ago(1h)
> | project TimeGenerated, Category, Subject, Event, UserName, Synthetic, Raw
> | order by TimeGenerated desc
> ```
>
> Summarize the real events by category, subject, and event:
>
> ```kql theme={"system"}
> FireblocksAudit_CL
> | where Synthetic == false
> | summarize Events = count() by Category, Subject, Event
> | order by Events desc
> ```
>
> 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](#limits-of-the-poller) describes:
>
> ```kql theme={"system"}
> FireblocksAudit_CL
> | summarize Rows = count() by EventId
> | where Rows > 1
> ```
>
> Measure the delay between an event and its row in the table:
>
> ```kql theme={"system"}
> FireblocksAudit_CL
> | where Synthetic == false
> | extend IngestionDelay = ingestion_time() - TimeGenerated
> | summarize AverageDelay = avg(IngestionDelay), MaxDelay = max(IngestionDelay)
> ```

> [tab] Webhook stack
>
> Show recent webhook events, including the full event in `Raw`:
>
> ```kql theme={"system"}
> FireblocksWebhook_CL
> | where Channel == "webhook"
> | project TimeGenerated, Category, Subject, Event, UserName, EventId, Raw
> | order by TimeGenerated desc
> | take 10
> ```
>
> Summarize the webhook events by category, subject, and event:
>
> ```kql theme={"system"}
> FireblocksWebhook_CL
> | where Channel == "webhook"
> | summarize Events = count() by Category, Subject, Event
> | order by Events desc
> ```
>
> To see what the receiver did with each delivery, query the Function's own log. The line `webhook mode=jwt status=200 bytes=<n> outcome=ok` is one delivery that was accepted:
>
> ```kql theme={"system"}
> AppTraces
> | where Message startswith "webhook mode="
> | project TimeGenerated, Message
> | order by TimeGenerated desc
> ```

To match a webhook row with its polled row, join on category, subject, event, user, and time. The query below returns the rows of both tables in one result, grouped by category, subject, event, user, and minute:

```kql theme={"system"}
union
  (FireblocksAudit_CL | where Synthetic == false | extend Channel = "poll"),
  (FireblocksWebhookDedup | where Channel == "webhook")
| where TimeGenerated > ago(1d)
| summarize Channels = make_set(Channel), Rows = count() by Category, Subject, Event, UserName, EventMinute = bin(TimeGenerated, 1m)
| order by EventMinute desc
```

#### 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 the `AppTraces` table.

| Log message | Level | Meaning |
| :- | :- | :- |
| `Fetched N events, uploaded M` | Information | One completed poller run. `N` is the number of events the window returned and `M` is the number that were new. `N` is larger than `M` in normal operation because of the overlap. |
| `Timer is past due; running now.` | Warning | The timer started later than scheduled. The run continues normally. |
| `Event <id> has an unreadable timestamp` | Warning | The event is uploaded with the time of the run as its `TimeGenerated`. |
| `Seen-id list capped at 500; consider a shorter poll interval` | Warning | More events were seen in the overlap than the list holds. See [Limits of the poller](#limits-of-the-poller). |
| `Event <id> has an out-of-range timestamp` | Warning | The timestamp is outside 1970 to 2100. The event is uploaded with the time of the run as its `TimeGenerated`. |
| `AUDIT_POLL_CAP_HIT` | Error | A backlog was larger than one run can fetch. |
| `webhook mode=<mode> status=<code> bytes=<n> outcome=<text>` | Information | One webhook delivery and the response the receiver sent. |
| `WEBHOOK_SECRET is empty or an unresolved Key Vault reference` | Error | The receiver answers `503`. Store the secret and restart the Function app. |
| `Enqueue failed: <ExceptionType>` | Error | The call that writes to the queue raised an error. |
| `Capture failed: <ExceptionType>` | Error | The mode is `capture` and the record could not be stored. |
| `Webhook message <id> failed on attempt <n> with <ExceptionType>; it will be retried` | Warning | The processor failed and the queue retries the message. |
| `WEBHOOK_POISON: ...` | Error | The last attempt failed and the message moved to the poison queue. |

> [!TIP]
>
> Create an alert rule on the `AUDIT_POLL_CAP_HIT` error, so that a backlog does not go unnoticed. This query returns the matching entries:
>
> ```kql theme={"system"}
> AppTraces
> | where Message has "AUDIT_POLL_CAP_HIT"
> ```

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](https://learn.microsoft.com/en-us/azure/azure-functions/functions-host-json#applicationinsights). 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

| Symptom | Likely cause and action |
| :- | :- |
| No rows appear after the first upload. | The role assignment on the rule is still propagating. Wait and run the query again. If rows never appear, confirm that `DCR_ENDPOINT` and `DCR_IMMUTABLE_ID` match the deployment outputs and that the identity has Monitoring Metrics Publisher on the rule. |
| The Function logs `Missing required setting`. | An app setting is empty. Deploy the template again and check the Function app's **Environment variables** page. |
| Fireblocks authentication fails or the API returns `403`. | If a Key Vault reference cannot be resolved, Azure uses the reference text as the value, so the Function sends the wrong key. Confirm that both secrets exist in the vault and that the Function's identity has Key Vault Secrets User on it. Confirm that `fireblocksBasePath` matches your workspace environment and that the API user has an allowed role. See [Audit Logs API](https://developers.fireblocks.com/docs/audit-logs-api.md#errors). |
| Uploads fail but the position does not move. | The next run retries the same window. Read the error in the logs and fix the cause, and no events are lost. |
| An event is in the Fireblocks Console but not in the table. | An event that becomes queryable more than 2 minutes after its timestamp is not fetched. Query the [Audit Logs API](https://developers.fireblocks.com/docs/audit-logs-api.md) for the event's time range to confirm that it is returned, and raise `OVERLAP_MS` to widen the window. |
| An analytics rule misses an event. | The row reached the table after the rule's filter window closed. The off-hours and policy rules filter on ingestion time with 5 minutes of slack, so check the delay with the last polling query in [Confirm ingestion](#confirm-ingestion) and increase the `ago()` window if ingestion is slower. The burst rule filters on event time and does not count rows that arrive more than 10 minutes after their event. |
| An Azure CLI command that calls the Function app's deployment endpoint fails with a certificate verification error behind a corporate proxy. | The proxy inspects TLS and the CLI does not trust its certificate. Add the proxy's root certificate to a CA bundle and point `REQUESTS_CA_BUNDLE` at it, as described in [Work behind a proxy](https://learn.microsoft.com/en-us/cli/azure/use-azure-cli-successfully-troubleshooting#work-behind-a-proxy). Do not disable certificate verification. |

#### Troubleshoot the webhook

| Symptom | Likely cause and action |
| :- | :- |
| No row appears after an event in a selected category. | Read the `webhook mode=` lines in `AppTraces`. If there are none, confirm that the Console URL equals the `webhookUrl` output, that you published the Functions, and that the request's source address is in `allowedSourceIps`. If the status is `401`, the secret in the Console differs from the secret in Key Vault, or you did not restart the Function app after storing it. If the status is `503`, store the secret and restart the Function app, or set `webhookAuthMode` to a valid value. If the status is `200` and the row is still missing, check the poison queue and the role assignment on the rule. |
| The Function logs `Missing required setting`. | An app setting is empty. Deploy the template again and check the Function app's **Environment variables** page. |
| An event is missing from the webhook table. | Check that the category is selected in the Console subscription, that the receiver answered within 10 seconds (read the `webhook mode=` lines in `AppTraces`), and that the Function app was running. |
| The Function logs `413`. | The delivery is larger than the body limit. Raise `WEBHOOK_MAX_BODY_BYTES` and `WEBHOOK_MAX_ENVELOPE_CHARS` if your deliveries are larger. |
| A delivery was rejected and is not in the table. | The receiver stores a delivery when it answers `200`. For a delivery answered with `401`, `413`, `503`, or another error, fix the cause with the rows above. |

##### Inspect deliveries in capture mode

To inspect what your endpoint receives, run the deployment command of step 2 in [1.2](#1-2-add-the-audit-event-webhook) 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.

> [!WARNING]
>
> In `capture` mode the receiver answers requests without authentication. Use `capture` mode for short setup sessions with `allowedSourceIps` set.

```bash theme={"system"}
set -a; source .env; set +a
.venv/bin/python tools/show_capture.py
```

Capture mode stores a sanitized record in the table `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](https://developers.fireblocks.com/docs/manage-api-keys.md#rotating-secrets).

1. Generate a new key pair and CSR, and create a new API user with the Auditor role, as in step 2 of [1.1](#1-1-send-audit-events-to-sentinel-polling).

2. Store the new API key and private key in Key Vault with the same `az keyvault secret set` commands. Each command creates a new secret version, and the Key Vault references in the Function app use the latest version.

3. Restart the Function app so that it resolves the new secret versions:

   ```bash theme={"system"}
   az functionapp restart -g <resource-group> -n <function-app-name>
   ```

4. Confirm that the next run logs `Fetched N events, uploaded M` without errors, and then delete the old API user in the Console.

#### Rotate the webhook secret

1. Generate a new value, and store it in Key Vault under the same secret name with the commands in step 3 of [1.2](#1-2-add-the-audit-event-webhook). Each command creates a new secret version.
2. Restart the Function app so that the reference resolves the new version.
3. Update the secret key in the Console webhook.

> [!NOTE]
>
> 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

> [!WARNING]
>
> Deleting a table removes its data permanently. The templates deploy into a resource group that also contains your workspace, so delete the individual resources and never the whole resource group.

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 default `namePrefix` values, `fbsent` for polling and `fbhook` for the webhook.

```bash theme={"system"}
# Polling stack
az functionapp delete -g <resource-group> -n <function-app-name>
az appservice plan delete -g <resource-group> -n fbsent-plan --yes
az monitor app-insights component delete -g <resource-group> --app fbsent-ai
az monitor data-collection rule delete -g <resource-group> -n fbsent-dcr --yes
az storage account delete -g <resource-group> -n <storage-account-name> --yes
az keyvault delete -g <resource-group> -n <key-vault-name>
az monitor log-analytics workspace table delete -g <resource-group> --workspace-name <workspace-name> -n FireblocksAudit_CL --yes

# Webhook stack
az functionapp delete -g <resource-group> -n <function-app-name>
az appservice plan delete -g <resource-group> -n fbhook-plan --yes
az monitor app-insights component delete -g <resource-group> --app fbhook-ai
az monitor data-collection rule delete -g <resource-group> -n fbhook-dcr --yes
az storage account delete -g <resource-group> -n <storage-account-name> --yes
az keyvault delete -g <resource-group> -n <key-vault-name>
az monitor log-analytics workspace saved-search delete -g <resource-group> --workspace-name <workspace-name> -n FireblocksWebhookDedup --yes
az monitor log-analytics workspace table delete -g <resource-group> --workspace-name <workspace-name> -n FireblocksWebhook_CL --yes
```

> [!NOTE]
>
> 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`.

Delete the API user in the Fireblocks Console as well.

### 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 `enableReconcile` is `true`. 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 `exp` to be a number in the future. It returns the same `unauthorized` response 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 its `exp`. 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. `allowedSourceIps` takes single IPv4 addresses, and the template adds `/32` to 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 (`maximumInstanceCount` is 2), and the platform buffers the body before the receiver checks its size.
* **Capture mode.** The receiver answers requests without authentication in `capture` mode, applies the same body-size limits as in `jwt` mode, and stores a sanitized record of each one in `fbcapture`. A record holds the redacted event body, `x-forwarded-for`, and `user-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. The `secret_header` report never stores the header value or the signature, and it stores the decoded token header and payload with values under sensitive key names redacted. Use `capture` mode for short setup sessions with `allowedSourceIps` set, and run `tools/show_capture.py --delete` to remove the table.
* **Poison queue.** `fb-audit-webhook-poison` holds 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 `adminPrincipalId` parameter 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_CL` and `FireblocksWebhook_CL` with 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.txt` pins every dependency and is resolved from `requirements.in`. Run `pip-audit -r function/requirements.txt` to check the pinned versions, and again after any change.

### Example repository

The [example repository](https://github.com/fireblocks/sentinel-siem-integration-example) holds the complete source for both stacks in the `polling/` 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**

Each folder has unit tests that use fakes and the Python standard library, so they need no network access and no Azure resources. Run them from the folder with `.venv/bin/python -m unittest discover -s tests -v`.

## Related

* [Audit Event webhooks](https://support.fireblocks.io/hc/en-us/articles/21630746432284-Audit-Event-webhooks-notifications) in the Help Center for the audit event webhook.
* [Audit Logs API](https://developers.fireblocks.com/docs/audit-logs-api.md) for filters, paging, and errors.
* [Manage API Access](https://developers.fireblocks.com/docs/manage-api-keys.md) for API users, key pairs, and rotation.
* [Audit Log Events](https://developers.fireblocks.com/reference/audit-log-events.md) for the categories, subjects, and events that appear in the tables.
