diff --git a/.github/workflows/eval-refresh.yml b/.github/workflows/eval-refresh.yml index 41fabf8..358d195 100644 --- a/.github/workflows/eval-refresh.yml +++ b/.github/workflows/eval-refresh.yml @@ -510,6 +510,24 @@ jobs: echo "::error::Could not cancel run ${{ github.run_id }} after three attempts. The provider-refusal marker stops publish-results, but the remaining cells will keep running and billing: cancel the run by hand." exit 1 + - name: Check artifacts for credentials + # The two uploads below are downloadable by any GitHub account, so they + # are gated on this rather than trusting that every write path redacted. + # It re-applies the harness's redaction passes to every file about to be + # uploaded and fails if any would still remove something, printing the + # file and kind and never the value. A failure here fails the job and + # skips both uploads. The score in the result file is not changed, but + # it is not published either: `publish-results` reads rows from these + # artifacts, so the cell counts as missing, and an earlier row stands + # in for it only where the missing-cell floor allows (#103). + id: artifact-check + if: ${{ !cancelled() }} + shell: bash + run: | + pnpm --filter @hookdeck-evals/framework check-artifacts -- \ + ".eval-runs/${{ matrix.experiment }}" \ + ".eval-errored/${{ matrix.experiment }}" + - name: Upload raw results # Even when the cell failed or errored. The transcript of a failing cell # is the one somebody actually needs — `regression-alert` tells the @@ -517,8 +535,9 @@ jobs: # kept, because this step is skipped by default when an earlier step # exits non-zero. That cost the transcript of the first real regression # failure, and had silently cost every errored cell's transcript before - # that: the 21 September run wrote 75 artifacts for 76 jobs. - if: ${{ !cancelled() }} + # that: the 21 September run wrote 75 artifacts for 76 jobs. Never when + # the credential check above failed. + if: ${{ !cancelled() && steps.artifact-check.outcome == 'success' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: raw-results-${{ matrix.experiment }}__${{ matrix.eval_id }} @@ -556,7 +575,8 @@ jobs: # `raw-results-*` file under `.eval-runs//` and break the # publish job's copy. The publish job never downloads this one, so # nothing in it can become a row. Absent for a cell that did not error. - if: ${{ !cancelled() }} + # Gated on the credential check like the upload above. + if: ${{ !cancelled() && steps.artifact-check.outcome == 'success' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: errored-attempts-${{ matrix.experiment }}__${{ matrix.eval_id }} @@ -588,7 +608,12 @@ jobs: # dispatch is how somebody checks what the schedule enforces, so it # has to enforce the same thing, and a run's conclusion is only worth # reading if it means the same on every trigger. - if: ${{ matrix.eval_suite == 'regression' }} + # + # `!cancelled()` so it still runs when the credential check above has + # failed. Without it the implicit `success()` skips this step, and a + # regression cell that is genuinely red would be reported only as a + # credential-check failure. A missing result file still exits 0 below. + if: ${{ !cancelled() && matrix.eval_suite == 'regression' }} shell: bash run: | set -euo pipefail diff --git a/AGENTS.md b/AGENTS.md index 1e27bef..dfd71f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1329,6 +1329,25 @@ echoed its project key into a transcript on the first real run. Raw results are gitignored and the export carries no transcripts today, but the guard is there for when per-run drill-down is added. +**Redacting what the harness injected is not redacting every credential.** The +sandbox can create credentials of its own: `hookdeck ci` mints a CLI key and +writes it to `~/.config/hookdeck/config.toml`, and an agent checking its setup +reasonably `cat`s that file. No env var holds that key, and it has no prefix to +match. So the harness reads the CLI's config files out of each sandbox before +teardown and redacts the values of their credential keys +(`harness/sandbox-credentials.ts`). `redact.ts` also finds any value of 16 or +more characters, containing a letter and a digit, that is assigned to a +credential-marking name (`api_key = '…'`, `"webhook_secret_key": "…"`, +`--webhook-secret …`), and then redacts that value everywhere it appears in +the artifact. `check-artifacts` re-applies those passes before the raw +artifacts are uploaded. If anything is left, the job fails and both uploads +are skipped. The cell's score is unchanged but is not published either: +`publish-results` reads rows from those artifacts, so the cell counts as +missing, and an earlier row stands in only where the missing-cell floor allows +(#103). A new place the sandbox writes a credential needs adding to the +discovery command; a new artifact writer needs to go through +`serializeRedacted`. + ## Attribution This repo is based on [supabase/evals](https://github.com/supabase/evals), diff --git a/apps/framework/harness/errored-cell.ts b/apps/framework/harness/errored-cell.ts index e0b54ee..5d18c22 100644 --- a/apps/framework/harness/errored-cell.ts +++ b/apps/framework/harness/errored-cell.ts @@ -49,7 +49,7 @@ import { import { dirname, join, relative, sep } from 'node:path'; import type { AttemptRecord } from './attempts.js'; import { describeError } from './describe-error.js'; -import { serializeRedacted, type SecretValue } from './redact.js'; +import { type SecretValue, secretValues, serializeRedacted } from './redact.js'; import type { DocsResult, SkillResult, TranscriptPart } from './types.js'; /** @@ -100,16 +100,56 @@ export interface ErroredAttemptRecord { * the cell is done, including through the session and sandbox teardown that * runs after the loop body. A teardown that throws then still has it. * - * Mutate it only through the two functions below, which `runOne` calls and - * the tests exercise directly. + * Mutate it only through the functions below, which `runOne` calls and the + * tests exercise directly. */ export interface AttemptLoopState { priorAttempts: AttemptRecord[]; current?: ErroredAttemptRecord; + /** + * Credentials the sandboxes created that the harness did not inject, read + * out of each attempt's container before it was torn down. Every artifact + * this cell writes is redacted with them, the result and the errored-cell + * evidence alike. See `sandbox-credentials.ts`. + */ + discoveredSecrets?: SecretValue[]; } export function newAttemptLoopState(): AttemptLoopState { - return { priorAttempts: [] }; + return { priorAttempts: [], discoveredSecrets: [] }; +} + +/** + * Add credentials found in an attempt's sandbox. Called before the attempt's + * guards and scorer, so a cell that throws afterwards is still redacted with + * them. + * + * Each distinct value gets its own numbered name, in the order the cell found + * them, so two keys minted by two attempts (or two `hookdeck ci` runs) stay + * distinguishable in the transcript: `` + * and `…-2`. A value already found keeps the name it was given. + */ +export function credentialsDiscovered( + loop: AttemptLoopState, + secrets: SecretValue[] +): void { + const known = loop.discoveredSecrets ?? []; + const seen = new Set(known.map((s) => s.value)); + const added: SecretValue[] = []; + for (const { name, value } of secrets) { + if (seen.has(value)) continue; + seen.add(value); + added.push({ name: `${name}-${known.length + added.length + 1}`, value }); + } + loop.discoveredSecrets = [...known, ...added]; +} + +/** The secrets an artifact from this cell is redacted with. */ +export function cellSecrets( + loop: AttemptLoopState, + base: SecretValue[] = secretValues() +): SecretValue[] { + return [...base, ...(loop.discoveredSecrets ?? [])]; } /** @@ -209,7 +249,13 @@ export function writeErroredEvidence( } const out = erroredEvidencePath(root, input.experiment, input.evalId); mkdirSync(dirname(out), { recursive: true }); - writeFileSync(out, serializeRedacted(buildErroredEvidence(input), secrets)); + writeFileSync( + out, + serializeRedacted( + buildErroredEvidence(input), + cellSecrets(input.state, secrets) + ) + ); return out; } diff --git a/apps/framework/harness/redact.ts b/apps/framework/harness/redact.ts index 6e0160b..a339e11 100644 --- a/apps/framework/harness/redact.ts +++ b/apps/framework/harness/redact.ts @@ -15,7 +15,7 @@ * wrong about that list is how a secret escapes. Redacting the finished string * has no such list: if the value is anywhere in the file, it goes. * - * Two layers, because each covers the other's blind spot: + * Three layers, because each covers another's blind spot: * * 1. **By value.** Every environment variable whose *name* looks like a secret * contributes its value. Exact, and it does not care what the value looks @@ -23,8 +23,24 @@ * 2. **By shape.** Known credential patterns, for a secret that reached the * sandbox without passing through an env var we can see: a key pasted into a * seed file, or one an agent read out of a config it created. + * 3. **By assignment.** A credential the harness never held at all: the key + * `hookdeck ci` mints inside the sandbox and writes to + * `~/.config/hookdeck/config.toml`, which an agent then `cat`s. It has no + * vendor prefix — the CLI validates only that a key is at least twelve + * characters — so there is no shape to match, and it is in no env var this + * process can see. What it does have is context: `api_key = '…'`. A value + * of 16 or more characters, containing a letter and a digit, assigned to a + * name that marks it as a credential is found by that name and then + * redacted by value *everywhere* in the artifact, so the same key pasted + * bare into a later `curl` goes too. * - * Neither layer is sufficient alone and neither is a substitute for keeping + * The harness also reads the CLI's config files out of each sandbox before it + * is torn down and adds what it finds to the by-value layer + * (`sandbox-credentials.ts`), which catches a minted key however it was later + * printed. Layer 3 is the backstop for when that read fails or the agent put a + * key somewhere it does not look. + * + * No layer is sufficient alone and none is a substitute for keeping * secrets out of the sandbox in the first place. An agent configuring a Hookdeck * integration has no use for `OPENAI_API_KEY`, and the narrower that environment * gets, the less this file has to catch. @@ -52,6 +68,67 @@ const SECRET_PATTERNS: { name: string; pattern: RegExp }[] = [ { name: 'slack', pattern: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g }, ]; +/** + * Credential-bearing text characters. No `.`, `$`, `{`, `<` or quotes, so + * `process.env.HOOKDECK_API_KEY`, `${HOOKDECK_API_KEY}`, `$KEY` and a redaction + * marker are never mistaken for a value. + */ +const VALUE = '[A-Za-z0-9_\\-+/=]{16,}'; +/** An optional quote, JSON-escaped any number of times (`'`, `"`, `\"`). */ +const QUOTE = `(?:\\\\*["'])?`; + +/** + * A value assigned to a name that marks it as a credential. + * + * Matched against the *serialized* artifact, so a TOML line the agent `cat`ed + * arrives as `api_key = '…'` or `api_key = \"…\"`. The value is the second + * group; it is collected and replaced as a literal, never by rewriting the + * match. Its character class holds no quote or backslash, so a replacement + * cannot break the JSON it sits in. Each pattern anchors on the *end* of the + * name, with no unbounded prefix, so a long identifier-like run cannot make + * the scan quadratic. + * + * - `=` (TOML, INI, env, shell): any name ending in key/token/secret/password. + * `api_key`, `HOOKDECK_API_KEY`, `client_secret`, `access_token`. + * - `:` (JSON, YAML): narrower, because `"key": "x-hookdeck-signature"` and + * `"header_key": "…"` name a header and are not credentials. Plain `key` is + * left out; a key is matched only as `api_key` or after `secret`, which + * covers Hookdeck's own `"webhook_secret_key"` source config as well as + * `"secret_key"` and `"secret_access_key"`. + * - `--flag value`: `hookdeck ci --api-key …`. + * - `Bearer …`: a curl the agent wrote with the literal key in it. + */ +const ASSIGNMENT_PATTERNS: RegExp[] = [ + new RegExp( + `((?:key|token|secret|password)${QUOTE}[ \\t]*=[ \\t]*${QUOTE})(${VALUE})`, + 'gi' + ), + new RegExp( + `((?:api[_-]?key|secret(?:[_-]?(?:access[_-]?)?key)?|token|password)${QUOTE}[ \\t]*:[ \\t]*${QUOTE})(${VALUE})`, + 'gi' + ), + new RegExp( + `(--[A-Za-z0-9-]{0,64}(?:key|token|secret|password)(?:[ \\t]+|=)${QUOTE})(${VALUE})`, + 'gi' + ), + // `.` and `~` are allowed here because a bearer token may be a JWT. + /(\bBearer[ \t]+)([A-Za-z0-9_\-+/=.~]{16,})/g, +]; + +/** + * Whether an assigned value is plausibly a credential rather than a word. + * + * Requiring a letter and a digit keeps `your_api_key_here` and + * `REPLACE_WITH_YOUR_SECRET` readable. A random 50-character key with no digit + * is about a one-in-ten-million event, and the by-value layer still has it. + */ +function looksLikeCredential(value: string): boolean { + return /[0-9]/.test(value) && /[A-Za-z]/.test(value); +} + +/** The marker name for a value found by assignment rather than by name. */ +export const ASSIGNED_CREDENTIAL = 'assigned-credential'; + export interface SecretValue { name: string; value: string; @@ -82,7 +159,93 @@ function escapeRegExp(value: string): string { } /** - * Replace every known secret value, then every known secret shape. + * Values assigned to a credential-marking name anywhere in `text`, longest + * first. Exported for the tests. + */ +export function assignedCredentialValues(text: string): string[] { + const found = new Set(); + for (const pattern of ASSIGNMENT_PATTERNS) { + for (const match of text.matchAll(pattern)) { + const value = match[2]; + if (looksLikeCredential(value)) found.add(value); + } + } + return [...found].sort((a, b) => b.length - a.length); +} + +/** Longest first and deduplicated by value, whatever order the caller used. */ +function orderSecrets(secrets: SecretValue[]): SecretValue[] { + const seen = new Set(); + return [...secrets] + .filter(({ value }) => value.length >= MIN_SECRET_LENGTH) + .sort((a, b) => b.value.length - a.value.length) + .filter(({ value }) => { + if (seen.has(value)) return false; + seen.add(value); + return true; + }); +} + +function redactCounting( + text: string, + secrets: SecretValue[] +): { text: string; counts: Map } { + const counts = new Map(); + const replaceAll = ( + source: string, + pattern: RegExp, + name: string, + marker = name + ) => + source.replace(pattern, () => { + counts.set(name, (counts.get(name) ?? 0) + 1); + return ``; + }); + + let out = text; + + // 1. By value: the environment's, and whatever the harness read out of the + // sandbox before tearing it down. + for (const { name, value } of orderSecrets(secrets)) { + out = replaceAll(out, new RegExp(escapeRegExp(value), 'g'), name); + } + + // 2. By shape. Before assignment, so `OPENAI_API_KEY=sk-…` is labelled as the + // vendor key it is rather than as a generic assignment. + for (const { name, pattern } of SECRET_PATTERNS) { + out = replaceAll(out, pattern, `${name}-key`); + } + + // 3. By assignment. Harvested and then replaced as literals, so a key seen + // once in `api_key = '…'` is also removed where it later appears bare. + // Numbered by first appearance, so the transcript still shows whether + // two places held the same value: an agent that configured a source with + // the wrong secret is a failure this benchmark exists to catch, and one + // marker for every value would hide it. + const assigned = assignedCredentialValues(out); + const firstSeen = new Map( + assigned.map((value) => [value, out.indexOf(value)]) + ); + const number = new Map( + [...assigned] + .sort((a, b) => (firstSeen.get(a) ?? 0) - (firstSeen.get(b) ?? 0)) + .map((value, i) => [value, i + 1]) + ); + for (const value of assigned) { + out = replaceAll( + out, + new RegExp(escapeRegExp(value), 'g'), + ASSIGNED_CREDENTIAL, + `${ASSIGNED_CREDENTIAL}-${number.get(value)}` + ); + } + + return { text: out, counts }; +} + +/** + * Replace every known secret value, then every known secret shape, then every + * value assigned to a credential-marking name. * * The marker names what was removed so a transcript stays readable: an agent * that failed *because* it had no credential looks identical to one that had a @@ -92,20 +255,24 @@ export function redactText( text: string, secrets: SecretValue[] = secretValues() ): string { - let out = text; - - for (const { name, value } of secrets) { - out = out.replace( - new RegExp(escapeRegExp(value), 'g'), - `` - ); - } - - for (const { name, pattern } of SECRET_PATTERNS) { - out = out.replace(pattern, ``); - } + return redactCounting(text, secrets).text; +} - return out; +/** + * What redaction would still remove from `text`, by kind and count. + * + * For checking a file that should already have been redacted: anything found + * means a write path bypassed `serializeRedacted`, or a pattern has changed + * since it ran. Names and counts only, so a caller can report a failure + * without printing the credential it found. + */ +export function findUnredacted( + text: string, + secrets: SecretValue[] = secretValues() +): Array<{ name: string; count: number }> { + return [...redactCounting(text, secrets).counts] + .map(([name, count]) => ({ name, count })) + .sort((a, b) => a.name.localeCompare(b.name)); } /** diff --git a/apps/framework/harness/run-eval.ts b/apps/framework/harness/run-eval.ts index 7f80446..718fecb 100644 --- a/apps/framework/harness/run-eval.ts +++ b/apps/framework/harness/run-eval.ts @@ -51,9 +51,12 @@ import { type AttemptRecord, } from './attempts.js'; import { describeError } from './describe-error.js'; +import { discoverSandboxCredentials } from './sandbox-credentials.js'; import { attemptRan, + cellSecrets, clearErroredEvidence, + credentialsDiscovered, newAttemptLoopState, settleAttempt, writeErroredEvidence, @@ -539,6 +542,16 @@ async function runOne( lastAgentReport = run.agentReport; lastStoppedReason = run.stoppedReason; lastUsage = run.usage; + // Before anything below can throw, and while the container still exists: + // the agent may have minted a credential the harness never held (`hookdeck + // ci` writes its own key to the CLI config) and printed it. Every artifact + // this cell writes is redacted with what is found. See + // `sandbox-credentials.ts`. + if (cliSandbox) + credentialsDiscovered( + loop, + await discoverSandboxCredentials(cliSandbox.sandbox) + ); // The attempt in flight. If anything below throws — either guard, the // scorer, the rehydrate — this is what the caller keeps of it. attemptRan(loop, { @@ -893,44 +906,48 @@ async function main() { const experimentDisplay = getExperimentDisplayMetadata(config); // Redacted, not raw. Agents run `env` while exploring and the dump // lands in the transcript below; these artifacts are downloadable by - // any GitHub account on a public repository. See `redact.ts`. + // any GitHub account on a public repository. See `redact.ts`. Includes + // what the sandboxes minted, which no env var here holds. writeFileSync( out, - serializeRedacted({ - experiment: name, - experimentSuite: SELECTED_EXPERIMENT_SUITE ?? config.suite?.[0], - experimentDisplay, - eval: ev.id, - // When this run finished. Recorded per run rather than per - // refresh, because the published grid is not one snapshot: the - // a dispatched run covers only the experiments it asked for, - // and a targeted re-run replaces some pairs and leaves the rest, - // so two cells side by side can be a month apart. Without this - // the page can only describe the schedule, which is not the same - // question as how old a number is. - ranAt: new Date().toISOString(), - // Which workflow run produced this row. Undefined locally, which - // is correct: a local run is not a published one. - // - // Per row rather than per snapshot. A snapshot's header names one - // run, but `--merge` means a published file carries rows from - // several, so the header attributes all of them to the newest and - // counting rows across snapshots double-counts. Neither can answer - // "how many runs are on record", and neither lets a reader trace a - // single number back to the job that produced it, which the page - // claims they can. - runId: process.env.GITHUB_RUN_ID, - // What this row was measured under, so `--merge` can tell a - // carried-forward row that is still current from one that is not. - // See `lib/provenance.ts` and #60. - provenance: { - harness: harnessFingerprint(basePromptFor(ev.mode), ROOT), - scenario: scenarioFingerprint(ev.dir), - skillsPin: skillsPin(ROOT), + serializeRedacted( + { + experiment: name, + experimentSuite: SELECTED_EXPERIMENT_SUITE ?? config.suite?.[0], + experimentDisplay, + eval: ev.id, + // When this run finished. Recorded per run rather than per + // refresh, because the published grid is not one snapshot: the + // a dispatched run covers only the experiments it asked for, + // and a targeted re-run replaces some pairs and leaves the rest, + // so two cells side by side can be a month apart. Without this + // the page can only describe the schedule, which is not the same + // question as how old a number is. + ranAt: new Date().toISOString(), + // Which workflow run produced this row. Undefined locally, which + // is correct: a local run is not a published one. + // + // Per row rather than per snapshot. A snapshot's header names one + // run, but `--merge` means a published file carries rows from + // several, so the header attributes all of them to the newest and + // counting rows across snapshots double-counts. Neither can answer + // "how many runs are on record", and neither lets a reader trace a + // single number back to the job that produced it, which the page + // claims they can. + runId: process.env.GITHUB_RUN_ID, + // What this row was measured under, so `--merge` can tell a + // carried-forward row that is still current from one that is not. + // See `lib/provenance.ts` and #60. + provenance: { + harness: harnessFingerprint(basePromptFor(ev.mode), ROOT), + scenario: scenarioFingerprint(ev.dir), + skillsPin: skillsPin(ROOT), + }, + ...ev.metadata, + ...res, }, - ...ev.metadata, - ...res, - }) + cellSecrets(loop) + ) ); const elapsed = Math.round((Date.now() - start) / 1000); console.log( diff --git a/apps/framework/harness/sandbox-credentials.ts b/apps/framework/harness/sandbox-credentials.ts new file mode 100644 index 0000000..5546f83 --- /dev/null +++ b/apps/framework/harness/sandbox-credentials.ts @@ -0,0 +1,106 @@ +/** + * Credentials the agent's sandbox created that the harness never injected. + * + * The harness redacts by value everything it puts into the sandbox, because it + * knows those values. It does not know the key `hookdeck ci` mints: the CLI + * exchanges the project key it was given for a CLI key of its own and writes + * that to its config file, and an agent checking which project it is pointed + * at reasonably `cat`s the file. The key then sits in the transcript and in no + * env var this process can see. + * + * So after the agent has run, and before the container is torn down, read the + * CLI's config files back out and treat every credential in them as a secret + * for the rest of the cell. Each attempt has its own container and mints its + * own key, so this runs per attempt and the values accumulate across them. + * + * Where the Hookdeck CLI (pinned in `packages/sandbox/src/image.ts`) keeps its + * config, from its `getConfigPath`: `--hookdeck-config `, then + * `$HOOKDECK_CONFIG_FILE`, then `./.hookdeck/config.toml` in the working + * directory, then `$XDG_CONFIG_HOME/hookdeck/config.toml`, defaulting to + * `~/.config/hookdeck/config.toml`. The search below covers all but an + * arbitrary `--hookdeck-config` path, which `redact.ts`'s assignment layer is + * the backstop for. A profile carries `api_key` and, for a guest account, + * `guest_url`, which is a link that claims the account. + */ +import type { AgentSandbox } from '@hookdeck-evals/core'; +import type { SecretValue } from './redact.js'; + +/** Config keys whose value is a credential. */ +const CREDENTIAL_KEY = /(?:key|token|secret|password)$|^guest_url$/i; + +/** Shorter than the CLI's own minimum key length; not a credential. */ +const MIN_LENGTH = 8; + +/** + * Lists every Hookdeck CLI config file in the places the CLI looks, then + * prints them. Run as the agent user, whose `HOME` the CLI wrote under, with + * the workspace as the working directory: a project-local `.hookdeck/` can be + * in any subdirectory the agent ran the CLI from. `node_modules` and `.git` + * are pruned so a workspace with a dependency tree does not turn this into a + * crawl. + */ +export const DISCOVER_COMMAND = [ + '{', + ' for f in "$HOME/.config/hookdeck/config.toml" "${XDG_CONFIG_HOME:-/nonexistent}/hookdeck/config.toml" "${HOOKDECK_CONFIG_FILE:-/nonexistent}"; do', + ' [ -f "$f" ] && printf "%s\\n" "$f";', + ' done;', + ' find "$HOME" "$PWD" -maxdepth 6 \\( -name node_modules -o -name .git \\) -prune -o -type f -name config.toml -path "*hookdeck*" -print 2>/dev/null;', + '} | sort -u | while IFS= read -r f; do cat "$f" 2>/dev/null; printf "\\n"; done', +].join('\n'); + +/** + * Every credential assignment in TOML text, named for where it came from. + * + * A line parser rather than a TOML library: the CLI writes flat `key = 'value'` + * lines under `[profile]` tables, and a parser that rejected a file the agent + * had half-edited would return nothing at exactly the moment it mattered. + */ +export function credentialsFromConfigText(text: string): SecretValue[] { + const out: SecretValue[] = []; + const seen = new Set(); + for (const line of text.split(/\r?\n/)) { + const match = line.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*(.+?)\s*$/); + if (!match) continue; + const [, key, raw] = match; + if (!CREDENTIAL_KEY.test(key)) continue; + const value = raw.replace(/^(['"])(.*)\1$/, '$2'); + if (value.length < MIN_LENGTH || seen.has(value)) continue; + seen.add(value); + out.push({ name: `hookdeck-cli-config:${key}`, value }); + } + return out; +} + +/** + * Read the sandbox's Hookdeck CLI config and return the credentials in it. + * + * Never throws. Discovery failing must not fail a cell the agent completed, + * and the assignment layer in `redact.ts` still covers a config that was + * printed. A failure is reported on stderr directly, because the runner stubs + * `console.error` for the whole run. + */ +export async function discoverSandboxCredentials( + sandbox: AgentSandbox +): Promise { + try { + const result = await sandbox.exec(DISCOVER_COMMAND, { timeoutMs: 30_000 }); + if (!result.ok) { + // Exit code only: stdout and stderr may hold the very values being + // looked for, and this goes to a public job log. Whatever was printed + // before the failure is still used. + process.stderr.write( + `reading the sandbox's Hookdeck CLI config for redaction did not complete ` + + `(exit ${result.exitCode ?? 'none, likely a timeout'}); ` + + 'redacting with what was read, plus the assignment layer\n' + ); + } + return credentialsFromConfigText(result.stdout); + } catch (error) { + process.stderr.write( + `could not read the sandbox's Hookdeck CLI config for redaction: ${ + error instanceof Error ? error.message : String(error) + }\n` + ); + return []; + } +} diff --git a/apps/framework/lib/artifact-check.ts b/apps/framework/lib/artifact-check.ts new file mode 100644 index 0000000..a7f3831 --- /dev/null +++ b/apps/framework/lib/artifact-check.ts @@ -0,0 +1,55 @@ +/** + * Find credentials still present in run artifacts that should already have + * been redacted. Used by `scripts/check-artifacts.ts` before upload. + * + * Applies the redactor's own passes to each file and reports anything they + * would still remove: the environment's secret values, the vendor shapes and + * the assignment layer (`api_key = '…'` and friends). It cannot check a + * credential that was only ever read out of a sandbox, because the sandbox is + * gone by now; those were redacted at write time. + * + * Findings carry file, kind and count, never a value: they are printed to a + * public job log. + */ +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; +import { + findUnredacted, + type SecretValue, + secretValues, +} from '../harness/redact.js'; + +export interface ArtifactFinding { + path: string; + name: string; + count: number; +} + +function filesUnder(path: string): string[] { + if (!existsSync(path)) return []; + if (!statSync(path).isDirectory()) return [path]; + return readdirSync(path).flatMap((entry) => + entry === 'node_modules' ? [] : filesUnder(join(path, entry)) + ); +} + +/** + * Check every file under `paths`, resolved against `root`. A path that does + * not exist contributes no files, so a cell that wrote no result still has + * whatever evidence it did write checked. + */ +export function checkArtifacts( + paths: string[], + root: string, + secrets: SecretValue[] = secretValues() +): { files: number; findings: ArtifactFinding[] } { + const files = paths.flatMap((p) => filesUnder(resolve(root, p))); + const findings: ArtifactFinding[] = []; + for (const file of files) { + const text = readFileSync(file, 'utf8'); + for (const { name, count } of findUnredacted(text, secrets)) { + findings.push({ path: relative(root, file), name, count }); + } + } + return { files: files.length, findings }; +} diff --git a/apps/framework/package.json b/apps/framework/package.json index 596a371..68797fa 100644 --- a/apps/framework/package.json +++ b/apps/framework/package.json @@ -15,6 +15,7 @@ "compare-snapshots": "node --import tsx/esm scripts/compare-snapshots.ts", "report-results": "node --import tsx/esm scripts/report-results.ts", "triage": "node --import tsx/esm scripts/triage.ts", + "check-artifacts": "node --env-file-if-exists=../../.env --import tsx/esm scripts/check-artifacts.ts", "scenario-criteria": "node --import tsx/esm scripts/scenario-criteria.ts" }, "dependencies": { diff --git a/apps/framework/scripts/check-artifacts.ts b/apps/framework/scripts/check-artifacts.ts new file mode 100644 index 0000000..fe74b0a --- /dev/null +++ b/apps/framework/scripts/check-artifacts.ts @@ -0,0 +1,37 @@ +/** + * Refuse to upload a run artifact that still contains a credential. + * + * Every artifact the harness writes goes through `serializeRedacted`, so this + * should find nothing. It exists because that is a property of the write paths + * that exist today, and the artifacts are downloadable by any GitHub account + * on a public repository: a new writer that forgets, or a credential shape the + * redactor learned after the file was written, is caught here before upload + * rather than discovered in a download. See `lib/artifact-check.ts`. + * + * pnpm --filter @hookdeck-evals/framework check-artifacts -- .eval-runs .eval-errored + * + * Paths are resolved against the repository root. Exits 1 on any finding, + * printing file, kind and count and never a value. + */ +import { checkArtifacts } from '../lib/artifact-check.js'; +import { EVALS_ROOT } from '../lib/discovery.js'; + +const paths = process.argv.slice(2).filter((a) => a !== '--'); +if (paths.length === 0) { + console.error('usage: check-artifacts ...'); + process.exit(2); +} + +const { files, findings } = checkArtifacts(paths, EVALS_ROOT); +if (findings.length > 0) { + for (const f of findings) { + console.error(`::error file=${f.path}::${f.count} unredacted ${f.name}`); + } + console.error( + `refusing to upload: ${findings.length} finding(s) across ${files} file(s). ` + + 'A write path is not going through serializeRedacted, or redact.ts has ' + + 'learned a pattern since these files were written.' + ); + process.exit(1); +} +console.log(`checked ${files} file(s): no unredacted credentials`); diff --git a/apps/framework/test/minted-credentials.test.ts b/apps/framework/test/minted-credentials.test.ts new file mode 100644 index 0000000..824d237 --- /dev/null +++ b/apps/framework/test/minted-credentials.test.ts @@ -0,0 +1,493 @@ +import { execFileSync } from 'node:child_process'; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { AgentSandbox } from '@hookdeck-evals/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildAttemptRecord } from '../harness/attempts.js'; +import { + cellSecrets, + credentialsDiscovered, + newAttemptLoopState, + writeErroredEvidence, +} from '../harness/errored-cell.js'; +import { + ASSIGNED_CREDENTIAL, + assignedCredentialValues, + findUnredacted, + redactText, + serializeRedacted, +} from '../harness/redact.js'; +import { + credentialsFromConfigText, + DISCOVER_COMMAND, + discoverSandboxCredentials, +} from '../harness/sandbox-credentials.js'; +import { checkArtifacts } from '../lib/artifact-check.js'; +import type { + DocsResult, + SkillResult, + TranscriptPart, +} from '../harness/types.js'; + +/** + * Credentials the harness never injected: the key `hookdeck ci` mints inside + * the sandbox and writes to the CLI config, which an agent then `cat`s. No env + * var holds it, so redaction by value alone let it through. + * + * Every value here is fake and says so. The shape matches what the CLI writes + * (fifty lowercase letters and digits), because the point is to prove the + * patterns catch that shape in the context it actually appears in. + */ +const MINTED = `fakeminted0${'x'.repeat(39)}`; +const MINTED_TWO = `fakeminted1${'y'.repeat(39)}`; +const GUEST_URL = 'https://dashboard.hookdeck.com/guest/fake0guest0token0000'; + +/** What `cat ~/.config/hookdeck/config.toml` prints after `hookdeck ci`. */ +function cliConfig(key = MINTED, extra = '') { + return [ + "profile = 'default'", + '', + '[default]', + `api_key = '${key}'`, + "project_id = 'tm_fakeproject0'", + "project_mode = 'inbound'", + "project_type = 'gateway'", + extra, + ].join('\n'); +} + +function toolResult(output: string): TranscriptPart { + return { + type: 'tool_result', + tool: { name: 'bash', originalName: 'exec_command' }, + output, + } as unknown as TranscriptPart; +} + +const skills: SkillResult = { available: [], loaded: [] }; +const docs: DocsResult = { calls: [] }; + +describe('redaction by assignment', () => { + it('removes the key from a CLI config the agent printed', () => { + const out = serializeRedacted({ output: cliConfig() }, []); + expect(out).not.toContain(MINTED); + expect(out).toContain(``); + // Everything that is not a credential stays readable. + expect(out).toContain('tm_fakeproject0'); + expect(out).toContain("project_mode = 'inbound'"); + }); + + /** + * "Configured the source with the wrong secret" is a failure the benchmark + * exists to catch, and reading why needs to see whether two places held the + * same value. + */ + it('keeps distinct values distinguishable and equal values equal', () => { + const out = redactText( + [ + `STRIPE_WEBHOOK_SECRET=${MINTED}`, + `--webhook-secret ${MINTED_TWO}`, + `--webhook-secret ${MINTED}`, + ].join('\n'), + [] + ); + expect(out).toBe( + [ + `STRIPE_WEBHOOK_SECRET=`, + `--webhook-secret `, + `--webhook-secret `, + ].join('\n') + ); + }); + + it('covers the other forms the same key turns up in', () => { + const forms = [ + `api_key = "${MINTED}"`, // TOML with double quotes, JSON-escaped below + `api_key = '${MINTED}'$`, // cat -A + `export HOOKDECK_CLI_TOKEN=${MINTED}`, + `hookdeck ci --api-key ${MINTED}`, + `hookdeck ci --api-key=${MINTED}`, + `{"api_key": "${MINTED}"}`, + `curl -H "Authorization: Bearer ${MINTED}" https://api.hookdeck.com`, + ]; + for (const form of forms) { + expect(serializeRedacted({ form }, [])).not.toContain(MINTED); + } + }); + + /** + * Hookdeck's own source auth config names its secret `webhook_secret_key`, + * and the `:` pattern once required `secret` to be followed directly by the + * quote, so a real value in that field reached a raw artifact. + */ + it('covers JSON names with a key suffix after secret', () => { + const hex = `0fake${'a1'.repeat(29)}0`; // 64 hex characters, fake + for (const name of [ + 'webhook_secret_key', + 'secret_key', + 'secret-key', + 'secretKey', + 'secret_access_key', + 'aws_secret_access_key', + ]) { + // Both as an agent printed it and as the API returned it inside JSON. + const asText = `{"auth": {"${name}": "${hex}"}}`; + expect(serializeRedacted({ output: asText }, [])).not.toContain(hex); + expect( + serializeRedacted({ config: { auth: { [name]: hex } } }, []) + ).not.toContain(hex); + } + }); + + it('removes the key where it later appears bare, once it was seen assigned', () => { + const artifact = { + transcript: [ + toolResult(cliConfig()), + // No credential-marking name anywhere near it. + toolResult(`hookdeck whoami # ${MINTED}`), + ], + agentReport: `Configured the CLI with ${MINTED}.`, + }; + // Bare, the key is not caught on its own... + expect(redactText(`hookdeck whoami # ${MINTED}`, [])).toContain(MINTED); + // ...but it is once the same artifact also shows it assigned. + expect(serializeRedacted(artifact, [])).not.toContain(MINTED); + }); + + it('leaves references, placeholders and non-credential settings alone', () => { + const benign = [ + "api_key = '${HOOKDECK_API_KEY}'", + 'const apiKey = process.env.HOOKDECK_API_KEY', + 'HOOKDECK_API_KEY=$HOOKDECK_API_KEY', + "api_key = 'your_api_key_goes_here'", + '--destination-auth-method api_key', + '{"key": "x-hookdeck-signature-header-name"}', + // Header names, with a digit so only the name keeps them out. + '{"key": "x-hookdeck-signature-v2-header"}', + '{"header_key": "x-signature-v2-header-name"}', + "project_id = 'tm_fakeproject0'", + ].join('\n'); + expect(assignedCredentialValues(benign)).toEqual([]); + expect(redactText(benign, [])).toBe(benign); + }); + + it('is idempotent, so the upload check passes on what the harness wrote', () => { + const once = serializeRedacted( + { + transcript: [ + toolResult(cliConfig()), + toolResult(`token=${MINTED_TWO}`), + ], + env: 'HOOKDECK_API_KEY=fakeenvkey0000000000', + }, + [{ name: 'HOOKDECK_API_KEY', value: 'fakeenvkey0000000000' }] + ); + expect(redactText(once, [])).toBe(once); + expect( + findUnredacted(once, [ + { name: 'HOOKDECK_API_KEY', value: 'fakeenvkey0000000000' }, + ]) + ).toEqual([]); + }); + + it('reports kind and count without the value', () => { + const found = findUnredacted( + JSON.stringify({ a: cliConfig(), b: cliConfig(MINTED_TWO) }), + [] + ); + expect(found).toEqual([{ name: ASSIGNED_CREDENTIAL, count: 2 }]); + expect(JSON.stringify(found)).not.toContain(MINTED); + }); +}); + +describe('credentialsFromConfigText', () => { + it('reads the key and guest link from a CLI config, and nothing else', () => { + const found = credentialsFromConfigText( + cliConfig(MINTED, `guest_url = '${GUEST_URL}'`) + ); + expect(found).toEqual([ + { name: 'hookdeck-cli-config:api_key', value: MINTED }, + { name: 'hookdeck-cli-config:guest_url', value: GUEST_URL }, + ]); + }); + + it('reads every profile, since each `hookdeck ci` can write one', () => { + const text = `${cliConfig()}\n[other]\napi_key = "${MINTED_TWO}"\n`; + expect(credentialsFromConfigText(text).map((s) => s.value)).toEqual([ + MINTED, + MINTED_TWO, + ]); + }); +}); + +describe('discoverSandboxCredentials', () => { + let home: string; + let workspace: string; + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'evals-home-')); + workspace = mkdtempSync(join(tmpdir(), 'evals-ws-')); + }); + afterEach(() => { + rmSync(home, { recursive: true, force: true }); + rmSync(workspace, { recursive: true, force: true }); + }); + + /** + * Runs the real command in a real shell against both places the CLI writes: + * the global config under `$HOME`, and a project-local `.hookdeck/` in the + * workspace. A sandbox whose `exec` is this shell is what the harness has. + */ + function shellSandbox(): AgentSandbox { + return { + workspace, + exec: async (command) => { + const stdout = execFileSync('bash', ['-c', command], { + cwd: workspace, + env: { PATH: process.env.PATH, HOME: home }, + encoding: 'utf8', + }); + return { ok: true, exitCode: 0, stdout, stderr: '' }; + }, + readFile: async (path) => readFileSync(path, 'utf8'), + }; + } + + it('finds keys in the global and the project-local CLI config', async () => { + mkdirSync(join(home, '.config', 'hookdeck'), { recursive: true }); + writeFileSync( + join(home, '.config', 'hookdeck', 'config.toml'), + cliConfig() + ); + mkdirSync(join(workspace, 'app', '.hookdeck'), { recursive: true }); + writeFileSync( + join(workspace, 'app', '.hookdeck', 'config.toml'), + cliConfig(MINTED_TWO) + ); + // Not a CLI config, so not read. + writeFileSync( + join(workspace, 'config.toml'), + `api_key = 'unrelated0000000000'` + ); + + const found = await discoverSandboxCredentials(shellSandbox()); + expect(found.map((s) => s.value).sort()).toEqual( + [MINTED, MINTED_TWO].sort() + ); + }); + + it('finds nothing, without failing, when the agent never ran the CLI', async () => { + expect(await discoverSandboxCredentials(shellSandbox())).toEqual([]); + }); + + it('never throws: a cell the agent finished is not failed by discovery', async () => { + const broken: AgentSandbox = { + workspace, + exec: async () => { + throw new Error('container is gone'); + }, + readFile: async () => '', + }; + expect(await discoverSandboxCredentials(broken)).toEqual([]); + }); + + it('says so on stderr when the read does not complete, without the values', async () => { + const timedOut: AgentSandbox = { + workspace, + // A timeout: no exit code, and part of a config already printed. + exec: async () => ({ + ok: false, + exitCode: null, + stdout: cliConfig(), + stderr: `partial ${MINTED}`, + }), + readFile: async () => '', + }; + const writes: string[] = []; + const spy = vi + .spyOn(process.stderr, 'write') + .mockImplementation((chunk: string | Uint8Array) => { + writes.push(String(chunk)); + return true; + }); + try { + const found = await discoverSandboxCredentials(timedOut); + // What was read before the failure is still used. + expect(found.map((s) => s.value)).toEqual([MINTED]); + } finally { + spy.mockRestore(); + } + expect(writes.join('')).toContain('did not complete'); + expect(writes.join('')).not.toContain(MINTED); + }); + + it('is a single shell command, so it runs through `exec` unchanged', () => { + expect(DISCOVER_COMMAND).toContain('.config/hookdeck/config.toml'); + expect(DISCOVER_COMMAND).toContain('HOOKDECK_CONFIG_FILE'); + }); +}); + +/** + * The value read out of the sandbox is what catches a key printed with no + * assignment around it, so it has to reach every artifact the cell writes. + */ +describe('discovered credentials reach every artifact', () => { + let root: string; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'evals-minted-')); + }); + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // Printed with nothing around it that marks it as a credential, so only the + // value read out of the sandbox can catch it. + const bare = `hookdeck whoami # ${MINTED}`; + + it('the result file, including a superseded attempt', () => { + const loop = newAttemptLoopState(); + credentialsDiscovered(loop, credentialsFromConfigText(cliConfig())); + const prior = buildAttemptRecord({ + attempt: 1, + result: { passed: false, checks: [] }, + stoppedReason: 'end_turn', + agentReport: 'done', + transcript: [toolResult(bare)], + skills, + docs, + }); + const out = serializeRedacted( + { agentReport: bare, priorAttempts: [prior] }, + cellSecrets(loop, []) + ); + expect(out).not.toContain(MINTED); + expect(out).toContain(''); + }); + + it('accumulates across attempts, each of which mints its own key', () => { + const loop = newAttemptLoopState(); + credentialsDiscovered(loop, credentialsFromConfigText(cliConfig())); + credentialsDiscovered( + loop, + credentialsFromConfigText(cliConfig(MINTED_TWO)) + ); + // Attempt three reads the second attempt's config again: same name. + credentialsDiscovered( + loop, + credentialsFromConfigText(cliConfig(MINTED_TWO)) + ); + const out = serializeRedacted( + { a: `k ${MINTED}`, b: `k ${MINTED_TWO}` }, + cellSecrets(loop, []) + ); + expect(out).not.toContain(MINTED); + expect(out).not.toContain(MINTED_TWO); + // Two minted keys stay distinguishable. + expect(JSON.parse(out)).toEqual({ + a: 'k ', + b: 'k ', + }); + expect(loop.discoveredSecrets).toHaveLength(2); + }); + + it('errored-cell evidence: earlier attempts and the attempt that errored', () => { + const state = newAttemptLoopState(); + credentialsDiscovered(state, credentialsFromConfigText(cliConfig())); + state.priorAttempts.push( + buildAttemptRecord({ + attempt: 1, + result: { passed: false, checks: [] }, + stoppedReason: 'end_turn', + agentReport: bare, + transcript: [toolResult(bare)], + skills, + docs, + }) + ); + state.current = { + attempt: 2, + stoppedReason: 'error_exit_255', + agentReport: '', + // Printed with no assignment, and a second key only the pattern sees. + transcript: [toolResult(bare), toolResult(cliConfig(MINTED_TWO))], + skills, + docs, + }; + const out = writeErroredEvidence( + root, + { + experiment: 'e', + evalId: 'v', + error: new Error(`died holding ${MINTED}`), + state, + }, + [] + ); + const text = readFileSync(out!, 'utf8'); + expect(text).not.toContain(MINTED); + expect(text).not.toContain(MINTED_TWO); + expect(JSON.parse(text).erroredAttempt.attempt).toBe(2); + }); +}); + +describe('checkArtifacts', () => { + let root: string; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'evals-check-')); + }); + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('passes what the harness wrote', () => { + mkdirSync(join(root, '.eval-runs', 'exp'), { recursive: true }); + writeFileSync( + join(root, '.eval-runs', 'exp', 'a.json'), + serializeRedacted({ transcript: [toolResult(cliConfig())] }, []) + ); + expect( + checkArtifacts(['.eval-runs/exp', '.eval-errored/exp'], root, []) + ).toEqual({ files: 1, findings: [] }); + }); + + it('fails a file a write path left unredacted, naming it but not the value', () => { + mkdirSync(join(root, '.eval-runs', 'exp'), { recursive: true }); + mkdirSync(join(root, '.eval-errored', 'exp'), { recursive: true }); + writeFileSync(join(root, '.eval-runs', 'exp', 'ok.json'), '{"a": 1}'); + writeFileSync( + join(root, '.eval-errored', 'exp', 'leak.json'), + JSON.stringify({ transcript: [toolResult(cliConfig())] }) + ); + const { findings } = checkArtifacts( + ['.eval-runs/exp', '.eval-errored/exp'], + root, + [] + ); + expect(findings).toEqual([ + { + path: join('.eval-errored', 'exp', 'leak.json'), + name: ASSIGNED_CREDENTIAL, + count: 1, + }, + ]); + expect(JSON.stringify(findings)).not.toContain(MINTED); + }); + + it('checks the environment values too, in any file type', () => { + mkdirSync(join(root, 'logs'), { recursive: true }); + writeFileSync(join(root, 'logs', 'run.log'), 'key fakeenvkey0000000000'); + const { findings } = checkArtifacts(['logs'], root, [ + { name: 'HOOKDECK_API_KEY', value: 'fakeenvkey0000000000' }, + ]); + expect(findings).toEqual([ + { path: join('logs', 'run.log'), name: 'HOOKDECK_API_KEY', count: 1 }, + ]); + }); +});