Files
gstack/test/ios-qa.test.ts
T
Garry Tan 943105f109 v1.91.8.0 test: smaller suite, derived paid selection, retired never-green evals (#2994)
* test: delete test-infrastructure dead code (G)

- exit-propagation drives the runner's real strict verdict
  (BunTestOutputClassifier + strictTestExitCode); delete the unused
  shardRunLooksTruncated predicate.
- delete skill-coverage-matrix registry + its gate (nothing reads it; the
  floor already iterates skillCensus()).
- delete touchfiles-facade export-parity tests (Bun fails missing imports
  at link time) and the duplicated E2E_TIERS tier-value test.
- delete brain-cache-spec TRANSPORT_DEFAULT_POLICY, SKILL_RUN_RETENTION_DAYS
  and the now-unused BrainTrustPolicy type with their literal tests.
  AUTOPLAN_PREFLIGHT_BUDGET_BYTES stays: skill-preflight-budget enforces it
  against real resolver output.
- delete audit-compliance's JSDoc-comment grep.

* test: replace product tests that fake the product with real-boundary tests (F)

- design: serve.test.ts drove an inline mirror server; now two tests run the
  real serve() on an ephemeral port (reload confinement, submit exit 0).
- setup-gbrain: rollback + voyage tests execute the template-extracted init
  blocks (3 sites) instead of drifted local bash copies.
- terminal-agent: internalHandler source greps replaced by a behavioral
  /internal/grant + /internal/revoke auth matrix (no/wrong/valid token).
- /health: server-security-surface and the server-auth / security-audit-r2 /
  sidebar-tabs source greps fold into one liveness-only check on the real
  body; the L4 sidecar wiring gets a behavioral /pty-inject-scan test.
- delete tautologies (browser-manager onDisconnect, memory-command #12),
  ios swiftui tap fixture self-check, memory-ingest put_page grep, detach
  source greps, sidebar-agent absence pins, dead-CSS pins + the dead CSS,
  security-audit-r2 Task 1 + the test-only meta-commands re-export,
  duplicate generated-SKILL.md checks.
- make-pdf coverage-gaps cases move into their owner test files.

* test: delete tests of dead eval code (A)

- A1: the retired Eng lexical oracle (evaluateEngSeedCoverage,
  isEngSeedDecisionAUQ), the completion-handoff detector and the retained
  corpus had no paid caller since v1.87.6; delete their 26 replay files,
  ~2.6k helper LOC and fixtures, and the dead blocks in 8 mixed files
  (live hasNativePlanTerminal / batching assertions stay).
- A2: dead viewport approvers in autoplan-artifact-permission and their 11
  replay files + fixtures; recorder/launcher cases stay.
- A3: never-wired oracles and seeders (autoplan-phase-order,
  eng-finding-fixture, ceo-paired-fixture, design-ui-scope,
  plan-skill-completion, pty-current-screen, required-reads,
  transcript-section-logger); plan-seed-submission now decodes through the
  production createPtyScreen; section manifests name their actual guard.
- A4: zero-reference helper exports, plus execGit and invokeAndObserve
  found by the reachability pass.
- 52 fixtures orphaned by the deletions; touchfile and selection-table
  entries for every deleted path.

* test: clean up the paid eval lane (B1-B4, B6, B7)

- B1: delete paid files that assert nothing or cannot pass meaningfully:
  skill-llm-eval-spec and skill-e2e-spec-execute (test.todo), gemini-e2e
  (+ gemini-session-runner; no gemini CLI in CI), ship-idempotency (red
  since v1.63), the two opus-4-7 *-sonnet overlay wrappers, conductor-prose
  (+ its source-evaluation replay), codex-e2e-plan-format; drop their keys,
  scripts and census rows.
- B2: skill-llm-eval grades browse/sections/command-list.md with one union
  judge that also carries the baseline score pin; regression-vs-baseline
  deleted (paid run: pass, c4/c4/a4).
- B3: memory-pipeline, ios-qa, ios-qa-swift-build and plan-tune-cathedral
  make no model calls; renamed out of the paid glob so they run on every
  PR. Swift builds need GSTACK_TEST_SWIFT=1; device stub deleted.
- B4: codex-e2e*, outside-voice, aside and ios-device cannot run in the CI
  image; excluded from the weekly lane with a tracked re-entry condition.
- B6: fold opus-47's negative routing controls into skill-routing-e2e
  journey-negatives (paid run: 3/3 unrouted) and delete the file.
- B7: delete the never-green brain-privacy-gate eval; a free
  gstack-skill-start test now proves consent precedes artifacts egress.

* test: retire the finding-count cluster and trim its helpers (C)

- C0/C1: the five never-green evals (skill-e2e-autoplan-chain and
  skill-e2e-plan-{ceo,eng,design,devex}-finding-count) failed on harness and
  budget, never on skill behavior; delete them, their touchfile/tier ids,
  AUTOPLAN_CHAIN_BUDGET and the dedicated eighth periodic slice (--slices 7).
- C2: delete the helper groups whose only paid consumers were those files
  (11 modules), trim claude-pty-runner and eng-seeded-coverage to the paid
  closure, and delete the free replay tests whose assertions exercised only
  that dead code (89 files, 135 orphaned fixtures). Blocks that used dead code
  only as input for a live subject keep their assertions: the multiSelect
  default moved to plan-review-decisions, runner PTY tests use inline caller
  policies, and the timer-safe budget checks moved to eng-finding-retry-budget.
- The eight production-touching files stay except ceo-current-decision-record
  (its template read only feeds the retired counter).
- CARVE_GUARDS.autoplan is behavioral 'none'; TODOS records the lost chain
  and per-finding cadence coverage with their re-entry tests.

* test: fold per-incident replay series into their detector owners (D)

Twelve detector families move into one owner test each: 73 incident files
become describe blocks in ceo-section-loading-fixture (stale-fill race),
model-overlays, coverage-audit-evidence, autoplan-phase-observer,
native-auto-decide, outside-voice-evidence, eng-first-review,
plan-count-completion, plan-count-file-permission, ceo-mode-option,
plan-scope-selection and plan-count-prerequisite. Each block keeps its original
code and fixture, so every case still runs; only tests asserting the incident
file's own touchfile registration are dropped (41). Touchfile lists that named
an incident now name its owner.

* test: start the plan-count history PTY on its readiness marker (H)

The fake CLI prints a startup marker and the runner waits for it instead of the
fixed 8 s startup sleep (8.6 s -> 0.9 s locally). eng-semantic-terminal's
sleeping registration cases went with C; plan-count-timeout keeps the fixed wait
because it asserts deadline behavior.

* test: derive paid touchfiles from each eval's static closure (E)

touchfiles.test.ts now checks, per key, that the paid file's static
test/helpers and test/fixtures closure (plus fixture paths it names in string
literals) is covered, and names the file, path, chain and key to fix when it is
not. Free *.test.ts files are no longer touchfiles, so editing a free replay
test stops selecting paid evals: 950 entries removed, 653 real closure paths
added. The hand-copied inventories go: periodic-fixture-selection,
fake-impeccable-touchfiles and 45 per-file selection examples. Selection for
the sample edits (plan-eng-review template, claude-pty-runner,
plan-count-fixture, gstack-config) loses no case under either profile.
CONTRIBUTING documents the rule and its lower bound.

* test: skip hollow tier shards and census judges in the paid planner (B5)

A paid file is now skipped for a tier lane only when every E2E id it registers
is known statically and none has that tier; ids come from the touchfile
registrations and literal testName/*IfSelected arguments, so a comment or
skill path that quotes another id cannot unschedule it, and computed names
keep today's scheduling. --list and the manifest show each skip as
"skipped: no E2E_TIERS id has tier <tier>". The weekly gate census drops the
LLM judges (--skip-judges); they still run in the periodic census and PR gate
lanes. Gate lane 52 -> 42 files, census 41; periodic 77 -> 69.

* test: run seven paid evals on the current default capture model (B8)

skill-e2e-{auq-matrix,plan-format,qa-bugs,retro,workflow} pinned
claude-opus-4-7 and skill-e2e-office-hours plus -brain-writeback pinned
claude-sonnet-4-6; none tests a historical model, so they now capture with
resolveEvalModel('capture'), and the free harness tests that execute these
registrations receive the same resolver. The paid re-pin run passed all of
them. skill-e2e-{design,office-hours-phase4,plan-prosons,plan} keep
claude-opus-4-7: six of their cases failed on the default model (three
timeouts, a missing report file, a format miss and a posture score of 3), so
per the plan's fallback they keep their pins with a TODOS entry. The pre-spend
estimate and drop threshold are in docs/test-audit-2026-09.md.

* test: guard the reduced suite against new test-of-test files

- test/test-of-test-ratchet.test.ts records the 228 free tests that import only
  test/ code and fails on a new one, naming the owner test to extend instead;
  a stale baseline entry fails with the remove instruction.
- test/helpers/resolve-repo-path.ts is the one specifier/literal resolver for
  the ratchet and the touchfile closure invariant, with its own unit tests.
- CONTRIBUTING "Test tiers" describes the paid-failure workflow (fix, then one
  row in the detector's owner test) and the ratchet; TEST_PORTFOLIO gains the
  detector -> owner-test table and no longer claims an Autoplan chain eval.
- TODOS: automatic exclusion policy for chronically red periodic files (P3),
  the deferred native-completion table collapse, the unused CEO payment
  seeder; the PTY readiness item is narrowed to the paid runner.
- docs/test-audit-2026-09.md collects the triage, security mapping, inventories,
  selection proof, behavior-commit decisions and retained false positives.

* v1.91.8.0 test: smaller suite, derived paid selection, retired never-green evals

Release metadata for the test-reduction branch: VERSION 1.91.8.0 (1.91.7.0 is
claimed by #2983), CHANGELOG with the measured before/after table and a
contributor section, durations re-recorded on Ubicloud standard-16 (857 files,
0 failures), the agents digest, CONTRIBUTING's after-measurement row, the B8
fallback TODOS entry, and the after metrics, kept-vs-plan notes, B8 run and
census estimate in docs/test-audit-2026-09.md.

* fix(ubicloud): skip retrieval globs that match nothing instead of reporting a failed pull

* test: count issue-numbered Design findings in the UI-scope gate eval
2026-09-29 08:58:49 -07:00

493 lines
20 KiB
TypeScript

// High-level E2E for /ios-qa skill flow.
//
// Runs the gen-accessors codegen against a SwiftUI fixture and simulates the
// agent flow against the daemon with a fake device tunnel — no hardware.
// Catches regression in source-read + codegen + cache + render paths without
// an iPhone. The real-device loop lives in test/skill-e2e-ios-device.test.ts.
//
// Note: The detailed daemon HTTP unit/integration tests live next to the
// daemon source (ios-qa/daemon/test/*). This file tests the agent-flow
// boundary — what the /ios-qa skill orchestrates end-to-end.
import { describe, test, expect, afterAll } from 'bun:test';
import { createServer, type Server, type IncomingMessage } from 'http';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { startDaemon, type RunningDaemon } from '../ios-qa/daemon/src/index';
import type { DeviceTunnel } from '../ios-qa/daemon/src/proxy';
import { grantIdentity } from '../ios-qa/daemon/src/allowlist';
import { generate } from '../ios-qa/scripts/gen-accessors';
const DEVICE_TOKEN = 'rotated-mock-bearer-token';
// Per-test isolation under `bun test --concurrent`: a single module-level
// `workDir` reassigned in beforeEach is clobbered by parallel tests, so they
// collide on the same daemon pidfile (`already_running`) and stomp each
// other's GSTACK_IOS_* env paths. Each test calls makeWorkDir() for its own
// dir instead; afterEach cleans up every dir created during the test.
const createdWorkDirs: string[] = [];
function makeWorkDir(): string {
const dir = mkdtempSync(join(tmpdir(), 'ios-e2e-'));
createdWorkDirs.push(dir);
return dir;
}
// Clean up ONCE after all tests, not per-test. Under `bun test --concurrent`
// an afterEach that drains the shared array would delete still-running tests'
// workDirs the moment ANY test finishes, vanishing their audit/attempts files
// mid-assertion. afterAll runs after every concurrent test has settled.
afterAll(() => {
for (const dir of createdWorkDirs) {
rmSync(dir, { recursive: true, force: true });
}
createdWorkDirs.length = 0;
});
interface StubState {
loggedIn: boolean;
username: string;
rawTaps: Array<{ x: number; y: number }>;
}
// Build a stub StateServer that mimics the iOS app's HTTP surface end-to-end:
// /auth/rotate, session lock, snapshot, restore, tap. Used for both NO_DEVICE
// and as the development harness for WITH_DEVICE.
function startStubStateServer(initial: StubState): Promise<{ server: Server; port: number; state: StubState }> {
const state = { ...initial };
let activeSession: string | null = null;
return new Promise((resolve) => {
const server = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on('data', (c) => chunks.push(c));
req.on('end', () => {
const body = Buffer.concat(chunks).toString('utf-8');
const auth = req.headers['authorization'];
const url = req.url ?? '/';
// /healthz public on loopback (the stub mimics that)
if (req.method === 'GET' && url === '/healthz') {
return respond(res, 200, { version: '1.0.0' });
}
// /auth/rotate: validates boot token (we accept any here for the stub)
if (req.method === 'POST' && url === '/auth/rotate') {
return respond(res, 200, { ok: true });
}
// Everything else requires our rotated token
if (auth !== `Bearer ${DEVICE_TOKEN}`) {
return respond(res, 401, { error: 'unauthorized' });
}
// Session ops
if (req.method === 'POST' && url === '/session/acquire') {
if (activeSession) return respond(res, 423, { error: 'device_locked' });
activeSession = 'stub-session-' + Math.random().toString(16).slice(2, 8);
return respond(res, 200, { session_id: activeSession, ttl_seconds: 300 });
}
if (req.method === 'POST' && url === '/session/release') {
activeSession = null;
return respond(res, 200, { ok: true });
}
// Snapshot
if (req.method === 'GET' && url === '/state/snapshot') {
return respond(res, 200, {
_schema_version: 1,
_app_build_id: 'stub-1.0',
_accessor_hash: 'stub-hash',
keys: {
loggedIn: state.loggedIn,
username: state.username,
},
});
}
// Mutations require session
const sessionHeader = req.headers['x-session-id'];
const sessionOk = !!sessionHeader && sessionHeader === activeSession;
const isMutation = req.method === 'POST' && (
url === '/tap' || url === '/swipe' || url === '/type' ||
url.startsWith('/state/') && !url.endsWith('/snapshot')
);
if (isMutation && !sessionOk) {
return respond(res, 409, { error: 'session_required' });
}
if (req.method === 'POST' && url === '/tap') {
const payload = JSON.parse(body || '{}');
state.rawTaps.push({ x: payload.x ?? 0, y: payload.y ?? 0 });
return respond(res, 200, { op: 'tap', ok: true });
}
if (req.method === 'POST' && url === '/state/restore') {
const payload = JSON.parse(body || '{}');
if (payload._accessor_hash && payload._accessor_hash !== 'stub-hash') {
return respond(res, 409, { error: 'schema_mismatch' });
}
if (payload.keys?.loggedIn !== undefined) state.loggedIn = payload.keys.loggedIn;
if (payload.keys?.username !== undefined) state.username = payload.keys.username;
return respond(res, 200, { ok: true });
}
respond(res, 404, { error: 'not_found' });
});
});
server.listen(0, '127.0.0.1', () => {
const addr = server.address();
const port = typeof addr === 'object' && addr ? addr.port : 0;
resolve({ server, port, state });
});
});
}
function respond(res: import('http').ServerResponse, status: number, body: unknown): void {
const payload = JSON.stringify(body);
res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) });
res.end(payload);
}
async function fetchJson(method: string, url: string, init: { headers?: Record<string, string>; body?: string } = {}): Promise<{ status: number; body: unknown }> {
const res = await fetch(url, { method, headers: init.headers, body: init.body });
const text = await res.text();
let body: unknown;
try { body = JSON.parse(text); } catch { body = text; }
return { status: res.status, body };
}
describe('ios-qa E2E (no-device path)', () => {
test('NO_DEVICE: codegen runs against a SwiftUI fixture and emits valid accessors', () => {
const workDir = makeWorkDir();
const srcDir = join(workDir, 'app-src');
mkdirSync(srcDir);
writeFileSync(join(srcDir, 'AppState.swift'), `
@Observable
class AppState {
// @Snapshotable
var isLoggedIn: Bool = false
// @Snapshotable
var username: String = ""
// @Snapshotable
var counter: Int = 0
var ephemeralCache: [String: Any] = [:]
}
`);
const cacheRoot = join(workDir, 'cache');
const result = generate({
inputDir: srcDir,
cacheRoot,
swiftVersion: '6.0.0',
toolGitRev: 'e2e-test',
platformTriple: 'darwin-arm64',
});
expect(result.cacheHit).toBe(false);
expect(result.specs).toHaveLength(1);
expect(result.specs[0]!.fields.map(f => f.name).sort()).toEqual(['counter', 'isLoggedIn', 'username']);
const generatedSwift = readFileSync(result.outputPath, 'utf-8');
expect(generatedSwift).toContain('enum AppStateAccessor');
expect(generatedSwift).not.toContain('public enum AppStateAccessor');
expect(generatedSwift).toContain('key: "isLoggedIn"');
expect(generatedSwift).toContain('key: "counter"');
expect(generatedSwift).not.toContain('key: "ephemeralCache"'); // not marked @Snapshotable
expect(generatedSwift).toContain('#if DEBUG');
});
test('NO_DEVICE: cache hit on rerun', () => {
const workDir = makeWorkDir();
const srcDir = join(workDir, 'app-src');
mkdirSync(srcDir);
writeFileSync(join(srcDir, 'AppState.swift'), '@Observable class A { @Snapshotable var x: Int = 0 }');
const cacheRoot = join(workDir, 'cache');
const r1 = generate({ inputDir: srcDir, cacheRoot, swiftVersion: '6', toolGitRev: 't', platformTriple: 'p' });
const r2 = generate({ inputDir: srcDir, cacheRoot, swiftVersion: '6', toolGitRev: 't', platformTriple: 'p' });
expect(r1.cacheHit).toBe(false);
expect(r2.cacheHit).toBe(true);
});
test('NO_DEVICE: schema mismatch returns 409 on restore', async () => {
const workDir = makeWorkDir();
const stub = await startStubStateServer({ loggedIn: false, username: '', rawTaps: [] });
try {
const tunnel: DeviceTunnel = {
udid: 'NO-DEVICE-UDID',
ipv6Addr: '127.0.0.1',
port: stub.port,
bootTokenRotated: DEVICE_TOKEN,
};
const daemon = await startDaemon({
loopbackPort: 0,
tailnetEnabled: false,
pidfilePath: join(workDir, 'daemon.pid'),
tunnelProvider: async () => tunnel,
});
if ('error' in daemon) throw new Error(daemon.error);
try {
// Acquire session first
const acqR = await fetchJson('POST', `http://127.0.0.1:${daemon.loopbackPort}/session/acquire`);
expect(acqR.status).toBe(200);
const sessionId = (acqR.body as { session_id: string }).session_id;
// Restore with wrong schema hash
const restoreR = await fetchJson('POST', `http://127.0.0.1:${daemon.loopbackPort}/state/restore`, {
headers: { 'content-type': 'application/json', 'x-session-id': sessionId },
body: JSON.stringify({
_schema_version: 1,
_accessor_hash: 'wrong-hash-xxxxxxxxxxxxx',
keys: { loggedIn: true },
}),
});
expect(restoreR.status).toBe(409);
expect((restoreR.body as { error: string }).error).toBe('schema_mismatch');
} finally {
await daemon.close();
}
} finally {
stub.server.close();
}
});
});
describe('ios-qa E2E (agent-flow simulation)', () => {
test('SCENARIO: acquire → snapshot → restore → tap → release', async () => {
const workDir = makeWorkDir();
const initial: StubState = { loggedIn: false, username: '', rawTaps: [] };
const stub = await startStubStateServer(initial);
try {
const tunnel: DeviceTunnel = {
udid: 'AGENT-UDID',
ipv6Addr: '127.0.0.1',
port: stub.port,
bootTokenRotated: DEVICE_TOKEN,
};
const daemon = await startDaemon({
loopbackPort: 0,
tailnetEnabled: false,
pidfilePath: join(workDir, 'daemon.pid'),
tunnelProvider: async () => tunnel,
});
if ('error' in daemon) throw new Error(daemon.error);
const base = `http://127.0.0.1:${daemon.loopbackPort}`;
try {
// 1. Acquire session
const acq = await fetchJson('POST', `${base}/session/acquire`);
expect(acq.status).toBe(200);
const sessionId = (acq.body as { session_id: string }).session_id;
// 2. Snapshot initial state
const snap = await fetchJson('GET', `${base}/state/snapshot`);
expect(snap.status).toBe(200);
expect((snap.body as { keys: { loggedIn: boolean } }).keys.loggedIn).toBe(false);
// 3. Restore: flip logged-in to true via the correct schema hash
const restore = await fetchJson('POST', `${base}/state/restore`, {
headers: { 'content-type': 'application/json', 'x-session-id': sessionId },
body: JSON.stringify({
_schema_version: 1,
_accessor_hash: 'stub-hash',
keys: { loggedIn: true, username: 'agent@e2e' },
}),
});
expect(restore.status).toBe(200);
// 4. Verify state changed
const snap2 = await fetchJson('GET', `${base}/state/snapshot`);
expect((snap2.body as { keys: { loggedIn: boolean; username: string } }).keys).toEqual({
loggedIn: true,
username: 'agent@e2e',
});
// 5. Tap (with session-id)
const tap = await fetchJson('POST', `${base}/tap`, {
headers: { 'content-type': 'application/json', 'x-session-id': sessionId },
body: JSON.stringify({ x: 100, y: 200 }),
});
expect(tap.status).toBe(200);
expect(stub.state.rawTaps).toEqual([{ x: 100, y: 200 }]);
// 6. Release
const rel = await fetchJson('POST', `${base}/session/release`);
expect(rel.status).toBe(200);
} finally {
await daemon.close();
}
} finally {
stub.server.close();
}
});
test('SCENARIO: contention — second session-acquire returns 423 while first holds', async () => {
const workDir = makeWorkDir();
const stub = await startStubStateServer({ loggedIn: false, username: '', rawTaps: [] });
try {
const tunnel: DeviceTunnel = {
udid: 'CONTENTION-UDID',
ipv6Addr: '127.0.0.1',
port: stub.port,
bootTokenRotated: DEVICE_TOKEN,
};
const daemon = await startDaemon({
loopbackPort: 0,
tailnetEnabled: false,
pidfilePath: join(workDir, 'daemon.pid'),
tunnelProvider: async () => tunnel,
});
if ('error' in daemon) throw new Error(daemon.error);
const base = `http://127.0.0.1:${daemon.loopbackPort}`;
try {
const a = await fetchJson('POST', `${base}/session/acquire`);
expect(a.status).toBe(200);
const b = await fetchJson('POST', `${base}/session/acquire`);
expect(b.status).toBe(423);
} finally {
await daemon.close();
}
} finally {
stub.server.close();
}
});
test('SCENARIO: tailnet allowlist gate + mint + audit log', async () => {
const workDir = makeWorkDir();
const stub = await startStubStateServer({ loggedIn: false, username: '', rawTaps: [] });
try {
const allowPath = join(workDir, 'allowlist.json');
const auditPath = join(workDir, 'audit.jsonl');
const attemptsPath = join(workDir, 'attempts.jsonl');
// Pass paths as daemon OPTIONS, not process.env — env is process-global
// and races across concurrent tests (the cause of the original
// intermittent failures). GSTACK_IOS_TAILNET_BIND is read from env but
// is the same constant for every tailnet test, so it can't diverge.
process.env.GSTACK_IOS_TAILNET_BIND = '127.0.0.1';
const tunnel: DeviceTunnel = {
udid: 'TAILNET-UDID',
ipv6Addr: '127.0.0.1',
port: stub.port,
bootTokenRotated: DEVICE_TOKEN,
};
const daemon = await startDaemon({
loopbackPort: 0,
tailnetEnabled: true,
allowlistPath: allowPath,
auditPath,
attemptsPath,
pidfilePath: join(workDir, 'daemon.pid'),
tunnelProvider: async () => tunnel,
probeImpl: async () => ({ ok: true, ownIdentity: 'mac@e2e' }),
whoIsImpl: async () => ({ identity: 'agent@e2e', raw: {} }),
});
if ('error' in daemon) throw new Error(daemon.error);
const tailnetBase = `http://127.0.0.1:${daemon.tailnetPort}`;
try {
// 1. Mint denied for un-allowlisted identity
const denied = await fetchJson('POST', `${tailnetBase}/auth/mint`, {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ capability: 'interact' }),
});
expect(denied.status).toBe(403);
// 2. Owner grants — then mint succeeds
await grantIdentity({ identity: 'agent@e2e', capability: 'mutate', path: allowPath });
const minted = await fetchJson('POST', `${tailnetBase}/auth/mint`, {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ capability: 'interact' }),
});
expect(minted.status).toBe(200);
const sessionToken = (minted.body as { session_token: string }).session_token;
// 3. Use session token to tap (with X-Session-Id)
const acqR = await fetchJson('POST', `${tailnetBase}/session/acquire`, {
headers: { 'authorization': `Bearer ${sessionToken}` },
});
expect(acqR.status).toBe(200);
const sessionId = (acqR.body as { session_id: string }).session_id;
const tapR = await fetchJson('POST', `${tailnetBase}/tap`, {
headers: { 'authorization': `Bearer ${sessionToken}`, 'content-type': 'application/json', 'x-session-id': sessionId },
body: JSON.stringify({ x: 50, y: 60 }),
});
expect(tapR.status).toBe(200);
// 4. Audit log must have an entry for /tap
await new Promise(r => setTimeout(r, 80));
expect(existsSync(auditPath)).toBe(true);
const rows = readFileSync(auditPath, 'utf-8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l));
const tapRow = rows.find(r => r.endpoint === 'POST /tap');
expect(tapRow).toBeDefined();
expect(tapRow.identity).toBe('agent@e2e');
expect(tapRow.capability).toBe('mutate');
expect(tapRow.device_udid).toBe('TAILNET-UDID');
// 5. Attempts log must have the denied-mint entry, with HASHED identity (no raw leak)
expect(existsSync(attemptsPath)).toBe(true);
const attempts = readFileSync(attemptsPath, 'utf-8');
expect(attempts).not.toContain('agent@e2e');
expect(attempts).toMatch(/"reason":"identity_not_allowed"/);
} finally {
await daemon.close();
delete process.env.GSTACK_IOS_TAILNET_BIND;
}
} finally {
stub.server.close();
}
});
test('SCENARIO: capability-tier enforcement — observe token cannot /tap', async () => {
const workDir = makeWorkDir();
const stub = await startStubStateServer({ loggedIn: false, username: '', rawTaps: [] });
try {
const allowPath = join(workDir, 'allowlist.json');
// Paths via daemon options, not process.env (concurrency-safe).
const tunnel: DeviceTunnel = {
udid: 'CAP-UDID', ipv6Addr: '127.0.0.1', port: stub.port, bootTokenRotated: DEVICE_TOKEN,
};
const daemon = await startDaemon({
loopbackPort: 0,
tailnetEnabled: true,
allowlistPath: allowPath,
auditPath: join(workDir, 'audit.jsonl'),
attemptsPath: join(workDir, 'attempts.jsonl'),
pidfilePath: join(workDir, 'daemon.pid'),
tunnelProvider: async () => tunnel,
probeImpl: async () => ({ ok: true, ownIdentity: 'mac@e2e' }),
whoIsImpl: async () => ({ identity: 'readonly@e2e', raw: {} }),
});
if ('error' in daemon) throw new Error(daemon.error);
const base = `http://127.0.0.1:${daemon.tailnetPort}`;
try {
await grantIdentity({ identity: 'readonly@e2e', capability: 'observe', path: allowPath });
const minted = await fetchJson('POST', `${base}/auth/mint`, {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ capability: 'observe' }),
});
const token = (minted.body as { session_token: string }).session_token;
// /screenshot (observe) → ok
const ss = await fetchJson('GET', `${base}/screenshot`, {
headers: { 'authorization': `Bearer ${token}` },
});
// The stub StateServer doesn't implement /screenshot, returns 404
// through the proxy. That's fine — what we're testing is the daemon's
// capability gate. observe is sufficient for /screenshot at the gate.
expect([200, 404]).toContain(ss.status);
// /tap (interact) → 403 capability_insufficient
const tap = await fetchJson('POST', `${base}/tap`, {
headers: { 'authorization': `Bearer ${token}`, 'content-type': 'application/json', 'x-session-id': 'x' },
body: JSON.stringify({ x: 1, y: 1 }),
});
expect(tap.status).toBe(403);
expect((tap.body as { error: string }).error).toBe('capability_insufficient');
} finally {
await daemon.close();
}
} finally {
stub.server.close();
}
});
});