Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

test(cli): authenticate loopback e2e fixtures (#1607)

0xken155241bc3bd73a
diff --git a/cli/e2e/agentMessages.e2e.ts b/cli/e2e/agentMessages.e2e.ts
index e553f9578..09b72e695 100644
--- a/cli/e2e/agentMessages.e2e.ts
+++ b/cli/e2e/agentMessages.e2e.ts
@@ -45,7 +45,7 @@ const reads = (relay: FakeBackend) => relay.seen.filter((line) => line.split('?'
/** `harness settings`, as the person turns a switch: through the daemon to the account, and kept here at once, which
* tells Agent Messages. */
const settings = (d: IsolatedDaemon, body: Record<string, boolean>) => fetch(`http://127.0.0.1:${d.port}/api/agent-settings`, {
- method: 'PATCH', headers: { 'x-adapter-local': '1', 'content-type': 'application/json' }, body: JSON.stringify(body) })
+ method: 'PATCH', headers: d.localHeaders({ 'x-adapter-local': '1', 'content-type': 'application/json' }), body: JSON.stringify(body) })
/** The account's agent experiments as this daemon keeps them (lib/agentSettings.ts), once it has read them. */
const kept = (d: IsolatedDaemon, want: (settings: Record<string, unknown>) => boolean = () => true) => until('the account\'s experiments to be kept', () => {
try {
@@ -160,7 +160,7 @@ describe('Agent Messages, end to end', () => {
await until('Agent Messages to connect from the edge host', () => connected(d) || null, 30_000, 200)
// An older window's chat icon still reaches the backend, and decides nothing here.
const tab = await fetch(`http://127.0.0.1:${d.port}/api/agent-messages/tabs/app`, {
- method: 'PATCH', headers: { 'x-adapter-local': '1', 'content-type': 'application/json' }, body: JSON.stringify({ enabled: true }) })
+ method: 'PATCH', headers: d.localHeaders({ 'x-adapter-local': '1', 'content-type': 'application/json' }), body: JSON.stringify({ enabled: true }) })
expect(tab.status).toBe(200)
expect((await settings(d, { pullRequestLine: true })).status).toBe(200)
expect(relay.experiments).toEqual({ agent_pull_request_line: true })
diff --git a/cli/e2e/deviceAck.e2e.ts b/cli/e2e/deviceAck.e2e.ts
index b17c4a9e5..72c35ad44 100644
--- a/cli/e2e/deviceAck.e2e.ts
+++ b/cli/e2e/deviceAck.e2e.ts
@@ -15,11 +15,10 @@ import { signedInDaemon, writeE2ee } from './harness/fleet.js'
type Listing = { pending?: string[]; members: Array<{ pub: string; label: string; confirmed?: { by: string; label: string } }> }
-const local = { 'x-adapter-local': '1', 'content-type': 'application/json' }
const devices = async (daemon: IsolatedDaemon): Promise<Listing> =>
- (await fetch(`http://127.0.0.1:${daemon.port}/api/devices`, { headers: local })).json() as Promise<Listing>
+ (await fetch(`http://127.0.0.1:${daemon.port}/api/devices`, { headers: daemon.localHeaders({ 'x-adapter-local': '1' }) })).json() as Promise<Listing>
const dismiss = async (daemon: IsolatedDaemon, body: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> => {
- const res = await fetch(`http://127.0.0.1:${daemon.port}/api/devices/dismiss`, { method: 'POST', headers: local, body: JSON.stringify(body) })
+ const res = await fetch(`http://127.0.0.1:${daemon.port}/api/devices/dismiss`, { method: 'POST', headers: daemon.localHeaders({ 'x-adapter-local': '1', 'content-type': 'application/json' }), body: JSON.stringify(body) })
return { status: res.status, body: await res.json() as Record<string, unknown> }
}
const pendingOn = async (daemon: IsolatedDaemon): Promise<string[]> => (await devices(daemon)).pending ?? []
diff --git a/cli/e2e/gatewayOnDemand.e2e.ts b/cli/e2e/gatewayOnDemand.e2e.ts
index f0cc9eb0d..61681eb84 100644
--- a/cli/e2e/gatewayOnDemand.e2e.ts
+++ b/cli/e2e/gatewayOnDemand.e2e.ts
@@ -24,7 +24,7 @@ import { RelayPhone, type PhoneFrame } from './harness/relayPhone.js'
const starts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service gateway started/g)].length
const connections = (d: IsolatedDaemon) => d.log().split('\n').filter((line) => line.includes('[services] gateway connected')).length
const pidsOf = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service gateway started \(pid (\d+)\)/g)].map((match) => Number(match[1]))
-const status = async (d: IsolatedDaemon) => await (await fetch(`http://127.0.0.1:${d.port}/api/status`)).json() as Record<string, any>
+const status = async (d: IsolatedDaemon) => await (await fetch(`http://127.0.0.1:${d.port}/api/status`, { headers: d.localHeaders() })).json() as Record<string, any>
const isTurn = (type: string, agentId: string) => (frame: Frame | PhoneFrame) => frame.type === type && frame.agentId === agentId
describe('the gateway\'s process, once it is needed', () => {
@@ -77,7 +77,7 @@ describe('the gateway\'s process, once it is needed', () => {
it('a key command starts it and is answered by it; killed, it comes back and answers again', async () => {
const d = await fresh()
- const pairs = async () => await (await fetch(`http://127.0.0.1:${d.port}/api/pairs`)).json() as Record<string, any>
+ const pairs = async () => await (await fetch(`http://127.0.0.1:${d.port}/api/pairs`, { headers: d.localHeaders() })).json() as Record<string, any>
expect(await pairs()).toEqual({ pairs: [] })
expect(starts(d)).toBe(1)
const [pid] = pidsOf(d)
diff --git a/cli/e2e/gatewayProcess.e2e.ts b/cli/e2e/gatewayProcess.e2e.ts
index ec72d6fff..023b85b96 100644
--- a/cli/e2e/gatewayProcess.e2e.ts
+++ b/cli/e2e/gatewayProcess.e2e.ts
@@ -103,7 +103,7 @@ describe('the gateway in its own process', () => {
const { machine, backend, desk, agentId } = await fresh({ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '10000', HARNESSD_SERVICE_MAX_BACKOFF_MS: '10000' }, { phone: false })
const d = machine.daemon
const machines = async () => {
- const response = await fetch(`http://127.0.0.1:${d.port}/api/machines`, { signal: AbortSignal.timeout(10_000) })
+ const response = await fetch(`http://127.0.0.1:${d.port}/api/machines`, { headers: d.localHeaders(), signal: AbortSignal.timeout(10_000) })
return { status: response.status, body: await response.json() as Record<string, any> }
}
const first = await machines()
@@ -137,7 +137,7 @@ describe('the gateway in its own process', () => {
expect(relayed.filter((f) => f.type === 'message' || f.type === 'turn_started').every((f) => (f.payload as any)?.__e2e)).toBe(true)
expect(JSON.stringify(relayed)).not.toContain('through the gateway')
// The machine's E2EE fingerprint and pairings, which the core asks the gateway for.
- const status = await (await fetch(`http://127.0.0.1:${machine.daemon.port}/api/status`)).json() as Record<string, any>
+ const status = await (await fetch(`http://127.0.0.1:${machine.daemon.port}/api/status`, { headers: machine.daemon.localHeaders() })).json() as Record<string, any>
expect(status.fingerprint).toEqual(expect.any(String))
expect(status.pairs).toEqual([expect.objectContaining({ label: 'phone', role: 'web' })])
expect(status.connected).toBe(true)
@@ -188,7 +188,7 @@ describe('the gateway in its own process', () => {
expect(w.backend.nodeUp(machine.machineId)).toBe(false)
await deskTurn(desk, agentId, 'the gateway is parked and nothing else cares')
// The pairings are the gateway's to tell: refused plainly, not hung.
- const pairs = await fetch(`http://127.0.0.1:${machine.daemon.port}/api/status`)
+ const pairs = await fetch(`http://127.0.0.1:${machine.daemon.port}/api/status`, { headers: machine.daemon.localHeaders() })
expect(pairs.ok).toBe(true)
expect(((await pairs.json()) as Record<string, any>).pairs).toEqual([])
expect(machine.daemon.coresStarted()).toBe(1)
diff --git a/cli/e2e/harness/client.ts b/cli/e2e/harness/client.ts
index c1fb26050..2681ebbc0 100644
--- a/cli/e2e/harness/client.ts
+++ b/cli/e2e/harness/client.ts
@@ -48,7 +48,7 @@ export class LocalClient {
const url = options.tcp
? `ws://127.0.0.1:${daemon.port}/api/local-ws`
: `ws+unix://${daemon.socketPath}:/api/local-ws`
- const ws = new WebSocket(url)
+ const ws = new WebSocket(url, options.tcp ? { headers: daemon.localHeaders() } : undefined)
await new Promise<void>((resolve, reject) => {
ws.once('open', () => resolve())
ws.once('error', reject)
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index f56a7f286..118abe2b7 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -18,6 +18,7 @@ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { promisify } from 'node:util'
import { isolatedTmux, type IsolatedTmux } from '../../src/testing/isolatedTmux.js'
+import { localCredentialHeaders } from '../../src/lib/localCredential.js'
import { artifactLog, artifactsEnabled } from './artifacts.js'
import { daemonEnvironment } from '../../src/testing/daemonEnvironment.js'
import { GH_FORBIDDEN_STUB } from '../../src/testing/ghStub.js'
@@ -445,6 +446,11 @@ export class IsolatedDaemon {
return readFileSync(join(this.dataDir, 'hook-credential'), 'utf8').trim()
}
+ /** Credentials for this daemon's loopback TCP API; its Unix socket needs none. */
+ localHeaders(extra: Record<string, string> = {}): Record<string, string> {
+ return { ...extra, ...localCredentialHeaders(this.dataDir) }
+ }
+
/**
* What every pane on this daemon's tmux server shows, for a failing test's artifacts: its command, how
* it started, and its screen with some history. A pane is the one thing the daemon's log cannot say:
diff --git a/cli/e2e/master.e2e.ts b/cli/e2e/master.e2e.ts
index fab098e8b..ca413f765 100644
--- a/cli/e2e/master.e2e.ts
+++ b/cli/e2e/master.e2e.ts
@@ -55,7 +55,7 @@ describe('harnessd', () => {
expect(d.corePid()).not.toBe(d.pid)
expect(readFileSync(join(d.dataDir, 'adapter.pid'), 'utf8').trim()).toBe(String(d.pid))
// The app judges who owns the daemon by this pid: the master's, as in the pid file, not the core's.
- const status = await (await fetch(`http://127.0.0.1:${d.port}/api/status`)).json() as Record<string, any>
+ const status = await (await fetch(`http://127.0.0.1:${d.port}/api/status`, { headers: d.localHeaders() })).json() as Record<string, any>
expect(status.pid).toBe(d.pid)
expect(status.corePid).toBe(d.corePid())
expect(status.harnessd.masterPid).toBe(d.pid)
@@ -127,7 +127,7 @@ describe('harnessd', () => {
const core = d.corePid()!
expect(core).not.toBe(master)
expect(Number(execFileSync('ps', ['-o', 'ppid=', '-p', String(core)], { encoding: 'utf8' }).trim())).toBe(master)
- const status = await (await fetch(`http://127.0.0.1:${d.port}/api/status`)).json() as Record<string, any>
+ const status = await (await fetch(`http://127.0.0.1:${d.port}/api/status`, { headers: d.localHeaders() })).json() as Record<string, any>
expect(status.harnessd.masterPid).toBe(master)
expect(readFileSync(join(d.dataDir, 'adapter.pid'), 'utf8').trim()).toBe(String(master))
// A crashed core is restarted under it, and the agent goes on.
diff --git a/cli/e2e/masterIpcExit.e2e.ts b/cli/e2e/masterIpcExit.e2e.ts
index 8b6476682..a201d13ce 100644
--- a/cli/e2e/masterIpcExit.e2e.ts
+++ b/cli/e2e/masterIpcExit.e2e.ts
@@ -57,7 +57,7 @@ if (process.argv[2] === '__run' && process.env.HARNESSD_RESTARTS === '0') {
await until('the master to receive the queued bind', () => daemon.log().includes(`core bound (pid ${firstCore},`))
writeFileSync(file('exit'), '')
await until('the next core to be ready', () => daemon.log().includes('[cli] ready'), 60_000)
- const status = await fetch(`http://127.0.0.1:${daemon.port}/api/status`).then(response => response.json()) as any
+ const status = await fetch(`http://127.0.0.1:${daemon.port}/api/status`, { headers: daemon.localHeaders() }).then(response => response.json()) as any
expect(status.harnessd).toMatchObject({ state: 'running', restarts: 1, lastExit: 'code 75', lastExitReason: 'update', masterPid: master })
await until('the update to be kept', () => daemon.log().includes('the update stayed up — keeping it'))
expect(daemon.coresStarted()).toBe(2)
diff --git a/cli/e2e/productUsage.e2e.ts b/cli/e2e/productUsage.e2e.ts
index 36dc75dd7..d86eebd78 100644
--- a/cli/e2e/productUsage.e2e.ts
+++ b/cli/e2e/productUsage.e2e.ts
@@ -22,7 +22,7 @@ it('reports only local counters from a real turn, and the account switch stops t
await d.start()
await until('sharing preference read', () => backend!.seen.includes('GET /api/product-usage/settings') || null, 45000)
const settings = `http://127.0.0.1:${d.port}/api/product-usage/settings`
- expect((await (await fetch(settings)).json())).toMatchObject({ data: { enabled: true } })
+ expect((await (await fetch(settings, { headers: d.localHeaders() })).json())).toMatchObject({ data: { enabled: true } })
client = await LocalClient.connect(d, { machineId: machine.machineId })
const cwd = join(d.projectsDir, 'PRIVATE_PROJECT_CANARY'); mkdirSync(cwd, { recursive: true })
const creationId = 'private-creation-canary'
@@ -51,7 +51,7 @@ it('reports only local counters from a real turn, and the account switch stops t
expect(missing.error).toBe('AGENT_NOT_FOUND')
// The same Desktop-format fixture must pass both the local proxy and the backend route tests.
const appReport = { ...JSON.parse(readFileSync(new URL('../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8')), day: new Date().toISOString().slice(0, 10) }
- const forwarded = await fetch(`http://127.0.0.1:${d.port}/api/product-usage/report`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: JSON.stringify(appReport) })
+ const forwarded = await fetch(`http://127.0.0.1:${d.port}/api/product-usage/report`, { method: 'POST', headers: d.localHeaders({ 'content-type': 'application/json', 'x-adapter-local': '1' }), body: JSON.stringify(appReport) })
expect(forwarded.status).toBe(200)
expect(backend.productUsage.reports).toContainEqual(appReport)
await turn()
@@ -71,7 +71,7 @@ it('reports only local counters from a real turn, and the account switch stops t
expect(sum('request_app_resume_reason_saved_state_missing')).toBe(1)
const wire = JSON.stringify(backend.productUsage.reports)
for (const privateValue of ['PRIVATE_', creationId, machine.machineId, machine.computerId, machine.token, agentId, cwd, 'userMessage', 'payload']) expect(wire).not.toContain(privateValue)
- expect((await fetch(settings, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"enabled":false}' })).status).toBe(200)
+ expect((await fetch(settings, { method: 'POST', headers: d.localHeaders({ 'content-type': 'application/json', 'x-adapter-local': '1' }), body: '{"enabled":false}' })).status).toBe(200)
const reportsBefore = backend.productUsage.reports.length
const checksBefore = backend.seen.filter(x => x === 'GET /api/product-usage/settings').length
await turn()
diff --git a/cli/e2e/reexec.e2e.ts b/cli/e2e/reexec.e2e.ts
index 2612b1ced..6ab585dae 100644
--- a/cli/e2e/reexec.e2e.ts
+++ b/cli/e2e/reexec.e2e.ts
@@ -43,7 +43,7 @@ describe('the master re-executing itself on an update', () => {
const rejected = () => JSON.parse(readFileSync(join(cliDir(), 'update-rejected.json'), 'utf8')) as string[]
const marker = () => join(daemon!.dataDir, 'harnessd-reexec.json')
const status = async (): Promise<Record<string, any> | null> =>
- fetch(`http://127.0.0.1:${daemon!.port}/api/status`).then((response) => response.json()).catch(() => null)
+ fetch(`http://127.0.0.1:${daemon!.port}/api/status`, { headers: daemon!.localHeaders() }).then((response) => response.json()).catch(() => null)
/** The build the core runs, and the one the master runs, as the daemon reports them. */
const builds = async (): Promise<{ core: string | null; master: string | null; masterPid: number | null; reexecs: number | null }> => {
const now = await status()
@@ -270,7 +270,7 @@ describe.skipIf(!RELEASED)('a released master and this one, each over the other\
let newest = NEXT
const cliDir = () => join(scratch, 'cli')
const status = async (): Promise<Record<string, any> | null> =>
- fetch(`http://127.0.0.1:${daemon!.port}/api/status`).then((response) => response.json()).catch(() => null)
+ fetch(`http://127.0.0.1:${daemon!.port}/api/status`, { headers: daemon!.localHeaders() }).then((response) => response.json()).catch(() => null)
beforeAll(async () => {
scratch = mkdtempSync(join(tmpdir(), 'harnessd-reexec-compat-'))
diff --git a/cli/e2e/updateHostile.e2e.ts b/cli/e2e/updateHostile.e2e.ts
index fd38ac5dd..14465c781 100644
--- a/cli/e2e/updateHostile.e2e.ts
+++ b/cli/e2e/updateHostile.e2e.ts
@@ -241,7 +241,7 @@ class Installed {
}
async status(): Promise<Row | null> {
- return fetch(`http://127.0.0.1:${this.daemon.port}/api/status`).then((response) => response.json() as Promise<Row>).catch(() => null)
+ return fetch(`http://127.0.0.1:${this.daemon.port}/api/status`, { headers: this.daemon.localHeaders() }).then((response) => response.json() as Promise<Row>).catch(() => null)
}
async version(): Promise<string | null> { return (await this.status())?.version ?? null }
diff --git a/cli/e2e/updateOnItsOwn.e2e.ts b/cli/e2e/updateOnItsOwn.e2e.ts
index eacea3f3e..01795c642 100644
--- a/cli/e2e/updateOnItsOwn.e2e.ts
+++ b/cli/e2e/updateOnItsOwn.e2e.ts
@@ -42,7 +42,7 @@ describe('a core with no master', () => {
const installed = () => readFileSync(join(cliDir(), 'cli.js'))
const rejected = () => JSON.parse(readFileSync(join(cliDir(), 'update-rejected.json'), 'utf8')) as string[]
const status = async (): Promise<Row | null> =>
- fetch(`http://127.0.0.1:${daemon!.port}/api/status`).then((response) => response.json() as Promise<Row>).catch(() => null)
+ fetch(`http://127.0.0.1:${daemon!.port}/api/status`, { headers: daemon!.localHeaders() }).then((response) => response.json() as Promise<Row>).catch(() => null)
/** The pids answering on the daemon's port: whatever runs it now. */
const listeners = (): number[] => {
try {
@@ -51,10 +51,10 @@ describe('a core with no master', () => {
}
/** What the daemon has said: what this test's process printed, and the log file the master the core
* started writes to (core/main.ts `startMasterHere`). */
- const logs = (): string => {
+ const logs = (source = daemon!): string => {
let file = ''
- try { file = readFileSync(join(daemon!.dataDir, 'harness.log'), 'utf8') } catch { /* none yet */ }
- return `${daemon!.log()}\n${file}`
+ try { file = readFileSync(join(source.dataDir, 'harness.log'), 'utf8') } catch { /* none yet */ }
+ return `${source.log()}\n${file}`
}
const parentOf = (pid: number): number => Number(execFileSync('ps', ['-o', 'ppid=', '-p', String(pid)], { encoding: 'utf8' }).trim())
const rows = async (client: LocalClient): Promise<Row[]> =>
@@ -164,7 +164,7 @@ describe('a core with no master', () => {
const d = await IsolatedDaemon.create({ scriptPath: join(cliDir(), 'cli.js'), noMaster: true, env: environment() })
daemon = d
;(d.options as { launch?: string[] }).launch = [join(CLI_ROOT, 'e2e/harness/olderReleaseHandoff.mjs'), join(cliDir(), 'cli.js'), join(d.dataDir, 'adapter.pid'), mayLeave]
- onTestFailed(() => { console.log(`---- daemon log\n${logs().split('\n').slice(-150).join('\n')}`) })
+ onTestFailed(() => { console.log(`---- daemon log\n${logs(d).split('\n').slice(-150).join('\n')}`) })
await d.start()
expect((await status())?.harnessd).toBeFalsy()
const client = await LocalClient.connect(d)