Back to all resources
Audit LogAudit LogPython

Audit Log: How do I export and verify a project's tamper-proof trail?

Export a project's signed audit chain with the Audit Log REST API - the JWK Set, every manifest, every batch of events and every checkpoint - with a reusable shell script, then verify the whole export offline with a Python script that recomputes every hash, follows every link and checks every signature.

Audit Log: How do I export and verify a project's tamper-proof trail?

This example covers the read side of the tamper-proof audit trail: the four Audit Log API endpoints

and what to do with their output.

The chain model:

- The audit events of a project (indykite.audit.capture.*, config.*, authorization.*, ciq.execute, cdc.*,

credentials.token.introspected) are appended to the project's chain in batches, provided the project has an

Audit Signing configuration and an Event Sink of the project delivered the event; an event no sink received is not chained.

- A batch is hashed (SHA-256 of its data array, as served) and that digest is signed.

- A manifest per batch links it to the previous one: head_hash = SHA-256 of

"<project_id>|<sequence>|<prev_hash>|<data_hash>|<batch_id>", and the head is signed.

- A checkpoint periodically signs "project-checkpoint|<project_id>|<sequence>|<head_hash>|<created_at>".

- Every signature is ES256-DER (ECDSA P-256 over SHA-256, DER, Base64) under a key named by kid;

the public keys are a JWK Set at GET /audit/.well-known/jwks.json.

What the scripts do:

1. audit-export.sh pages all three listing endpoints to has_more: false and keeps every page byte for

byte, plus the JWKS and jq-friendly .jsonl files. Any HTTP error stops it: no silent truncation.

2. audit-verify.py reads the raw pages and checks contiguity, links, recomputed hashes, cross-references

between batches and manifests, checkpoint heads, and every signature. Exit 0 when the trail is intact,

exit 1 with one line per failed check otherwise.

Why raw pages: the batch hash covers the data array exactly as served. A re-serialized copy (jq -c,

a JSON library) can change escaping or number formatting and no longer hash to the same value.

Use case

Scenario: an auditor asks for proof that a production project's audit log has not been altered,

and wants to check it without an IndyKite account.

Flow:

1. Ops creates an Application Agent with the Audit permission and mints a credential

2. A nightly job runs audit-export.sh into a dated folder per project, JWKS included

3. The same job runs audit-verify.py on the fresh export and keeps its output next to the data

4. The auditor receives one dated folder: the raw pages, the JWKS that names the signing keys, and

the verifier; they rerun it and get "OK: every hash, link and signature verified"

5. When the signing key changes, new records carry a new kid and the JWKS changes with it, so every

export keeps its own JWKS and older folders stay checkable with the one they hold

The export is evidence: events contain whatever the callers sent, so they are stored, indexed and

reported, never executed. For live alerting the same events are also available as Outbound Events.

ikg

Requirements

Prerequisites:

- An Application Agent of the project holding the Audit API permission (api_permissions: ["Audit"]),

and one of its credentials in the X-IK-ClientKey header. No user token, no Service Account token.

- The project GID as project_id on every call, and the project's regional base URL

(https://eu.api.indykite.com or https://us.api.indykite.com).

- curl and jq for the export; Python 3.8+ with the cryptography package for the verifier.

Contract reminders:

- pagesize defaults to and is capped at 50; copy next_cursor verbatim; loop until has_more is false.

- /logs and /manifests share cursors and page in lockstep; /checkpoints has its own cursors and pages newest first.

- The JWKS endpoint is public, cacheable for 5 minutes, and carries no alg member on purpose.

- An empty chain is a 200 with "items": [], not an error.

Steps

Step 1: Grant the Audit permission

- POST /configs/v1/application-agents (Service Account token) with "Audit" in api_permissions, or PUT it onto an existing agent

- Mint a credential: POST /configs/v1/application-agent-credentials; the token goes into X-IK-ClientKey

Step 2: Fetch the signing keys

- GET /audit/.well-known/jwks.json?project_id=<gid>, no credential; keep the file with the export

Step 3: Page the manifests, the logs and the checkpoints

- GET /audit/v1/manifests, /logs, /checkpoints with project_id, pagesize=50 and the cursor from the previous page

- audit-export.sh does all three, storing raw pages and .jsonl files, and stops on any HTTP error

Step 4: Verify the export offline

- python3 audit-verify.py <export-dir>: recomputes data hashes from the raw pages, head hashes from the five

manifest fields, checkpoint digests, and checks every ES256-DER signature under the JWK named by kid

Step 5: Work with the events

- jq recipes: events per batch, one event per line, counts by eventType, deduplication on the whole event object

Step 6: Read the errors

- 401 insufficient API access level: add the Audit permission (applied asynchronously)

- 403 credential does not have access to this project: project_id is not the credential's project

- 400 invalid cursor / pagesize must be a positive integer: copy next_cursor verbatim, pagesize 1-50

Step 1

The three values every call uses: the regional base URL, the project GID, and an Application Agent credential holding the Audit permission.

export API_URL=https://eu.api.indykite.com      # or https://us.api.indykite.com, matching the project's region
export PROJECT_ID="gid:YOUR_PROJECT_GID"
export CLIENT_KEY="<application agent credential with the Audit permission>"
# exported, because audit-export.sh runs as a separate process and reads them from the environment

Step 1

Create an agent that holds the Audit permission (Service Account token). To grant it to an existing agent, PUT the full api_permissions list including "Audit". The grant is applied asynchronously.

POST https://eu.api.indykite.com/configs/v1/application-agentsJson
{
  "application_id": "gid:YOUR_APPLICATION_GID",
  "name": "audit-exporter",
  "display_name": "Audit exporter",
  "api_permissions": [
    "Audit"
  ]
}

Step 2

Fetch the JWK Set. No credential: the public keys are public by design. Keep the file next to the export, it names the keys the records were signed with.

GET https://eu.api.indykite.com/audit/.well-known/jwks.json?project_id=<gid>Bash
curl -sS "$API_URL/audit/.well-known/jwks.json?project_id=$PROJECT_ID" -o jwks.json

The JWK Set: EC P-256 keys with a kid and use sig, and deliberately no alg member, since the signatures are DER-encoded rather than the raw R||S form JWS defines for ES256.


{
  "keys": [
    {
      "crv": "P-256",
      "kid": "…",
      "kty": "EC",
      "use": "sig",
      "x": "…",
      "y": "…"
    }
  ]
}

Step 3

The first page of manifests. The envelope is the same on all three listing endpoints: next_cursor, has_more, items.

GET https://eu.api.indykite.com/audit/v1/manifests?project_id=<gid>&pagesize=50Bash
curl -sS "$API_URL/audit/v1/manifests?project_id=$PROJECT_ID&pagesize=50" \
  -H "X-IK-ClientKey: $CLIENT_KEY"

A manifest: the batch's position and hashes, the previous head, the new head, and a signature over the head. prev_hash is empty for sequence 1.


{
  "next_cursor": "NTA",
  "has_more": true,
  "items": [
    {
      "manifest_id": "0d1a7a6e-6c6c-4a53-9f1c-0e0f4b4a1c2d",
      "batch_id": "7b3f2b9a-5d1e-4c1b-8a4e-2f6c9d8e7a10",
      "batch_uri": "…",
      "project_id": "gid:YOUR_PROJECT_GID",
      "sequence": 1,
      "prev_hash": "",
      "data_hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
      "head_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
      "kid": "…",
      "alg": "ES256-DER",
      "signature": "MEUCIQ…",
      "created_at": "2026-10-07T09:22:11.482913604Z"
    }
  ]
}

A log item is one batch: the signed hash of its data array and the events themselves, each with top-level keys in alphabetical order, an initiator object, and a typed data payload.

GET https://eu.api.indykite.com/audit/v1/logs?project_id=<gid>&pagesize=50Json

{
  "next_cursor": "MQ",
  "has_more": true,
  "items": [
    {
      "batch_id": "7b3f2b9a-5d1e-4c1b-8a4e-2f6c9d8e7a10",
      "project_id": "gid:YOUR_PROJECT_GID",
      "sequence": 1,
      "hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
      "signature": "MEQCIB…",
      "kid": "…",
      "alg": "ES256-DER",
      "chain_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
      "manifest_id": "0d1a7a6e-6c6c-4a53-9f1c-0e0f4b4a1c2d",
      "data": [
        {
          "appSpaceId": "gid:YOUR_PROJECT_GID",
          "customerId": "gid:YOUR_CUSTOMER_GID",
          "data": {
            "@type": "type.googleapis.com/indykite.auditsink.v1beta1.UpsertData",
            "node": {
              "id": "…",
              "externalId": "customerA",
              "type": "Customer",
              "isIdentity": true,
              "properties": [
                { "type": "email", "value": { "stringValue": "aanderson@mailinator.com" }, "externalValue": "" }
              ]
            }
          },
          "eventSource": "…",
          "eventType": "indykite.audit.capture.upsert.node",
          "initiator": {
            "appAgentCredentialsId": "gid:YOUR_APP_AGENT_CREDENTIALS_GID",
            "appAgentId": "gid:YOUR_APP_AGENT_GID",
            "appSpaceId": "gid:YOUR_PROJECT_GID",
            "applicationId": "gid:YOUR_APPLICATION_GID",
            "customerId": "gid:YOUR_CUSTOMER_GID"
          },
          "requestId": "…",
          "time": "2026-10-07T09:21:58.113904211Z"
        }
      ]
    }
  ]
}

A checkpoint: a signed statement that at created_at the chain had reached sequence with head_hash. Checkpoints page newest first.

GET https://eu.api.indykite.com/audit/v1/checkpoints?project_id=<gid>Json

{
  "next_cursor": "",
  "has_more": false,
  "items": [
    {
      "checkpoint_id": "4e2d9c5a-1b7f-4e0a-9c3d-6a8b2f1e0d47",
      "project_id": "gid:YOUR_PROJECT_GID",
      "sequence": 128,
      "head_hash": "b3a8e0e1e4c3…",
      "created_at": "2026-10-08T13:47:09.219540877Z",
      "signature": "MEUCIG…",
      "kid": "…",
      "alg": "ES256-DER"
    }
  ]
}

Step 3

audit-export.sh: fetch the JWKS and every page of the three listing endpoints into a dated folder, byte for byte, plus .jsonl files for jq. Stops on any HTTP error so an export is never silently truncated.

audit-export.shBash
#!/usr/bin/env bash
# audit-export.sh - export one project's tamper-proof audit trail from the IndyKite Audit Log API.
#
# Required environment:
#   API_URL     https://eu.api.indykite.com or https://us.api.indykite.com (the project's region)
#   PROJECT_ID  the project GID, gid:...
#   CLIENT_KEY  an Application Agent credential of that project, holding the Audit API permission
#
# Usage: audit-export.sh [output-dir]      default: audit-export/<project>/<UTC timestamp>
#
# Writes:
#   jwks.json                     the JWK Set current at export time
#   jwks-<digest>.json            every JWK Set this project has ever exported (see below)
#   checkpoints/page-NNNN.json    every page of GET /audit/v1/checkpoints, byte for byte
#   manifests/page-NNNN.json      every page of GET /audit/v1/manifests, byte for byte
#   logs/page-NNNN.json           every page of GET /audit/v1/logs, byte for byte
#   manifests.jsonl, logs.jsonl, checkpoints.jsonl   one item per line, for jq
#
# Raw pages are kept because the batch hash covers the data array exactly as served;
# audit-verify.py reads them. The .jsonl files are a convenience and are not what gets verified.
#
# Key rotation: the JWK Set lists every key that has signed for the project, current and retired.
# Every JWK Set fetched is also kept in JWKS_ARCHIVE (default: <parent of output-dir>/jwks-archive),
# and every file in that archive is copied into each export, so each export folder verifies on its
# own, without the API. The set is fetched again after the pages, in case the key rotated meanwhile,
# and the export fails if any kid in the exported records is in none of the saved sets (a new key
# can take up to 2 minutes to be listed, and the JWK Set may be cached for up to 60 seconds, so
# rerun a little later in that case).
#
# Consistency: the three endpoints are read in turn while the chain may still grow. Checkpoints
# are read first, so none can point past the manifests; afterwards whichever of logs and
# manifests is behind is read again until both end at the same sequence.
# Any HTTP error stops the export: a partial export is reported, never silently truncated.
set -euo pipefail

: "${API_URL:?set API_URL}" "${PROJECT_ID:?set PROJECT_ID}" "${CLIENT_KEY:?set CLIENT_KEY}"
command -v jq >/dev/null || {
    echo "jq is required" >&2
    exit 2
}

stamp="$(date -u +%Y-%m-%dT%H-%M-%SZ)"
OUT="${1:-audit-export/${PROJECT_ID#gid:}/${stamp}}"
parent="$(dirname "${OUT}")"
JWKS_ARCHIVE="${JWKS_ARCHIVE:-${parent}/jwks-archive}"
mkdir -p "${OUT}/manifests" "${OUT}/logs" "${OUT}/checkpoints" "${JWKS_ARCHIVE}"

fetch_jwks() { # fetch the current JWK Set, archive it by content digest, copy every archived set into the export
    local kids digest archived
    curl -fsS "${API_URL}/audit/.well-known/jwks.json?project_id=${PROJECT_ID}" -o "${OUT}/jwks.json"
    kids="$(jq -r '[.keys[].kid] | sort | join(", ")' "${OUT}/jwks.json")"
    digest="$(sha256sum "${OUT}/jwks.json" | cut -c1-16)" # named by content, so distinct sets never collide
    [[ -f "${JWKS_ARCHIVE}/jwks-${digest}.json" ]] || cp "${OUT}/jwks.json" "${JWKS_ARCHIVE}/jwks-${digest}.json"
    cp "${JWKS_ARCHIVE}"/jwks-*.json "${OUT}/"
    archived="$(find "${JWKS_ARCHIVE}" -name 'jwks-*.json' | wc -l)"
    echo "keys: ${kids} (${archived} JWK Set(s) kept with the export)"
}

fetch_jwks

fetch_all() { # $1 = logs | manifests | checkpoints
    local endpoint="$1" cursor="" n=0 page has_more items
    rm -f "${OUT}/${endpoint}"/page-*.json
    : >"${OUT}/${endpoint}.jsonl"
    while :; do
        n=$((n + 1))
        page="${OUT}/${endpoint}/page-$(printf '%04d' "${n}").json"
        curl -fsS "${API_URL}/audit/v1/${endpoint}?project_id=${PROJECT_ID}&pagesize=50&cursor=${cursor}" \
            -H "X-IK-ClientKey: ${CLIENT_KEY}" -o "${page}" ||
            {
                echo "export of ${endpoint} failed on page ${n}; ${OUT} is incomplete" >&2
                exit 1
            }
        jq -c '.items[]' "${page}" >>"${OUT}/${endpoint}.jsonl"
        has_more="$(jq -r '.has_more' "${page}")"
        [[ "${has_more}" == "true" ]] || break
        cursor="$(jq -r '.next_cursor' "${page}")"
    done
    items="$(wc -l <"${OUT}/${endpoint}.jsonl")"
    echo "${endpoint}: ${n} page(s), ${items} item(s)"
}

newest_of() { # $1 = manifests | logs
    jq -s 'map(.sequence) | max // 0' "${OUT}/$1.jsonl"
}

fetch_all checkpoints
fetch_all manifests
fetch_all logs
for _ in 1 2 3 4 5; do
    newest_manifest="$(newest_of manifests)"
    newest_log="$(newest_of logs)"
    [[ "${newest_log}" -eq "${newest_manifest}" ]] && break
    if [[ "${newest_log}" -gt "${newest_manifest}" ]]; then
        echo "logs reach sequence ${newest_log}, manifests ${newest_manifest}: reading manifests again"
        fetch_all manifests
    else
        echo "manifests reach sequence ${newest_manifest}, logs ${newest_log}: reading logs again"
        fetch_all logs
    fi
done
newest_manifest="$(newest_of manifests)"
newest_log="$(newest_of logs)"
if [[ "${newest_log}" -ne "${newest_manifest}" ]]; then
    echo "chain still growing: logs at ${newest_log}, manifests at ${newest_manifest}; rerun the export" >&2
    exit 1
fi

# the key may have rotated while the pages were read: fetch the set again, then check that every
# kid the exported records name is in one of the saved sets
fetch_jwks
known_kids="$(jq -s '[.[].keys[].kid] | unique' "${OUT}"/jwks*.json)"
missing_kids="$(jq -cs --argjson known "${known_kids}" '([.[].kid] | unique) - $known' \
    "${OUT}/manifests.jsonl" "${OUT}/logs.jsonl" "${OUT}/checkpoints.jsonl")"
if [[ "${missing_kids}" != "[]" ]]; then
    echo "incomplete export: no saved JWK Set holds the signing keys ${missing_kids}; rerun in a few minutes" >&2
    exit 1
fi

echo "newest sequence: ${newest_manifest}"
echo "export written to ${OUT}"

Running the export.

chmod +x audit-export.sh
./audit-export.sh
# keys: … (1 JWK Set(s) kept with the export)
# checkpoints: 1 page(s), 4 item(s)
# manifests: 3 page(s), 128 item(s)
# logs: 3 page(s), 128 item(s)
# keys: … (1 JWK Set(s) kept with the export)
# newest sequence: 128
# export written to audit-export/YOUR_PROJECT_GID/2026-10-07T10-00-00Z

Step 4

audit-verify.py: read the raw pages and check the whole chain offline. Hashes are recomputed from the bytes as served, head hashes from the five manifest fields, checkpoint digests from the prefixed string, and every ES256-DER signature is verified under the JWK its kid names.

audit-verify.pyPython
#!/usr/bin/env python3
"""audit-verify.py - check an IndyKite Audit Log API export without the platform.

Usage: audit-verify.py <export-dir>

The directory is the one audit-export.sh writes:
  jwks*.json              the JWK Set current at export time, plus any earlier snapshots
  manifests/page-*.json   raw pages of GET /audit/v1/manifests
  logs/page-*.json        raw pages of GET /audit/v1/logs
  checkpoints/page-*.json raw pages of GET /audit/v1/checkpoints

Checks, per the Audit Log API guide:
  - every endpoint has its pages, numbered consecutively, each a valid envelope, with
    has_more true on every page but the last and next_cursor empty only on the last
  - manifests are contiguous from sequence 1 and each prev_hash equals the previous head_hash
  - head_hash recomputes as SHA-256 of "<project_id>|<sequence>|<prev_hash>|<data_hash>|<batch_id>"
  - batch hash recomputes as SHA-256 of the data array exactly as served, and equals data_hash
  - batch chain_hash, batch_id, manifest_id, sequence and project_id agree with the manifest;
    no sequence appears twice in logs/
  - every signature (alg ES256-DER: ECDSA P-256, DER, Base64) verifies under the JWK named by kid
  - every checkpoint signs "project-checkpoint|<project_id>|<sequence>|<head_hash>|<created_at>"
    and names the head the manifest at that sequence has

What this cannot tell you: whether the chain is complete. A valid prefix is still valid after
its tail is removed. Compare the newest sequence and head reported here with a value you kept
independently (the previous export, or a checkpoint fetched at another time), and authenticate
the JWKS you rely on independently of the party that handed you the export.

Requires Python 3.8+ and the "cryptography" package (pip install cryptography).
Exit code 0 when every check passes, 1 otherwise; failures are listed on stderr.
"""
import base64
import glob
import hashlib
import json
import os
import re
import sys

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, utils

ALG = "ES256-DER"
PAGE_NAME = re.compile(r"^page-(\d{4,})\.json$")


class Fail(Exception):
    pass


# --- JSON scanning: the batch hash covers the data array exactly as served, so the raw bytes
# --- of each item's "data" value are taken from the page text instead of re-serializing it.

def _skip_ws(s, i):
    while i < len(s) and s[i] in " \t\r\n":
        i += 1
    return i


def _scan_string(s, i):
    i += 1
    while True:
        c = s[i]
        if c == "\\":
            i += 2
        elif c == '"':
            return i + 1
        else:
            i += 1


def _scan_value(s, i):
    c = s[i]
    if c == '"':
        return _scan_string(s, i)
    if c in "[{":
        depth = 0
        while True:
            c = s[i]
            if c == '"':
                i = _scan_string(s, i)
                continue
            if c in "[{":
                depth += 1
            elif c in "]}":
                depth -= 1
                if depth == 0:
                    return i + 1
            i += 1
    j = i
    while j < len(s) and s[j] not in ",]} \t\r\n":
        j += 1
    return j


def _members(s, i):
    """Yield (key, value_start, value_end) for the object starting at s[i] == '{'."""
    i = _skip_ws(s, i + 1)
    while s[i] != "}":
        kend = _scan_string(s, i)
        key = json.loads(s[i:kend])
        i = _skip_ws(s, kend)
        assert s[i] == ":"
        i = _skip_ws(s, i + 1)
        vend = _scan_value(s, i)
        yield key, i, vend
        i = _skip_ws(s, vend)
        if s[i] == ",":
            i = _skip_ws(s, i + 1)


def _elements(s, i):
    """Yield (start, end) for each element of the array starting at s[i] == '['."""
    i = _skip_ws(s, i + 1)
    while s[i] != "]":
        end = _scan_value(s, i)
        yield i, end
        i = _skip_ws(s, end)
        if s[i] == ",":
            i = _skip_ws(s, i + 1)


def raw_items(page_text):
    """Return [(item_dict, raw_data_bytes_or_None)] for one page."""
    out = []
    start = _skip_ws(page_text, 0)
    for key, vs, ve in _members(page_text, start):
        if key != "items":
            continue
        for es, ee in _elements(page_text, vs):
            item = json.loads(page_text[es:ee])
            raw = None
            for k, ds, de in _members(page_text, es):
                if k == "data":
                    raw = page_text[ds:de].encode("utf-8")
            out.append((item, raw))
    return out


def load_items(dirname):
    """Load every page of one endpoint, checking the saved pagination is complete."""
    if not os.path.isdir(dirname):
        raise Fail(f"{dirname}: directory missing (incomplete export)")
    files = {}
    for p in glob.glob(os.path.join(dirname, "page-*.json")):
        m = PAGE_NAME.match(os.path.basename(p))
        if not m:
            raise Fail(f"{p}: unexpected page file name")
        files[int(m.group(1))] = p
    if not files:
        raise Fail(f"{dirname}: no response pages (incomplete export)")
    last = max(files)
    items = []
    for n in range(1, last + 1):
        p = files.get(n)
        if p is None:
            raise Fail(f"{dirname}: page {n:04d} is missing")
        with open(p, "r", encoding="utf-8", newline="") as f:
            text = f.read()
        try:
            env = json.loads(text)
        except ValueError:
            raise Fail(f"{p}: not valid JSON")
        if not isinstance(env, dict) or not isinstance(env.get("items"), list):
            raise Fail(f"{p}: not a response envelope")
        expect_more = n < last
        if env.get("has_more") is not expect_more:
            raise Fail(f"{p}: has_more is {env.get('has_more')!r}, but this is page {n} of {last} (truncated export?)")
        cursor = env.get("next_cursor")
        if not isinstance(cursor, str) or bool(cursor) != expect_more:
            raise Fail(f"{p}: next_cursor does not match has_more")
        items.extend(raw_items(text))
    return items


# --- keys and signatures

def b64url_int(s):
    return int.from_bytes(base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)), "big")


def load_keys(export_dir):
    keys = {}
    for p in sorted(glob.glob(os.path.join(export_dir, "jwks*.json"))):
        with open(p, "r", encoding="utf-8") as f:
            for k in json.load(f).get("keys", []):
                if k.get("kty") != "EC" or k.get("crv") != "P-256":
                    continue
                keys[k["kid"]] = ec.EllipticCurvePublicNumbers(
                    b64url_int(k["x"]), b64url_int(k["y"]), ec.SECP256R1()
                ).public_key()
    if not keys:
        raise Fail("no EC P-256 key found in jwks*.json")
    return keys


def check_signature(keys, what, kid, alg, hex_digest, signature_b64):
    if alg != ALG:
        raise Fail(f"{what}: alg is {alg!r}, expected {ALG!r}")
    key = keys.get(kid)
    if key is None:
        raise Fail(f"{what}: kid {kid!r} is in none of the JWK Sets kept with the export")
    try:
        key.verify(
            base64.b64decode(signature_b64),
            bytes.fromhex(hex_digest),
            ec.ECDSA(utils.Prehashed(hashes.SHA256())),
        )
    except (InvalidSignature, ValueError) as e:
        raise Fail(f"{what}: signature does not verify under kid {kid!r} ({e.__class__.__name__})")


def sha256_hex(data):
    return hashlib.sha256(data).hexdigest()


# --- the chain

def verify(export_dir):
    failures = []
    keys = load_keys(export_dir)

    manifests = [m for m, _ in load_items(os.path.join(export_dir, "manifests"))]
    batches = {}
    for b, raw in load_items(os.path.join(export_dir, "logs")):
        seq = b["sequence"]
        if seq in batches:
            raise Fail(f"batch {seq}: sequence appears twice in logs/")
        batches[seq] = (b, raw)
    checkpoints = [c for c, _ in load_items(os.path.join(export_dir, "checkpoints"))]
    manifests.sort(key=lambda m: m["sequence"])

    heads = {}
    prev_head = ""
    expected_seq = 1
    for m in manifests:
        seq = m["sequence"]
        what = f"manifest {seq}"
        try:
            if seq != expected_seq:
                raise Fail(f"{what}: expected sequence {expected_seq}, gap or duplicate in the export")
            if m["prev_hash"] != prev_head:
                raise Fail(f"{what}: prev_hash does not match head_hash of manifest {seq - 1}")
            head = sha256_hex(
                f"{m['project_id']}|{seq}|{m['prev_hash']}|{m['data_hash']}|{m['batch_id']}".encode()
            )
            if head != m["head_hash"]:
                raise Fail(f"{what}: head_hash does not recompute from its fields")
            check_signature(keys, what, m["kid"], m["alg"], m["head_hash"], m["signature"])
        except Fail as e:
            failures.append(str(e))
        heads[seq] = m["head_hash"]
        prev_head = m["head_hash"]
        expected_seq = seq + 1

        what = f"batch {seq}"
        try:
            if seq not in batches:
                raise Fail(f"{what}: no batch in logs/ for this manifest (incomplete export?)")
            b, raw = batches[seq]
            for field in ("batch_id", "manifest_id", "project_id"):
                if b.get(field) != m.get(field):
                    raise Fail(f"{what}: {field} differs from the manifest")
            if raw is None:
                raise Fail(f"{what}: no data array")
            data_hash = sha256_hex(raw)
            if data_hash != b["hash"] or data_hash != m["data_hash"]:
                raise Fail(f"{what}: SHA-256 of data as served differs from hash / data_hash")
            if b["chain_hash"] != m["head_hash"]:
                raise Fail(f"{what}: chain_hash differs from the manifest head_hash")
            check_signature(keys, what, b["kid"], b["alg"], b["hash"], b["signature"])
        except Fail as e:
            failures.append(str(e))

    for seq in sorted(set(batches) - set(heads)):
        failures.append(f"batch {seq}: no manifest in manifests/ for this batch")

    for c in checkpoints:
        what = f"checkpoint {c['checkpoint_id']} (sequence {c['sequence']})"
        try:
            digest = sha256_hex(
                f"project-checkpoint|{c['project_id']}|{c['sequence']}|{c['head_hash']}|{c['created_at']}".encode()
            )
            check_signature(keys, what, c["kid"], c["alg"], digest, c["signature"])
            if c["sequence"] not in heads:
                raise Fail(f"{what}: no manifest at that sequence in the export")
            if heads[c["sequence"]] != c["head_hash"]:
                raise Fail(f"{what}: head_hash differs from the manifest at that sequence")
        except Fail as e:
            failures.append(str(e))

    events = sum(len(json.loads(raw)) for _, raw in batches.values() if raw is not None)
    kids = sorted({m["kid"] for m in manifests} | {b["kid"] for b, _ in batches.values()} | {c["kid"] for c in checkpoints})
    newest = manifests[-1]["sequence"] if manifests else 0
    print(f"manifests: {len(manifests)}  batches: {len(batches)}  events: {events}  checkpoints: {len(checkpoints)}")
    print(f"sequences: 1..{newest}  keys used: {', '.join(kids) or '-'}")
    if manifests:
        print(f"newest head: sequence {newest} = {manifests[-1]['head_hash']}  (compare with the value you kept)")
    if failures:
        for f in failures:
            print("FAIL " + f, file=sys.stderr)
        print(f"{len(failures)} check(s) failed", file=sys.stderr)
        return 1
    print("OK: every hash, link and signature verified")
    return 0


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(__doc__, file=sys.stderr)
        sys.exit(2)
    try:
        sys.exit(verify(sys.argv[1]))
    except Fail as e:
        print("FAIL " + str(e), file=sys.stderr)
        sys.exit(1)

Running the verifier on an intact export, and what a tampered one reports.

pip install cryptography
python3 audit-verify.py audit-export/YOUR_PROJECT_GID/2026-10-07T10-00-00Z
# manifests: 128  batches: 128  events: 2311  checkpoints: 4
# sequences: 1..128  keys used: …
# newest head: sequence 128 = …  (compare with the value you kept)
# OK: every hash, link and signature verified

# what a tampered export looks like (exit code 1, one line per failed check):
# FAIL batch 57: SHA-256 of data as served differs from hash / data_hash
# FAIL manifest 58: prev_hash does not match head_hash of manifest 57
# 2 check(s) failed

Checking one manifest signature by hand with OpenSSL, as a cross-check of the verifier.

# one manifest signature by hand: convert the JWK the record names to PEM, then verify with OpenSSL
KID=$(head -n 1 manifests.jsonl | jq -r '.kid')          # the key the first exported manifest names
python3 - "$KID" <<'EOF' > key.pem
import json, base64, sys, glob
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
keys = {}
for path in sorted(glob.glob("jwks*.json")):          # the current set and every archived snapshot
    with open(path, encoding="utf-8") as f:
        doc = json.load(f)
        for key in doc["keys"]:
            keys[key["kid"]] = key
k = keys[sys.argv[1]]
n = lambda s: int.from_bytes(base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)), "big")
pub = ec.EllipticCurvePublicNumbers(n(k["x"]), n(k["y"]), ec.SECP256R1()).public_key()
print(pub.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode(), end="")
EOF
HEAD_HASH=$(head -n 1 manifests.jsonl | jq -r '.head_hash')
SIGNATURE=$(head -n 1 manifests.jsonl | jq -r '.signature')
echo -n "$HEAD_HASH" | xxd -r -p > digest.bin         # the 32 bytes the signature covers
echo "$SIGNATURE" | base64 -d > signature.der
openssl pkeyutl -verify -pubin -inkey key.pem -in digest.bin -sigfile signature.der
# Signature Verified Successfully

Step 5

jq recipes over the .jsonl files: newest sequence, events per batch, one event per line, counts by type, deduplication, keys used.

jq -s 'map(.sequence) | max' manifests.jsonl                 # newest sequence in the export
jq -c '{sequence, events: (.data | length)}' logs.jsonl       # events per batch
jq -c '.data[]' logs.jsonl > events.jsonl                      # one event per line
jq -r '.eventType' events.jsonl | sort | uniq -c | sort -rn    # event types, most frequent first
jq -c 'select(.eventType | startswith("indykite.audit.config."))' events.jsonl
sort -u events.jsonl | wc -l                                   # distinct events (a redelivery is byte-identical)
jq -r '.kid' manifests.jsonl | sort -u                         # every key that signed this trail

Step 6

401 when the agent lacks the Audit permission.


{
  "message": "insufficient API access level for appAgent"
}

403 when project_id is not the credential's project.


{
  "message": "the authenticated credential does not have access to this project"
}

ikg

API Endpoints

/audit/v1/logs
/audit/v1/manifests
/audit/v1/checkpoints
/audit/.well-known/jwks.json
/configs/v1/application-agents
View OpenAPI docs

Tags

Audit LogTamper-proofExportVerificationJWKSComplianceSIEM

Related Resources

No related resources found.