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

# SIEM

> Forward Toktra security events to Splunk, Datadog, or Elasticsearch in real time.

Toktra's SIEM integration delivers security events to your existing monitoring stack as they happen. All events are HMAC-signed so your SIEM can verify authenticity before ingesting.

## Supported platforms

<CardGroup cols={3}>
  <Card title="Splunk" icon="database">
    HTTP Event Collector (HEC) — events are delivered to `/services/collector/event` with a `Splunk` bearer token.
  </Card>

  <Card title="Datadog" icon="chart-line">
    Logs API (`/api/v2/logs`) and Metrics API (`/api/v2/series`) — uses an `DD-API-KEY` header.
  </Card>

  <Card title="Elasticsearch" icon="search">
    Bulk index API — daily indices named `toktra-security-events-YYYY.MM.DD`.
  </Card>
</CardGroup>

***

## Configuring a SIEM connector

<Steps>
  <Step title="Open the Integrations page">
    In your Toktra dashboard, go to **Integrations → SIEM** (`/integrations/siem`). Click **Add connector**.
  </Step>

  <Step title="Choose a platform">
    Select **Splunk**, **Datadog**, or **Elasticsearch** from the platform dropdown.
  </Step>

  <Step title="Enter credentials">
    Fill in the platform-specific fields. See [Required credentials](#required-credentials) below for what each platform needs.
  </Step>

  <Step title="Configure event filters">
    Optionally restrict which event types and severity levels are forwarded. See [Filtering events](#filtering-events).
  </Step>

  <Step title="Send a test event">
    Click **Test delivery**. Toktra sends a synthetic `test_connection` event to your SIEM and shows you the response. Confirm the event appears before saving.
  </Step>

  <Step title="Save and activate">
    Toggle **Active** on, then click **Save**. Toktra begins forwarding events immediately.
  </Step>
</Steps>

***

## Required credentials

<Tabs>
  <Tab title="Splunk">
    | Field              | Description                                                                                                                         |
    | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
    | **HEC URL**        | Base URL of your Splunk instance, e.g. `https://splunk.company.com:8088`. Toktra appends `/services/collector/event` automatically. |
    | **HEC token**      | The HTTP Event Collector token from **Settings → Data Inputs → HTTP Event Collector** in Splunk.                                    |
    | **Signing secret** | Optional. Set this to the same value as `SIEM_SIGNING_SECRET` in your Toktra environment to enable HMAC verification.               |

    ```bash title="Environment variables" theme={null}
    SIEM_SPLUNK_HEC_URL=https://splunk.company.com:8088
    SIEM_SPLUNK_HEC_TOKEN=your-hec-token
    SIEM_SIGNING_SECRET=your-signing-secret
    ```
  </Tab>

  <Tab title="Datadog">
    | Field       | Description                                                                                                                    |
    | ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
    | **API key** | A Datadog API key from **Organization Settings → API Keys**. Logs and metrics are sent to the US1 intake endpoints by default. |

    <Note>
      Datadog events map severity levels to log statuses: `low → info`, `medium → warn`, `high → error`, `critical → critical`.
    </Note>

    ```bash title="Environment variables" theme={null}
    SIEM_DATADOG_API_KEY=your-datadog-api-key
    ```
  </Tab>

  <Tab title="Elasticsearch">
    | Field              | Description                                                                                   |
    | ------------------ | --------------------------------------------------------------------------------------------- |
    | **Endpoint URL**   | The base URL of your Elasticsearch cluster, e.g. `https://es.company.com:9200`.               |
    | **API key**        | An Elasticsearch API key with `write` access to the `toktra-security-events-*` index pattern. |
    | **Signing secret** | Optional. Enables HMAC-SHA256 signature verification on inbound documents.                    |

    <Tip>
      Run **Create index template** after saving your connector. This creates an index template for `toktra-security-events-*` with correct field mappings (`@timestamp`, `event_type`, `severity`, `org_id`, etc.).
    </Tip>

    ```bash title="Environment variables" theme={null}
    SIEM_ELASTIC_URL=https://es.company.com:9200
    SIEM_SIGNING_SECRET=your-signing-secret
    ```
  </Tab>
</Tabs>

***

## Event payload format

Every event Toktra delivers has this JSON structure:

```json title="Policy violation event" theme={null}
{
  "event_type": "policy_violation",
  "org_id": "uuid",
  "user_id": "uuid",
  "severity": "high",
  "provider": "openai",
  "model": "gpt-4",
  "timestamp": "2025-01-15T10:30:00Z",
  "details": {
    "policy_name": "max-tokens",
    "threshold": 100000,
    "actual": 150000
  }
}
```

The full payload sent to your SIEM also includes an `event_id` (UUID), `summary` (human-readable description), `source` (`"toktra"`), `user_email`, and a `tags` object for custom metadata.

### Event types

| `event_type`       | When it fires                                   |
| ------------------ | ----------------------------------------------- |
| `policy_violation` | A usage policy threshold is breached            |
| `anomaly`          | Pre-departure or unusual usage pattern detected |
| `budget_alert`     | Spend crosses an alert threshold                |
| `lockout`          | Employee access revoked                         |
| `test_connection`  | Manual test delivery                            |

***

## Signature verification

Toktra signs every outbound payload with HMAC-SHA256 using your `SIEM_SIGNING_SECRET`. The signature is included in the `X-Toktra-Signature` header in the format `sha256=<hex-digest>`.

To verify the signature on your SIEM side:

```python title="Python verification example" theme={null}
import hmac
import hashlib

def verify_toktra_signature(payload: bytes, secret: str, header: str) -> bool:
    expected = "sha256=" + hmac.new(
        secret.encode(),
        payload,
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(expected, header)
```

```javascript title="Node.js verification example" theme={null}
const crypto = require("crypto");

function verifyToktraSignature(payload, secret, header) {
  const expected =
    "sha256=" +
    crypto.createHmac("sha256", secret).update(payload).digest("hex");
  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(header));
}
```

<Warning>
  Always use a constant-time comparison (e.g. `hmac.compare_digest` or `crypto.timingSafeEqual`) when verifying signatures. Standard string equality is vulnerable to timing attacks.
</Warning>

***

## Retry behavior

If delivery fails (non-2xx response or network error), Toktra retries up to **3 times** using exponential backoff:

| Attempt | Delay before retry |
| ------- | ------------------ |
| 1       | immediate          |
| 2       | 1 second           |
| 3       | 2 seconds          |

After three failed attempts, the delivery is marked `failed` and logged. You can inspect delivery logs in **Integrations → SIEM → \[connector name] → Delivery history**.

***

## Test delivery

Click **Test delivery** on any connector to send a synthetic `test_connection` event. The dashboard shows whether delivery succeeded and returns the `event_id`. Use this button after:

* Initial setup to confirm credentials are correct
* Rotating credentials
* Recovering from a delivery failure

***

## Filtering events

By default, all event types at all severity levels are forwarded. To restrict forwarding, set an event filter in the connector configuration:

```json title="Events filter example" theme={null}
{
  "severity": ["high", "critical"],
  "event_types": ["policy_violation", "anomaly", "lockout"]
}
```

Save your connector after updating the filter. The new filter applies to events from that point forward — historical events already delivered are not affected.

***

## Splunk index template

Toktra delivers events to the `toktra` index with sourcetype `toktra:security`. To use a different index, update the connector configuration and ensure that index exists in Splunk with appropriate access controls.

## Elasticsearch index template

Toktra creates a daily index named `toktra-security-events-YYYY.MM.DD` (UTC). Apply the built-in index template via the **Create index template** button on your Elasticsearch connector to ensure correct field mappings and shard configuration.

```json title="Index template (applied automatically)" theme={null}
{
  "index_patterns": ["toktra-security-events-*"],
  "template": {
    "settings": { "number_of_shards": 1, "number_of_replicas": 1 },
    "mappings": {
      "properties": {
        "@timestamp":  { "type": "date" },
        "event_id":    { "type": "keyword" },
        "event_type":  { "type": "keyword" },
        "severity":    { "type": "keyword" },
        "org_id":      { "type": "keyword" },
        "user_email":  { "type": "keyword" },
        "policy_id":   { "type": "keyword" },
        "summary":     { "type": "text" }
      }
    }
  }
}
```
