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
33 changes: 33 additions & 0 deletions packages/databricks-vscode/src/features/ssh/SshTunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@ import { CancelledError, UserFacingError } from "../../platform/errors";
import type { Logger } from "../../platform/log";
import { when } from "../../platform/reactive";
import { detectShellKind, type ShellKind } from "../../platform/shell";
import { settingId } from "../../platform/settings";
import type { QuickInputFactory } from "../../platform/ui/quickPick";
import {
EXTENSIONS_ALLOWED,
findHostCliInInstall,
hostCliCommand,
hostIde,
isHostCliOnPath,
isRemoteSshAllowed,
pathSetupDocs,
remoteSshExtension,
} from "./host";
Expand Down Expand Up @@ -63,6 +66,7 @@ export class SshTunnel {
this.deps.log.error("Failed to handle the host CLI PATH prompt", e),
);
}
this.ensureRemoteSshAllowed(ide);
await this.ensureRemoteSsh(ide);
const connection = await this.connect();
const compute = await pickSshCompute({
Expand Down Expand Up @@ -112,6 +116,35 @@ export class SshTunnel {
}
}

/**
* When `extensions.allowed` blocks Remote-SSH, installing it fails and
* the tunnel can't open its window; say so before anything starts,
* with the way to the setting.
*/
private ensureRemoteSshAllowed(ide: SshIde): void {
if (isRemoteSshAllowed(ide, this.deps.kernel.settings.get(EXTENSIONS_ALLOWED))) {
return;
}
const { id } = remoteSshExtension(ide);
throw new UserFacingError(
"EXTENSION_NOT_ALLOWED",
`The 'Remote - SSH' extension is required to start an SSH tunnel, but installing it is blocked. ` +
`Please modify the 'extensions.allowed' setting to allow '${id}', then try again.`,
{
actions: [
{
title: "Open setting",
run: () =>
commands.executeCommand(
"workbench.action.openSettings",
settingId(EXTENSIONS_ALLOWED),
),
},
],
},
);
}

/**
* The remote window needs the editor's Remote-SSH extension, in a
* version the CLI accepts. The CLI would install or update it too
Expand Down
81 changes: 81 additions & 0 deletions packages/databricks-vscode/src/features/ssh/host.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import {
hostCliCommand,
hostIde,
isHostCliOnPath,
isRemoteSshAllowed,
remoteSshExtension,
} from "./host";

const VSCODE_SSH = "ms-vscode-remote.remote-ssh";
const CURSOR_SSH = "anysphere.remote-ssh";

const log = fakeLog();

describe("the host editor", () => {
Expand Down Expand Up @@ -110,6 +114,83 @@ describe("the PATH probe", () => {
});
});

describe("whether extensions.allowed lets Remote-SSH run", () => {
it.each<[string, unknown]>([
["the setting is unset", undefined],
['the setting is the string "*"', "*"],
["all extensions are allowed", { "*": true }],
["the publisher is allowed", { "*": false, "ms-vscode-remote": true }],
[
'Microsoft is allowed through the "microsoft" special case',
{ "*": false, "microsoft": true },
],
["the extension is allowed", { "*": false, [VSCODE_SSH]: true }],
[
"only stable releases of the extension are allowed",
{ "*": false, [VSCODE_SSH]: "stable" },
],
[
"specific versions of the extension are allowed",
{ "*": false, [VSCODE_SSH]: ["0.120.0"] },
],
[
"the extension is allowed though its publisher is blocked",
{ "*": true, "ms-vscode-remote": false, [VSCODE_SSH]: true },
],
[
"only unrelated extensions are blocked",
{ "*": true, "other-publisher": false, "other.ext": false },
],
["the setting is null", null],
["the setting is an array", [VSCODE_SSH]],
[
"the extension is allowed with different casing",
{ "*": false, [VSCODE_SSH.toUpperCase()]: true },
],
["Microsoft is allowed with different casing", { "*": false, "Microsoft": true }],
])("allows it in VS Code when %s", (_name, allowed) => {
expect(isRemoteSshAllowed("vscode", allowed)).toBe(true);
});

it.each<[string, unknown]>([
["all extensions are blocked", { "*": false }],
[
"only unrelated extensions are allowed",
{ "*": false, "other-publisher": true, "anysphere": true },
],
[
"the extension is blocked though its publisher is allowed",
{ "*": false, "ms-vscode-remote": true, [VSCODE_SSH]: false },
],
[
"the extension is blocked though Microsoft is allowed",
{ "*": false, "microsoft": true, [VSCODE_SSH]: false },
],
[
"the extension is blocked under an allow-all wildcard",
{ "*": true, [VSCODE_SSH]: false },
],
[
"the publisher is blocked under an allow-all wildcard",
{ "*": true, "ms-vscode-remote": false },
],
["Microsoft is blocked under an allow-all wildcard", { "*": true, "microsoft": false }],
[
"the extension is blocked with different casing",
{ "*": true, [VSCODE_SSH.toUpperCase()]: false },
],
])("blocks it in VS Code when %s", (_name, allowed) => {
expect(isRemoteSshAllowed("vscode", allowed)).toBe(false);
});

it("checks Cursor's extension and publisher in Cursor, not VS Code's or Microsoft's", () => {
expect(isRemoteSshAllowed("cursor", { "*": false, [VSCODE_SSH]: true })).toBe(false);
expect(isRemoteSshAllowed("cursor", { "*": false, "microsoft": true })).toBe(false);
expect(isRemoteSshAllowed("cursor", { "*": false, "anysphere": true })).toBe(true);
expect(isRemoteSshAllowed("cursor", { "*": true, [CURSOR_SSH]: false })).toBe(false);
});
});

describe("the editor's command in its install folder", () => {
const tempDir = useTempDirs();

Expand Down
36 changes: 36 additions & 0 deletions packages/databricks-vscode/src/features/ssh/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { REMOTE_SSH_CURSOR, REMOTE_SSH_VSCODE } from "../../kernel/extensionDepe
import type { ExtensionDependency } from "../../platform/extensions";
import type { Logger } from "../../platform/log";
import type { ProcessRunner } from "../../platform/process";
import { setting } from "../../platform/settings";

/*
* The editor the tunnel opens its remote window in, and the two things that
Expand Down Expand Up @@ -70,6 +71,41 @@ export function remoteSshExtension(ide: SshIde): ExtensionDependency {
return ide === "cursor" ? REMOTE_SSH_CURSOR : REMOTE_SSH_VSCODE;
}

/**
* VS Code's `extensions.allowed` policy. Anything but a plain object (unset,
* the string `"*"`, null, an array) allows everything; otherwise keys are
* extension IDs, publishers or `"*"`, matched case-insensitively, and only
* `false` blocks: other values restrict versions or release channels.
*/
export const EXTENSIONS_ALLOWED = setting<unknown>("extensions", "allowed", undefined);

/**
* Whether `extensions.allowed` lets the editor's Remote-SSH extension run.
* VS Code applies the most specific rule: the extension ID, then its
* publisher, then `"*"`. In VS Code the publisher `microsoft` also covers
* Microsoft's extensions whatever their publisher ID; Cursor's isn't one.
*/
export function isRemoteSshAllowed(ide: SshIde, allowed: unknown): boolean {
if (typeof allowed !== "object" || allowed === null || Array.isArray(allowed)) {
return true;
}
// VS Code lowercases the keys; extension IDs are lowercase already.
const rules: Readonly<Record<string, unknown>> = Object.fromEntries(
Object.entries(allowed).map(([key, value]) => [key.toLowerCase(), value]),
);
const { id } = remoteSshExtension(ide);
if (rules[id] !== undefined) {
return rules[id] !== false;
}
const publisher = id.slice(0, id.indexOf("."));
const publishers = ide === "cursor" ? [publisher] : ["microsoft", publisher];
const publisherRules = publishers.map((p) => rules[p]).filter((r) => r !== undefined);
if (publisherRules.length > 0) {
return publisherRules.every((r) => r !== false);
}
return rules["*"] !== false;
}

/** Where to read how to put the shell command on PATH. */
export function pathSetupDocs(ide: SshIde): string {
return ide === "cursor"
Expand Down
69 changes: 66 additions & 3 deletions packages/databricks-vscode/src/features/ssh/ssh.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os from "node:os";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { registerFeatures, startFeatures } from "../../kernel/feature";
import { CancelledError } from "../../platform/errors";
import { CancelledError, type UserFacingError } from "../../platform/errors";
import { MutableState, when } from "../../platform/reactive";
import { environmentOf, PROBE_ENV, PROBE_SETTINGS } from "../../test-support/childEnvironment";
import { apiCluster, FakeClusters } from "../../test-support/fakeClusters";
Expand Down Expand Up @@ -33,7 +33,12 @@ function deferred() {
* With `probe`, the host env and settings tell the child environments apart.
*/
async function setup(
options: { project?: boolean; overrides?: Record<string, unknown>; probe?: boolean } = {},
options: {
project?: boolean;
overrides?: Record<string, unknown>;
probe?: boolean;
settings?: Record<string, unknown>;
} = {},
) {
const t = tempDir();
const config = t.write(".databrickscfg", `[DEFAULT]\nhost = ${A}\ntoken = dapi-default\n`);
Expand Down Expand Up @@ -82,7 +87,10 @@ async function setup(
DATABRICKS_TOKEN: "ambient",
PATH: "/usr/bin",
},
settings: fakeSettings(options.probe ? { ...PROBE_SETTINGS } : {}),
settings: fakeSettings({
...(options.probe ? PROBE_SETTINGS : {}),
...options.settings,
}),
httpClient: http,
folders: new MutableState<readonly string[]>(folders),
files: new FakeFileEvents(),
Expand Down Expand Up @@ -489,6 +497,61 @@ describe("starting the SSH tunnel (SSH-01)", () => {
expect(signIn).not.toHaveBeenCalled();
expect(vscode.quickInputs).toHaveLength(0);
});

it("stops before installing Remote-SSH, signing in or picking compute when extensions.allowed blocks it", async () => {
const s = await setup({ settings: { "extensions.allowed": { "*": false } } });
vscode.extensions.clear();
const signIn = vi.fn(async () => {});
const error = await s
.tunnel({ signIn })
.start()
.then(
() => undefined,
(e: unknown) => e as UserFacingError,
);
expect(error).toMatchObject({
code: "EXTENSION_NOT_ALLOWED",
userMessage:
"The 'Remote - SSH' extension is required to start an SSH tunnel, but installing it is blocked. " +
"Please modify the 'extensions.allowed' setting to allow 'ms-vscode-remote.remote-ssh', then try again.",
});
expect(vscode.executed.map((e) => e.command)).not.toContain(
"workbench.extensions.installExtension",
);
expect(signIn).not.toHaveBeenCalled();
expect(vscode.quickInputs).toHaveLength(0);

expect(error!.actions.map((a) => a.title)).toEqual(["Open setting"]);
await error!.actions[0]!.run();
expect(vscode.executed).toContainEqual({
command: "workbench.action.openSettings",
args: ["extensions.allowed"],
});
});

it("names Cursor's Remote-SSH when extensions.allowed blocks it in Cursor", async () => {
const s = await setup({
settings: { "extensions.allowed": { "*": false, "microsoft": true } },
});
env.uriScheme = "cursor";
await expect(s.tunnel().start()).rejects.toMatchObject({
code: "EXTENSION_NOT_ALLOWED",
userMessage: expect.stringContaining("allow 'anysphere.remote-ssh'"),
});
});

it("carries on when extensions.allowed allows Remote-SSH", async () => {
const s = await setup({
settings: {
"extensions.allowed": { "*": false, "ms-vscode-remote.remote-ssh": "stable" },
},
});
const started = s.tunnel().start();
await vi.waitFor(() => expect(vscode.quickInputs).toHaveLength(1));
s.picker().accept(SERVERLESS_LABEL);
await started;
expect(vscode.terminals).toHaveLength(1);
});
});

describe("the host CLI hint", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ describe("SSH tunnel transfer", () => {
processes: kernel.processes,
childEnv: (options?: Parameters<Kernel["childEnv"]>[0]) => kernel.childEnv(options),
extensionDependencies: kernel.extensionDependencies,
settings: kernel.settings,
connection: {
state: new MutableState<ConnectionState>({
status: "connected",
Expand Down