|
| 1 | +/** |
| 2 | + * Adversarial tests for the v0.9.5 release surface. |
| 3 | + * |
| 4 | + * Covers the 8 upstream commits (`#1049`, `#1063`, `#1064`, `#1067`, `#1068`, |
| 5 | + * `#1069`+`#1071`, `#1074`, `#1078`) plus the 6 pre-release review-fix commits |
| 6 | + * that landed via PR #1086. The per-surface unit tests |
| 7 | + * (`test/telemetry/*`, `test/altimate/sample-setup-helpers.test.ts`) hit the |
| 8 | + * happy path and the documented failure modes; this file layers boundary / |
| 9 | + * injection / type-confusion / oversized-input cases on top so the FINAL |
| 10 | + * shipped code — not just what the unit tests exercised — is what gets tagged. |
| 11 | + * |
| 12 | + * Every assertion is deterministic — no timing dependencies, no shared state, |
| 13 | + * no `mock.module()`. Real helpers, real fs where needed, real |
| 14 | + * `process.env` mutation with snapshot/restore. |
| 15 | + */ |
| 16 | + |
| 17 | +import { afterEach, beforeEach, describe, expect, test } from "bun:test" |
| 18 | +import fs from "node:fs" |
| 19 | +import os from "node:os" |
| 20 | +import path from "node:path" |
| 21 | + |
| 22 | +import { Flag } from "../../src/flag/flag" |
| 23 | +import { Telemetry } from "../../src/altimate/telemetry" |
| 24 | +import * as OnboardingTelemetry from "../../src/altimate/telemetry/onboarding" |
| 25 | +import { redactPaths, countSampleContents } from "../../src/altimate/tools/sample-setup" |
| 26 | +import { buildCliContext, buildAuthorizeUrl } from "../../src/altimate/plugin/altimate" |
| 27 | + |
| 28 | +// ----------------------------------------------------------------------------- |
| 29 | +// 1. Telemetry opt-out — `Flag.truthyEnv` on hostile / oversized env values |
| 30 | +// ----------------------------------------------------------------------------- |
| 31 | + |
| 32 | +describe("v0.9.5 — Flag.truthyEnv adversarial", () => { |
| 33 | + // Kilo review on PR #1088: env-var snapshot/restore hooks were previously |
| 34 | + // file-scoped, so they ran for every test in this file even though only the |
| 35 | + // tests in this describe block ever touch `ALTIMATE_TELEMETRY_DISABLED`. |
| 36 | + // Scoping them here matches usage. |
| 37 | + const OPT_OUT_VAR = "ALTIMATE_TELEMETRY_DISABLED" |
| 38 | + let optOutSnapshot: string | undefined |
| 39 | + beforeEach(() => { |
| 40 | + optOutSnapshot = process.env[OPT_OUT_VAR] |
| 41 | + }) |
| 42 | + afterEach(() => { |
| 43 | + if (optOutSnapshot === undefined) delete process.env[OPT_OUT_VAR] |
| 44 | + else process.env[OPT_OUT_VAR] = optOutSnapshot |
| 45 | + }) |
| 46 | + |
| 47 | + test("very long value (32KB) — must not enable, must not throw", () => { |
| 48 | + // A 32KB env value should be rejected as a non-truthy string, not crash the |
| 49 | + // parser. Real users don't hit this, but a shell injection into the env |
| 50 | + // could. |
| 51 | + process.env[OPT_OUT_VAR] = "x".repeat(32 * 1024) |
| 52 | + expect(Flag.truthyEnv(OPT_OUT_VAR)).toBe(false) |
| 53 | + }) |
| 54 | + |
| 55 | + test("value with embedded null byte — must not enable", () => { |
| 56 | + process.env[OPT_OUT_VAR] = "true\x00" |
| 57 | + // JS's `===` doesn't treat "true\0" as "true", so this rejects — asserting |
| 58 | + // that the parser doesn't stringify-and-substring-check. |
| 59 | + expect(Flag.truthyEnv(OPT_OUT_VAR)).toBe(false) |
| 60 | + }) |
| 61 | + |
| 62 | + test("value with leading/trailing whitespace — rejected (no trimming)", () => { |
| 63 | + // Documented semantic — matches the existing `truthy()` behaviour. If a |
| 64 | + // future edit adds trim(), this test flips and the reviewer must decide |
| 65 | + // whether that's intentional. |
| 66 | + process.env[OPT_OUT_VAR] = "\ttrue\n" |
| 67 | + expect(Flag.truthyEnv(OPT_OUT_VAR)).toBe(false) |
| 68 | + }) |
| 69 | + |
| 70 | + test("unknown env var name — always false, never crash on missing key", () => { |
| 71 | + expect(Flag.truthyEnv("SOME_TOTALLY_UNSET_VAR_" + "A".repeat(50))).toBe(false) |
| 72 | + }) |
| 73 | +}) |
| 74 | + |
| 75 | +// ----------------------------------------------------------------------------- |
| 76 | +// 2. `Telemetry.classifyProvider` — hostile ids + prototype defense stress |
| 77 | +// ----------------------------------------------------------------------------- |
| 78 | + |
| 79 | +describe("v0.9.5 — Telemetry.classifyProvider adversarial", () => { |
| 80 | + test("very long providerID (10K chars) — 'other', no id leaked, no throw", () => { |
| 81 | + const huge = "z".repeat(10_000) |
| 82 | + const r = Telemetry.classifyProvider(huge) |
| 83 | + expect(r.provider).toBe("other") |
| 84 | + expect(r.provider_id).toBeUndefined() |
| 85 | + }) |
| 86 | + |
| 87 | + test("providerID with embedded null byte — 'other', id dropped", () => { |
| 88 | + const r = Telemetry.classifyProvider("anthropic\x00injected") |
| 89 | + expect(r.provider).toBe("other") |
| 90 | + expect(r.provider_id).toBeUndefined() |
| 91 | + }) |
| 92 | + |
| 93 | + test("providerID with newlines and control characters — 'other', id dropped", () => { |
| 94 | + const r = Telemetry.classifyProvider("anthropic\n\r\tinjected") |
| 95 | + expect(r.provider).toBe("other") |
| 96 | + expect(r.provider_id).toBeUndefined() |
| 97 | + }) |
| 98 | + |
| 99 | + test("providerID that is a JSON stringification of an object — 'other'", () => { |
| 100 | + const r = Telemetry.classifyProvider('{"provider":"anthropic"}') |
| 101 | + expect(r.provider).toBe("other") |
| 102 | + expect(r.provider_id).toBeUndefined() |
| 103 | + }) |
| 104 | + |
| 105 | + test("__proto__ / prototype as providerID — must NOT poison and must NOT enum", () => { |
| 106 | + for (const key of ["__proto__", "prototype", "hasOwnProperty", "isPrototypeOf"]) { |
| 107 | + const r = Telemetry.classifyProvider(key) |
| 108 | + expect(r.provider).toBe("other") |
| 109 | + } |
| 110 | + // Sanity: prototype pollution attempt at this call site didn't extend Object. |
| 111 | + // If CURATED_PROVIDER_ENUM were a plain object and a caller managed to write |
| 112 | + // to it, unrelated code paths could leak an inherited property here. |
| 113 | + expect(({} as any).polluted).toBeUndefined() |
| 114 | + }) |
| 115 | + |
| 116 | + test("modelID with unusual types (empty string, whitespace, unicode) — no big_pickle unless exact", () => { |
| 117 | + // Contract: `big_pickle` only fires on the exact pair ("opencode","big-pickle"). |
| 118 | + // Anything else on the opencode provider must fall through to "other" with the id kept. |
| 119 | + for (const modelID of ["", " big-pickle ", "BIG-PICKLE", "big-pickle" /* zero-width */]) { |
| 120 | + const r = Telemetry.classifyProvider("opencode", modelID) |
| 121 | + expect(r.provider).toBe("other") |
| 122 | + expect(r.provider_id).toBe("opencode") |
| 123 | + } |
| 124 | + }) |
| 125 | +}) |
| 126 | + |
| 127 | +// ----------------------------------------------------------------------------- |
| 128 | +// 3. `OnboardingTelemetry.claimEnvironmentScan` — hostile sessionIDs |
| 129 | +// ----------------------------------------------------------------------------- |
| 130 | + |
| 131 | +describe("v0.9.5 — OnboardingTelemetry claim adversarial", () => { |
| 132 | + beforeEach(() => OnboardingTelemetry.resetForTest()) |
| 133 | + afterEach(() => OnboardingTelemetry.resetForTest()) |
| 134 | + |
| 135 | + test("empty-string sessionID — treated as its own session", () => { |
| 136 | + // Not a user-reachable shape (SessionPrompt always synthesizes an id) but |
| 137 | + // the helper must not crash and must remain idempotent for whatever key it |
| 138 | + // receives. |
| 139 | + expect(OnboardingTelemetry.claimEnvironmentScan("")).toBe(true) |
| 140 | + expect(OnboardingTelemetry.claimEnvironmentScan("")).toBe(false) |
| 141 | + }) |
| 142 | + |
| 143 | + test("very long sessionID (10K chars) — one claim, then locked", () => { |
| 144 | + const huge = "s".repeat(10_000) |
| 145 | + expect(OnboardingTelemetry.claimEnvironmentScan(huge)).toBe(true) |
| 146 | + expect(OnboardingTelemetry.claimEnvironmentScan(huge)).toBe(false) |
| 147 | + }) |
| 148 | + |
| 149 | + test("sessionID with special characters — treated as distinct keys", () => { |
| 150 | + const a = "sess/../etc/passwd" |
| 151 | + const b = "sess'; DROP TABLE users;--" |
| 152 | + const c = "sess\x00null" |
| 153 | + for (const s of [a, b, c]) { |
| 154 | + expect(OnboardingTelemetry.claimEnvironmentScan(s)).toBe(true) |
| 155 | + expect(OnboardingTelemetry.claimEnvironmentScan(s)).toBe(false) |
| 156 | + } |
| 157 | + }) |
| 158 | + |
| 159 | + test("isOnboardingSession stays false for a session that only claimed (no markOnboardingSession)", () => { |
| 160 | + // The composed gate (`isOnboardingSession && claim`) at project-scan.ts:952 |
| 161 | + // relies on markOnboardingSession being called separately. A session that |
| 162 | + // only ever hit `claim()` must NOT be reported as onboarding — that would |
| 163 | + // silently promote random /discover calls to funnel events. |
| 164 | + OnboardingTelemetry.claimEnvironmentScan("random-session") |
| 165 | + expect(OnboardingTelemetry.isOnboardingSession("random-session")).toBe(false) |
| 166 | + }) |
| 167 | +}) |
| 168 | + |
| 169 | +// ----------------------------------------------------------------------------- |
| 170 | +// 4. `redactPaths` / `countSampleContents` — oversize / metachar / hostile fs |
| 171 | +// ----------------------------------------------------------------------------- |
| 172 | + |
| 173 | +describe("v0.9.5 — sample-setup helpers adversarial", () => { |
| 174 | + test("redactPaths handles empty message without throwing", () => { |
| 175 | + expect(redactPaths("")).toBe("") |
| 176 | + }) |
| 177 | + |
| 178 | + test("redactPaths handles a 100KB message without leaking paths or degenerating markers", () => { |
| 179 | + // Coderabbit review on PR #1088: previous version used `repeat(1000)` which is |
| 180 | + // ~20 KB not 100 KB, and a `performance.now()` wall-clock assertion which is |
| 181 | + // flaky under host load / parallel test runners. Build exactly 100,000 chars |
| 182 | + // deterministically and assert only the redaction shape. |
| 183 | + const segment = "normal text here /Users/alice/x/y/z " |
| 184 | + const msg = segment.repeat(Math.ceil(100_000 / segment.length)).slice(0, 100_000) |
| 185 | + const out = redactPaths(msg) |
| 186 | + expect(out).not.toContain("/Users/alice") |
| 187 | + // Should not have degenerated to `<path><path><path>...` |
| 188 | + expect(out).not.toMatch(/<path><path>/) |
| 189 | + }) |
| 190 | + |
| 191 | + test("redactPaths accepts extras containing regex metacharacters (treated as literal via split)", () => { |
| 192 | + // The known-value pass uses `split(known).join("<path>")`, which is a literal |
| 193 | + // substring split — regex metachars in `known` don't have any special meaning. |
| 194 | + // A future rewrite that regressed to `.replace(new RegExp(known), ...)` would |
| 195 | + // either crash on the unclosed `[` or match wildly. This test locks the |
| 196 | + // literal-split semantics in. |
| 197 | + const out = redactPaths("failed at /tmp/checkout-.+*[xyz", ["/tmp/checkout-.+*[xyz"]) |
| 198 | + expect(out).toBe("failed at <path>") |
| 199 | + }) |
| 200 | + |
| 201 | + test("redactPaths does not leak the marker back if a user's error text already contains '<path>'", () => { |
| 202 | + // If the input already contained `<path>` as literal user text, the collapse |
| 203 | + // step could double-eat surrounding characters. Assert the marker is |
| 204 | + // preserved as-is when it's not adjacent to another marker. |
| 205 | + const out = redactPaths("caller received sentinel <path> from upstream") |
| 206 | + expect(out).toContain("<path>") |
| 207 | + expect(out).toContain("sentinel") |
| 208 | + expect(out).toContain("upstream") |
| 209 | + }) |
| 210 | + |
| 211 | + test("countSampleContents on a symlink loop returns 0 rather than crashing", () => { |
| 212 | + // fs.readdirSync follows the surface entries but doesn't recurse into loops |
| 213 | + // in this helper (countFilesWithExtension only recurses via `isDirectory()` |
| 214 | + // on the entry itself). The loop link itself does not resolve to a |
| 215 | + // directory here, so it's counted as a file (and skipped by the .sql / .csv |
| 216 | + // extension filter). Still: the important adversarial guarantee is "does |
| 217 | + // not blow up". |
| 218 | + const root = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-symlink-")) |
| 219 | + try { |
| 220 | + fs.mkdirSync(path.join(root, "models")) |
| 221 | + // Create a symlink pointing back to models — a real loop. |
| 222 | + // Coderabbit review on PR #1088: bare `catch` used to swallow every symlink |
| 223 | + // setup failure into a passing test, and `toBeGreaterThanOrEqual(0)` was |
| 224 | + // trivially true for any non-negative count. Narrow the skip to the one |
| 225 | + // known-unsupported-symlink error class (EPERM on Windows without |
| 226 | + // dev-mode); re-throw anything else so a real filesystem regression |
| 227 | + // doesn't hide behind the skip. Assert exact `models === 0` — the loop |
| 228 | + // link resolves to a directory but has no `.sql` inside; anything nonzero |
| 229 | + // would mean the helper is following the loop. |
| 230 | + try { |
| 231 | + fs.symlinkSync(path.join(root, "models"), path.join(root, "models", "loop")) |
| 232 | + } catch (error) { |
| 233 | + if ((error as NodeJS.ErrnoException).code === "EPERM") return |
| 234 | + throw error |
| 235 | + } |
| 236 | + const counts = countSampleContents(root) |
| 237 | + expect(counts.models).toBe(0) |
| 238 | + expect(counts.tables).toBe(0) |
| 239 | + } finally { |
| 240 | + fs.rmSync(root, { recursive: true, force: true }) |
| 241 | + } |
| 242 | + }) |
| 243 | +}) |
| 244 | + |
| 245 | +// ----------------------------------------------------------------------------- |
| 246 | +// 5. `buildCliContext` / `buildAuthorizeUrl` — cli_context URL fragment |
| 247 | +// ----------------------------------------------------------------------------- |
| 248 | + |
| 249 | +describe("v0.9.5 — cli_context builder adversarial", () => { |
| 250 | + test("buildCliContext produces valid base64url that decodes to v=1 payload", async () => { |
| 251 | + // Machine-id file lives at ~/.altimate/machine-id in the runtime path; |
| 252 | + // point at a tmpfile so the runner's real state is untouched. |
| 253 | + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-mid-")) |
| 254 | + try { |
| 255 | + const midPath = path.join(tmp, "machine-id") |
| 256 | + const encoded = await buildCliContext(midPath) |
| 257 | + // base64url characters only — no `+`, `/`, `=`. |
| 258 | + expect(encoded).toMatch(/^[A-Za-z0-9_-]+$/) |
| 259 | + const decoded = Buffer.from(encoded, "base64url").toString("utf8") |
| 260 | + const payload = JSON.parse(decoded) |
| 261 | + expect(payload.v).toBe(1) |
| 262 | + expect(typeof payload.cli_version).toBe("string") |
| 263 | + } finally { |
| 264 | + fs.rmSync(tmp, { recursive: true, force: true }) |
| 265 | + } |
| 266 | + }) |
| 267 | + |
| 268 | + test("buildAuthorizeUrl encodes redirect and state (no naked control chars)", async () => { |
| 269 | + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-authurl-")) |
| 270 | + try { |
| 271 | + const midPath = path.join(tmp, "machine-id") |
| 272 | + const hostile = "https://evil.example/callback?a=1&b=2#frag" |
| 273 | + const url = await buildAuthorizeUrl( |
| 274 | + "https://app.example.com", |
| 275 | + hostile, |
| 276 | + "state\nvalue\twith\tspecials", |
| 277 | + midPath, |
| 278 | + ) |
| 279 | + // No literal newline / tab / naked `#` in the query-param portion. |
| 280 | + // (Fragment starts with `#cli_context=...` — that's the only allowed `#`.) |
| 281 | + const [queryPortion] = url.split("#") |
| 282 | + expect(queryPortion).not.toContain("\n") |
| 283 | + expect(queryPortion).not.toContain("\t") |
| 284 | + // Fragment is present and comes last. |
| 285 | + expect(url).toContain("#cli_context=") |
| 286 | + expect(url.indexOf("#cli_context=")).toBe(url.lastIndexOf("#")) |
| 287 | + // The redirect param carries the encoded form, not the raw URL — |
| 288 | + // an escaped `#` (%23) must be present, not a naked one. |
| 289 | + expect(url).toContain("redirect=" + encodeURIComponent(hostile)) |
| 290 | + } finally { |
| 291 | + fs.rmSync(tmp, { recursive: true, force: true }) |
| 292 | + } |
| 293 | + }) |
| 294 | + |
| 295 | + test("buildCliContext returns valid payload even when machine-id path is unreadable", async () => { |
| 296 | + // Point at a directory (not a file) — the machine-id read/write should |
| 297 | + // fail internally, but the builder should still return a valid payload |
| 298 | + // WITHOUT machine_id rather than throw. |
| 299 | + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-badmid-")) |
| 300 | + try { |
| 301 | + const encoded = await buildCliContext(tmp) // tmp is a dir, not a file |
| 302 | + const decoded = Buffer.from(encoded, "base64url").toString("utf8") |
| 303 | + const payload = JSON.parse(decoded) |
| 304 | + expect(payload.v).toBe(1) |
| 305 | + // machine_id must NOT be present when it can't be read/minted. |
| 306 | + // (`buildCliContext` uses `if (machineId) ctx.machine_id = machineId`.) |
| 307 | + expect(payload.machine_id).toBeUndefined() |
| 308 | + } finally { |
| 309 | + fs.rmSync(tmp, { recursive: true, force: true }) |
| 310 | + } |
| 311 | + }) |
| 312 | +}) |
0 commit comments