trunkjet

Reference

On this page

SDK examples: webhooks, check results, deployments

Three integrations that run outside the SCM and talk to it over the public API: a webhook receiver, a check executor that posts signed results, and deployment tooling that records deployments. The programs are in examples/sdk/ and use only the Python standard library, except result signing, which needs the cryptography package. The HTTP conventions (request IDs, retries, error codes) are the ones on the API examples page. nscm_http.py is a small client that applies them. It resends the identical body with the same request_id after a lost response and never invents a new ID for a retry.

Verification. Every bash block on this page runs, in order and unedited, under tools/checks/verify_api_examples.sh, the same way as the API examples. The script's --serve mode starts its own isolated tjetd --dev twice. The first start bootstraps the development identities. Before the second start it configures what these examples need: a webhook allowlist entry for the receiver's loopback port and the ci executor's Ed25519 public key. The T069 evidence record names the commit, server and exit code of the last verified run. text blocks show output captured during that run.

Setup

The script provides the server URL, the path of examples/, the receiver's port (allowlisted by the server) and the ci executor's signing key file with its configured key ID.

On a server you run yourself, an administrator does the same configuration:

# executor host, once: creates the private key (mode 600) and prints the public key
tjet validation keygen --out /etc/ci/nscm-signing.key
# tjetd.toml (then restart tjetd):
[security]
webhook_allowlist = ["127.0.0.1:8750"]      # only for a non-public receiver address
[[validation.executor_keys]]
principal = "<ci principal id>"             # tjet --json whoami, run as the executor
key_id = "ci-2026"
ed25519_public_key = "<printed by keygen>"
B="${TJET_EXAMPLES_SERVER:-http://127.0.0.1:8640}"
EX="${TJET_EXAMPLES_DIR:?path of the examples directory of the repository}"
HOOK_PORT="${TJET_EXAMPLES_WEBHOOK_PORT:?a loopback port the server allowlists for webhooks}"
CI_KEY="${TJET_EXAMPLES_CI_KEY:?Ed25519 key file of the ci executor}"
CI_KEY_ID="${TJET_EXAMPLES_CI_KEY_ID:?the key id configured for it}"
api() {
  curl -sS -X POST "$B/v1/$1" -H 'content-type: application/json' \
    -H "authorization: Bearer ${TOKEN:-dev:${AS:-alice}}" -d "$2"
}
rid() { python3 -c 'import uuid; print(uuid.uuid4())'; }
expect() { [ "$1" = "$2" ] || { echo "expected '$2', got '$1'" >&2; exit 1; }; }
# wait_for KIND: block until the receiver has processed an event of that kind (60 s at most).
wait_for() {
  for _ in $(seq 120); do
    if [ -f hook/events.jsonl ] && jq -e --arg k "$1" 'select(.kind == $k)' hook/events.jsonl > /dev/null; then
      return 0
    fi
    sleep 0.5
  done
  echo "no $1 event arrived" >&2; return 1
}

REPO_NAME="sdk-demo-$(date +%s)"
REPO=$(api repository/create "{\"request_id\":\"$(rid)\",\"name\":\"$REPO_NAME\",\"path_profile\":\"portable-v1\"}" | jq -r .result.repository_id)
BOB=$(api principal/lookup '{"subject":"bob"}' | jq -r .result.principal_id)
api role/put "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"principal\":\"$BOB\",\"role\":\"reviewer\"}" > /dev/null
export TJET_SERVER="$B" TJET_DEV_IDENTITY=alice
tjet --json workspace open "$REPO_NAME" ws > /dev/null
# main needs one approval and a PASS of check `unit` reported by the executor `ci`.
(cd ws && tjet --json stream set-policy --approvals 1 --check unit --executor ci > /dev/null)

1. A webhook receiver

An administrator registers the webhook. Destinations must be https, unless the exact host (or host:port) is on the installation's webhook_allowlist, and they are checked against private, loopback and link-local addresses at every delivery (SSRF protection). An empty event_kinds means every non-audit event. The secret, 64 hex digits, appears only in this response. The receiver uses the 32 bytes it encodes as the HMAC key.

webhook_receiver.py verifies x-tjet-signature: t=<unix seconds>,v1=<hex HMAC-SHA-256 of "<t>.<body>">, refuses timestamps outside a 5-minute window, and deduplicates by the signed event_id. Delivery is at least once, with exponential backoff and a dead-letter queue.

hook=$(api webhook/create "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"url\":\"http://127.0.0.1:$HOOK_PORT/trunkjet\",\"event_kinds\":[\"validation.requested\",\"validation.result\",\"stream.integrated\",\"release.deployment\"]}")
echo "$hook" | jq -c '.result | {webhook_id, url, event_kinds, active, generation}'
HOOK_ID=$(echo "$hook" | jq -r .result.webhook_id)
(umask 077 && echo "$hook" | jq -r .result.secret > hook.secret)
expect "$(wc -c < hook.secret | tr -d ' ')" 65   # 64 hex digits and a newline

python3 "$EX/sdk/webhook_receiver.py" --listen "127.0.0.1:$HOOK_PORT" \
  --secret-file hook.secret --state-dir hook 2> receiver.log > receiver.out &
RECEIVER=$!
trap 'kill "$RECEIVER" 2> /dev/null || true' EXIT   # stop it however this script ends
for _ in $(seq 50); do grep -q listening receiver.out 2> /dev/null && break; sleep 0.1; done
grep -q listening receiver.out

# Only administrators register destinations: bob (a reviewer) is refused.
expect "$(AS=bob api webhook/create "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"url\":\"https://hooks.example.com/x\",\"event_kinds\":[]}" | jq -r .error.code)" ACCESS_DENIED
{"webhook_id":"a46c778d-…","url":"http://127.0.0.1:37403/trunkjet","event_kinds":["validation.requested","validation.result","stream.integrated","release.deployment"],"active":true,"generation":"1"}

2. Post a signed check result

Alice saves a change, opens a review and bob approves it. tjet land --prepare-only then prepares the integration candidate. Because the policy requires check unit, the server emits validation.requested. The executor takes the candidate ID and input digest from that event (here from the webhook; tjet inbox list works as well) and runs the check against exactly that input.

post_validation.py builds the D-173 signing message (domain nscm-validation-result-v1\0, then length-prefixed fields starting with the executor's own principal ID), signs it with the Ed25519 seed and posts validation/submit. The server verifies the signature against the configured public key. An executor that has a key must sign every result.

cd ws
printf 'hello\n' > README.txt
tjet --json add README.txt > /dev/null
tjet --json --no-progress save -m "Add README" --remote > save.json
CHANGE=$(jq -r .result.sync.change_id save.json)
REV=$(jq -r .result.sync.revision save.json)
tjet --json review create > /dev/null
cd ..
DIGEST=$(AS=bob api revision/get "{\"repository_id\":\"$REPO\",\"revision\":\"$REV\"}" | jq -r .result.patch_digest)
AS=bob api review/approve "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"change_id\":\"$CHANGE\",\"revision\":\"$REV\",\"patch_digest\":\"$DIGEST\"}" > /dev/null

(cd ws && tjet --json land --prepare-only > prepared.json)
jq -c '.result | {candidate_id, merge_mode, eligibility}' ws/prepared.json

# The executor's view: the validation.requested event names the exact candidate input.
wait_for validation.requested
REQ=$(jq -c 'select(.kind == "validation.requested")' hook/events.jsonl | head -1)
CAND=$(echo "$REQ" | jq -r .data.candidate)
INPUT=$(echo "$REQ" | jq -r .data.input_digest)
expect "$CAND" "$(jq -r .result.candidate_id ws/prepared.json)"

# An unsigned result from an executor with a configured key is refused.
set +e
TJET_TOKEN=dev:ci python3 "$EX/sdk/post_validation.py" --server "$B" --repo "$REPO" \
  --candidate "$CAND" --input-digest "$INPUT" --check unit --result PASS > unsigned.json
code=$?; set -e
expect "$code" 1
expect "$(jq -r .error.code unsigned.json)" ACCESS_DENIED

# Signed with the ci key: recorded, with the key ID and a server receipt.
TJET_TOKEN=dev:ci python3 "$EX/sdk/post_validation.py" --server "$B" --repo "$REPO" \
  --candidate "$CAND" --input-digest "$INPUT" --check unit --result PASS \
  --check-version 1 --environment "sha256:$(printf 'python3 example runner' | sha256sum | cut -c1-64)" \
  --log "runner-log:build-42" --signing-key "$CI_KEY" --key-id "$CI_KEY_ID" > signed.json
jq -c '.result | {attempt_id, check, result, signature_key_id, receipt}' signed.json
expect "$(jq -r .result.signature_key_id signed.json)" "$CI_KEY_ID"
[ "$(jq -r '.result.receipt | length' signed.json)" = 64 ]

# Retrying with the same request_id replays the recorded attempt instead of adding one.
RID_SIGNED=$(jq -r .request_id signed.json)
TJET_TOKEN=dev:ci python3 "$EX/sdk/post_validation.py" --server "$B" --repo "$REPO" \
  --candidate "$CAND" --input-digest "$INPUT" --check unit --result PASS \
  --check-version 1 --environment "sha256:$(printf 'python3 example runner' | sha256sum | cut -c1-64)" \
  --log "runner-log:build-42" --signing-key "$CI_KEY" --key-id "$CI_KEY_ID" \
  --request-id "$RID_SIGNED" --started-at-ms "$(jq -r .result.completed_at_ms signed.json)" \
  --completed-at-ms "$(jq -r .result.completed_at_ms signed.json)" > replay.json
expect "$(jq -r .result.attempt_id replay.json)" "$(jq -r .result.attempt_id signed.json)"

# The check is satisfied: land the prepared candidate.
(cd ws && tjet --json land --candidate "$CAND" > landed.json && jq -c '{ok}' landed.json)
expect "$(jq -r .ok ws/landed.json)" true
{"candidate_id":"4ffd4bfc-…","merge_mode":"fast-forward","eligibility":["check unit has no trusted result"]}
{"attempt_id":"5e128498-…","check":"unit","result":"PASS","signature_key_id":"docs-ci","receipt":"cd10a963…"}
{"ok":true}

3. Record a deployment

A release is an immutable manifest of exact sources, a toolchain document and artifact digests. Here it is created over the API as a DRAFT. Certification is a separate step, with its own evidence and artifact-provider checks, and is not shown. Deployment tooling then reports what it deployed where with record_deployment.py. A deployment record is an externally reported event; it does not certify anything.

HEAD2=$(api stream/get "{\"repository_id\":\"$REPO\",\"stream\":\"main\"}" | jq -r .result.head)
printf 'example artifact bytes\n' > app.tar.gz
SHA=$(sha256sum app.tar.gz | cut -c1-64)
LEN=$(wc -c < app.tar.gz | tr -d ' ')
rel=$(api release/create "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"name\":\"v1.0.0\",\"sources\":[{\"alias\":\"app\",\"repository_id\":\"$REPO\",\"revision\":\"$HEAD2\",\"stream\":\"main\"}],\"toolchain\":\"python3 example toolchain v1\\n\",\"artifacts\":[{\"name\":\"app.tar.gz\",\"sha256\":\"$SHA\",\"byte_length\":\"$LEN\"}]}")
echo "$rel" | jq -c '.result | {release_id, name, state}'
RELEASE=$(echo "$rel" | jq -r .result.release_id)

TJET_TOKEN=dev:alice python3 "$EX/sdk/record_deployment.py" --server "$B" --repo "$REPO" --release "$RELEASE" \
  --environment staging --status STARTED --artifact "app.tar.gz=$SHA:$LEN" \
  --external-ref deploy-job-1 > started.json
TJET_TOKEN=dev:alice python3 "$EX/sdk/record_deployment.py" --server "$B" --repo "$REPO" --release "$RELEASE" \
  --environment staging --status SUCCEEDED --artifact "app.tar.gz=$SHA:$LEN" \
  --external-ref deploy-job-1 > succeeded.json
jq -c '.result | {deployment_id, environment, status, release_state, actor}' succeeded.json

# The same report again with its request_id returns the recorded deployment, not a new one.
TJET_TOKEN=dev:alice python3 "$EX/sdk/record_deployment.py" --server "$B" --repo "$REPO" --release "$RELEASE" \
  --environment staging --status SUCCEEDED --artifact "app.tar.gz=$SHA:$LEN" \
  --external-ref deploy-job-1 --request-id "$(jq -r .request_id succeeded.json)" > again.json
expect "$(jq -r .result.deployment_id again.json)" "$(jq -r .result.deployment_id succeeded.json)"

# Only artifacts the release lists can be reported.
set +e
TJET_TOKEN=dev:alice python3 "$EX/sdk/record_deployment.py" --server "$B" --repo "$REPO" --release "$RELEASE" \
  --environment staging --status SUCCEEDED --artifact "other.bin=$SHA:$LEN" > wrong.json
code=$?; set -e
expect "$code" 1
expect "$(jq -r .error.code wrong.json)" INVALID_ARGUMENT

api release/get "{\"repository_id\":\"$REPO\",\"release_id\":\"$RELEASE\"}" | jq -c '[.result.events[].kind]'
{"release_id":"61f7c735-…","name":"v1.0.0","state":"DRAFT"}
{"deployment_id":"61f557c7-…","environment":"staging","status":"SUCCEEDED","release_state":"DRAFT","actor":"154817bb-…"}
["created","deployment.started","deployment.succeeded"]

4. What the receiver saw, and replays

Each event arrived once, verified. In the captured run below, the SUCCEEDED deployment arrived before STARTED: deliveries are not ordered, so a receiver orders by at_ms and the event data, never by arrival. A captured delivery sent again is acknowledged as a duplicate and not processed a second time. A modified body or a stale timestamp is refused with 401. When the receiver refuses a delivery, the server retries it and finally dead-letters it. An administrator lists dead letters with webhook/dead_letters and resends them with webhook/replay.

wait_for validation.result
wait_for stream.integrated
for _ in $(seq 120); do
  [ "$(jq -s '[.[] | select(.kind == "release.deployment")] | length' hook/events.jsonl)" -ge 2 ] && break
  sleep 0.5
done
jq -c '{kind, data: (.data | {status, environment, check, result} | with_entries(select(.value != null)))}' hook/events.jsonl
expect "$(jq -s '[.[] | select(.kind == "release.deployment")] | length' hook/events.jsonl)" 2
expect "$(jq -s 'map(.event_id) | length == (unique | length)' hook/events.jsonl)" true

# Replay one captured delivery byte for byte: acknowledged as a duplicate.
EV=$(jq -r 'select(.kind == "stream.integrated") | .event_id' hook/events.jsonl | head -1)
RAW="hook/raw-$EV.json"
jq -j .body "$RAW" > body.json
post_raw() { # SIGNATURE BODYFILE -> HTTP status
  curl -sS -o reply.json -w '%{http_code}' -X POST "http://127.0.0.1:$HOOK_PORT/trunkjet" \
    -H 'content-type: application/json' -H "x-tjet-event: $EV" -H "x-tjet-signature: $1" \
    --data-binary "@$2"
}
expect "$(post_raw "$(jq -r .signature "$RAW")" body.json)" 200
expect "$(jq -r .duplicate reply.json)" true

# One changed byte: refused.
sed 's/stream.integrated/stream.integrateX/' body.json > tampered.json
expect "$(post_raw "$(jq -r .signature "$RAW")" tampered.json)" 401

# Correctly signed but 10 minutes old: refused (replay window).
OLD=$(( $(date +%s) - 600 ))
MAC=$( (printf '%s.' "$OLD"; cat body.json) | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$(cat hook.secret)" -r | cut -c1-64)
expect "$(post_raw "t=$OLD,v1=$MAC" body.json)" 401
expect "$(jq -r .error reply.json)" "timestamp outside the tolerance window"

# The receiver processed each event exactly once despite the replays.
expect "$(grep -c "$EV" hook/seen.txt)" 1
expect "$(api webhook/dead_letters "{\"repository_id\":\"$REPO\",\"webhook_id\":\"$HOOK_ID\"}" | jq -r '.result.dead_letters | length')" 0
kill "$RECEIVER"
{"kind":"validation.requested","data":{}}
{"kind":"validation.result","data":{"check":"unit","result":"PASS"}}
{"kind":"release.deployment","data":{"status":"SUCCEEDED","environment":"staging"}}
{"kind":"stream.integrated","data":{}}
{"kind":"release.deployment","data":{"status":"STARTED","environment":"staging"}}

Rust and TypeScript

The Rust client is client/api-client (see API examples). No TypeScript client is generated from the OpenAPI file. The web application keeps hand-written types that npm run check-api checks against the contract. Whether to generate a published TypeScript client is an owner decision that is still open.