Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 63 additions & 4 deletions src/spin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConfirmingKey> }).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 {
Expand All @@ -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<Ran> {
/** 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<Ran> {
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 });
});
Expand All @@ -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);
}

Expand All @@ -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(' ');
}
}
9 changes: 8 additions & 1 deletion src/spin/open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -49,7 +53,10 @@ export async function openWorkspace(o: OpenOptions): Promise<OpenedWorkspace> {
}

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));
}
Expand Down
33 changes: 26 additions & 7 deletions src/spin/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -50,29 +51,38 @@ 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<string>('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}`);
return new vscode.ResolvedAuthority('127.0.0.1', localPort, opened.connectionToken);
} 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);
Expand All @@ -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));
}
}
Expand Down Expand Up @@ -119,3 +129,12 @@ async function showRefusal(workspace: string, refusal: Refusal): Promise<void> {
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<boolean>('telemetry', true) === true;
}
25 changes: 25 additions & 0 deletions src/spin/trace.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
27 changes: 21 additions & 6 deletions test/e2e/spin.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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 });
}
Expand Down
32 changes: 30 additions & 2 deletions test/mocks/vscode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const version = '1.146.0';

export const env = {
appCommit: undefined as string | undefined,
isTelemetryEnabled: false,
openExternal(_uri: unknown): Promise<boolean> {
return Promise.resolve(true);
},
Expand All @@ -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<string, unknown>();

/** 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<string, unknown>();

Expand Down Expand Up @@ -59,8 +66,29 @@ export const window = {
createOutputChannel(name: string): MockOutputChannel {
return new MockOutputChannel(name);
},
withProgress<T>(_options: unknown, task: () => Promise<T>): Promise<T> {
return task();
withProgress<T>(
_options: unknown,
task: (p: { report(value: { message?: string }): void }, token: { onCancellationRequested(listener: () => void): { dispose(): void } }) => Promise<T>,
): Promise<T> {
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<unknown> {
shownErrors.push([message, ...items]);
Expand Down
5 changes: 4 additions & 1 deletion test/package-manifest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
});

Expand Down
Loading
Loading