# Pull your audit log into your SIEM

> Send a team's Sume audit log to Splunk, Datadog, Elastic or any SIEM: a first export, a follower, a chain check and a stream receiver.

Source: https://www.sume.com/docs/audit-log-siem

This guide moves a team's audit log into your SIEM and keeps it there: one
export for the history, then a follower that picks up each new event, and a
chain check that proves nothing was changed. Every call is in the
[Audit log API](https://www.sume.com/docs/audit-logs) reference.

1. Make the key.
2. Backfill with an export.
3. Follow the log.
4. Verify the chain.
5. Or receive a stream.
6. Forward to your SIEM.

## 1. Make the key

In the team, open [Settings → API keys](https://www.sume.com/dashboard/api-keys)
and make a key with Access **Audit log only**. Give it an expiry your policy
asks for. Only an Owner or Admin can make one. Keep it in your secret store as
`SUME_AUDIT_KEY`.

The key reads the audit log and nothing else. It cannot change anything,
generate or spend. It stops working when its owner is no longer an Owner or
Admin of the team, so make it with an account that will stay one.

```bash
export SUME_AUDIT_KEY="sume_live_..."
curl -sS "https://api.sume.com/v1/admin/audit_logs?limit=1" \
  -H "Authorization: Bearer $SUME_AUDIT_KEY"
```

## 2. Backfill with an export

An export writes the history to one file. It is a snapshot up to
`snapshot_sequence`, so the follower starts just after it.

```bash
API="https://api.sume.com/v1/admin/audit_logs"
AUTH="Authorization: Bearer $SUME_AUDIT_KEY"

export_id=$(curl -sS -X POST "$API/exports" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d '{ "format": "ndjson", "compression": "gzip", "filter": { "exclude_event_types": ["audit_log.api_read"] } }' \
  | jq -r .id)

while :; do
  curl -sS "$API/exports/$export_id" -H "$AUTH" > export.json
  status=$(jq -r .status export.json)
  [ "$status" = succeeded ] && break
  if [ "$status" = failed ] || [ "$status" = expired ]; then
    jq .error export.json
    exit 1
  fi
  sleep 10
done

curl -sS "$API/exports/$export_id/download?redirect=false" -H "$AUTH" > link.json
curl -sS -o sume-audit.ndjson.gz "$(jq -r .url link.json)"
echo "$(jq -r .sha256 link.json)  sume-audit.ndjson.gz" | sha256sum -c -
gunzip -c sume-audit.ndjson.gz | head -n 2
jq '{ rows, first_sequence, last_sequence, snapshot_sequence }' export.json
```

- On macOS, use `shasum -a 256 -c -` for `sha256sum -c -`.
- Do not send your key to the download link: it is signed already, and it is
  valid for 15 minutes. Ask for a new one when it runs out.
- Start the follower at `snapshot_sequence + 1`:
  `export START_SEQUENCE=$(( $(jq -r .snapshot_sequence export.json) + 1 ))`.
- An export holds at most 2,000,000 events and keeps to the API's window
  (365 days, or 730 for an enterprise team). For more, export by time or by
  `sequence` ranges.

## 3. Follow the log

The follower reads in `asc` order, keeps `next_cursor` as its checkpoint and
asks again when it is caught up.

- Send the same filters with every page. The cursor is bound to them, to the
  team and to `asc`, so the samples send `order=asc` each time to keep one
  query string.
- Save the cursor after your SIEM has the page, never before.
- When `has_more` is `false`, wait, then ask again with the same cursor. The
  next page holds only the events written since.
- On `429`, wait `retry-after` seconds. On a `5xx` or a network error, wait
  and send the same request again.
- Leave out `audit_log.api_read`, or each poll adds one event to the log.
- The follower sends each event at least once. After a crash it can send the
  last page again, so key your SIEM records on the event `id`
  ([step 6](#6-forward-to-your-siem)). The samples also skip any event whose
  `sequence` is not above the last one they sent.

Keep `START_SEQUENCE` the same for the life of a checkpoint: it is one of the
filters the cursor is bound to.

### Follow with curl

```bash
#!/usr/bin/env bash
set -euo pipefail

API="https://api.sume.com/v1/admin/audit_logs"
AUTH="Authorization: Bearer $SUME_AUDIT_KEY"
QUERY="order=asc&limit=1000&exclude_event_types=audit_log.api_read&sequence%5Bgte%5D=${START_SEQUENCE:-1}"
STATE="sume-audit.cursor"

while :; do
  url="$API?$QUERY"
  if [ -s "$STATE" ]; then url="$url&cursor=$(cat "$STATE")"; fi
  code=$(curl -sS -o page.json -D headers.txt -w '%{http_code}' -H "$AUTH" "$url") || code=000
  case "$code" in
    200) ;;
    429)
      wait=$(awk 'tolower($1) == "retry-after:" { print $2 + 0 }' headers.txt)
      sleep "${wait:-5}"
      continue
      ;;
    5*|000)
      sleep 10
      continue
      ;;
    *)
      cat page.json >&2
      exit 1
      ;;
  esac
  jq -c '.data[]' page.json >> sume-audit.ndjson
  jq -r '.next_cursor' page.json > "$STATE.tmp"
  mv "$STATE.tmp" "$STATE"
  if [ "$(jq -r '.has_more' page.json)" != true ]; then sleep 60; fi
done
```

### Follow with Python

```python
import json
import os
import time

import requests

API = "https://api.sume.com/v1/admin/audit_logs"
STATE = "sume-audit-state.json"
QUERY = {
    "order": "asc",
    "limit": "1000",
    "exclude_event_types": "audit_log.api_read",
    "sequence[gte]": os.environ.get("START_SEQUENCE", "1"),
}


def load_state():
    try:
        with open(STATE) as file:
            return json.load(file)
    except FileNotFoundError:
        return {"cursor": None, "last_sequence": 0}


def save_state(state):
    with open(STATE + ".tmp", "w") as file:
        json.dump(state, file)
    os.replace(STATE + ".tmp", STATE)


def forward(events):
    for event in events:
        print(json.dumps(event), flush=True)


def main():
    session = requests.Session()
    session.headers["Authorization"] = "Bearer " + os.environ["SUME_AUDIT_KEY"]
    state = load_state()
    while True:
        params = dict(QUERY)
        if state["cursor"]:
            params["cursor"] = state["cursor"]
        try:
            response = session.get(API, params=params, timeout=30)
        except requests.RequestException:
            time.sleep(10)
            continue
        if response.status_code == 429:
            time.sleep(int(response.headers.get("retry-after", "5")))
            continue
        if response.status_code >= 500:
            time.sleep(10)
            continue
        response.raise_for_status()
        page = response.json()
        fresh = [e for e in page["data"] if e["sequence"] > state["last_sequence"]]
        forward(fresh)
        if fresh:
            state["last_sequence"] = fresh[-1]["sequence"]
        state["cursor"] = page["next_cursor"]
        save_state(state)
        if not page["has_more"]:
            time.sleep(60)


if __name__ == "__main__":
    main()
```

### Follow with Node

```js
import { readFile, rename, writeFile } from "node:fs/promises";

const API = "https://api.sume.com/v1/admin/audit_logs";
const STATE = "sume-audit-state.json";
const QUERY = {
  order: "asc",
  limit: "1000",
  exclude_event_types: "audit_log.api_read",
  "sequence[gte]": process.env.START_SEQUENCE ?? "1",
};

const sleep = (seconds) =>
  new Promise((resolve) => setTimeout(resolve, seconds * 1000));

async function loadState() {
  try {
    return JSON.parse(await readFile(STATE, "utf8"));
  } catch (error) {
    if (error.code === "ENOENT") return { cursor: null, lastSequence: 0 };
    throw error;
  }
}

async function saveState(state) {
  await writeFile(`${STATE}.tmp`, JSON.stringify(state));
  await rename(`${STATE}.tmp`, STATE);
}

async function forward(events) {
  for (const event of events) process.stdout.write(`${JSON.stringify(event)}\n`);
}

const state = await loadState();
for (;;) {
  const url = new URL(API);
  for (const [name, value] of Object.entries(QUERY))
    url.searchParams.set(name, value);
  if (state.cursor) url.searchParams.set("cursor", state.cursor);
  let response;
  try {
    response = await fetch(url, {
      headers: { Authorization: `Bearer ${process.env.SUME_AUDIT_KEY}` },
      signal: AbortSignal.timeout(30_000),
    });
  } catch {
    await sleep(10);
    continue;
  }
  if (response.status === 429) {
    await sleep(Number(response.headers.get("retry-after") ?? 5));
    continue;
  }
  if (response.status >= 500) {
    await sleep(10);
    continue;
  }
  if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
  const page = await response.json();
  const fresh = page.data.filter((event) => event.sequence > state.lastSequence);
  await forward(fresh);
  if (fresh.length) state.lastSequence = fresh.at(-1).sequence;
  state.cursor = page.next_cursor;
  await saveState(state);
  if (!page.has_more) await sleep(60);
}
```

Replace `forward` with a call to your SIEM ([step 6](#6-forward-to-your-siem)).
The Node sample runs as an ES module on Node 18 or newer (`node follow.mjs`).

## 4. Verify the chain

Each team's events form one SHA-256 hash chain. An event's hash covers its
stored fields and the hash of the event before it. With
`include=integrity.preimage`, each event carries the 22 hashed fields: join
them with U+001F and hash the UTF-8 bytes to get `integrity.hash`.

Check a range without filters, since a filter leaves gaps on purpose. These
scripts read from a start sequence to the newest event, and check each hash,
each link and each sequence. Run them after the backfill, then from the last
sequence they verified.

### Verify with Python

```python
import hashlib
import os
import sys
import time

import requests

API = "https://api.sume.com/v1/admin/audit_logs"
SEPARATOR = "\x1f"


def problem(event, previous):
    integrity = event["integrity"]
    preimage = integrity["preimage"]
    digest = hashlib.sha256(SEPARATOR.join(preimage).encode("utf-8")).hexdigest()
    if digest != integrity["hash"]:
        return "hash"
    if (
        preimage[1] != str(event["sequence"])
        or preimage[3] != event["effective_at"]
        or preimage[4] != event["type"]
    ):
        return "hash"
    if preimage[0] != (integrity["prev_hash"] or ""):
        return "link"
    if previous is not None:
        if event["sequence"] != previous["sequence"] + 1:
            return "gap"
        if integrity["prev_hash"] != previous["integrity"]["hash"]:
            return "link"
    return None


def main(start):
    session = requests.Session()
    session.headers["Authorization"] = "Bearer " + os.environ["SUME_AUDIT_KEY"]
    params = {
        "order": "asc",
        "limit": "1000",
        "include": "integrity.preimage",
        "sequence[gte]": str(start),
    }
    previous = None
    while True:
        response = session.get(API, params=params, timeout=30)
        if response.status_code == 429:
            time.sleep(int(response.headers.get("retry-after", "5")))
            continue
        response.raise_for_status()
        page = response.json()
        for event in page["data"]:
            reason = problem(event, previous)
            if reason:
                print(f"broken at sequence {event['sequence']}: {reason}")
                return 1
            previous = event
        if not page["has_more"]:
            break
        params["cursor"] = page["next_cursor"]
    if previous:
        print(f"verified to sequence {previous['sequence']}, hash {previous['integrity']['hash']}")
    return 0


if __name__ == "__main__":
    sys.exit(main(int(sys.argv[1]) if len(sys.argv) > 1 else 1))
```

### Verify with Node

```js
import { createHash } from "node:crypto";

const API = "https://api.sume.com/v1/admin/audit_logs";
const SEPARATOR = "\u001f";
const start = process.argv[2] ?? "1";

function problem(event, previous) {
  const { hash, prev_hash: prevHash, preimage } = event.integrity;
  const digest = createHash("sha256").update(preimage.join(SEPARATOR), "utf8").digest("hex");
  if (digest !== hash) return "hash";
  if (
    preimage[1] !== String(event.sequence) ||
    preimage[3] !== event.effective_at ||
    preimage[4] !== event.type
  )
    return "hash";
  if (preimage[0] !== (prevHash ?? "")) return "link";
  if (previous) {
    if (event.sequence !== previous.sequence + 1) return "gap";
    if (prevHash !== previous.integrity.hash) return "link";
  }
  return null;
}

const params = new URLSearchParams({
  order: "asc",
  limit: "1000",
  include: "integrity.preimage",
  "sequence[gte]": start,
});
let previous = null;
for (;;) {
  const response = await fetch(`${API}?${params}`, {
    headers: { Authorization: `Bearer ${process.env.SUME_AUDIT_KEY}` },
  });
  if (response.status === 429) {
    await new Promise((resolve) =>
      setTimeout(resolve, Number(response.headers.get("retry-after") ?? 5) * 1000),
    );
    continue;
  }
  if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
  const page = await response.json();
  for (const event of page.data) {
    const reason = problem(event, previous);
    if (reason) {
      console.log(`broken at sequence ${event.sequence}: ${reason}`);
      process.exit(1);
    }
    previous = event;
  }
  if (!page.has_more) break;
  params.set("cursor", page.next_cursor);
}
if (previous)
  console.log(`verified to sequence ${previous.sequence}, hash ${previous.integrity.hash}`);
```

- The first event a run reads anchors the chain: its `prev_hash` names an
  event the run does not read. To link runs, start the next run at the last
  verified sequence and compare that event's hash with the one you kept.
- Start from `retention.oldest_sequence` on any page: the window keeps every
  sequence from there on, so a pull from it has no gaps. For a range older
  than the window, use Sume's own chain check, which reads the whole chain:

```bash
curl -sS "https://api.sume.com/v1/admin/audit_logs/verify?from_sequence=1200&to_sequence=1300" \
  -H "Authorization: Bearer $SUME_AUDIT_KEY" | jq '{ status, first_break, complete }'
```

- Alert on any `hash`, `link` or `gap` break.

## 5. Or receive a stream

Instead of polling, an Admin can have Sume POST new events to your endpoint
as they are written. Making a stream takes an **Admin** key
(`audit_logs:write`), not the Audit log only key:

```bash
curl -sS -X POST "https://api.sume.com/v1/admin/audit_logs/streams" \
  -H "Authorization: Bearer $SUME_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://siem-bridge.example.com/sume/audit", "filter": { "exclude_event_types": ["audit_log.api_read"] }, "batch_size": 500, "start": "now" }'
```

Each delivery is signed like a Sume webhook: HMAC SHA-256 with the team's
webhook signing secret over `<timestamp>.<raw_body>`. Read the secret on the
dashboard's **Webhooks** tab and keep it as `SUME_COM_WEBHOOK_SIGNING_SECRET`.
Check the signature on the raw body, store the batch, then answer `2xx` within
10 seconds. A delivery that does not get a `2xx` is sent again, so store
events by `id`.

### Receive with Node

```js
import { createHmac, timingSafeEqual } from "node:crypto";
import { appendFile } from "node:fs/promises";
import { createServer } from "node:http";

const SECRET = process.env.SUME_COM_WEBHOOK_SIGNING_SECRET;

function verified(raw, timestamp, signatures) {
  if (!/^\d+$/.test(timestamp ?? "")) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const digest = createHmac("sha256", SECRET)
    .update(Buffer.concat([Buffer.from(`${timestamp}.`), raw]))
    .digest("hex");
  const expected = Buffer.from(`sume-v1=${digest}`);
  let ok = false;
  for (const entry of (signatures ?? "").split(",")) {
    const actual = Buffer.from(entry.trim());
    if (actual.length === expected.length && timingSafeEqual(actual, expected)) ok = true;
  }
  return ok;
}

createServer(async (request, response) => {
  const chunks = [];
  for await (const chunk of request) chunks.push(chunk);
  const raw = Buffer.concat(chunks);
  if (
    !verified(
      raw,
      request.headers["x-sume-webhook-timestamp"],
      request.headers["x-sume-webhook-signature"],
    )
  ) {
    response.writeHead(401).end();
    return;
  }
  const delivery = JSON.parse(raw.toString("utf8"));
  if (!delivery.test && delivery.data.length)
    await appendFile(
      "sume-audit-spool.ndjson",
      delivery.data.map((event) => `${JSON.stringify(event)}\n`).join(""),
    );
  response.writeHead(204).end();
}).listen(8080);
```

### Receive with Python

```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

app = Flask(__name__)
SECRET = os.environ["SUME_COM_WEBHOOK_SIGNING_SECRET"].encode()


def verified(raw, timestamp, signatures):
    if not timestamp or not timestamp.isdigit():
        return False
    if abs(time.time() - int(timestamp)) > 300:
        return False
    digest = hmac.new(SECRET, timestamp.encode() + b"." + raw, hashlib.sha256).hexdigest()
    expected = "sume-v1=" + digest
    return any(hmac.compare_digest(entry.strip(), expected) for entry in (signatures or "").split(","))


@app.post("/sume/audit")
def receive():
    raw = request.get_data()
    if not verified(
        raw,
        request.headers.get("x-sume-webhook-timestamp"),
        request.headers.get("x-sume-webhook-signature"),
    ):
        return "", 401
    delivery = json.loads(raw)
    if not delivery.get("test"):
        with open("sume-audit-spool.ndjson", "a") as spool:
            for event in delivery["data"]:
                spool.write(json.dumps(event) + "\n")
    return "", 204
```

- During a signing-secret rotation the signature header carries two entries,
  newest first. Both receivers accept either.
- `POST /v1/admin/audit_logs/streams/{id}/test` sends a signed delivery with
  `"test": true` and no events, to check your endpoint.
- In TypeScript, `verifyWebhook` from `@sume-com/sdk` checks these
  deliveries.
- A forwarder reads the spool file and sends it on (step 6).

## 6. Forward to your SIEM

Each sample takes a list of events, as a follower page or a stream delivery
holds them, and sends it in one request. Use the event `id` as the record id
wherever the SIEM has one, so an event sent twice is stored once.

### Splunk HTTP Event Collector

```python
import json
import os
from datetime import datetime

import requests


def to_splunk(events):
    body = "".join(
        json.dumps(
            {
                "time": datetime.fromisoformat(event["effective_at"].replace("Z", "+00:00")).timestamp(),
                "source": "sume",
                "sourcetype": "sume:audit",
                "fields": {"event_id": event["id"], "sequence": event["sequence"]},
                "event": event,
            }
        )
        for event in events
    )
    requests.post(
        os.environ["SPLUNK_HEC_URL"] + "/services/collector/event",
        headers={"Authorization": "Splunk " + os.environ["SPLUNK_HEC_TOKEN"]},
        data=body,
        timeout=30,
    ).raise_for_status()
```

The collector does not de-duplicate. Search with `dedup event_id`.

### Datadog Logs

```python
import json
import os

import requests


def to_datadog(events):
    requests.post(
        "https://http-intake.logs.datadoghq.com/api/v2/logs",
        headers={"DD-API-KEY": os.environ["DD_API_KEY"], "Content-Type": "application/json"},
        json=[
            {
                "ddsource": "sume",
                "service": "sume-audit-log",
                "ddtags": f"category:{event['category']},type:{event['type']}",
                "message": json.dumps(event),
            }
            for event in events
        ],
        timeout=30,
    ).raise_for_status()
```

Use the intake host of your Datadog site (for example
`http-intake.logs.datadoghq.eu`). One request takes up to 1,000 entries and
5 MB, so send a full page of 1,000 events in one call or split it.

### Elastic

```python
import json
import os

import requests


def to_elastic(events):
    lines = []
    for event in events:
        lines.append(json.dumps({"create": {"_index": "sume-audit", "_id": event["id"]}}))
        lines.append(json.dumps(event))
    response = requests.post(
        os.environ["ELASTIC_URL"] + "/_bulk",
        headers={
            "Authorization": "ApiKey " + os.environ["ELASTIC_API_KEY"],
            "Content-Type": "application/x-ndjson",
        },
        data="\n".join(lines) + "\n",
        timeout=30,
    )
    response.raise_for_status()
    for item in response.json()["items"]:
        status = item["create"]["status"]
        if status >= 300 and status != 409:
            raise RuntimeError(item["create"])
```

With the event `id` as `_id`, an event sent twice answers `409` inside the
bulk response and is stored once.

## Run it well

- Make one key per pipeline, with an expiry, and make a new one before it
  runs out.
- Alert when the follower has not saved a cursor for a while, and when a
  chain check finds a break.
- Run the chain check every day from the last sequence it verified.
- The audit log API reads take half of your plan's write budget per minute
  (60 on Free), and the chain check and exports a twentieth. Use
  `limit=1000`, and wait a minute when you are caught up.
- Sume does not push to Splunk, Datadog, Elastic or an S3 bucket by itself
  yet. Run the follower or a stream receiver, then forward from there.
