diff --git a/README.md b/README.md index c50bf58..fc0a7d2 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ from `main`; every merge needs Raghav's code-owner approval. | Path | What it is | | --- | --- | | `.claude-plugin/marketplace.json` | The `setkernel` marketplace. It lists one plugin. | -| `plugins/setkernel/` | The org plugin: skills `verify`, `review-blockers`, `ship-pr`, `request-review`; subagents `explorer`, `reviewer`; POSIX-shell hooks: `SessionStart` session context, the git guard (`PreToolUse` on Bash, see below), a `PreToolUse` guard that denies remote D1 writes (always on: it has no env switch) and the opt-in `Stop` verify gate. `plugin.json` has no `version`, so every commit on `main` is a release. | +| `plugins/setkernel/` | The org plugin: skills `verify`, `review-blockers`, `ship-pr`, `request-review`; subagents `explorer`, `reviewer`; POSIX-shell hooks: `SessionStart` session context, the git guard (`PreToolUse` on Bash, see below), a `PreToolUse` guard that denies remote D1 writes (always on: it has no env switch), the opt-in `Stop` verify gate and the `ConfigChange` settings-change audit. `plugin.json` has no `version`, so every commit on `main` is a release. | | `rules/org-rules.md` | **The one source of the org rules.** Every session gets them as `claudeMd` in the managed settings; a repo's `AGENTS.md` header links to setkernel/hq's `docs/repo-standard.md`, not to this file. | | `managed/settings.base.json` | Hand-edited part of the server-managed settings: the org `permissions.deny` list, the marketplace, the enabled plugin, org-only hooks (`allowManagedHooksOnly`), merging with the VMs' policy file (`managedSourcesBehavior: "merge"`), login, update and retention policy, and the Claude Code telemetry `env` (OTLP to sk-obs01, content redacted; setkernel/hq#90). | | `managed/settings.json` | Generated. The draft JSON Raghav pastes into the Claude org console (server-managed settings). | @@ -20,7 +20,7 @@ from `main`; every merge needs Raghav's code-owner approval. | `policy/versions.json` | **The one source of the org version holds** (Node, TypeScript, PHPCS, …). | | `plugins/setkernel/policy/holds.md` | Generated. The holds as text; the plugin's SessionStart hook prints it into every Claude session. | | `bin/dependabot-policy` | Writes the holds into a repo's `.github/dependabot.yml` (`--check` for drift; `crosses` tells whether a version crosses a hold). Python 3, standard library only. | -| `tests/run.sh` | Tests for the generator, the session hook, the verify gate, the D1 guard, the request-review skill and `bin/dependabot-policy`. | +| `tests/run.sh` | Tests for the generator, the session hook, the verify gate, the D1 guard, the settings-change audit, the request-review skill and `bin/dependabot-policy`. | In Claude Code the plugin's components are namespaced: `/setkernel:verify`, `setkernel:reviewer`. @@ -171,6 +171,37 @@ canaried on one VM before it reaches every seat. already passed is not checked again. - State (baseline, last green tree, block count, last log) lives in `CLAUDE_PLUGIN_DATA`. +## The settings-change audit (ConfigChange hook) + +`hooks/config-change.sh` records every change to a Claude Code settings file as an OTel log event +(setkernel/agent-plugins#91, setkernel/hq#2193). It blocks nothing: every path exits 0. + +- **When**: on `ConfigChange` for the `user_settings`, `project_settings`, `local_settings` and + `policy_settings` sources (not `skills`), and on `SessionStart` for the user, project and local + files, to catch edits made while no session ran. +- **What**: the settings file, its source, the names of the keys added, removed and changed, the + user (`id -un`), the host and the session. Never a value: `env` can hold tokens. A key is a path + of object keys, such as `env.GH_TOKEN` or `permissions.allow`; an array counts as one key. +- **How it knows**: a snapshot per settings file in `CLAUDE_PLUGIN_DATA` holds each key's name and a + 32-bit hash of its value, never the value. The first time SessionStart sees a file it only takes + the snapshot. Nothing is logged when no key changed, so two open sessions log a change once. +- **Where to**: OTLP/HTTP JSON to the endpoint Claude Code's own telemetry uses (`/v1/logs` under + `OTEL_EXPORTER_OTLP_ENDPOINT`, sk-obs01), with `service.name` `claude-code`. It sends only while + `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `OTEL_LOGS_EXPORTER=otlp`, as the managed `env` sets them. + The snapshot moves on only once the collector accepts the event, so a change made off the network + is sent with the next one. Needs `jq` and `curl`; without them it does nothing. + +To list the events, in Grafana Explore pick the Loki data source and run: + +```logql +{service_name="claude-code"} | event_name = `setkernel.config_change` + | line_format `{{.user_name}}@{{.host_name}} {{.config_source}} {{.config_file}} added=[{{.config_keys_added}}] removed=[{{.config_keys_removed}}] changed=[{{.config_keys_changed}}]` +``` + +Loki's OTLP ingestion turns the dots in attribute names into underscores (`config.keys_added` is +`config_keys_added`). `config_trigger` is `session_start` for an edit found when a session started, +and `config_parse_error` is `true` when the file was not valid JSON (no keys are listed then). + ## Try the plugin locally ```sh diff --git a/plugins/setkernel/hooks/config-change.sh b/plugins/setkernel/hooks/config-change.sh new file mode 100644 index 0000000..fb85d55 --- /dev/null +++ b/plugins/setkernel/hooks/config-change.sh @@ -0,0 +1,116 @@ +#!/bin/sh +# config-change: log every change to a Claude Code settings file as an OTel log event (#91). +# sh config-change.sh ConfigChange: the hook JSON on stdin names the source and file_path. +# sh config-change.sh start SessionStart: check the user, project and local settings files for +# changes made while no session was running. Prints nothing. +# The event carries the settings file, the names of the keys that were added, removed or changed, +# the user and the host. Never a value: settings can hold tokens in `env`. A key is a path of object +# keys (`permissions.allow`, `env.GH_TOKEN`); an array is one key, so any edit to it changes that key. +# To tell what changed, it keeps a snapshot per settings file in CLAUDE_PLUGIN_DATA: each key's name +# and a 32-bit hash of its value, never the value. A file seen for the first time at SessionStart only +# gets a snapshot; one seen first on ConfigChange logs all its keys as added. No key changed (a second +# session seeing the same change, a whitespace edit): nothing is logged. +# The snapshot moves on only after the collector accepted the event, so a change made while the +# collector was unreachable is logged with the next one. +# Sends OTLP/HTTP JSON to the endpoint Claude Code's own telemetry uses (OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, +# else OTEL_EXPORTER_OTLP_ENDPOINT + /v1/logs), only while CLAUDE_CODE_ENABLE_TELEMETRY=1 and +# OTEL_LOGS_EXPORTER is otlp. It sends no OTEL_EXPORTER_OTLP_HEADERS: the org collector takes none. +# Blocks nothing: every path exits 0, and it prints nothing. POSIX sh; needs jq and curl, else does nothing. +mode=${1:-change} +exec >/dev/null 2>&1 + +[ "${CLAUDE_CODE_ENABLE_TELEMETRY:-}" = 1 ] || exit 0 +case ,${OTEL_LOGS_EXPORTER:-}, in *,otlp,*) ;; *) exit 0 ;; esac +case ${OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:-${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}} in grpc) exit 0 ;; esac +url=${OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:-} +if [ -z "$url" ]; then + [ -n "${OTEL_EXPORTER_OTLP_ENDPOINT:-}" ] || exit 0 + url=${OTEL_EXPORTER_OTLP_ENDPOINT%/}/v1/logs +fi +command -v jq && command -v curl || exit 0 + +state=${CLAUDE_PLUGIN_DATA:-${TMPDIR:-/tmp}/setkernel}/config-change +mkdir -p "$state" || exit 0 +input=$(cat) +sid=$(printf '%s' "$input" | jq -r '.session_id // "" | strings') || sid= +user=$(id -un) || user=unknown +host=$(uname -n) || host=unknown + +# keys : the file's keys as {"a.b": hash}. A missing file has none. Fails on a file that isn't JSON. +keys() { + if [ -f "$1" ]; then + jq -c 'def h: tojson | explode | reduce .[] as $c (5381; (. * 33 + $c) % 4294967296); + . as $root | if type != "object" then error("not an object") else . end + | reduce (paths(type != "object" or length == 0) | select(all(.[]; type == "string"))) as $p + ({}; .[$p | join(".")] = ($root | getpath($p) | h))' "$1" + else + echo '{}' + fi +} + +# check : log the keys of that differ from its snapshot, then move the snapshot on. +check() { + src=$1 file=$2 trigger=$3 + # One snapshot per source and settings folder: a staged change is shown to the hook as a copy beside + # the settings file, and that copy must compare with the file it stands for. + dir=$(cd "$(dirname "$file")" 2>/dev/null && pwd -P) || dir=$(dirname "$file") + snap=$state/$(printf '%s %s' "$src" "$dir" | cksum | cut -d' ' -f1).json + [ "$trigger" = session_start ] && [ ! -f "$snap" ] && first=1 || first= + now=$state/now.$$ + if keys "$file" >"$now"; then + parse_error=false + else + parse_error=true + cp "$snap" "$now" 2>/dev/null || echo '{}' >"$now" + fi + if [ -n "$first" ]; then + [ "$parse_error" = false ] && mv "$now" "$snap" + rm -f "$now" + return 0 + fi + [ -f "$snap" ] || echo '{}' >"$snap" + body=$(jq -n -c --slurpfile old "$snap" --slurpfile new "$now" \ + --arg src "$src" --arg file "$file" --arg trigger "$trigger" --argjson parse_error "$parse_error" \ + --arg user "$user" --arg host "$host" --arg sid "$sid" --arg ns "$(date +%s)000000000" ' + $old[0] as $o | $new[0] as $n + | [$n | keys[] | select($o[.] == null)] as $added + | [$o | keys[] | select($n[.] == null)] as $removed + | [$n | keys[] | select($o[.] != null and $o[.] != $n[.])] as $changed + | if ($added + $removed + $changed | length) == 0 and ($parse_error | not) then empty else + def s($k; $v): {key: $k, value: {stringValue: $v}}; + {resourceLogs: [{ + resource: {attributes: [s("service.name"; "claude-code"), s("host.name"; $host)]}, + scopeLogs: [{scope: {name: "setkernel.config_change"}, logRecords: [{ + timeUnixNano: $ns, observedTimeUnixNano: $ns, severityNumber: 9, severityText: "INFO", + body: {stringValue: "setkernel.config_change"}, + attributes: ([ + s("event.name"; "setkernel.config_change"), s("config.source"; $src), s("config.file"; $file), + s("config.trigger"; $trigger), s("config.keys_added"; $added | join(",")), + s("config.keys_removed"; $removed | join(",")), s("config.keys_changed"; $changed | join(",")), + s("config.parse_error"; $parse_error | tostring), s("user.name"; $user), s("host.name"; $host) + ] + if $sid == "" then [] else [s("session.id"; $sid)] end) + }]}] + }]} end') + if [ -n "$body" ]; then + printf '%s' "$body" | curl -sf --connect-timeout 2 -m 4 -o /dev/null \ + -H 'Content-Type: application/json' --data-binary @- "$url" || { rm -f "$now"; return 0; } + fi + mv "$now" "$snap" + rm -f "$now" +} + +if [ "$mode" = start ]; then + user_dir=${CLAUDE_CONFIG_DIR:-$HOME/.claude} + project=${CLAUDE_PROJECT_DIR:-$(pwd)} + check user_settings "$user_dir/settings.json" session_start + check project_settings "$project/.claude/settings.json" session_start + check local_settings "$project/.claude/settings.local.json" session_start + exit 0 +fi + +src=$(printf '%s' "$input" | jq -r '.source // "" | strings') || exit 0 +file=$(printf '%s' "$input" | jq -r '.file_path // "" | strings') || exit 0 +case $src in user_settings | project_settings | local_settings | policy_settings) ;; *) exit 0 ;; esac +[ -n "$file" ] || exit 0 +check "$src" "$file" config_change +exit 0 diff --git a/plugins/setkernel/hooks/hooks.json b/plugins/setkernel/hooks/hooks.json index 4876f81..9ef16a9 100644 --- a/plugins/setkernel/hooks/hooks.json +++ b/plugins/setkernel/hooks/hooks.json @@ -12,6 +12,23 @@ "type": "command", "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/verify-gate.sh\" start", "timeout": 30 + }, + { + "type": "command", + "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/config-change.sh\" start", + "timeout": 15 + } + ] + } + ], + "ConfigChange": [ + { + "matcher": "user_settings|project_settings|local_settings|policy_settings", + "hooks": [ + { + "type": "command", + "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/config-change.sh\"", + "timeout": 10 } ] } diff --git a/tests/run.sh b/tests/run.sh index 536a200..ff0fc68 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -1,5 +1,5 @@ #!/bin/sh -# Tests for bin/generate, the session hook, the verify gate, the D1 guard, the request-review skill and bin/dependabot-policy. POSIX sh; needs jq for the generator tests. +# Tests for bin/generate, the session hook, the verify gate, the D1 guard, the settings-change audit, the request-review skill and bin/dependabot-policy. POSIX sh; needs jq for the generator tests. # Usage: tests/run.sh (set SHELL_UNDER_TEST=dash or "busybox sh" to try other shells) set -eu @@ -850,6 +850,83 @@ expect 0 '^$' "outside a git repo the gate lets the run stop" -- \ sh -c "printf '%s' '{\"session_id\":\"s4\"}' | env CLAUDE_PROJECT_DIR='$tmp/nogit' CLAUDE_PLUGIN_DATA='$gstate' SETKERNEL_VERIFY_GATE=1 $sh_cmd '$gate' stop" expect 0 "" "the repo's own index is untouched" -- git -C "$gaterepo" diff --cached --quiet +# The ConfigChange audit hook (#91): logs which keys of a settings file changed, never their values, +# as an OTLP log event, and always exits 0. A curl stub records what would be sent (and the URL), +# and fails while $tmp/cc-down exists. +cc=$root/plugins/setkernel/hooks/config-change.sh +mkdir -p "$tmp/cc-bin" "$tmp/cc-home/.claude" "$tmp/cc-proj/.claude" +cat >"$tmp/cc-bin/curl" <>"$tmp/cc-sent" +EOF +chmod +x "$tmp/cc-bin/curl" +ccuser=$tmp/cc-home/.claude/settings.json +printf '{"env":{"GH_TOKEN":"sekrit-one"},"permissions":{"allow":["Bash(ls)"]},"model":"opus"}\n' >"$ccuser" +# cc_run [VAR=value...]: run the hook as Claude Code would, with the org's telemetry env. +cc_run() { + m=$1 j=$2 + shift 2 + printf '%s' "$j" | env PATH="$tmp/cc-bin:$PATH" HOME="$tmp/cc-home" CLAUDE_CONFIG_DIR= CLAUDE_PROJECT_DIR="$tmp/cc-proj" \ + CLAUDE_PLUGIN_DATA="$tmp/cc-data" CLAUDE_CODE_ENABLE_TELEMETRY=1 OTEL_LOGS_EXPORTER=otlp \ + OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.test:4318/ \ + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT= "$@" $sh_cmd "$cc" "$m" +} +cc_in="{\"session_id\":\"s1\",\"hook_event_name\":\"ConfigChange\",\"source\":\"user_settings\",\"file_path\":\"$ccuser\"}" +# cc_attr : that attribute of the last event sent. +cc_attr() { tail -n 1 "$tmp/cc-sent" | jq -r --arg k "$1" '.resourceLogs[0].scopeLogs[0].logRecords[0].attributes[] | select(.key == $k) | .value.stringValue'; } +cc_sent() { if [ -f "$tmp/cc-sent" ]; then grep -c '^{' "$tmp/cc-sent"; else echo 0; fi; } + +expect 0 "config-change.sh" "hooks.json runs the audit hook on ConfigChange" -- jq -r '.hooks.ConfigChange[0].hooks[0].command' "$root/plugins/setkernel/hooks/hooks.json" +expect 0 "^user_settings|project_settings|local_settings|policy_settings$" "for the settings sources, not skills" -- jq -r '.hooks.ConfigChange[0].matcher' "$root/plugins/setkernel/hooks/hooks.json" +expect 0 'config-change.sh\\" start' "and on SessionStart for changes made between sessions" -- jq -r '[.hooks.SessionStart[0].hooks[].command] | @json' "$root/plugins/setkernel/hooks/hooks.json" +expect 0 '^$' "SessionStart on a new machine prints nothing" -- cc_run start '{"session_id":"s1"}' +expect 0 "^0$" "and sends nothing: it only takes the snapshot" -- cc_sent +printf '{"env":{"GH_TOKEN":"sekrit-two","NEW_VAR":"x"},"permissions":{"allow":["Bash(ls)","Bash(rm:*)"]}}\n' >"$ccuser" +expect 0 '^$' "a changed settings file: the hook prints nothing and exits 0" -- cc_run change "$cc_in" +expect 0 "^1$" "and sends one event" -- cc_sent +expect 0 "^http://collector.test:4318/v1/logs$" "to the OTLP logs endpoint" -- sed -n 1p "$tmp/cc-sent" +expect 0 "^env.NEW_VAR$" "it names the added key" -- cc_attr config.keys_added +expect 0 "^model$" "the removed key" -- cc_attr config.keys_removed +expect 0 "^env.GH_TOKEN,permissions.allow$" "and the changed keys" -- cc_attr config.keys_changed +expect 0 "^$ccuser$" "the settings file" -- cc_attr config.file +expect 0 "^user_settings$" "its source" -- cc_attr config.source +expect 0 "^$(id -un)$" "the user" -- cc_attr user.name +expect 0 "^$(uname -n)$" "and the host" -- cc_attr host.name +expect 0 "^setkernel.config_change$" "as a setkernel.config_change event" -- cc_attr event.name +expect 1 "" "no value reaches the event" -- grep -e sekrit -e 'Bash(rm' -e opus "$tmp/cc-sent" +expect 1 "" "nor the snapshot" -- grep -r -e sekrit -e Bash -e opus "$tmp/cc-data" +expect 0 '^$' "a second session seeing the same change" -- cc_run change "$cc_in" +expect 0 "^1$" "sends nothing more" -- cc_sent +touch "$tmp/cc-down" +printf '{"env":{"GH_TOKEN":"sekrit-two"}}\n' >"$ccuser" +expect 0 '^$' "with the collector down the hook still exits 0" -- cc_run change "$cc_in" +rm -f "$tmp/cc-down" +printf '{"env":{"GH_TOKEN":"sekrit-two"},"model":"sonnet"}\n' >"$ccuser" +expect 0 '^$' "SessionStart after edits made between sessions" -- cc_run start '{"session_id":"s2"}' +expect 0 "^2$" "sends them" -- cc_sent +expect 0 "^env.NEW_VAR,permissions.allow$" "with the change the collector missed" -- cc_attr config.keys_removed +expect 0 "^model$" "and the new one" -- cc_attr config.keys_added +expect 0 "^session_start$" "marked as found at session start" -- cc_attr config.trigger +printf '{"env": {' >"$ccuser" +expect 0 '^$' "a settings file that isn't JSON: exit 0" -- cc_run change "$cc_in" +expect 0 "^true$" "and the event says it could not be read" -- cc_attr config.parse_error +printf '{"env":{"GH_TOKEN":"sekrit-two"},"model":"sonnet","effortLevel":"high"}\n' >"$ccuser" +expect 0 '^$' "after it" -- cc_run change "$cc_in" +expect 0 "^effortLevel$" "the next change compares with the last good snapshot" -- cc_attr config.keys_added +printf '{"permissions":{"allow":["Bash(ls)"]}}\n' >"$tmp/cc-proj/.claude/settings.local.json" +expect 0 '^$' "a local settings file seen first on ConfigChange" -- \ + cc_run change "{\"source\":\"local_settings\",\"file_path\":\"$tmp/cc-proj/.claude/settings.local.json\"}" +expect 0 "^permissions.allow$" "logs all its keys as added" -- cc_attr config.keys_added +before=$(cc_sent) +expect 0 '^$' "a skills change is not a settings file" -- cc_run change "{\"source\":\"skills\",\"file_path\":\"$ccuser\"}" +expect 0 '^$' "garbage on stdin" -- cc_run change 'not json' +printf '{"model":"haiku"}\n' >"$ccuser" +expect 0 '^$' "telemetry off" -- cc_run change "$cc_in" CLAUDE_CODE_ENABLE_TELEMETRY= +expect 0 '^$' "an OTLP gRPC collector" -- cc_run change "$cc_in" OTEL_EXPORTER_OTLP_PROTOCOL=grpc +expect 0 "^$before$" "none of those sent anything" -- cc_sent + # bin/dependabot-policy: writes the block, is idempotent, keeps the repo's own ignores, lifts cleanly. dp() { python3 "$root/bin/dependabot-policy" "$@"; } dbrepo() {