Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
chore(security): beacon rate limit, dev environment, weekly CodeQL triage (#4008)
Tejas Chopra5698e91b2a20
diff --git a/.github/workflows/codeql-triage.yml b/.github/workflows/codeql-triage.ymlnew file mode 100644index 000000000..e34cf3034--- /dev/null+++ b/.github/workflows/codeql-triage.yml@@ -0,0 +1,52 @@+name: CodeQL Weekly Triage++# Gives code scanning alerts an owner and a cadence. Alert #63 was found by+# CodeQL the day it was introduced and then sat open for five months because+# nobody was assigned to look (INC-2026-001). Every Monday this opens one issue,+# assigned to the security owner, listing the open critical/high alerts; the+# owner fixes or dismisses each with a reason and closes the issue. The issue+# history is the record that triage happened.++on:+ schedule:+ # Mondays, US morning.+ - cron: '23 15 * * 1'+ workflow_dispatch:++permissions:+ contents: read # checkout, for scripts/codeql_triage.sh+ issues: write+ security-events: read++concurrency:+ group: codeql-triage+ cancel-in-progress: false++env:+ # Security owner: Tejas Chopra ([email protected]).+ TRIAGE_ASSIGNEE: chopratejas++jobs:+ triage:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - name: Ensure security label exists+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ gh label create "security" \+ --repo "${{ github.repository }}" \+ --color "b60205" \+ --description "Security-relevant; exempt from stale triage" \+ --force++ - uses: actions/checkout@v7++ # One issue per ISO week: re-runs and later dispatches reuse it (see the+ # script header). Tested by tests/test_codeql_triage_script.py.+ - name: Open or update this week's triage issue+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ REPO: ${{ github.repository }}+ run: scripts/codeql_triage.shdiff --git a/.gitignore b/.gitignoreindex 3445a7647..77d77787e 100644--- a/.gitignore+++ b/.gitignore@@ -20,6 +20,7 @@ scripts/*!scripts/verify-ruff-version.py!scripts/pr-governance.py!scripts/bootstrap-windows-dev.ps1+!scripts/codeql_triage.sh!scripts/build_npm_release_assets.mjs!scripts/build_python_release_smoke.py!scripts/release_smoke_all.pydiff --git a/deploy/beacon/test-rollup.mjs b/deploy/beacon/test-rollup.mjsindex 8fa186e99..3326139e4 100644--- a/deploy/beacon/test-rollup.mjs+++ b/deploy/beacon/test-rollup.mjs@@ -13,7 +13,7 @@*/import { readdirSync, readFileSync } from 'node:fs';import assert from 'node:assert/strict';-import { inflate, oldestRawDay, rollupHour } from './worker.js';+import worker, { inflate, oldestRawDay, rollupHour } from './worker.js';// R2 returns at most 1000 keys per list page, so on a real hour (~4,000// objects) the cursor loop in rollupHour is load-bearing. The stub paginates at@@ -254,4 +254,39 @@ if (dir) {console.log(`gzip: ${payload.length} B -> ${packed.length} B, bomb refused`);}+// ---- fetch(): the RATE_LIMIT binding -----------------------------------------+//+// A body with no log records stops at the 204 right after parsing, so these+// exercise the limiter without touching R2.+{+ const post = () =>+ new Request('https://beacon.test/v1/logs', { method: 'POST', body: '{}' });+ const limiter = (impl) => ({ RATE_LIMIT: { limit: impl } });++ const over = await worker.fetch(post(), limiter(async () => ({ success: false })), {});+ assert.equal(over.status, 429, 'over the limit is refused');++ const under = await worker.fetch(post(), limiter(async () => ({ success: true })), {});+ assert.equal(under.status, 204, 'under the limit proceeds');++ const quiet = console.error;+ console.error = () => {};+ let down;+ try {+ down = await worker.fetch(post(), limiter(async () => { throw new Error('limiter down'); }), {});+ } finally {+ console.error = quiet;+ }+ assert.equal(down.status, 204, 'a limiter outage fails open instead of dropping beacons');++ const unbound = await worker.fetch(post(), {}, {});+ assert.equal(unbound.status, 204, 'no binding fails open');++ let keys = [];+ await worker.fetch(post(), limiter(async (opts) => { keys.push(opts.key); return { success: true }; }), {});+ assert.deepEqual(keys, ['all'], 'one shared key: the sender is never read');++ console.log('rate limit: 429 over, fail-open on outage and when unbound');+}+console.log('ok');diff --git a/deploy/beacon/worker.js b/deploy/beacon/worker.jsindex 208f70e76..91d5c4f03 100644--- a/deploy/beacon/worker.js+++ b/deploy/beacon/worker.js@@ -125,10 +125,8 @@ const ALLOWED_RESOURCE = [// retried, so the event would simply be lost.//// Restored to ~3x the worst legitimate payload. This is not the abuse control-// and never was: the endpoint is unauthenticated by design and the WAF rate-// limit (60 req/min/IP, see wrangler.toml) is what bounds a bad actor. At 60-// requests a minute the difference between these two ceilings is 3.8 MB/min-// and 15 MB/min, neither of which is interesting to Cloudflare.+// and never was: the endpoint is unauthenticated by design and the RATE_LIMIT+// binding (see fetch() and wrangler.toml) is what bounds a bad actor.const MAX_BODY_BYTES = 256 * 1024;// Cap on what an arriving body EXPANDS to. `raw.byteLength` cannot see this:@@ -408,6 +406,31 @@ export default {return new Response('not found', { status: 404 });}+ // Abuse bound, checked before the body is read so a flood costs neither+ // the inflate nor an R2 write. Keyed on one constant rather than the+ // sender: a per-IP limit would mean reading cf-connecting-ip, which this+ // Worker never does (see the header). The price is that a flood also+ // sheds real events until the window rolls over -- acceptable for+ // fire-and-forget telemetry, and the cap sits ~10x above normal traffic.+ //+ // 429 is safe for old clients: only 400/415 make them drop gzip+ // (_GZIP_REFUSED_STATUSES in headroom/telemetry/session.py).+ //+ // Fails open: with no binding (local tests, an old wrangler.toml) or when+ // the rate-limit service itself errors, the upload proceeds. A limiter+ // outage must not drop every legitimate beacon; the cost is that a flood+ // during that outage is unbounded until the service recovers.+ if (env.RATE_LIMIT) {+ let limited = false;+ try {+ const { success } = await env.RATE_LIMIT.limit({ key: 'all' });+ limited = !success;+ } catch (err) {+ console.error('beacon: rate limiter unavailable, failing open:', String(err));+ }+ if (limited) return new Response('rate limited', { status: 429 });+ }+const raw = await request.arrayBuffer();if (raw.byteLength > MAX_BODY_BYTES) {return new Response('payload too large', { status: 413 });diff --git a/deploy/beacon/wrangler.toml b/deploy/beacon/wrangler.tomlindex 1824fb34d..7588db987 100644--- a/deploy/beacon/wrangler.toml+++ b/deploy/beacon/wrangler.toml@@ -61,10 +61,35 @@ enabled = true[observability.logs]invocation_logs = false-# Rate limiting is configured in the Cloudflare dashboard, not here — this-# endpoint is unauthenticated by design (anonymity is the product), so it is-# the only thing between the Worker and a bored stranger:-# Security > WAF > Rate limiting rules-# otlp.headroomlabs.ai/v1/logs -> 60 requests / minute / IP-# A real client sends ~2 requests/hour, so that is ~1000x headroom while still-# capping a single abusive source hard.+# Abuse bound for this unauthenticated endpoint, enforced in fetch(). One+# shared key, not per-IP: the Worker never reads the sender's address, and a+# per-IP key would mean reading it. Counters are per Cloudflare location, so+# this caps each location, not the planet. Normal load is ~300 req/min in+# total (~2 req/hour per client), so 3000/min per location is ~10x headroom+# while still bounding what a flood can cost in Worker time and R2 writes.+# Only 10 or 60 is accepted for `period`.+[[ratelimits]]+name = "RATE_LIMIT"+namespace_id = "1001"+ [ratelimits.simple]+ limit = 3000+ period = 60++# Dev/test deployment: `npx wrangler deploy --env dev`. Its own Worker+# (headroom-beacon-dev) and its own bucket, so test traffic can never land in+# the production corpus. Bindings are not inherited by environments, so each+# one is restated here.+[env.dev]+name = "headroom-beacon-dev"+workers_dev = true++[[env.dev.r2_buckets]]+binding = "CORPUS"+bucket_name = "headroom-telemetry-dev"++[[env.dev.ratelimits]]+name = "RATE_LIMIT"+namespace_id = "1002"+ [env.dev.ratelimits.simple]+ limit = 600+ period = 60diff --git a/scripts/codeql_triage.sh b/scripts/codeql_triage.shnew file mode 100755index 000000000..d39e52dcb--- /dev/null+++ b/scripts/codeql_triage.sh@@ -0,0 +1,96 @@+#!/usr/bin/env bash+# Weekly CodeQL triage issue, run by .github/workflows/codeql-triage.yml.+#+# Idempotent per ISO week. The week key is the ISO week of "today" (UTC), so a+# re-run of Monday's job and a manual dispatch later the same week both find+# the issue already opened for that week, including a closed one, and reuse it+# instead of opening another. A reused issue is never edited, reopened or+# retitled, so ticked checkboxes and its closure stand. Open critical/high+# alerts it does not list unticked (new ones, or ones reopened after being+# ticked) are added as a comment; otherwise the run does nothing.+#+# Env: REPO (owner/name), TRIAGE_ASSIGNEE (login). TRIAGE_TODAY (YYYY-MM-DD)+# overrides the date for tests. Needs gh, jq and python3.+set -euo pipefail++: "${REPO:?REPO is required}"+: "${TRIAGE_ASSIGNEE:?TRIAGE_ASSIGNEE is required}"+today="${TRIAGE_TODAY:-$(date -u +%Y-%m-%d)}"++# ISO week key (e.g. 2026-W41) and that week's Monday. Python's isocalendar+# handles the year boundary (2027-01-01 is in 2026-W53) on any platform's date.+read -r week_key week_start < <(python3 -c '+import datetime, sys+d = datetime.date.fromisoformat(sys.argv[1])+y, w, wd = d.isocalendar()+print(f"{y}-W{w:02d}", d - datetime.timedelta(days=wd - 1))+' "$today")+marker="<!-- codeql-triage:${week_key} -->"++# jq programs live in quoted heredocs: they are literal jq, not shell, so+# nothing in them is expanded and no single-quoted '$' or backtick is left for+# ShellCheck (SC2016) to misread.+alert_lines_jq=$(cat <<'JQ'+.[] | select(.rule.security_severity_level == "critical" or .rule.security_severity_level == "high")+ | "- [ ] [#\(.number)](\(.html_url)) **\(.rule.security_severity_level)** `\(.rule.id)` in `\(.most_recent_instance.location.path):\(.most_recent_instance.location.start_line)` (open since \(.created_at[:10]))"+JQ+)+week_issue_jq=$(cat <<'JQ'+.[] | select(.pull_request | not) | select((.body // "") | contains($marker)) | .number+JQ+)++alerts="$(gh api --paginate -X GET "repos/$REPO/code-scanning/alerts" -f state=open -f per_page=100 \+ | jq -r "$alert_lines_jq")"++# Listing, not search: the search index lags, so an issue created seconds ago+# by the previous run could be missed. state=all so a closed issue counts.+existing="$(gh api --paginate "repos/$REPO/issues?state=all&labels=security&per_page=100" \+ | jq -r --arg marker "$marker" "$week_issue_jq" | head -n 1)"++if [ -n "$existing" ]; then+ # Alerts already listed, unticked, in the issue or an earlier re-run+ # comment. A ticked alert that is open again (dismissed, then reopened) is+ # reported again rather than hidden behind its old tick.+ known="$(gh api "repos/$REPO/issues/$existing" | jq -r '.body // ""')"+ known="$known"$'\n'"$(gh api --paginate "repos/$REPO/issues/$existing/comments" | jq -r '.[].body // ""')"+ new=""+ while IFS= read -r line; do+ [ -n "$line" ] || continue+ ref="${line#*\[#}" # after "- [ ] [#"+ ref="- [ ] [#${ref%%\]*}](" # "- [ ] [#123]("+ case "$known" in *"$ref"*) ;; *) new="${new}${line}"$'\n' ;; esac+ done <<< "$alerts"+ if [ -z "$new" ]; then+ echo "Week $week_key already has issue #$existing and no new critical/high alerts. Nothing to do."+ exit 0+ fi+ {+ echo "Re-run on $today: critical/high alerts that are open and not yet listed here (new, or reopened after being ticked):"+ echo+ printf '%s' "$new"+ } > comment.md+ gh issue comment "$existing" --repo "$REPO" --body-file comment.md+ echo "Week $week_key: added $(printf '%s' "$new" | grep -c '^- ') new alert(s) to #$existing."+ exit 0+fi++count="$(printf '%s' "$alerts" | grep -c '^- ' || true)"+{+ echo "$marker"+ echo "Weekly code scanning triage for the week of **$week_start** ($week_key). Owner: @$TRIAGE_ASSIGNEE ([email protected])."+ echo+ echo "For each alert: fix it (link the PR) or dismiss it in code scanning with a reason. Close this issue when every box is ticked."+ echo "Target: critical and high fixed or dismissed within the vulnerability management SLA."+ echo+ echo "### Open critical/high alerts: $count"+ echo+ if [ "$count" -eq 0 ]; then echo "None. Close this issue to record the review."; else printf '%s\n' "$alerts"; fi+ echo+ echo "All open alerts: https://github.com/$REPO/security/code-scanning"+} > body.md+gh issue create --repo "$REPO" \+ --title "CodeQL triage: week of $week_start ($count critical/high open)" \+ --body-file body.md \+ --assignee "$TRIAGE_ASSIGNEE" \+ --label securitydiff --git a/tests/test_codeql_triage_script.py b/tests/test_codeql_triage_script.pynew file mode 100644index 000000000..8b0fa319e--- /dev/null+++ b/tests/test_codeql_triage_script.py@@ -0,0 +1,222 @@+"""scripts/codeql_triage.sh: one triage issue per ISO week, however often it runs.++The script runs for real against a fake ``gh`` on PATH that keeps alerts and+issues in a JSON file, so re-runs, later dispatches in the same week, a closed+issue with ticked boxes, and the ISO year boundary are all exercised end to end.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[1]+SCRIPT = ROOT / "scripts" / "codeql_triage.sh"++pytestmark = pytest.mark.skipif(+ sys.platform == "win32" or not (shutil.which("bash") and shutil.which("jq")),+ reason="needs bash and jq (present on the Linux runner that executes the workflow)",+)++FAKE_GH = r'''#!/usr/bin/env python3+"""Just enough of `gh` for scripts/codeql_triage.sh, backed by $FAKE_GH_STATE."""+import json, os, sys++path = os.environ["FAKE_GH_STATE"]+state = json.load(open(path))+args = sys.argv[1:]++def save():+ json.dump(state, open(path, "w"))++def opt(name):+ return args[args.index(name) + 1]++if args[0] == "api":+ target = next(a for a in args[1:] if a.startswith("repos/"))+ if "/code-scanning/alerts" in target:+ print(json.dumps(state["alerts"]))+ elif "/issues?" in target:+ print(json.dumps(state["issues"]))+ elif target.endswith("/comments"):+ number = int(target.split("/")[-2])+ issue = next(i for i in state["issues"] if i["number"] == number)+ print(json.dumps([{"body": c} for c in issue["comments"]]))+ else:+ number = int(target.rsplit("/", 1)[1])+ print(json.dumps(next(i for i in state["issues"] if i["number"] == number)))+elif args[:2] == ["issue", "create"]:+ number = len(state["issues"]) + 1+ state["issues"].append({+ "number": number,+ "title": opt("--title"),+ "body": open(opt("--body-file")).read(),+ "state": "open",+ "labels": [opt("--label")],+ "comments": [],+ })+ save()+ print(f"https://github.com/o/r/issues/{number}")+elif args[:2] == ["issue", "comment"]:+ number = int(args[2])+ issue = next(i for i in state["issues"] if i["number"] == number)+ issue["comments"].append(open(opt("--body-file")).read())+ save()+else:+ sys.exit(f"fake gh: unsupported {args}")+'''+++def _alert(number: int, severity: str = "high") -> dict:+ return {+ "number": number,+ "html_url": f"https://github.com/o/r/security/code-scanning/{number}",+ "rule": {"id": f"py/rule-{number}", "security_severity_level": severity},+ "most_recent_instance": {"location": {"path": "headroom/x.py", "start_line": number}},+ "created_at": "2026-10-01T00:00:00Z",+ }+++def harness(tmp_path):+ bindir = tmp_path / "bin"+ bindir.mkdir()+ gh = bindir / "gh"+ gh.write_text(FAKE_GH)+ gh.chmod(0o755)+ state_path = tmp_path / "state.json"+ workdir = tmp_path / "work"+ workdir.mkdir()++ def set_alerts(*alerts):+ state = json.loads(state_path.read_text()) if state_path.exists() else {"issues": []}+ state["alerts"] = list(alerts)+ state_path.write_text(json.dumps(state))++ def state():+ return json.loads(state_path.read_text())++ def edit_issue(number, **changes):+ s = state()+ next(i for i in s["issues"] if i["number"] == number).update(changes)+ state_path.write_text(json.dumps(s))++ def run(today: str) -> subprocess.CompletedProcess:+ env = {+ **os.environ,+ "PATH": f"{bindir}{os.pathsep}{os.environ['PATH']}",+ "FAKE_GH_STATE": str(state_path),+ "REPO": "o/r",+ "TRIAGE_ASSIGNEE": "owner",+ "TRIAGE_TODAY": today,+ }+ result = subprocess.run(+ ["bash", str(SCRIPT)], cwd=workdir, env=env, capture_output=True, text=True+ )+ assert result.returncode == 0, result.stderr+ return result++ set_alerts()+ return set_alerts, state, edit_issue, run+++def test_first_run_opens_one_issue_keyed_to_the_iso_week(harness):+ set_alerts, state, _, run = harness+ set_alerts(_alert(1), _alert(2, "critical"), _alert(3, "medium"))++ run("2026-10-07") # a Wednesday++ (issue,) = state()["issues"]+ assert issue["title"] == "CodeQL triage: week of 2026-10-05 (2 critical/high open)"+ assert "<!-- codeql-triage:2026-W41 -->" in issue["body"]+ assert "[#1]" in issue["body"] and "[#2]" in issue["body"]+ assert "[#3]" not in issue["body"] # medium is out of scope+++def test_rerun_same_day_creates_nothing(harness):+ set_alerts, state, _, run = harness+ set_alerts(_alert(1))+ run("2026-10-05")+ result = run("2026-10-05")++ (issue,) = state()["issues"]+ assert issue["comments"] == []+ assert "Nothing to do" in result.stdout+++def test_later_dispatch_reuses_a_closed_issue_and_keeps_its_ticks(harness):+ set_alerts, state, edit_issue, run = harness+ set_alerts(_alert(1))+ run("2026-10-05") # Monday's scheduled run++ ticked = state()["issues"][0]["body"].replace("- [ ]", "- [x]")+ edit_issue(1, body=ticked, state="closed") # #1 fixed, box ticked+ set_alerts(_alert(7)) # a new high alert midweek++ run("2026-10-09") # Friday's manual dispatch++ (issue,) = state()["issues"]+ assert issue["state"] == "closed"+ assert issue["body"] == ticked+ (comment,) = issue["comments"]+ assert "[#7]" in comment and "[#1]" not in comment++ run("2026-10-11") # Sunday: same ISO week, nothing new since the comment+ (issue,) = state()["issues"]+ assert len(issue["comments"]) == 1 # #7 is not reported twice+++def test_next_week_opens_a_new_issue(harness):+ set_alerts, state, _, run = harness+ set_alerts(_alert(1))+ run("2026-10-05")+ run("2026-10-12")++ titles = [i["title"] for i in state()["issues"]]+ assert titles == [+ "CodeQL triage: week of 2026-10-05 (1 critical/high open)",+ "CodeQL triage: week of 2026-10-12 (1 critical/high open)",+ ]+++def test_iso_year_boundary_shares_one_week(harness):+ set_alerts, state, _, run = harness+ set_alerts(_alert(1))+ run("2026-12-28") # Monday of 2026-W53+ run("2027-01-01") # Friday, same ISO week in a new calendar year++ (issue,) = state()["issues"]+ assert "<!-- codeql-triage:2026-W53 -->" in issue["body"]+ assert issue["title"].startswith("CodeQL triage: week of 2026-12-28")+++def test_no_alerts_still_records_the_review(harness):+ _, state, _, run = harness+ run("2026-10-05")+ (issue,) = state()["issues"]+ assert "(0 critical/high open)" in issue["title"]+ assert "None. Close this issue to record the review." in issue["body"]+++def test_an_alert_reopened_after_its_box_was_ticked_is_reported_again(harness):+ set_alerts, state, edit_issue, run = harness+ set_alerts(_alert(1))+ run("2026-10-05")+ ticked = state()["issues"][0]["body"].replace("- [ ]", "- [x]")+ edit_issue(1, body=ticked, state="closed") # dismissed and ticked++ # Reopened later the same week: open again, and its only mention is ticked.+ run("2026-10-08")+ (issue,) = state()["issues"]+ (comment,) = issue["comments"]+ assert "[#1]" in comment+ assert issue["body"] == ticked and issue["state"] == "closed"++ run("2026-10-09") # listed unticked in that comment now: not repeated+ assert len(state()["issues"][0]["comments"]) == 1