diff --git a/src/spin/cli.ts b/src/spin/cli.ts index dbac8cf2..4fd0bb78 100644 --- a/src/spin/cli.ts +++ b/src/spin/cli.ts @@ -14,6 +14,34 @@ export interface CodeOptions { version?: string; /** Start the workspace when it is stopped. */ start: boolean; + /** Hears that this computer's key waits for the person's passkey, on the page spin opened. */ + onConfirmingKey?: (waiting: ConfirmingKey) => void; + /** Ends the command when the person cancels the open. */ + signal?: AbortSignal; +} + +/** + * What `spin code` writes, as a line of its own, while this computer's key waits to be added to + * the person's account with their passkey (spin's cmd/cli/cmd/ssh.go, connectingIdentity). + */ +export interface ConfirmingKey { + url: string; + fingerprint: string; + name: string; +} + +function confirmingKeyOf(line: string): ConfirmingKey | undefined { + if (!line.includes('"confirming_key"')) { + return undefined; + } + try { + const c = (JSON.parse(line) as { confirming_key?: Partial }).confirming_key; + return c && typeof c.url === 'string' + ? { url: c.url, fingerprint: String(c.fingerprint ?? ''), name: String(c.name ?? 'this computer') } + : undefined; + } catch { + return undefined; + } } interface Ran { @@ -27,24 +55,50 @@ export class SpinCli { private readonly binary: string, /** The CLI's environment, and the ssh's that runs it as ProxyCommand. */ readonly env: NodeJS.ProcessEnv = process.env, + /** The trace every command of this connection joins (trace.ts); none while telemetry is off. */ + private readonly traceparent?: string, ) { } - private run(args: string[], timeoutMs: number): Promise { + /** The flag that has a command join the connection's trace, after its own arguments. */ + private traced(): string[] { + return this.traceparent ? ['--traceparent', this.traceparent] : []; + } + + /** Runs a command; onLine hears each line of its stdout as it is written. */ + private run(given: string[], timeoutMs: number, onLine?: (line: string) => void, signal?: AbortSignal): Promise { + const args = [...given, ...this.traced()]; return new Promise((resolve, reject) => { const child = spawn(this.binary, args, { env: this.env, stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; + let heard = 0; const timer = setTimeout(() => { child.kill(); reject(new Error(`spin ${args[0]} did not answer in ${timeoutMs / 1000} s`)); }, timeoutMs); - child.stdout.on('data', (d: Buffer) => { stdout += d.toString(); }); + // A person who cancels the open ends the command, and its wait for them with it. + const cancel = () => { + child.kill(); + reject(new Error(`spin ${args[0]} was cancelled`)); + }; + if (signal?.aborted) { + cancel(); + } + signal?.addEventListener('abort', cancel, { once: true }); + child.stdout.on('data', (d: Buffer) => { + stdout += d.toString(); + for (let end = stdout.indexOf('\n', heard); end >= 0; end = stdout.indexOf('\n', heard)) { + onLine?.(stdout.slice(heard, end)); + heard = end + 1; + } + }); child.stderr.on('data', (d: Buffer) => { stderr += d.toString(); }); child.on('error', e => { clearTimeout(timer); reject(new Error(`running ${this.binary}: ${e.message}`)); }); child.on('close', exitCode => { + signal?.removeEventListener('abort', cancel); clearTimeout(timer); resolve({ stdout, stderr, exitCode }); }); @@ -63,7 +117,12 @@ export class SpinCli { if (o.start) { args.push('--start'); } - const ran = await this.run(args, 10 * 60_000); + const ran = await this.run(args, 10 * 60_000, line => { + const waiting = confirmingKeyOf(line); + if (waiting) { + o.onConfirmingKey?.(waiting); + } + }, o.signal); return readCodeAnswer(ran.stdout, ran.stderr, ran.exitCode); } @@ -82,6 +141,6 @@ export class SpinCli { * the shell ssh runs it through reads it back. */ tunnelCommand(session: string): string { - return `${escapeShellArg(this.binary)} tunnel ${escapeShellArg(session)}`; + return [this.binary, 'tunnel', session, ...this.traced()].map(escapeShellArg).join(' '); } } diff --git a/src/spin/open.ts b/src/spin/open.ts index 006430d0..20cf380e 100644 --- a/src/spin/open.ts +++ b/src/spin/open.ts @@ -20,6 +20,10 @@ export interface OpenOptions { version?: string; start: boolean; log: (line: string) => void; + /** Says what the person is waited on for, in the progress they see. */ + say?: (message: string) => void; + /** Ends what runs when the person cancels the open. */ + signal?: AbortSignal; readyTimeoutMs?: number; } @@ -49,7 +53,10 @@ export async function openWorkspace(o: OpenOptions): Promise { } o.log(`spin code ${o.workspace} (VS Code ${o.version ?? ''} ${o.commit})`); - const answer = await o.cli.code({ workspace: o.workspace, commit: o.commit, version: o.version, start: o.start }); + const answer = await o.cli.code({ + workspace: o.workspace, commit: o.commit, version: o.version, start: o.start, signal: o.signal, + onConfirmingKey: c => o.say?.(`Confirm with your passkey, in the browser page spin opened, that ${c.name} connects to your workspaces`), + }); if ('error' in answer) { throw new SpinRefusal(refusalOf(answer.error)); } diff --git a/src/spin/resolver.ts b/src/spin/resolver.ts index ee8a47b3..8a02e8e9 100644 --- a/src/spin/resolver.ts +++ b/src/spin/resolver.ts @@ -10,6 +10,7 @@ import { parseSpinAuthority, SPIN_AUTHORITY } from './authority'; import { SpinCli } from './cli'; import { openWorkspace, type OpenedWorkspace } from './open'; import { type Refusal, SpinRefusal } from './refusal'; +import { newTraceparent, traceIdOf } from './trace'; /** The Spinbox extension, which carries the spin CLI of its release. */ const SPINBOX_EXTENSION = 'spin-stack.spinbox'; @@ -50,21 +51,30 @@ export class SpinboxResolver implements vscode.RemoteAuthorityResolver, vscode.D this.logger.info(`Resolving Spinbox workspace '${workspace}' (attempt #${context.resolveAttempt})`); await this.close(); const commit = editorCommit(); + const traceparent = traced() ? newTraceparent() : undefined; const cli = new SpinCli(spinBinary( vscode.workspace.getConfiguration('remote.spin').get('cliPath', ''), vscode.extensions.getExtension(SPINBOX_EXTENSION)?.extensionPath, process.platform === 'win32' ? 'win32' : process.platform, process.arch, - )); + ), process.env, traceparent); + const trace = traceparent ? ` (trace ${traceIdOf(traceparent)})` : ''; try { const opened = await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Opening Spinbox workspace ${workspace}`, - }, () => openWorkspace({ - cli, workspace, commit, version: vscode.version, start: true, - log: line => this.logger.trace(line), - })); + // spin code waits up to ten minutes for a passkey that adds this computer's key. + cancellable: true, + }, (progress, token) => { + const cancelled = new AbortController(); + token.onCancellationRequested(() => cancelled.abort()); + return openWorkspace({ + cli, workspace, commit, version: vscode.version, start: true, signal: cancelled.signal, + log: line => this.logger.trace(line), + say: message => progress.report({ message }), + }); + }); this.opened = opened; const localPort = await opened.connection.forwardLocal(opened.port); this.logger.info(`Spinbox workspace '${workspace}' (${opened.workspaceId}) open on 127.0.0.1:${localPort}`); @@ -72,7 +82,7 @@ export class SpinboxResolver implements vscode.RemoteAuthorityResolver, vscode.D } catch (e) { await this.close(); if (e instanceof SpinRefusal) { - this.logger.error(`Spinbox refused '${workspace}': ${e.refusal.code}`, e.message); + this.logger.error(`Spinbox refused '${workspace}': ${e.refusal.code}${trace}`, e.message); // VS Code tries a temporary one again by itself: said once, on the first try. if (!e.refusal.temporary || context.resolveAttempt === 1) { void showRefusal(workspace, e.refusal); @@ -81,7 +91,7 @@ export class SpinboxResolver implements vscode.RemoteAuthorityResolver, vscode.D ? vscode.RemoteAuthorityResolverError.TemporarilyNotAvailable(e.message) : vscode.RemoteAuthorityResolverError.NotAvailable(e.message, true); } - this.logger.error(`Opening Spinbox workspace '${workspace}' failed`, e); + this.logger.error(`Opening Spinbox workspace '${workspace}' failed${trace}`, e); throw vscode.RemoteAuthorityResolverError.TemporarilyNotAvailable(e instanceof Error ? e.message : String(e)); } } @@ -119,3 +129,12 @@ async function showRefusal(workspace: string, refusal: Refusal): Promise { terminal.sendText(action.command, false); } } + +/** + * Whether a connection is traced: as VS Code's telemetry setting allows, which every extension + * is asked to respect, and the Spinbox extension's own (spinbox.telemetry), which this one shares. + */ +function traced(): boolean { + return vscode.env.isTelemetryEnabled + && vscode.workspace.getConfiguration('spinbox').get('telemetry', true) === true; +} diff --git a/src/spin/trace.ts b/src/spin/trace.ts new file mode 100644 index 00000000..ad279aee --- /dev/null +++ b/src/spin/trace.ts @@ -0,0 +1,25 @@ +// A connection is one trace: the resolver hands the spin CLI a W3C traceparent of its own for each +// resolve, which `spin code`, `spin ssh-session` and `spin tunnel` join with --traceparent and +// export their spans under, so Admin → Traces shows what opening the workspace did under one id. +// The resolver exports no spans of its own; the Spinbox extension does the same for its commands. + +import { randomBytes } from 'crypto'; + +/** Version 00, a random trace-id and parent-id, sampled. An id of all zeros is invalid, so drawn again. */ +export function newTraceparent(): string { + return `00-${randomHex(16)}-${randomHex(8)}-01`; +} + +/** The trace-id of a traceparent: what a trace is found by. */ +export function traceIdOf(traceparent: string): string { + return traceparent.split('-')[1] ?? ''; +} + +function randomHex(bytes: number): string { + for (;;) { + const hex = randomBytes(bytes).toString('hex'); + if (!/^0+$/.test(hex)) { + return hex; + } + } +} diff --git a/test/e2e/spin.e2e.test.ts b/test/e2e/spin.e2e.test.ts index 0107704c..0635140b 100644 --- a/test/e2e/spin.e2e.test.ts +++ b/test/e2e/spin.e2e.test.ts @@ -30,6 +30,11 @@ const stopped = process.env.SPIN_E2E_STOPPED ?? 'e2e-stopped'; // would find it on a machine of theirs. const sshShim = fs.mkdtempSync(path.join(os.tmpdir(), 'spin-e2e-ssh-')); fs.writeFileSync(path.join(sshShim, 'ssh'), '#!/bin/sh\nexec /usr/bin/ssh -F "$HOME/.ssh/config" "$@"\n', { mode: 0o755 }); +// A browser that opens nothing: the CLI opens the page a passkey confirms on, and no test opens +// one on the machine that runs it. +for (const name of ['xdg-open', 'open']) { + fs.writeFileSync(path.join(sshShim, name), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); +} function cliFor(h: string) { return new SpinCli(cliPath, { @@ -105,18 +110,28 @@ describe('a Spinbox workspace through the real CLI', () => { expect(refusal.message).toMatch(/stopped/i); }, 5 * 60_000); - it('says a key the installation does not know is not enrolled, with where to add it', async () => { - // The same person on a machine whose only key nobody enrolled. + // spin#1253: the CLI adds a machine's key with the person's passkey rather than be refused for + // it, and says so while it waits; the open says it where the person looks. + it('waits, on a machine whose key nobody added, for the passkey that adds it, and says so', async () => { + // The same person on a machine whose only key nobody added. const stranger = fs.mkdtempSync(path.join(os.tmpdir(), 'spin-e2e-stranger-')); fs.mkdirSync(path.join(stranger, '.ssh'), { mode: 0o700 }); fs.cpSync(path.join(home, '.spin', 'config.yaml'), path.join(stranger, '.spin', 'config.yaml')); fs.cpSync(path.join(home, '.trust'), path.join(stranger, '.trust'), { recursive: true }); execFileSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', path.join(stranger, '.ssh', 'id_ed25519')]); + const said: string[] = []; + const cancelled = new AbortController(); try { - const refusal = await refusalOf(open(running, stranger)); - expect(refusal.code).toBe('key_not_enrolled'); - expect(refusal.action?.title).toBe('Add This Machine\'s Key'); - expect(refusal.action?.url).toMatch(/\/settings\/keys/); + await expect(openWorkspace({ + cli: cliFor(stranger), workspace: running, commit, start: true, signal: cancelled.signal, + log: line => console.log(line), + say: message => { + said.push(message); + cancelled.abort(); + }, + })).rejects.toThrow(/cancelled/); + expect(said).toHaveLength(1); + expect(said[0]).toMatch(/^Confirm with your passkey, in the browser page spin opened, that .+ connects to your workspaces$/); } finally { fs.rmSync(stranger, { recursive: true, force: true }); } diff --git a/test/mocks/vscode.ts b/test/mocks/vscode.ts index d7c99c6a..97423f26 100644 --- a/test/mocks/vscode.ts +++ b/test/mocks/vscode.ts @@ -6,6 +6,7 @@ export const version = '1.146.0'; export const env = { appCommit: undefined as string | undefined, + isTelemetryEnabled: false, openExternal(_uri: unknown): Promise { return Promise.resolve(true); }, @@ -14,6 +15,12 @@ export const env = { /** Settings a test sets, by their whole id (remote.spin.cliPath); the rest are their defaults. */ export const configOverrides = new Map(); +/** What a resolve said in its progress, in order. */ +export const reported: string[] = []; + +/** Whether a progress is cancelled by the person as soon as it says something, as one who reads it and gives up. */ +export const progress = { cancelOnReport: false }; + /** The resolvers activate registered, by authority. */ export const resolvers = new Map(); @@ -59,8 +66,29 @@ export const window = { createOutputChannel(name: string): MockOutputChannel { return new MockOutputChannel(name); }, - withProgress(_options: unknown, task: () => Promise): Promise { - return task(); + withProgress( + _options: unknown, + task: (p: { report(value: { message?: string }): void }, token: { onCancellationRequested(listener: () => void): { dispose(): void } }) => Promise, + ): Promise { + const cancelled: (() => void)[] = []; + const token = { + onCancellationRequested(listener: () => void) { + cancelled.push(listener); + return { dispose() { } }; + }, + }; + return task({ + report: value => { + if (value.message) { + reported.push(value.message); + if (progress.cancelOnReport) { + for (const listener of cancelled) { + listener(); + } + } + } + }, + }, token); }, showErrorMessage(message: string, ...items: unknown[]): Promise { shownErrors.push([message, ...items]); diff --git a/test/package-manifest.test.ts b/test/package-manifest.test.ts index 48abb39a..4a6ab40c 100644 --- a/test/package-manifest.test.ts +++ b/test/package-manifest.test.ts @@ -41,7 +41,10 @@ describe('package.json', () => { it('declares the settings the code reads, and no other', () => { const src = sources(); - const read = [...src.matchAll(/getConfiguration\('([\w.]+)'\)\.get<\w+>\('([\w.]+)'/g)].map(m => `${m[1]}.${m[2]}`); + // spinbox.* is the Spinbox extension's, which declares it: the two share its telemetry switch. + const read = [...src.matchAll(/getConfiguration\('([\w.]+)'\)\.get<\w+>\('([\w.]+)'/g)] + .filter(m => m[1] !== 'spinbox') + .map(m => `${m[1]}.${m[2]}`); expect(Object.keys(pkg.contributes.configuration.properties).sort()).toEqual([...new Set(read)].sort()); }); diff --git a/test/spin/resolve.test.ts b/test/spin/resolve.test.ts index bfb66b35..51b36f67 100644 --- a/test/spin/resolve.test.ts +++ b/test/spin/resolve.test.ts @@ -7,7 +7,7 @@ import * as path from 'path'; import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import type * as vscodeTypes from 'vscode'; import { activate } from '../../src/extension'; -import { configOverrides, env, ResolvedAuthority, RemoteAuthorityResolverError, resolvers, shownErrors } from '../mocks/vscode'; +import { configOverrides, env, progress, reported, ResolvedAuthority, RemoteAuthorityResolverError, resolvers, shownErrors } from '../mocks/vscode'; import { keygen, type Sshd, startSshd } from '../sshd'; // `spin+` from the extension's activation to a request answered by the workspace's @@ -41,6 +41,8 @@ const [cmd, ...args] = process.argv.slice(2); fs.appendFileSync(path.join(fixture, 'calls'), JSON.stringify([cmd, ...args]) + '\\n'); if (cmd === 'code' || cmd === 'ssh-session') { const a = JSON.parse(fs.readFileSync(path.join(fixture, cmd === 'code' ? 'code.json' : 'session.json'), 'utf8')); + for (const line of a.before ?? []) { process.stdout.write(JSON.stringify(line) + '\\n'); } + if (a.hang) { setInterval(() => undefined, 1000); return; } process.stdout.write(JSON.stringify(a.answer, null, 2) + '\\n'); process.exit(a.exit); } else if (cmd === 'tunnel' && args[0] === '${SESSION}') { @@ -70,8 +72,8 @@ id=$(printf '%s\\n' "$SSH_ORIGINAL_COMMAND" | sed -n 's/.*echo "\\(spinbox-[0-9a printf '%s: start\\nexitCode==0==\\nlisteningOn==%s==\\nconnectionToken==%s==\\n%s: end\\n' "$id" ${codePort} ${TOKEN} "$id" `; -function answerCode(answer: unknown, exit = 0) { - fs.writeFileSync(path.join(fixture, 'code.json'), JSON.stringify({ answer, exit })); +function answerCode(answer: unknown, exit = 0, before: unknown[] = [], hang = false) { + fs.writeFileSync(path.join(fixture, 'code.json'), JSON.stringify({ answer, exit, before, hang })); } function answerSession(answer: unknown, exit = 0) { @@ -139,6 +141,10 @@ afterEach(() => { fs.rmSync(path.join(fixture, f), { force: true }); } shownErrors.length = 0; + reported.length = 0; + progress.cancelOnReport = false; + env.isTelemetryEnabled = false; + configOverrides.delete('spinbox.telemetry'); }); afterAll(async () => { @@ -203,6 +209,63 @@ describe('spin+', () => { expect(ran.some(r => /-W 127\.0\.0\.1:\d+ root@/.test(r)), 'the request went through ssh -W').toBe(true); }, 30_000); + // A connection is one trace: what the CLI does for it - the workspace readied, the session + // opened, the tunnel carried - is found in Admin → Traces under one id. Off as VS Code's + // telemetry is, or Spinbox's own setting. + for (const tc of [ + { name: 'with telemetry on', telemetry: true, spinbox: true, traced: true }, + { name: 'with VS Code\'s telemetry off', telemetry: false, spinbox: true, traced: false }, + { name: 'with Spinbox\'s telemetry off', telemetry: true, spinbox: false, traced: false }, + ]) { + it(`traces the connection's CLI commands as one ${tc.name}`, async () => { + env.isTelemetryEnabled = tc.telemetry; + configOverrides.set('spinbox.telemetry', tc.spinbox); + answerCode({ workspace_id: 'w1', host: 'spin.unit-ws', folder_uri: 'vscode-remote://spin+unit-ws/root', server: 'carried' }); + opensSession(); + await resolve('spin+unit-ws'); + + const asked = calls(); + expect(asked.map(c => c[0])).toEqual(['code', 'ssh-session', 'tunnel']); + const parents = asked.map(c => { + const i = c.indexOf('--traceparent'); + return i < 0 ? undefined : c[i + 1]; + }); + if (!tc.traced) { + expect(parents, 'a command was traced with telemetry off').toEqual([undefined, undefined, undefined]); + return; + } + expect(parents[0]).toMatch(/^00-[0-9a-f]{32}-[0-9a-f]{16}-01$/); + expect(parents, 'the connection\'s commands are not one trace').toEqual([parents[0], parents[0], parents[0]]); + }, 30_000); + } + + // A first connection from this computer waits for the person's passkey to add its key + // (spin#1253): the wait is said where they look, not left as a progress that does not move. + it('says, while this computer\'s key waits for a passkey, what to do', async () => { + answerCode( + { workspace_id: 'w1', host: 'spin.unit-ws', folder_uri: 'vscode-remote://spin+unit-ws/root', server: 'carried' }, + 0, + [{ confirming_key: { url: 'https://app.example/settings/keys?add=k', fingerprint: 'SHA256:x', name: 'laptop' } }], + ); + opensSession(); + await resolve('spin+unit-ws'); + expect(reported).toEqual(['Confirm with your passkey, in the browser page spin opened, that laptop connects to your workspaces']); + }, 30_000); + + // spin code waits ten minutes for a passkey; a person who will not give one ends the open + // rather than wait them out. + it('ends the open, and spin code with it, when the person cancels it while the key waits', async () => { + answerCode( + { workspace_id: 'w1', host: 'spin.unit-ws', folder_uri: 'vscode-remote://spin+unit-ws/root', server: 'carried' }, + 0, + [{ confirming_key: { url: 'https://app.example/settings/keys?add=k', fingerprint: 'SHA256:x', name: 'laptop' } }], + true, + ); + progress.cancelOnReport = true; + await expect(resolve('spin+unit-ws')).rejects.toBeInstanceOf(RemoteAuthorityResolverError); + expect(calls().map(c => c[0]), 'the open went on past its cancel').toEqual(['code']); + }, 30_000); + it('refuses a workspace that answers with another host key than the session\'s', async () => { answerCode({ workspace_id: 'w1', host: 'spin.unit-ws', folder_uri: 'vscode-remote://spin+unit-ws/root', server: 'carried' }); opensSession();