Preserve ordered SSH and proxy connection layers (#802)

* Preserve ordered SSH and proxy connection layers

Replace separate SSH/proxy connection fields with ordered transport_layers while keeping legacy migration and secret fallback paths intact. The UI now edits SSH tunnel/proxy layers in configured order without a global SSH enable gate.

Constraint: Existing saved SSH tunnels, proxy settings, and secret-store keys must continue to load through migration.
Rejected: Folding proxy fields into SshTunnelConfig | mixes proxy semantics into an SSH-specific structure.
Confidence: high
Scope-risk: moderate
Directive: Keep SSH/proxy structs provider-specific; put cross-layer chaining in transport_layer_tunnel orchestration.
Tested: git diff --check; cargo fmt --check; cargo check --workspace; cargo test -p dbx-core --lib; vue-tsc --noEmit --project apps/desktop/tsconfig.json; tsc -p packages/node-core/tsconfig.json --noEmit; oxlint --vue-plugin apps/desktop/src; tsx --tsconfig apps/desktop/tsconfig.json --test packages/app-tests/*.test.ts; tsx --test packages/node-core/tests/*.test.ts
Not-tested: Live external SSH/proxy/database endpoint integration.

* Keep ordered transport changes CI-format clean

Constraint: CI pnpm check failed only on oxfmt formatting for two desktop TypeScript files
Confidence: high
Scope-risk: narrow
Directive: Keep generated/editor config changes out of this PR fix commit
Tested: PATH="/Volumes/data/code/rust/dbx/node_modules/.bin:/Users/hekx/.codex/tmp/arg0/codex-arg0nuL34n:/Users/hekx/.cargo/bin:/Users/hekx/.local/bin:/opt/homebrew/opt/llvm/bin:/opt/homebrew/opt/libpq/bin:/Volumes/data/Users/hekx/.opencode/bin:/Users/hekx/.bun/bin:/Volumes/data/sdks/flutter/bin:/Volumes/data/Users/hekx/.cargo/bin:/Users/hekx/.local/bin:/opt/homebrew/opt/llvm/bin:/opt/homebrew/opt/libpq/bin:/Volumes/data/Users/hekx/.opencode/bin:/Users/hekx/.bun/bin:/Volumes/data/Users/hekx/Library/pnpm:/Volumes/data/sdks/flutter/bin:/Volumes/data/Users/hekx/.cargo/bin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/pkg/env/global/bin:/opt/X11/bin:/Library/Apple/usr/bin:/Applications/Wireshark.app/Contents/MacOS:/usr/local/go/bin:/opt/homebrew/bin:/opt/podman/bin:/Applications/Ghostty.app/Contents/MacOS" rtk node scripts/run-check.mjs
Not-tested: GitHub Actions rerun not observed locally

* Keep Rust checks warning-clean

Constraint: cargo clippy --workspace --all-targets --all-features -- -D warnings failed across core, web, and tauri crates
Rejected: Broad workspace-level clippy suppression | kept allows local to long-argument command/API boundaries
Confidence: high
Scope-risk: moderate
Directive: Preserve src-tauri/tauri.conf.json as an unrelated local change outside this commit
Tested: rtk cargo clippy --workspace --all-targets --all-features -- -D warnings
Not-tested: Full GitHub Actions rerun not observed locally

* Reuse existing proxy tunnels on retry

Proxy tunnel startup now mirrors SSH tunnel behavior by returning the existing local port for an active connection id instead of replacing the managed handle. A second map check aborts a just-spawned duplicate handle if a concurrent retry won the race before insertion, preventing orphaned listeners while keeping the change narrow.

Constraint: Reviewer requested proxy tunnel behavior align with SSH local-port reuse

Rejected: Always overwrite and abort the previous handle | less consistent with SSH behavior and churns listeners during retries

Confidence: high

Scope-risk: narrow

Tested: cargo fmt --check --all

Tested: cargo test -p dbx-core db::proxy_tunnel::tests::start_tunnel_reuses_existing_local_port

Tested: cargo clippy -p dbx-core --all-targets -- -D warnings

---------

Co-authored-by: hekx <hekx@momandeMac-mini.local>
Co-authored-by: caisin <caisin@caisins-Mac-mini.local>
This commit is contained in:
Caisin
2026-06-06 23:22:29 +08:00
committed by GitHub
co-authored by hekx caisin
parent 0c3572d779
commit e9ee982843
54 changed files with 1869 additions and 1188 deletions
@@ -9,7 +9,14 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { ConnectionConfig, DatabaseType, JdbcDriverInfo, SshTunnelConfig } from "@/types/database";
import type {
ConnectionConfig,
DatabaseType,
JdbcDriverInfo,
ProxyTunnelConfig,
SshTunnelConfig,
TransportLayerConfig,
} from "@/types/database";
import { useConnectionStore } from "@/stores/connectionStore";
import { useToast } from "@/composables/useToast";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
@@ -45,7 +52,28 @@ type DbOption = { value: string; label: string };
type DbCategory = { key: string; title: string; options: DbOption[] };
type DialogStep = "select" | "config";
type DbPickerView = "icon" | "list";
type ConfigTab = "connection" | "advanced" | "tls" | "ssh" | "proxy";
type ConfigTab = "connection" | "advanced" | "tls" | "transport";
type LegacyTransportFields = {
ssh_enabled?: boolean;
ssh_host?: string;
ssh_port?: number;
ssh_user?: string;
ssh_password?: string;
ssh_key_path?: string;
ssh_key_passphrase?: string;
ssh_expose_lan?: boolean;
ssh_connect_timeout_secs?: number;
ssh_tunnels?: SshTunnelConfig[];
proxy_enabled?: boolean;
proxy_type?: "socks5" | "http";
proxy_host?: string;
proxy_port?: number;
proxy_username?: string;
proxy_password?: string;
};
type LegacyConnectionConfig = ConnectionConfig & LegacyTransportFields;
type ConnectionForm = Omit<ConnectionConfig, "id">;
const { t } = useI18n();
const { toast } = useToast();
@@ -71,7 +99,7 @@ const testResult = ref<{ ok: boolean; message: string } | null>(null);
const editingId = ref<string | null>(null);
let testRunId = 0;
const defaultForm = (): Omit<ConnectionConfig, "id"> => ({
const defaultForm = (): ConnectionForm => ({
name: "",
db_type: "mysql",
driver_profile: "mysql",
@@ -83,24 +111,9 @@ const defaultForm = (): Omit<ConnectionConfig, "id"> => ({
password: "",
database: undefined,
color: "",
ssh_enabled: false,
ssh_host: "",
ssh_port: 22,
ssh_user: "",
ssh_password: "",
ssh_key_path: "",
ssh_key_passphrase: "",
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
ssh_tunnels: [],
transport_layers: [],
connect_timeout_secs: 5,
query_timeout_secs: 30,
proxy_enabled: false,
proxy_type: "socks5",
proxy_host: "",
proxy_port: 1080,
proxy_username: "",
proxy_password: "",
ssl: false,
ca_cert_path: "",
sysdba: false,
@@ -149,7 +162,62 @@ function normalizeSshTunnel(hop: Partial<SshTunnelConfig>): SshTunnelConfig {
};
}
function sshTunnelsForConfig(config: ConnectionConfig): SshTunnelConfig[] {
function defaultProxyTunnel(): ProxyTunnelConfig {
return {
id: uuid(),
name: "",
enabled: true,
proxy_type: "socks5",
host: "",
port: 1080,
username: "",
password: "",
};
}
function normalizeProxyTunnel(layer: Partial<ProxyTunnelConfig>): ProxyTunnelConfig {
return {
id: layer.id || uuid(),
name: layer.name || "",
enabled: layer.enabled !== false,
proxy_type: layer.proxy_type || "socks5",
host: layer.host || "",
port: Number(layer.port) || 1080,
username: layer.username || "",
password: layer.password || "",
};
}
function normalizeTransportLayer(layer: Partial<TransportLayerConfig>): TransportLayerConfig {
if (layer.type === "proxy") {
return { type: "proxy", ...normalizeProxyTunnel(layer) };
}
return { type: "ssh", ...normalizeSshTunnel(layer as Partial<SshTunnelConfig>) };
}
function transportLayersForConfig(config: LegacyConnectionConfig): TransportLayerConfig[] {
if (config.transport_layers?.length) {
return config.transport_layers.map(normalizeTransportLayer);
}
const layers: TransportLayerConfig[] = sshLayersForConfig(config).map((hop) => ({ type: "ssh", ...hop }));
if (config.proxy_enabled || config.proxy_host || config.proxy_username || config.proxy_password) {
layers.push({
type: "proxy",
...normalizeProxyTunnel({
id: "legacy-proxy",
enabled: true,
proxy_type: config.proxy_type || "socks5",
host: config.proxy_host || "",
port: config.proxy_port || 1080,
username: config.proxy_username || "",
password: config.proxy_password || "",
}),
});
}
return layers;
}
function sshLayersForConfig(config: LegacyConnectionConfig): SshTunnelConfig[] {
if (config.ssh_tunnels?.length) {
return config.ssh_tunnels.map(normalizeSshTunnel);
}
@@ -180,8 +248,8 @@ function sshTunnelsForConfig(config: ConnectionConfig): SshTunnelConfig[] {
}
const form = ref(defaultForm());
const selectedSshTunnelId = ref<string | null>(null);
const draggedSshTunnelId = ref<string | null>(null);
const selectedTransportLayerId = ref<string | null>(null);
const draggedTransportLayerId = ref<string | null>(null);
const selectedType = ref("mysql");
const customDriverName = ref("");
const mongoUseUrl = ref(false);
@@ -422,6 +490,7 @@ watch(
() => props.editConfig,
(config) => {
if (config) {
const legacyConfig = config as LegacyConnectionConfig;
const profile = profileForConfig(config);
editingId.value = config.id;
const profileConfig = driverProfiles[profile];
@@ -437,24 +506,9 @@ watch(
password: config.password,
database: config.database,
color: config.color || "",
ssh_enabled: config.ssh_enabled || false,
ssh_host: config.ssh_host || "",
ssh_port: config.ssh_port || 22,
ssh_user: config.ssh_user || "",
ssh_password: config.ssh_password || "",
ssh_key_path: config.ssh_key_path || "",
ssh_key_passphrase: config.ssh_key_passphrase || "",
ssh_expose_lan: config.ssh_expose_lan || false,
ssh_connect_timeout_secs: config.ssh_connect_timeout_secs || 5,
ssh_tunnels: sshTunnelsForConfig(config),
transport_layers: transportLayersForConfig(legacyConfig),
connect_timeout_secs: config.connect_timeout_secs || 5,
query_timeout_secs: config.query_timeout_secs ?? 30,
proxy_enabled: config.proxy_enabled || false,
proxy_type: config.proxy_type || "socks5",
proxy_host: config.proxy_host || "",
proxy_port: config.proxy_port || 1080,
proxy_username: config.proxy_username || "",
proxy_password: config.proxy_password || "",
ssl: config.ssl || false,
ca_cert_path: config.ca_cert_path || "",
sysdba: config.sysdba || isOracleSysUser(config),
@@ -470,7 +524,7 @@ watch(
redis_sentinel_tls: config.redis_sentinel_tls || false,
redis_cluster_nodes: config.redis_cluster_nodes || "",
};
selectedSshTunnelId.value = form.value.ssh_tunnels?.[0]?.id || null;
selectedTransportLayerId.value = form.value.transport_layers?.[0]?.id || null;
selectedType.value = profile;
if (profile === "oceanbase") {
oceanbaseSubMode.value = config.driver_profile === "oceanbase-oracle" ? "oracle" : "mysql";
@@ -486,7 +540,7 @@ watch(
} else {
editingId.value = null;
form.value = defaultForm();
selectedSshTunnelId.value = null;
selectedTransportLayerId.value = null;
selectedType.value = "mysql";
customDriverName.value = "";
oceanbaseSubMode.value = "mysql";
@@ -516,16 +570,25 @@ const databasePlaceholder = computed(() => {
return t("connection.databasePlaceholderWithDefault", { database: fallback });
});
const sshTunnels = computed(() => form.value.ssh_tunnels || []);
const selectedSshTunnel = computed(() => {
const tunnels = sshTunnels.value;
return tunnels.find((hop) => hop.id === selectedSshTunnelId.value) || tunnels[0] || null;
const transportLayers = computed(() => form.value.transport_layers || []);
const selectedTransportLayer = computed(() => {
const layers = transportLayers.value;
return layers.find((layer) => layer.id === selectedTransportLayerId.value) || layers[0] || null;
});
const sshPathSegments = computed(() => {
const hops = sshTunnels.value.filter((hop) => hop.enabled !== false);
const selectedSshLayer = computed(() =>
selectedTransportLayer.value?.type === "ssh" ? selectedTransportLayer.value : null,
);
const selectedProxyLayer = computed(() =>
selectedTransportLayer.value?.type === "proxy" ? selectedTransportLayer.value : null,
);
const transportPathSegments = computed(() => {
const layers = transportLayers.value.filter((layer) => layer.enabled !== false);
return [
"DBX",
...hops.map((hop, index) => hop.name?.trim() || hop.host?.trim() || `SSH ${index + 1}`),
...layers.map((layer, index) => {
const fallback = layer.type === "proxy" ? `Proxy ${index + 1}` : `SSH ${index + 1}`;
return layer.name?.trim() || layer.host?.trim() || fallback;
}),
form.value.host || "Database",
];
});
@@ -784,10 +847,7 @@ const redisTlsInsecure = computed({
form.value.url_params = setUrlParam(form.value.url_params, "insecure", value ? "true" : "");
},
});
const canUseSsh = computed(() => form.value.db_type !== "sqlite" && form.value.db_type !== "access");
const canUseProxy = computed(
() => form.value.db_type !== "sqlite" && form.value.db_type !== "duckdb" && form.value.db_type !== "access",
);
const canUseTransportLayers = computed(() => form.value.db_type !== "sqlite" && form.value.db_type !== "access");
const shouldShowAgentDriverInstallHint = computed(() =>
showAgentDriverInstallHint(form.value.db_type, agentDrivers.value, form.value.driver_profile),
);
@@ -881,36 +941,23 @@ function generateConnectionName(): string {
}
function connectionConfigForSubmit(id: string): ConnectionConfig {
const config: ConnectionConfig = { ...form.value, id };
const config = { ...form.value, id } as LegacyConnectionConfig;
if (!config.name?.trim()) {
config.name = generateConnectionName();
}
const sshTimeout = Number(config.ssh_connect_timeout_secs);
config.ssh_connect_timeout_secs = Number.isFinite(sshTimeout) && sshTimeout > 0 ? sshTimeout : 5;
config.ssh_tunnels = (config.ssh_tunnels || []).map((hop) => {
const normalized = normalizeSshTunnel(hop);
config.transport_layers = (config.transport_layers || []).map(normalizeTransportLayer);
config.transport_layers = config.transport_layers.map((layer) => {
if (layer.type !== "ssh") return layer;
const normalized = normalizeSshTunnel(layer);
const timeout = Number(normalized.connect_timeout_secs);
normalized.connect_timeout_secs = Number.isFinite(timeout) && timeout > 0 ? timeout : 5;
return normalized;
return { type: "ssh", ...normalized };
});
const firstSshTunnel = config.ssh_tunnels[0];
if (firstSshTunnel) {
config.ssh_host = firstSshTunnel.host;
config.ssh_port = firstSshTunnel.port;
config.ssh_user = firstSshTunnel.user;
config.ssh_password = firstSshTunnel.password || "";
config.ssh_key_path = firstSshTunnel.key_path || "";
config.ssh_key_passphrase = firstSshTunnel.key_passphrase || "";
config.ssh_expose_lan = !!firstSshTunnel.expose_lan;
config.ssh_connect_timeout_secs = firstSshTunnel.connect_timeout_secs || config.ssh_connect_timeout_secs;
}
validateSshTunnels(config);
validateTransportLayers(config);
const connectTimeout = Number(config.connect_timeout_secs);
config.connect_timeout_secs = Number.isFinite(connectTimeout) && connectTimeout > 0 ? connectTimeout : 5;
const queryTimeout = Number(config.query_timeout_secs);
config.query_timeout_secs = Number.isFinite(queryTimeout) && queryTimeout >= 0 ? queryTimeout : 30;
const proxyPort = Number(config.proxy_port);
config.proxy_port = Number.isFinite(proxyPort) && proxyPort > 0 ? proxyPort : 1080;
if (!config.one_time) config.one_time = undefined;
if (config.db_type === "mongodb" && !mongoUseUrl.value) {
config.connection_string = undefined;
@@ -978,7 +1025,24 @@ function connectionConfigForSubmit(id: string): ConnectionConfig {
.map((path) => path.trim())
.filter(Boolean);
}
return config;
const legacy = config as LegacyConnectionConfig;
delete legacy.ssh_enabled;
delete legacy.ssh_host;
delete legacy.ssh_port;
delete legacy.ssh_user;
delete legacy.ssh_password;
delete legacy.ssh_key_path;
delete legacy.ssh_key_passphrase;
delete legacy.ssh_expose_lan;
delete legacy.ssh_connect_timeout_secs;
delete legacy.ssh_tunnels;
delete legacy.proxy_enabled;
delete legacy.proxy_type;
delete legacy.proxy_host;
delete legacy.proxy_port;
delete legacy.proxy_username;
delete legacy.proxy_password;
return config as ConnectionConfig;
}
function getUrlParam(params: string | undefined, key: string): string {
@@ -1174,8 +1238,8 @@ async function copyTestResult() {
function resetForm() {
editingId.value = null;
form.value = defaultForm();
selectedSshTunnelId.value = null;
draggedSshTunnelId.value = null;
selectedTransportLayerId.value = null;
draggedTransportLayerId.value = null;
selectedType.value = "mysql";
customDriverName.value = "";
mongoUseUrl.value = false;
@@ -1290,14 +1354,8 @@ watch([() => form.value.db_type, () => form.value.username], () => {
if (isOracleSysUser(form.value)) form.value.sysdba = true;
});
watch(canUseSsh, (value) => {
if (!value && configTab.value === "ssh") {
configTab.value = "connection";
}
});
watch(canUseProxy, (value) => {
if (!value && configTab.value === "proxy") {
watch(canUseTransportLayers, (value) => {
if (!value && configTab.value === "transport") {
configTab.value = "connection";
}
});
@@ -1308,76 +1366,105 @@ watch(supportsTlsToggle, (value) => {
}
});
function ensureSelectedSshTunnel() {
if (!selectedSshTunnelId.value || !sshTunnels.value.some((hop) => hop.id === selectedSshTunnelId.value)) {
selectedSshTunnelId.value = sshTunnels.value[0]?.id || null;
function ensureSelectedTransportLayer() {
if (
!selectedTransportLayerId.value ||
!transportLayers.value.some((layer) => layer.id === selectedTransportLayerId.value)
) {
selectedTransportLayerId.value = transportLayers.value[0]?.id || null;
}
}
function addSshTunnel() {
const next = defaultSshTunnel();
next.name = t("connection.sshHopDefaultName", { index: sshTunnels.value.length + 1 });
form.value.ssh_tunnels = [...sshTunnels.value, next];
form.value.ssh_enabled = true;
selectedSshTunnelId.value = next.id;
const next: TransportLayerConfig = { type: "ssh", ...defaultSshTunnel() };
next.name = t("connection.sshHopDefaultName", { index: transportLayers.value.length + 1 });
form.value.transport_layers = [...transportLayers.value, next];
selectedTransportLayerId.value = next.id;
resetTestState();
}
function duplicateSshTunnel(hop: SshTunnelConfig) {
const next = { ...normalizeSshTunnel(hop), id: uuid(), name: hop.name ? `${hop.name} copy` : "" };
form.value.ssh_tunnels = [...sshTunnels.value, next];
selectedSshTunnelId.value = next.id;
function addProxyTunnel() {
const next: TransportLayerConfig = { type: "proxy", ...defaultProxyTunnel() };
next.name = `Proxy ${transportLayers.value.length + 1}`;
form.value.transport_layers = [...transportLayers.value, next];
selectedTransportLayerId.value = next.id;
resetTestState();
}
function removeSshTunnel(id: string) {
form.value.ssh_tunnels = sshTunnels.value.filter((hop) => hop.id !== id);
ensureSelectedSshTunnel();
function duplicateTransportLayer(layer: TransportLayerConfig) {
const next = normalizeTransportLayer({ ...layer, id: uuid(), name: layer.name ? `${layer.name} copy` : "" });
form.value.transport_layers = [...transportLayers.value, next];
selectedTransportLayerId.value = next.id;
resetTestState();
}
function moveSshTunnel(id: string, direction: -1 | 1) {
const tunnels = [...sshTunnels.value];
const index = tunnels.findIndex((hop) => hop.id === id);
function removeTransportLayer(id: string) {
form.value.transport_layers = transportLayers.value.filter((layer) => layer.id !== id);
ensureSelectedTransportLayer();
resetTestState();
}
function moveTransportLayer(id: string, direction: -1 | 1) {
const layers = [...transportLayers.value];
const index = layers.findIndex((layer) => layer.id === id);
const target = index + direction;
if (index < 0 || target < 0 || target >= tunnels.length) return;
[tunnels[index], tunnels[target]] = [tunnels[target], tunnels[index]];
form.value.ssh_tunnels = tunnels;
if (index < 0 || target < 0 || target >= layers.length) return;
[layers[index], layers[target]] = [layers[target], layers[index]];
form.value.transport_layers = layers;
resetTestState();
}
function dropSshTunnel(targetId: string) {
const sourceId = draggedSshTunnelId.value;
draggedSshTunnelId.value = null;
function dropTransportLayer(targetId: string) {
const sourceId = draggedTransportLayerId.value;
draggedTransportLayerId.value = null;
if (!sourceId || sourceId === targetId) return;
const tunnels = [...sshTunnels.value];
const sourceIndex = tunnels.findIndex((hop) => hop.id === sourceId);
const targetIndex = tunnels.findIndex((hop) => hop.id === targetId);
const layers = [...transportLayers.value];
const sourceIndex = layers.findIndex((layer) => layer.id === sourceId);
const targetIndex = layers.findIndex((layer) => layer.id === targetId);
if (sourceIndex < 0 || targetIndex < 0) return;
const [source] = tunnels.splice(sourceIndex, 1);
tunnels.splice(targetIndex, 0, source);
form.value.ssh_tunnels = tunnels;
const [source] = layers.splice(sourceIndex, 1);
layers.splice(targetIndex, 0, source);
form.value.transport_layers = layers;
resetTestState();
}
function validateSshTunnels(config: ConnectionConfig) {
if (!config.ssh_enabled) return;
const tunnels = config.ssh_tunnels || [];
tunnels.forEach((hop, index) => {
if (hop.enabled === false) return;
const label = hop.name?.trim() || t("connection.sshHopDefaultName", { index: index + 1 });
if (!hop.host?.trim()) throw new Error(t("connection.sshHopInvalidHost", { hop: label }));
if (!hop.user?.trim()) throw new Error(t("connection.sshHopInvalidUser", { hop: label }));
const port = Number(hop.port);
function changeSelectedTransportLayerType(type: "ssh" | "proxy") {
const selected = selectedTransportLayer.value;
if (!selected || selected.type === type) return;
const replacement: TransportLayerConfig =
type === "proxy"
? { type: "proxy", ...defaultProxyTunnel(), id: selected.id, name: selected.name }
: { type: "ssh", ...defaultSshTunnel(), id: selected.id, name: selected.name };
form.value.transport_layers = transportLayers.value.map((layer) => (layer.id === selected.id ? replacement : layer));
resetTestState();
}
function updateSelectedProxyType(value: unknown) {
const layer = selectedProxyLayer.value;
if (!layer) return;
layer.proxy_type = value === "http" ? "http" : "socks5";
resetTestState();
}
function validateTransportLayers(config: LegacyConnectionConfig) {
const layers = config.transport_layers || [];
layers.forEach((layer, index) => {
if (layer.enabled === false) return;
const label = layer.name?.trim() || t("connection.sshHopDefaultName", { index: index + 1 });
if (!layer.host?.trim()) throw new Error(t("connection.sshHopInvalidHost", { hop: label }));
const port = Number(layer.port);
if (!Number.isFinite(port) || port < 1 || port > 65535) {
throw new Error(t("connection.sshHopInvalidPort", { hop: label }));
}
if (!hop.password?.trim() && !hop.key_path?.trim()) {
throw new Error(t("connection.sshHopInvalidAuth", { hop: label }));
}
const timeout = Number(hop.connect_timeout_secs);
if (!Number.isFinite(timeout) || timeout < 1 || timeout > 300) {
throw new Error(t("connection.sshHopInvalidTimeout", { hop: label }));
if (layer.type === "ssh") {
if (!layer.user?.trim()) throw new Error(t("connection.sshHopInvalidUser", { hop: label }));
if (!layer.password?.trim() && !layer.key_path?.trim()) {
throw new Error(t("connection.sshHopInvalidAuth", { hop: label }));
}
const timeout = Number(layer.connect_timeout_secs);
if (!Number.isFinite(timeout) || timeout < 1 || timeout > 300) {
throw new Error(t("connection.sshHopInvalidTimeout", { hop: label }));
}
}
});
}
@@ -1436,8 +1523,6 @@ async function browseSshKeyPath(target?: SshTunnelConfig | null) {
if (selected && typeof selected === "string") {
if (target) {
target.key_path = selected;
} else {
form.value.ssh_key_path = selected;
}
}
}
@@ -1761,8 +1846,9 @@ function openExternalUrl(url: string) {
<TabsList>
<TabsTrigger value="connection">{{ t("connection.basicTab") }}</TabsTrigger>
<TabsTrigger v-if="supportsTlsToggle" value="tls">{{ t("connection.tlsTab") }}</TabsTrigger>
<TabsTrigger v-if="canUseSsh" value="ssh">{{ t("connection.sshTunnel") }}</TabsTrigger>
<TabsTrigger v-if="canUseProxy" value="proxy">{{ t("connection.proxy") }}</TabsTrigger>
<TabsTrigger v-if="canUseTransportLayers" value="transport">{{
t("connection.sshTunnel")
}}</TabsTrigger>
<TabsTrigger value="advanced">{{ t("connection.advancedTab") }}</TabsTrigger>
</TabsList>
</div>
@@ -2640,50 +2726,43 @@ function openExternalUrl(url: string) {
</div>
</TabsContent>
<TabsContent v-if="canUseSsh" value="ssh" class="m-0">
<TabsContent v-if="canUseTransportLayers" value="transport" class="m-0">
<div class="grid gap-4 py-4 pr-2 max-h-[65vh] overflow-y-auto">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshTunnel") }}</Label>
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="form.ssh_enabled" class="mr-0" />
<span class="text-xs text-muted-foreground">{{ t("connection.sshEnable") }}</span>
</label>
</div>
<div class="grid grid-cols-4 items-start gap-4">
<Label class="pt-2 text-right text-xs">{{ t("connection.sshHops") }}</Label>
<div class="col-span-3 grid gap-3">
<div class="flex flex-wrap items-center gap-1 text-[11px] text-muted-foreground">
<template v-for="(segment, index) in sshPathSegments" :key="`${segment}-${index}`">
<template v-for="(segment, index) in transportPathSegments" :key="`${segment}-${index}`">
<span class="rounded border bg-muted/40 px-2 py-1">{{ segment }}</span>
<ChevronRight v-if="index < sshPathSegments.length - 1" class="h-3 w-3" />
<ChevronRight v-if="index < transportPathSegments.length - 1" class="h-3 w-3" />
</template>
</div>
<div class="grid gap-2">
<button
v-for="(hop, index) in sshTunnels"
v-for="(hop, index) in transportLayers"
:key="hop.id"
type="button"
draggable="true"
class="flex min-h-10 items-center gap-2 rounded-md border px-2 text-left text-xs transition-colors"
:class="hop.id === selectedSshTunnel?.id ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'"
:disabled="!form.ssh_enabled"
@click="selectedSshTunnelId = hop.id"
@dragstart="draggedSshTunnelId = hop.id"
:class="
hop.id === selectedTransportLayer?.id ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'
"
@click="selectedTransportLayerId = hop.id"
@dragstart="draggedTransportLayerId = hop.id"
@dragover.prevent
@drop="dropSshTunnel(hop.id)"
@drop="dropTransportLayer(hop.id)"
>
<GripVertical class="h-4 w-4 shrink-0 text-muted-foreground" />
<span class="w-5 shrink-0 text-muted-foreground">{{ index + 1 }}</span>
<input
v-model="hop.enabled"
type="checkbox"
class="mr-0"
:disabled="!form.ssh_enabled"
@click.stop
/>
<input v-model="hop.enabled" type="checkbox" class="mr-0" @click.stop />
<span class="min-w-0 flex-1 truncate">
{{ hop.name || hop.host || t("connection.sshHopDefaultName", { index: index + 1 }) }}
{{
hop.name ||
hop.host ||
(hop.type === "proxy"
? `Proxy ${index + 1}`
: t("connection.sshHopDefaultName", { index: index + 1 }))
}}
</span>
<Tooltip>
<TooltipTrigger as-child>
@@ -2691,8 +2770,8 @@ function openExternalUrl(url: string) {
variant="ghost"
size="icon"
class="h-7 w-7"
:disabled="index === 0 || !form.ssh_enabled"
@click.stop="moveSshTunnel(hop.id, -1)"
:disabled="index === 0"
@click.stop="moveTransportLayer(hop.id, -1)"
>
<ArrowUp class="h-3.5 w-3.5" />
</Button>
@@ -2705,8 +2784,8 @@ function openExternalUrl(url: string) {
variant="ghost"
size="icon"
class="h-7 w-7"
:disabled="index === sshTunnels.length - 1 || !form.ssh_enabled"
@click.stop="moveSshTunnel(hop.id, 1)"
:disabled="index === transportLayers.length - 1"
@click.stop="moveTransportLayer(hop.id, 1)"
>
<ArrowDown class="h-3.5 w-3.5" />
</Button>
@@ -2716,34 +2795,30 @@ function openExternalUrl(url: string) {
</button>
</div>
<div class="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
:disabled="!form.ssh_enabled"
@click="addSshTunnel"
>
<Button type="button" variant="outline" size="sm" @click="addSshTunnel">
<Plus class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.sshHopAdd") }}
</Button>
<Button type="button" variant="outline" size="sm" @click="addProxyTunnel">
<Plus class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.proxy") }}
</Button>
<Button
v-if="selectedSshTunnel"
v-if="selectedTransportLayer"
type="button"
variant="outline"
size="sm"
:disabled="!form.ssh_enabled"
@click="duplicateSshTunnel(selectedSshTunnel)"
@click="duplicateTransportLayer(selectedTransportLayer)"
>
<Copy class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.sshHopDuplicate") }}
</Button>
<Button
v-if="selectedSshTunnel"
v-if="selectedTransportLayer"
type="button"
variant="outline"
size="sm"
:disabled="!form.ssh_enabled"
@click="removeSshTunnel(selectedSshTunnel.id)"
@click="removeTransportLayer(selectedTransportLayer.id)"
>
<Trash2 class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.sshHopDelete") }}
@@ -2752,179 +2827,182 @@ function openExternalUrl(url: string) {
</div>
</div>
<template v-if="selectedSshTunnel">
<template v-if="selectedTransportLayer">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshHopName") }}</Label>
<Input
v-model="selectedSshTunnel.name"
v-model="selectedTransportLayer.name"
class="col-span-3"
:placeholder="t('connection.sshHopNamePlaceholder')"
:disabled="!form.ssh_enabled"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshHost") }}</Label>
<Input
v-model="selectedSshTunnel.host"
class="col-span-2"
placeholder="ssh.example.com"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
/>
<Input
v-model.number="selectedSshTunnel.port"
type="number"
min="1"
max="65535"
class="col-span-1"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshUser") }}</Label>
<Input
v-model="selectedSshTunnel.user"
class="col-span-3"
placeholder="root"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshPassword") }}</Label>
<Input
v-model="selectedSshTunnel.password"
type="password"
class="col-span-3"
:placeholder="t('connection.sshPasswordPlaceholder')"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshKeyPath") }}</Label>
<div class="col-span-3 flex items-center gap-1">
<Input
v-model="selectedSshTunnel.key_path"
class="flex-1"
placeholder="~/.ssh/id_rsa"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
/>
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
<Button
variant="outline"
size="icon"
class="h-9 w-9 shrink-0"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
@click="browseSshKeyPath(selectedSshTunnel)"
>
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{{ t("connection.sshKeyPathBrowse") }}</TooltipContent>
</Tooltip>
</div>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshKeyPassphrase") }}</Label>
<Input
v-model="selectedSshTunnel.key_passphrase"
type="password"
class="col-span-3"
:placeholder="t('connection.sshKeyPassphrasePlaceholder')"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label
class="col-span-3 flex items-center gap-2"
:class="form.ssh_enabled ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'"
<Label class="text-right text-xs">Type</Label>
<Select
:model-value="selectedTransportLayer.type"
@update:model-value="(value: any) => changeSelectedTransportLayerType(value)"
>
<input
type="checkbox"
v-model="selectedSshTunnel.expose_lan"
class="mr-0"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
<SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ssh">SSH</SelectItem>
<SelectItem value="proxy">Proxy</SelectItem>
</SelectContent>
</Select>
</div>
<template v-if="selectedSshLayer">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshHost") }}</Label>
<Input
v-model="selectedSshLayer.host"
class="col-span-2"
placeholder="ssh.example.com"
:disabled="selectedSshLayer.enabled === false"
/>
<span class="text-xs text-muted-foreground">{{ t("connection.sshExposeLan") }}</span>
</label>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshConnectTimeout") }}</Label>
<Input
v-model.number="selectedSshTunnel.connect_timeout_secs"
type="number"
min="1"
max="300"
step="1"
class="col-span-3"
:disabled="!form.ssh_enabled || selectedSshTunnel.enabled === false"
/>
</div>
<Input
v-model.number="selectedSshLayer.port"
type="number"
min="1"
max="65535"
class="col-span-1"
:disabled="selectedSshLayer.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshUser") }}</Label>
<Input
v-model="selectedSshLayer.user"
class="col-span-3"
placeholder="root"
:disabled="selectedSshLayer.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshPassword") }}</Label>
<Input
v-model="selectedSshLayer.password"
type="password"
class="col-span-3"
:placeholder="t('connection.sshPasswordPlaceholder')"
:disabled="selectedSshLayer.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshKeyPath") }}</Label>
<div class="col-span-3 flex items-center gap-1">
<Input
v-model="selectedSshLayer.key_path"
class="flex-1"
placeholder="~/.ssh/id_rsa"
:disabled="selectedSshLayer.enabled === false"
/>
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
<Button
variant="outline"
size="icon"
class="h-9 w-9 shrink-0"
:disabled="selectedSshLayer.enabled === false"
@click="browseSshKeyPath(selectedSshLayer)"
>
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{{ t("connection.sshKeyPathBrowse") }}</TooltipContent>
</Tooltip>
</div>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshKeyPassphrase") }}</Label>
<Input
v-model="selectedSshLayer.key_passphrase"
type="password"
class="col-span-3"
:placeholder="t('connection.sshKeyPassphrasePlaceholder')"
:disabled="selectedSshLayer.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
v-model="selectedSshLayer.expose_lan"
class="mr-0"
:disabled="selectedSshLayer.enabled === false"
/>
<span class="text-xs text-muted-foreground">{{ t("connection.sshExposeLan") }}</span>
</label>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshConnectTimeout") }}</Label>
<Input
v-model.number="selectedSshLayer.connect_timeout_secs"
type="number"
min="1"
max="300"
step="1"
class="col-span-3"
:disabled="selectedSshLayer.enabled === false"
/>
</div>
</template>
<template v-else-if="selectedProxyLayer">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyType") }}</Label>
<Select
:model-value="selectedProxyLayer.proxy_type || 'socks5'"
:disabled="selectedProxyLayer.enabled === false"
@update:model-value="updateSelectedProxyType"
>
<SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="socks5">SOCKS5</SelectItem>
<SelectItem value="http">HTTP CONNECT</SelectItem>
</SelectContent>
</Select>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyHost") }}</Label>
<Input
v-model="selectedProxyLayer.host"
class="col-span-2"
placeholder="127.0.0.1"
:disabled="selectedProxyLayer.enabled === false"
/>
<Input
v-model.number="selectedProxyLayer.port"
type="number"
class="col-span-1"
:disabled="selectedProxyLayer.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyUsername") }}</Label>
<Input
v-model="selectedProxyLayer.username"
class="col-span-3"
:placeholder="t('connection.proxyUsernamePlaceholder')"
:disabled="selectedProxyLayer.enabled === false"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyPassword") }}</Label>
<Input
v-model="selectedProxyLayer.password"
type="password"
class="col-span-3"
:placeholder="t('connection.proxyPasswordPlaceholder')"
:disabled="selectedProxyLayer.enabled === false"
/>
</div>
</template>
</template>
</div>
</TabsContent>
<TabsContent v-if="canUseProxy" value="proxy" class="m-0">
<div class="grid gap-4 py-4 pr-2 max-h-[65vh] overflow-y-auto">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxy") }}</Label>
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="form.proxy_enabled" class="mr-0" />
<span class="text-xs text-muted-foreground">{{ t("connection.proxyEnable") }}</span>
</label>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyType") }}</Label>
<Select
:model-value="form.proxy_type || 'socks5'"
:disabled="!form.proxy_enabled"
@update:model-value="(value: any) => (form.proxy_type = value)"
>
<SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="socks5">SOCKS5</SelectItem>
<SelectItem value="http">HTTP CONNECT</SelectItem>
</SelectContent>
</Select>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyHost") }}</Label>
<Input
v-model="form.proxy_host"
class="col-span-2"
placeholder="127.0.0.1"
:disabled="!form.proxy_enabled"
/>
<Input
v-model.number="form.proxy_port"
type="number"
class="col-span-1"
:disabled="!form.proxy_enabled"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyUsername") }}</Label>
<Input
v-model="form.proxy_username"
class="col-span-3"
:placeholder="t('connection.proxyUsernamePlaceholder')"
:disabled="!form.proxy_enabled"
/>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyPassword") }}</Label>
<Input
v-model="form.proxy_password"
type="password"
class="col-span-3"
:placeholder="t('connection.proxyPasswordPlaceholder')"
:disabled="!form.proxy_enabled"
/>
</div>
</div>
</TabsContent>
</Tabs>
</div>
+6 -6
View File
@@ -229,9 +229,9 @@ export default {
duplicated: "Connection duplicated",
groupDeleted: "Group deleted",
loadFailed: "Failed to load saved connections: {message}",
sshTunnel: "SSH Tunnel",
sshTunnel: "SSH Tunnel / Proxy",
advancedTab: "Advanced",
sshEnable: "Connect via SSH tunnel",
sshEnable: "Use SSH tunnel / proxy",
sshHost: "SSH Host",
sshUser: "SSH User",
sshPassword: "SSH Password",
@@ -242,15 +242,15 @@ export default {
sshKeyPathBrowse: "Browse",
sshExposeLan: "Expose tunnel to LAN",
sshConnectTimeout: "SSH Timeout (seconds)",
sshHops: "SSH Hops",
sshHopAdd: "Add hop",
sshHops: "SSH Tunnel / Proxy Layers",
sshHopAdd: "Add SSH layer",
sshHopDuplicate: "Duplicate",
sshHopDelete: "Delete",
sshHopMoveUp: "Move up",
sshHopMoveDown: "Move down",
sshHopName: "Hop Name",
sshHopName: "Layer Name",
sshHopNamePlaceholder: "Bastion, jump host, production gateway",
sshHopDefaultName: "Hop {index}",
sshHopDefaultName: "Layer {index}",
sshHopInvalidHost: "{hop}: SSH host is required",
sshHopInvalidUser: "{hop}: SSH user is required",
sshHopInvalidPort: "{hop}: SSH port must be between 1 and 65535",
+6 -6
View File
@@ -221,9 +221,9 @@ export default {
duplicated: "Conexión duplicada",
groupDeleted: "Grupo eliminado",
loadFailed: "Error al cargar las conexiones guardadas: {message}",
sshTunnel: "Túnel SSH",
sshTunnel: "Túnel SSH / Proxy",
advancedTab: "Avanzado",
sshEnable: "Conectar mediante túnel SSH",
sshEnable: "Usar túnel SSH / proxy",
sshHost: "Host SSH",
sshUser: "Usuario SSH",
sshPassword: "Contraseña SSH",
@@ -234,15 +234,15 @@ export default {
sshKeyPathBrowse: "Examinar",
sshExposeLan: "Exponer túnel a la red local",
sshConnectTimeout: "Tiempo de espera SSH (segundos)",
sshHops: "Saltos SSH",
sshHopAdd: "Agregar salto",
sshHops: "Capas de túnel SSH / proxy",
sshHopAdd: "Agregar capa SSH",
sshHopDuplicate: "Duplicar",
sshHopDelete: "Eliminar",
sshHopMoveUp: "Subir",
sshHopMoveDown: "Bajar",
sshHopName: "Nombre del salto",
sshHopName: "Nombre de la capa",
sshHopNamePlaceholder: "Bastión, jump host, puerta de producción",
sshHopDefaultName: "Salto {index}",
sshHopDefaultName: "Capa {index}",
sshHopInvalidHost: "{hop}: el host SSH es obligatorio",
sshHopInvalidUser: "{hop}: el usuario SSH es obligatorio",
sshHopInvalidPort: "{hop}: el puerto SSH debe estar entre 1 y 65535",
+6 -6
View File
@@ -232,9 +232,9 @@ export default {
duplicated: "Connessione duplicata",
groupDeleted: "Gruppo eliminato",
loadFailed: "Impossibile caricare le connessioni salvate: {message}",
sshTunnel: "Tunnel SSH",
sshTunnel: "Tunnel SSH / Proxy",
advancedTab: "Avanzate",
sshEnable: "Connetti tramite tunnel SSH",
sshEnable: "Usa tunnel SSH / proxy",
sshHost: "Host SSH",
sshUser: "Utente SSH",
sshPassword: "Password SSH",
@@ -245,15 +245,15 @@ export default {
sshKeyPathBrowse: "Sfoglia",
sshExposeLan: "Esponi tunnel alla LAN",
sshConnectTimeout: "Timeout SSH (secondi)",
sshHops: "Hop SSH",
sshHopAdd: "Aggiungi hop",
sshHops: "Livelli tunnel SSH / proxy",
sshHopAdd: "Aggiungi livello SSH",
sshHopDuplicate: "Duplica",
sshHopDelete: "Elimina",
sshHopMoveUp: "Sposta su",
sshHopMoveDown: "Sposta giù",
sshHopName: "Nome Hop",
sshHopName: "Nome livello",
sshHopNamePlaceholder: "Bastion, jump host, gateway di produzione",
sshHopDefaultName: "Hop {index}",
sshHopDefaultName: "Livello {index}",
sshHopInvalidHost: "{hop}: Host SSH richiesto",
sshHopInvalidUser: "{hop}: Utente SSH richiesto",
sshHopInvalidPort: "{hop}: La porta SSH deve essere compresa tra 1 e 65535",
+6 -6
View File
@@ -231,9 +231,9 @@ export default {
duplicated: "Conexão duplicada",
groupDeleted: "Grupo excluído",
loadFailed: "Falha ao carregar as conexões salvas: {message}",
sshTunnel: "Túnel SSH",
sshTunnel: "Túnel SSH / Proxy",
advancedTab: "Avançado",
sshEnable: "Conectar via túnel SSH",
sshEnable: "Usar túnel SSH / proxy",
sshHost: "Host SSH",
sshUser: "Usuário SSH",
sshPassword: "Senha SSH",
@@ -244,15 +244,15 @@ export default {
sshKeyPathBrowse: "Procurar",
sshExposeLan: "Expor túnel à LAN",
sshConnectTimeout: "Timeout SSH (segundos)",
sshHops: "Saltos SSH",
sshHopAdd: "Adicionar salto",
sshHops: "Camadas de túnel SSH / proxy",
sshHopAdd: "Adicionar camada SSH",
sshHopDuplicate: "Duplicar",
sshHopDelete: "Excluir",
sshHopMoveUp: "Mover para cima",
sshHopMoveDown: "Mover para baixo",
sshHopName: "Nome do Salto",
sshHopName: "Nome da Camada",
sshHopNamePlaceholder: "Bastion, host de salto, gateway de produção",
sshHopDefaultName: "Salto {index}",
sshHopDefaultName: "Camada {index}",
sshHopInvalidHost: "{hop}: o host SSH é obrigatório",
sshHopInvalidUser: "{hop}: o usuário SSH é obrigatório",
sshHopInvalidPort: "{hop}: a porta SSH deve estar entre 1 e 65535",
+6 -6
View File
@@ -225,9 +225,9 @@ export default {
duplicated: "连接已复制",
groupDeleted: "分组已删除",
loadFailed: "加载已保存连接失败:{message}",
sshTunnel: "SSH 隧道",
sshTunnel: "SSH 隧道/代理",
advancedTab: "高级",
sshEnable: "通过 SSH 隧道连接",
sshEnable: "使用 SSH 隧道/代理连接",
sshHost: "SSH 主机",
sshUser: "SSH 用户",
sshPassword: "SSH 密码",
@@ -238,15 +238,15 @@ export default {
sshKeyPathBrowse: "浏览",
sshExposeLan: "允许局域网访问隧道",
sshConnectTimeout: "SSH 超时时间(秒)",
sshHops: "SSH 层级",
sshHopAdd: "添加层级",
sshHops: "SSH 隧道/代理层级",
sshHopAdd: "添加 SSH 层",
sshHopDuplicate: "复制",
sshHopDelete: "删除",
sshHopMoveUp: "上移",
sshHopMoveDown: "下移",
sshHopName: "层级名称",
sshHopName: "连接层名称",
sshHopNamePlaceholder: "堡垒机、跳板机、生产网关",
sshHopDefaultName: "第 {index} 跳",
sshHopDefaultName: "第 {index} 层",
sshHopInvalidHost: "{hop}:SSH 主机不能为空",
sshHopInvalidUser: "{hop}:SSH 用户不能为空",
sshHopInvalidPort: "{hop}:SSH 端口必须在 1 到 65535 之间",
+5 -5
View File
@@ -225,9 +225,9 @@ export default {
duplicated: "連線已複製",
groupDeleted: "群組已刪除",
loadFailed: "載入已儲存連線失敗:{message}",
sshTunnel: "SSH 隧道",
sshTunnel: "SSH 隧道/代理",
advancedTab: "進階",
sshEnable: "藉由 SSH 隧道連線",
sshEnable: "使用 SSH 隧道/代理連線",
sshHost: "SSH 主機",
sshUser: "SSH 使用者",
sshPassword: "SSH 密碼",
@@ -238,13 +238,13 @@ export default {
sshKeyPathBrowse: "瀏覽",
sshExposeLan: "允許區域網路存取隧道",
sshConnectTimeout: "SSH 逾時時間(秒)",
sshHops: "SSH 層級",
sshHopAdd: "新增層級",
sshHops: "SSH 隧道/代理層級",
sshHopAdd: "新增 SSH 層",
sshHopDuplicate: "複製",
sshHopDelete: "刪除",
sshHopMoveUp: "上移",
sshHopMoveDown: "下移",
sshHopName: "層級名稱",
sshHopName: "連線層名稱",
sshHopNamePlaceholder: "堡壘機、跳板機、生產閘道器",
sshHopDefaultName: "第 {index} 層",
sshHopInvalidHost: "{hop}:SSH 主機不能為空",
@@ -9,14 +9,13 @@ function positiveSeconds(value: unknown, fallback: number): number {
}
export function connectionAttemptTimeoutMs(
config: Pick<ConnectionConfig, "connect_timeout_secs" | "ssh_enabled" | "ssh_connect_timeout_secs" | "ssh_tunnels"> &
config: Pick<ConnectionConfig, "connect_timeout_secs" | "transport_layers"> &
Partial<Pick<ConnectionConfig, "db_type">>,
): number {
const timeouts = [positiveSeconds(config.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS)];
if (config.ssh_enabled) {
timeouts.push(positiveSeconds(config.ssh_connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS));
for (const tunnel of config.ssh_tunnels ?? []) {
timeouts.push(positiveSeconds(tunnel.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS));
for (const layer of config.transport_layers ?? []) {
if (layer.type === "ssh") {
timeouts.push(positiveSeconds(layer.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS));
}
}
const fallbackBuffer = config.db_type === "mongodb" ? MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS : 0;
+1 -9
View File
@@ -222,15 +222,7 @@ function buildConnection(
password: credentials.password || getString(parsedUrl.password),
database: database || undefined,
color: getString(config.color || config["connection-color"]),
ssh_enabled: false,
ssh_host: "",
ssh_port: 22,
ssh_user: "",
ssh_password: "",
ssh_key_path: "",
ssh_key_passphrase: "",
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
transport_layers: [],
connect_timeout_secs: 5,
query_timeout_secs: 30,
ssl: false,
+1 -9
View File
@@ -155,15 +155,7 @@ async function parseConnection(node: ParsedNode): Promise<ConnectionConfig | nul
password,
database: database || undefined,
color: "",
ssh_enabled: false,
ssh_host: "",
ssh_port: 22,
ssh_user: "",
ssh_password: "",
ssh_key_path: "",
ssh_key_passphrase: "",
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
transport_layers: [],
connect_timeout_secs: 5,
query_timeout_secs: 30,
ssl: false,
+1 -4
View File
@@ -290,12 +290,9 @@ export const useConnectionStore = defineStore("connection", () => {
attached_databases: Array.isArray(config.attached_databases)
? config.attached_databases.filter((database) => database.name?.trim() && database.path?.trim())
: [],
ssh_connect_timeout_secs: config.ssh_connect_timeout_secs || 5,
ssh_tunnels: Array.isArray(config.ssh_tunnels) ? config.ssh_tunnels : [],
transport_layers: Array.isArray(config.transport_layers) ? config.transport_layers : [],
connect_timeout_secs: config.connect_timeout_secs || 5,
query_timeout_secs: config.query_timeout_secs ?? 30,
proxy_type: config.proxy_type || "socks5",
proxy_port: config.proxy_port || 1080,
};
}
+14 -16
View File
@@ -69,24 +69,9 @@ export interface ConnectionConfig {
visible_databases?: string[];
attached_databases?: AttachedDatabaseConfig[];
color?: string;
ssh_enabled?: boolean;
ssh_host?: string;
ssh_port?: number;
ssh_user?: string;
ssh_password?: string;
ssh_key_path?: string;
ssh_key_passphrase?: string;
ssh_expose_lan?: boolean;
ssh_connect_timeout_secs?: number;
ssh_tunnels?: SshTunnelConfig[];
transport_layers?: TransportLayerConfig[];
connect_timeout_secs?: number;
query_timeout_secs?: number;
proxy_enabled?: boolean;
proxy_type?: "socks5" | "http";
proxy_host?: string;
proxy_port?: number;
proxy_username?: string;
proxy_password?: string;
ssl?: boolean;
ca_cert_path?: string;
sysdba?: boolean;
@@ -104,6 +89,8 @@ export interface ConnectionConfig {
one_time?: boolean;
}
export type TransportLayerConfig = ({ type: "ssh" } & SshTunnelConfig) | ({ type: "proxy" } & ProxyTunnelConfig);
export interface SshTunnelConfig {
id: string;
name?: string;
@@ -118,6 +105,17 @@ export interface SshTunnelConfig {
expose_lan?: boolean;
}
export interface ProxyTunnelConfig {
id: string;
name?: string;
enabled?: boolean;
proxy_type?: "socks5" | "http";
host: string;
port: number;
username?: string;
password?: string;
}
export interface AttachedDatabaseConfig {
name: string;
path: string;
+2 -19
View File
@@ -202,9 +202,7 @@ fn append_agent_url_params(base: String, params: Option<&str>) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::models::connection::{
default_connect_timeout_secs, default_query_timeout_secs, default_ssh_connect_timeout_secs, ProxyType,
};
use crate::models::connection::{default_connect_timeout_secs, default_query_timeout_secs};
fn config(db_type: DatabaseType, database: Option<&str>) -> ConnectionConfig {
ConnectionConfig {
@@ -222,24 +220,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: default_ssh_connect_timeout_secs(),
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: default_connect_timeout_secs(),
query_timeout_secs: default_query_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
+1
View File
@@ -419,6 +419,7 @@ async fn install_agent_driver_from_registry(
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn download_with_progress(
am: &AgentManager,
progress: &impl Fn(AgentProgressEvent),
+2 -2
View File
@@ -1063,9 +1063,9 @@ mod tests {
}))
.unwrap();
assert_eq!(config.proxy_enabled, false);
assert!(!config.proxy_enabled);
assert_eq!(config.proxy_url, "");
assert_eq!(config.enable_thinking, true);
assert!(config.enable_thinking);
}
#[test]
+74 -53
View File
@@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::ai::AiConfig;
use crate::models::connection::ConnectionConfig;
use crate::models::connection::{ConnectionConfig, TransportLayerConfig};
use crate::saved_sql::SavedSqlLibrary;
use crate::storage::{DesktopSettings, Storage};
@@ -25,6 +25,7 @@ const SECRET_KEYS: &[&str] = &[
"connection_string",
];
const SSH_TUNNEL_SECRET_PREFIX: &str = "ssh_tunnels.";
const TRANSPORT_LAYER_SECRET_PREFIX: &str = "transport_layers.";
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -301,13 +302,17 @@ impl WebDavClient {
fn scrub_connection_secrets(config: &mut ConnectionConfig) {
config.password.clear();
config.ssh_password.clear();
config.ssh_key_passphrase.clear();
for hop in &mut config.ssh_tunnels {
hop.password.clear();
hop.key_passphrase.clear();
for layer in &mut config.transport_layers {
match layer {
TransportLayerConfig::Ssh(ssh) => {
ssh.password.clear();
ssh.key_passphrase.clear();
}
TransportLayerConfig::Proxy(proxy) => {
proxy.password.clear();
}
}
}
config.proxy_password.clear();
config.redis_sentinel_password.clear();
config.connection_string = None;
}
@@ -327,18 +332,32 @@ async fn build_sensitive_payload(
let mut connection_secrets = Vec::new();
for config in connections {
push_secret(&mut connection_secrets, &config.id, "password", &config.password);
push_secret(&mut connection_secrets, &config.id, "ssh_password", &config.ssh_password);
push_secret(&mut connection_secrets, &config.id, "ssh_key_passphrase", &config.ssh_key_passphrase);
for (index, hop) in config.ssh_tunnels.iter().enumerate() {
push_secret(&mut connection_secrets, &config.id, &ssh_tunnel_password_key(index, hop), &hop.password);
push_secret(
&mut connection_secrets,
&config.id,
&ssh_tunnel_key_passphrase_key(index, hop),
&hop.key_passphrase,
);
for (index, layer) in config.transport_layers.iter().enumerate() {
match layer {
TransportLayerConfig::Ssh(ssh) => {
push_secret(
&mut connection_secrets,
&config.id,
&transport_layer_ssh_password_key(index, layer),
&ssh.password,
);
push_secret(
&mut connection_secrets,
&config.id,
&transport_layer_ssh_key_passphrase_key(index, layer),
&ssh.key_passphrase,
);
}
TransportLayerConfig::Proxy(proxy) => {
push_secret(
&mut connection_secrets,
&config.id,
&transport_layer_proxy_password_key(index, layer),
&proxy.password,
);
}
}
}
push_secret(&mut connection_secrets, &config.id, "proxy_password", &config.proxy_password);
push_secret(&mut connection_secrets, &config.id, "redis_sentinel_password", &config.redis_sentinel_password);
if let Some(connection_string) = &config.connection_string {
push_secret(&mut connection_secrets, &config.id, "connection_string", connection_string);
@@ -361,7 +380,10 @@ fn push_secret(secrets: &mut Vec<ConnectionSecretSnapshot>, connection_id: &str,
async fn apply_sensitive_payload(storage: &Storage, payload: &SensitiveSyncPayload) -> Result<(), String> {
for secret in &payload.connection_secrets {
if !SECRET_KEYS.contains(&secret.key.as_str()) && !secret.key.starts_with(SSH_TUNNEL_SECRET_PREFIX) {
if !SECRET_KEYS.contains(&secret.key.as_str())
&& !secret.key.starts_with(SSH_TUNNEL_SECRET_PREFIX)
&& !secret.key.starts_with(TRANSPORT_LAYER_SECRET_PREFIX)
{
continue;
}
storage.set_secret(&secret.connection_id, &secret.key, &secret.secret).await?;
@@ -377,28 +399,40 @@ async fn clear_connection_secrets(storage: &Storage, connections: &[ConnectionCo
for key in SECRET_KEYS {
storage.delete_secret(&config.id, key).await?;
}
for (index, hop) in config.ssh_tunnels.iter().enumerate() {
storage.delete_secret(&config.id, &ssh_tunnel_password_key(index, hop)).await?;
storage.delete_secret(&config.id, &ssh_tunnel_key_passphrase_key(index, hop)).await?;
for (index, layer) in config.transport_layers.iter().enumerate() {
match layer {
TransportLayerConfig::Ssh(_) => {
storage.delete_secret(&config.id, &transport_layer_ssh_password_key(index, layer)).await?;
storage.delete_secret(&config.id, &transport_layer_ssh_key_passphrase_key(index, layer)).await?;
}
TransportLayerConfig::Proxy(_) => {
storage.delete_secret(&config.id, &transport_layer_proxy_password_key(index, layer)).await?;
}
}
}
}
Ok(())
}
fn ssh_tunnel_secret_segment(index: usize, hop: &crate::models::connection::SshTunnelConfig) -> String {
if hop.id.trim().is_empty() {
fn transport_layer_secret_segment(index: usize, layer: &TransportLayerConfig) -> String {
let id = layer.id().trim();
if id.is_empty() {
index.to_string()
} else {
hop.id.clone()
id.to_string()
}
}
fn ssh_tunnel_password_key(index: usize, hop: &crate::models::connection::SshTunnelConfig) -> String {
format!("{}{}.password", SSH_TUNNEL_SECRET_PREFIX, ssh_tunnel_secret_segment(index, hop))
fn transport_layer_ssh_password_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.ssh_password", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn ssh_tunnel_key_passphrase_key(index: usize, hop: &crate::models::connection::SshTunnelConfig) -> String {
format!("{}{}.key_passphrase", SSH_TUNNEL_SECRET_PREFIX, ssh_tunnel_secret_segment(index, hop))
fn transport_layer_ssh_key_passphrase_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.ssh_key_passphrase", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn transport_layer_proxy_password_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.proxy_password", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn encrypt_sensitive_payload(payload: &SensitiveSyncPayload, passphrase: &str) -> Result<EncryptedSecretsBlob, String> {
@@ -496,7 +530,7 @@ mod tests {
decrypt_sensitive_payload, encrypt_sensitive_payload, normalized_remote_path, parent_collection_paths,
scrub_connection_secrets, ConnectionSecretSnapshot, SensitiveSyncPayload,
};
use crate::models::connection::{ConnectionConfig, DatabaseType, ProxyType, SshTunnelConfig};
use crate::models::connection::{ConnectionConfig, DatabaseType, TransportLayerConfig};
#[test]
fn normalizes_empty_remote_path_to_default() {
@@ -527,16 +561,7 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: "ssh".to_string(),
ssh_key_path: String::new(),
ssh_key_passphrase: "key".to_string(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
ssh_tunnels: vec![SshTunnelConfig {
transport_layers: vec![TransportLayerConfig::Ssh(crate::models::connection::SshTunnelConfig {
id: "hop-1".to_string(),
name: String::new(),
enabled: true,
@@ -548,15 +573,9 @@ mod tests {
key_passphrase: "hop-passphrase".to_string(),
connect_timeout_secs: 5,
expose_lan: false,
}],
})],
connect_timeout_secs: 5,
query_timeout_secs: 30,
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: "proxy".to_string(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -576,11 +595,13 @@ mod tests {
};
scrub_connection_secrets(&mut config);
assert!(config.password.is_empty());
assert!(config.ssh_password.is_empty());
assert!(config.ssh_key_passphrase.is_empty());
assert!(config.ssh_tunnels[0].password.is_empty());
assert!(config.ssh_tunnels[0].key_passphrase.is_empty());
assert!(config.proxy_password.is_empty());
match &config.transport_layers[0] {
TransportLayerConfig::Ssh(ssh) => {
assert!(ssh.password.is_empty());
assert!(ssh.key_passphrase.is_empty());
}
TransportLayerConfig::Proxy(_) => panic!("expected ssh layer"),
}
assert!(config.redis_sentinel_password.is_empty());
assert!(config.connection_string.is_none());
}
@@ -596,7 +617,7 @@ mod tests {
},
ConnectionSecretSnapshot {
connection_id: "c1".to_string(),
key: "ssh_tunnels.hop-1.password".to_string(),
key: "transport_layers.hop-1.ssh_password".to_string(),
secret: "hop-secret".to_string(),
},
],
+75 -102
View File
@@ -565,72 +565,21 @@ impl AppState {
connection_id: &str,
config: &ConnectionConfig,
) -> Result<(String, u16), String> {
let ssh_hops = config.effective_ssh_tunnels();
if ssh_hops.is_empty() {
if config.proxy_enabled && !config.proxy_host.is_empty() {
if let Some(local_port) = self.proxy_tunnels.local_port(connection_id).await {
return Ok(("127.0.0.1".to_string(), local_port));
}
let (remote_host, remote_port) = if config.db_type == DatabaseType::MongoDb {
config
.connection_string
.as_deref()
.filter(|s| !s.is_empty())
.and_then(parse_mongo_first_host)
.unwrap_or_else(|| (config.host.clone(), config.port))
} else if config.db_type == DatabaseType::Jdbc {
config
.connection_string
.as_deref()
.filter(|s| !s.is_empty())
.and_then(parse_jdbc_host_port)
.unwrap_or_else(|| (config.host.clone(), config.port))
} else {
(config.host.clone(), config.port)
};
let local_port = self
.proxy_tunnels
.start_tunnel(
connection_id,
config.proxy_type,
&config.proxy_host,
config.proxy_port,
&config.proxy_username,
&config.proxy_password,
&remote_host,
remote_port,
)
.await?;
return Ok(("127.0.0.1".to_string(), local_port));
}
let transport_layers = config.effective_transport_layers();
if transport_layers.is_empty() {
return Ok((config.host.clone(), config.port));
}
if let Some(local_port) = self.tunnels.local_port(connection_id).await {
return Ok(("127.0.0.1".to_string(), local_port));
}
let (remote_host, remote_port) = if config.db_type == DatabaseType::MongoDb {
config
.connection_string
.as_deref()
.filter(|s| !s.is_empty())
.and_then(parse_mongo_first_host)
.unwrap_or_else(|| (config.host.clone(), config.port))
} else if config.db_type == DatabaseType::Jdbc {
config
.connection_string
.as_deref()
.filter(|s| !s.is_empty())
.and_then(parse_jdbc_host_port)
.unwrap_or_else(|| (config.host.clone(), config.port))
} else {
(config.host.clone(), config.port)
};
let local_port = self.tunnels.start_chain(connection_id, &ssh_hops, &remote_host, remote_port).await?;
let (remote_host, remote_port) = connection_remote_endpoint(config);
let local_port = db::transport_layer_tunnel::start_transport_layers(
connection_id,
&transport_layers,
&remote_host,
remote_port,
&self.tunnels,
&self.proxy_tunnels,
)
.await?;
Ok(("127.0.0.1".to_string(), local_port))
}
@@ -778,6 +727,30 @@ impl AppState {
}
pub async fn reset_connection_transport(&self, connection_id: &str) {
let layer_count = {
let configs = self.configs.read().await;
configs.get(connection_id).map(|config| config.effective_transport_layers().len()).unwrap_or(0)
};
self.reset_connection_transport_layers(connection_id, layer_count).await;
}
pub async fn reset_connection_transport_for_config(&self, connection_id: &str, config: &ConnectionConfig) {
let existing_layer_count = {
let configs = self.configs.read().await;
configs.get(connection_id).map(|config| config.effective_transport_layers().len()).unwrap_or(0)
};
let layer_count = existing_layer_count.max(config.effective_transport_layers().len());
self.reset_connection_transport_layers(connection_id, layer_count).await;
}
async fn reset_connection_transport_layers(&self, connection_id: &str, layer_count: usize) {
db::transport_layer_tunnel::stop_transport_layers(
connection_id,
layer_count,
&self.tunnels,
&self.proxy_tunnels,
)
.await;
self.tunnels.stop_tunnel(connection_id).await;
self.proxy_tunnels.stop_tunnel(connection_id).await;
}
@@ -837,25 +810,12 @@ impl AppState {
// Re-establish SSH tunnels that have died
let tunnel_connection_ids: Vec<String> = {
let configs = self.configs.read().await;
configs.iter().filter(|(_, c)| c.has_effective_ssh_tunnels()).map(|(id, _)| id.clone()).collect()
configs.iter().filter(|(_, c)| c.has_effective_transport_layers()).map(|(id, _)| id.clone()).collect()
};
for connection_id in tunnel_connection_ids {
self.tunnels.stop_tunnel(&connection_id).await;
self.reset_connection_transport(&connection_id).await;
// Tunnels will be re-created on next pool access via connection_host_port
}
// Re-establish proxy tunnels
let proxy_connection_ids: Vec<String> = {
let configs = self.configs.read().await;
configs
.iter()
.filter(|(_, c)| c.proxy_enabled && !c.proxy_host.is_empty())
.map(|(id, _)| id.clone())
.collect()
};
for connection_id in proxy_connection_ids {
self.proxy_tunnels.stop_tunnel(&connection_id).await;
}
}
pub async fn remove_connection_pools(&self, connection_id: &str) {
@@ -879,9 +839,27 @@ impl AppState {
async fn uses_forwarded_transport(&self, connection_id: &str) -> bool {
let configs = self.configs.read().await;
configs.get(connection_id).is_some_and(|config| {
config.has_effective_ssh_tunnels() || (config.proxy_enabled && !config.proxy_host.is_empty())
})
configs.get(connection_id).is_some_and(|config| config.has_effective_transport_layers())
}
}
fn connection_remote_endpoint(config: &ConnectionConfig) -> (String, u16) {
if config.db_type == DatabaseType::MongoDb {
config
.connection_string
.as_deref()
.filter(|s| !s.is_empty())
.and_then(parse_mongo_first_host)
.unwrap_or_else(|| (config.host.clone(), config.port))
} else if config.db_type == DatabaseType::Jdbc {
config
.connection_string
.as_deref()
.filter(|s| !s.is_empty())
.and_then(parse_jdbc_host_port)
.unwrap_or_else(|| (config.host.clone(), config.port))
} else {
(config.host.clone(), config.port)
}
}
@@ -1126,7 +1104,10 @@ mod tests {
};
use crate::agent_manager::{AgentState, JavaRuntimeConfig, JavaRuntimeMode, DEFAULT_JRE_KEY};
use crate::db;
use crate::models::connection::{default_connect_timeout_secs, ConnectionConfig, DatabaseType, ProxyType};
use crate::models::connection::{
default_connect_timeout_secs, ConnectionConfig, DatabaseType, ProxyTunnelConfig, ProxyType,
TransportLayerConfig,
};
use crate::query;
use crate::schema;
use crate::storage::Storage;
@@ -1147,24 +1128,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: crate::models::connection::default_ssh_connect_timeout_secs(),
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: default_connect_timeout_secs(),
query_timeout_secs: crate::models::connection::default_query_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -1914,15 +1880,22 @@ mod tests {
async fn proxy_connection_uses_local_forward_endpoint() {
let (state, dir) = test_app_state().await;
let mut config = mysql_config(Some("app"));
config.proxy_enabled = true;
config.proxy_host = "127.0.0.1".to_string();
config.proxy_port = 65000;
config.transport_layers = vec![TransportLayerConfig::Proxy(ProxyTunnelConfig {
id: "proxy".to_string(),
name: String::new(),
enabled: true,
proxy_type: ProxyType::Socks5,
host: "127.0.0.1".to_string(),
port: 65000,
username: String::new(),
password: String::new(),
})];
let (host, port) = state.connection_host_port("proxied", &config).await.unwrap();
assert_eq!(host, "127.0.0.1");
assert_ne!(port, config.port);
state.proxy_tunnels.stop_tunnel("proxied").await;
state.proxy_tunnels.stop_tunnel("proxied:transport:0").await;
let _ = std::fs::remove_dir_all(dir);
}
+218 -92
View File
@@ -1,4 +1,4 @@
use crate::models::connection::ConnectionConfig;
use crate::models::connection::{ConnectionConfig, TransportLayerConfig};
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
@@ -7,6 +7,7 @@ pub const MAIN_PASSWORD_KEY: &str = "password";
pub const SSH_PASSWORD_KEY: &str = "ssh_password";
pub const SSH_KEY_PASSPHRASE_KEY: &str = "ssh_key_passphrase";
pub const SSH_TUNNEL_SECRET_PREFIX: &str = "ssh_tunnels.";
pub const TRANSPORT_LAYER_SECRET_PREFIX: &str = "transport_layers.";
pub const PROXY_PASSWORD_KEY: &str = "proxy_password";
pub const REDIS_SENTINEL_PASSWORD_KEY: &str = "redis_sentinel_password";
pub const CONNECTION_STRING_KEY: &str = "connection_string";
@@ -72,16 +73,19 @@ pub fn save_connections_to_file(
delete_removed_connection_secrets(path, configs, store)?;
for config in configs {
persist_secret(store, &config.id, MAIN_PASSWORD_KEY, &config.password)?;
persist_secret(store, &config.id, SSH_PASSWORD_KEY, &config.ssh_password)?;
persist_secret(store, &config.id, SSH_KEY_PASSPHRASE_KEY, &config.ssh_key_passphrase)?;
delete_secret_prefix(store, &config.id, SSH_TUNNEL_SECRET_PREFIX)?;
for (index, hop) in config.ssh_tunnels.iter().enumerate() {
persist_secret(store, &config.id, &ssh_tunnel_password_key(index, hop), &hop.password)?;
persist_secret(store, &config.id, &ssh_tunnel_key_passphrase_key(index, hop), &hop.key_passphrase)?;
delete_secret_prefix(store, &config.id, TRANSPORT_LAYER_SECRET_PREFIX)?;
for (index, layer) in config.transport_layers.iter().enumerate() {
persist_transport_layer_secrets(store, &config.id, index, layer)?;
}
persist_secret(store, &config.id, PROXY_PASSWORD_KEY, &config.proxy_password)?;
persist_secret(store, &config.id, REDIS_SENTINEL_PASSWORD_KEY, &config.redis_sentinel_password)?;
persist_optional_secret(store, &config.id, CONNECTION_STRING_KEY, config.connection_string.as_deref())?;
// New configs persist transport-layer secrets only. Remove legacy transport secret slots after the
// migrated layer values have been written so old configs do not keep two sources of truth.
store.delete_secret(&config.id, SSH_PASSWORD_KEY)?;
store.delete_secret(&config.id, SSH_KEY_PASSPHRASE_KEY)?;
store.delete_secret(&config.id, PROXY_PASSWORD_KEY)?;
delete_secret_prefix(store, &config.id, SSH_TUNNEL_SECRET_PREFIX)?;
}
write_sanitized_connections(path, configs)
@@ -107,51 +111,7 @@ pub fn load_connections_from_file(
needs_rewrite = true;
}
if config.ssh_password.is_empty() {
if let Some(secret) = store.get_secret(&config.id, SSH_PASSWORD_KEY)? {
config.ssh_password = secret;
}
} else {
store.set_secret(&config.id, SSH_PASSWORD_KEY, &config.ssh_password)?;
needs_rewrite = true;
}
if config.ssh_key_passphrase.is_empty() {
if let Some(secret) = store.get_secret(&config.id, SSH_KEY_PASSPHRASE_KEY)? {
config.ssh_key_passphrase = secret;
}
} else {
store.set_secret(&config.id, SSH_KEY_PASSPHRASE_KEY, &config.ssh_key_passphrase)?;
needs_rewrite = true;
}
for (index, hop) in config.ssh_tunnels.iter_mut().enumerate() {
if hop.password.is_empty() {
if let Some(secret) = store.get_secret(&config.id, &ssh_tunnel_password_key(index, hop))? {
hop.password = secret;
}
} else {
store.set_secret(&config.id, &ssh_tunnel_password_key(index, hop), &hop.password)?;
needs_rewrite = true;
}
if hop.key_passphrase.is_empty() {
if let Some(secret) = store.get_secret(&config.id, &ssh_tunnel_key_passphrase_key(index, hop))? {
hop.key_passphrase = secret;
}
} else {
store.set_secret(&config.id, &ssh_tunnel_key_passphrase_key(index, hop), &hop.key_passphrase)?;
needs_rewrite = true;
}
}
if config.proxy_password.is_empty() {
if let Some(secret) = store.get_secret(&config.id, PROXY_PASSWORD_KEY)? {
config.proxy_password = secret;
}
} else {
store.set_secret(&config.id, PROXY_PASSWORD_KEY, &config.proxy_password)?;
needs_rewrite = true;
}
hydrate_transport_layer_secrets(store, config, &mut needs_rewrite)?;
if config.redis_sentinel_password.is_empty() {
if let Some(secret) = store.get_secret(&config.id, REDIS_SENTINEL_PASSWORD_KEY)? {
@@ -182,6 +142,134 @@ pub fn load_connections_from_file(
Ok(configs)
}
fn persist_transport_layer_secrets(
store: &dyn ConnectionSecretStore,
connection_id: &str,
index: usize,
layer: &TransportLayerConfig,
) -> Result<(), String> {
match layer {
TransportLayerConfig::Ssh(ssh) => {
persist_secret(store, connection_id, &transport_layer_ssh_password_key(index, layer), &ssh.password)?;
persist_secret(
store,
connection_id,
&transport_layer_ssh_key_passphrase_key(index, layer),
&ssh.key_passphrase,
)?;
}
TransportLayerConfig::Proxy(proxy) => {
persist_secret(store, connection_id, &transport_layer_proxy_password_key(index, layer), &proxy.password)?;
}
}
Ok(())
}
fn hydrate_transport_layer_secrets(
store: &dyn ConnectionSecretStore,
config: &mut ConnectionConfig,
needs_rewrite: &mut bool,
) -> Result<(), String> {
for index in 0..config.transport_layers.len() {
let layer_for_key = config.transport_layers[index].clone();
match &mut config.transport_layers[index] {
TransportLayerConfig::Ssh(ssh) => {
let password_key = transport_layer_ssh_password_key(index, &layer_for_key);
if ssh.password.is_empty() {
if let Some(secret) = store.get_secret(&config.id, &password_key)?.or(legacy_ssh_password_secret(
store,
&config.id,
index,
&layer_for_key,
)?) {
ssh.password = secret;
}
} else {
store.set_secret(&config.id, &password_key, &ssh.password)?;
*needs_rewrite = true;
}
let passphrase_key = transport_layer_ssh_key_passphrase_key(index, &layer_for_key);
if ssh.key_passphrase.is_empty() {
if let Some(secret) = store
.get_secret(&config.id, &passphrase_key)?
.or(legacy_ssh_key_passphrase_secret(store, &config.id, index, &layer_for_key)?)
{
ssh.key_passphrase = secret;
}
} else {
store.set_secret(&config.id, &passphrase_key, &ssh.key_passphrase)?;
*needs_rewrite = true;
}
}
TransportLayerConfig::Proxy(proxy) => {
let password_key = transport_layer_proxy_password_key(index, &layer_for_key);
if proxy.password.is_empty() {
if let Some(secret) = store.get_secret(&config.id, &password_key)?.or(legacy_proxy_password_secret(
store,
&config.id,
&layer_for_key,
)?) {
proxy.password = secret;
}
} else {
store.set_secret(&config.id, &password_key, &proxy.password)?;
*needs_rewrite = true;
}
}
}
}
Ok(())
}
fn legacy_ssh_password_secret(
store: &dyn ConnectionSecretStore,
connection_id: &str,
index: usize,
layer: &TransportLayerConfig,
) -> Result<Option<String>, String> {
if let TransportLayerConfig::Ssh(ssh) = layer {
if ssh.id == "legacy" {
if let Some(secret) = store.get_secret(connection_id, SSH_PASSWORD_KEY)? {
return Ok(Some(secret));
}
}
store.get_secret(connection_id, &ssh_tunnel_password_key(index, ssh))
} else {
Ok(None)
}
}
fn legacy_ssh_key_passphrase_secret(
store: &dyn ConnectionSecretStore,
connection_id: &str,
index: usize,
layer: &TransportLayerConfig,
) -> Result<Option<String>, String> {
if let TransportLayerConfig::Ssh(ssh) = layer {
if ssh.id == "legacy" {
if let Some(secret) = store.get_secret(connection_id, SSH_KEY_PASSPHRASE_KEY)? {
return Ok(Some(secret));
}
}
store.get_secret(connection_id, &ssh_tunnel_key_passphrase_key(index, ssh))
} else {
Ok(None)
}
}
fn legacy_proxy_password_secret(
store: &dyn ConnectionSecretStore,
connection_id: &str,
layer: &TransportLayerConfig,
) -> Result<Option<String>, String> {
if matches!(layer, TransportLayerConfig::Proxy(proxy) if proxy.id == "legacy-proxy") {
store.get_secret(connection_id, PROXY_PASSWORD_KEY)
} else {
Ok(None)
}
}
fn delete_removed_connection_secrets(
path: &Path,
configs: &[ConnectionConfig],
@@ -204,6 +292,7 @@ fn delete_removed_connection_secrets(
store.delete_secret(&config.id, SSH_PASSWORD_KEY)?;
store.delete_secret(&config.id, SSH_KEY_PASSPHRASE_KEY)?;
delete_secret_prefix(store, &config.id, SSH_TUNNEL_SECRET_PREFIX)?;
delete_secret_prefix(store, &config.id, TRANSPORT_LAYER_SECRET_PREFIX)?;
store.delete_secret(&config.id, CONNECTION_STRING_KEY)?;
}
Ok(())
@@ -258,6 +347,27 @@ fn ssh_tunnel_key_passphrase_key(index: usize, hop: &crate::models::connection::
format!("{}{}.key_passphrase", SSH_TUNNEL_SECRET_PREFIX, ssh_tunnel_secret_segment(index, hop))
}
fn transport_layer_secret_segment(index: usize, layer: &TransportLayerConfig) -> String {
let id = layer.id().trim();
if id.is_empty() {
index.to_string()
} else {
id.to_string()
}
}
fn transport_layer_ssh_password_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.ssh_password", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn transport_layer_ssh_key_passphrase_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.ssh_key_passphrase", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn transport_layer_proxy_password_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.proxy_password", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn read_connections(path: &Path) -> Result<Vec<ConnectionConfig>, String> {
let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
serde_json::from_str(&json).map_err(|e| e.to_string())
@@ -275,13 +385,17 @@ fn sanitize_connections(configs: &[ConnectionConfig]) -> Vec<ConnectionConfig> {
.cloned()
.map(|mut config| {
config.password.clear();
config.ssh_password.clear();
config.ssh_key_passphrase.clear();
for hop in &mut config.ssh_tunnels {
hop.password.clear();
hop.key_passphrase.clear();
for layer in &mut config.transport_layers {
match layer {
TransportLayerConfig::Ssh(ssh) => {
ssh.password.clear();
ssh.key_passphrase.clear();
}
TransportLayerConfig::Proxy(proxy) => {
proxy.password.clear();
}
}
}
config.proxy_password.clear();
config.redis_sentinel_password.clear();
config.connection_string = None;
config
@@ -299,7 +413,7 @@ mod tests {
load_connections_from_file, save_connections_to_file, ConnectionSecretStore, CONNECTION_STRING_KEY,
MAIN_PASSWORD_KEY, REDIS_SENTINEL_PASSWORD_KEY, SSH_PASSWORD_KEY,
};
use crate::models::connection::{ConnectionConfig, DatabaseType, ProxyType, SshTunnelConfig};
use crate::models::connection::{ConnectionConfig, DatabaseType, SshTunnelConfig, TransportLayerConfig};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;
@@ -358,7 +472,7 @@ mod tests {
dir.join("connections.json")
}
fn connection(id: &str, password: &str, ssh_password: &str) -> ConnectionConfig {
fn connection(id: &str, password: &str, _ssh_password: &str) -> ConnectionConfig {
ConnectionConfig {
id: id.to_string(),
name: format!("{id} connection"),
@@ -374,24 +488,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: !ssh_password.is_empty(),
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: ssh_password.to_string(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: crate::models::connection::default_ssh_connect_timeout_secs(),
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: crate::models::connection::default_connect_timeout_secs(),
query_timeout_secs: crate::models::connection::default_query_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -437,22 +536,25 @@ mod tests {
let path = temp_connections_file("save-redacts");
let store = MemorySecretStore::default();
let mut config = connection("main", "db-secret", "ssh-secret");
config.ssh_tunnels = vec![ssh_hop("hop-1", "hop-secret", "hop-key")];
config.transport_layers = vec![TransportLayerConfig::Ssh(ssh_hop("hop-1", "hop-secret", "hop-key"))];
config.redis_sentinel_password = "sentinel-secret".to_string();
let configs = vec![config];
save_connections_to_file(&path, &configs, &store).unwrap();
assert_eq!(store.get_existing("main", MAIN_PASSWORD_KEY).as_deref(), Some("db-secret"));
assert_eq!(store.get_existing("main", SSH_PASSWORD_KEY).as_deref(), Some("ssh-secret"));
assert_eq!(store.get_existing("main", "ssh_tunnels.hop-1.password").as_deref(), Some("hop-secret"));
assert_eq!(store.get_existing("main", "ssh_tunnels.hop-1.key_passphrase").as_deref(), Some("hop-key"));
assert_eq!(store.get_existing("main", "transport_layers.hop-1.ssh_password").as_deref(), Some("hop-secret"));
assert_eq!(store.get_existing("main", "transport_layers.hop-1.ssh_key_passphrase").as_deref(), Some("hop-key"));
assert_eq!(store.get_existing("main", REDIS_SENTINEL_PASSWORD_KEY).as_deref(), Some("sentinel-secret"));
let persisted = read_configs(&path);
assert_eq!(persisted[0].password, "");
assert_eq!(persisted[0].ssh_password, "");
assert_eq!(persisted[0].ssh_tunnels[0].password, "");
assert_eq!(persisted[0].ssh_tunnels[0].key_passphrase, "");
match &persisted[0].transport_layers[0] {
TransportLayerConfig::Ssh(ssh) => {
assert_eq!(ssh.password, "");
assert_eq!(ssh.key_passphrase, "");
}
TransportLayerConfig::Proxy(_) => panic!("expected ssh layer"),
}
assert_eq!(persisted[0].redis_sentinel_password, "");
}
@@ -466,16 +568,20 @@ mod tests {
store.set_existing("main", "ssh_tunnels.hop-1.key_passphrase", "hop-key");
store.set_existing("main", REDIS_SENTINEL_PASSWORD_KEY, "sentinel-secret");
let mut sanitized_config = connection("main", "", "");
sanitized_config.ssh_tunnels = vec![ssh_hop("hop-1", "", "")];
sanitized_config.transport_layers = vec![TransportLayerConfig::Ssh(ssh_hop("hop-1", "", ""))];
let sanitized = vec![sanitized_config];
std::fs::write(&path, serde_json::to_string_pretty(&sanitized).unwrap()).unwrap();
let loaded = load_connections_from_file(&path, &store).unwrap();
assert_eq!(loaded[0].password, "db-secret");
assert_eq!(loaded[0].ssh_password, "ssh-secret");
assert_eq!(loaded[0].ssh_tunnels[0].password, "hop-secret");
assert_eq!(loaded[0].ssh_tunnels[0].key_passphrase, "hop-key");
match &loaded[0].transport_layers[0] {
TransportLayerConfig::Ssh(ssh) => {
assert_eq!(ssh.password, "hop-secret");
assert_eq!(ssh.key_passphrase, "hop-key");
}
TransportLayerConfig::Proxy(_) => panic!("expected ssh layer"),
}
assert_eq!(loaded[0].redis_sentinel_password, "sentinel-secret");
}
@@ -483,18 +589,38 @@ mod tests {
fn load_connections_migrates_plaintext_passwords_and_rewrites_sanitized_file() {
let path = temp_connections_file("migrates-plaintext");
let store = MemorySecretStore::default();
let legacy = vec![connection("legacy", "plain-db", "plain-ssh")];
let legacy = serde_json::json!([{
"id": "legacy",
"name": "legacy connection",
"db_type": "postgres",
"host": "localhost",
"port": 5432,
"username": "postgres",
"password": "plain-db",
"database": "postgres",
"ssh_enabled": true,
"ssh_host": "bastion",
"ssh_port": 22,
"ssh_user": "user",
"ssh_password": "plain-ssh"
}]);
std::fs::write(&path, serde_json::to_string_pretty(&legacy).unwrap()).unwrap();
let loaded = load_connections_from_file(&path, &store).unwrap();
assert_eq!(loaded[0].password, "plain-db");
assert_eq!(loaded[0].ssh_password, "plain-ssh");
match &loaded[0].transport_layers[0] {
TransportLayerConfig::Ssh(ssh) => assert_eq!(ssh.password, "plain-ssh"),
TransportLayerConfig::Proxy(_) => panic!("expected ssh layer"),
}
assert_eq!(store.get_existing("legacy", MAIN_PASSWORD_KEY).as_deref(), Some("plain-db"));
assert_eq!(store.get_existing("legacy", SSH_PASSWORD_KEY).as_deref(), Some("plain-ssh"));
assert_eq!(store.get_existing("legacy", "transport_layers.legacy.ssh_password").as_deref(), Some("plain-ssh"));
let persisted = read_configs(&path);
assert_eq!(persisted[0].password, "");
assert_eq!(persisted[0].ssh_password, "");
match &persisted[0].transport_layers[0] {
TransportLayerConfig::Ssh(ssh) => assert_eq!(ssh.password, ""),
TransportLayerConfig::Proxy(_) => panic!("expected ssh layer"),
}
}
#[test]
+1 -1
View File
@@ -114,7 +114,7 @@ pub async fn export_table_data_csv_core(state: &AppState, options: TableCsvExpor
.await?;
if !wrote_header {
write_csv_row(&mut writer, result.columns.into_iter())?;
write_csv_row(&mut writer, result.columns)?;
wrote_header = true;
}
+4 -4
View File
@@ -501,6 +501,9 @@ enum SourceDiff {
Modified(DataCompareModifiedRow),
}
type CompareRowValues = HashMap<String, Value>;
type CompareRowMap = HashMap<String, CompareRowValues>;
fn parallel_compare_rows(columns: &[String], key_columns: &[String], rows: &[Vec<Value>]) -> Vec<CompareRow> {
rows.par_iter()
.map(|row| {
@@ -511,10 +514,7 @@ fn parallel_compare_rows(columns: &[String], key_columns: &[String], rows: &[Vec
.collect()
}
fn collect_compare_rows(
rows: Vec<CompareRow>,
label: &str,
) -> Result<(HashMap<String, HashMap<String, Value>>, Vec<String>), String> {
fn collect_compare_rows(rows: Vec<CompareRow>, label: &str) -> Result<(CompareRowMap, Vec<String>), String> {
let mut items = HashMap::with_capacity(rows.len());
let mut order = Vec::with_capacity(rows.len());
+1 -1
View File
@@ -854,7 +854,7 @@ mod tests {
assert_eq!(
sql,
vec![
[
"-- DBX database export".to_string(),
"-- Database: app".to_string(),
"-- Exported at: 2026-05-02T00:00:00.000Z".to_string(),
+1
View File
@@ -13,6 +13,7 @@ pub mod rqlite_driver;
pub mod sqlite;
pub mod sqlserver;
pub mod ssh_tunnel;
pub mod transport_layer_tunnel;
use std::future::Future;
use std::time::Duration;
+1 -1
View File
@@ -1350,7 +1350,7 @@ fn requires_text_protocol_query(sql: &str, dialect: MySqlQueryDialect) -> bool {
fn is_admin_show_query(sql: &str) -> bool {
let tokens = leading_sql_word_tokens(sql, 2);
tokens.get(0).is_some_and(|token| token == "admin") && tokens.get(1).is_some_and(|token| token == "show")
tokens.first().is_some_and(|token| token == "admin") && tokens.get(1).is_some_and(|token| token == "show")
}
fn leading_sql_word_tokens(sql: &str, limit: usize) -> Vec<String> {
+3 -3
View File
@@ -1841,7 +1841,7 @@ mod tests {
let escaped = pg_quote_ident(malicious);
// Double quotes should be doubled, not breaking out
assert_eq!(escaped, r#""public""; DROP TABLE users; --""#);
assert!(escaped.matches('"').count() % 2 == 0, "quote count should be even");
assert!(escaped.matches('"').count().is_multiple_of(2), "quote count should be even");
}
// --- query_result_row_limit ---
@@ -2131,14 +2131,14 @@ mod tests {
#[tokio::test]
async fn execute_batch_whitespace_only_is_filtered() {
let statements = vec![" ".to_string(), "\t\n".to_string(), "".to_string()];
let statements = [" ".to_string(), "\t\n".to_string(), "".to_string()];
let combined = statements.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(";\n");
assert!(combined.is_empty());
}
#[test]
fn execute_batch_joins_with_semicolons() {
let statements = vec!["SELECT 1".to_string(), "SELECT 2".to_string()];
let statements = ["SELECT 1".to_string(), "SELECT 2".to_string()];
let combined = statements.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(";\n");
assert_eq!(combined, "SELECT 1;\nSELECT 2");
}
+37 -1
View File
@@ -31,6 +31,10 @@ impl ProxyTunnelManager {
remote_host: &str,
remote_port: u16,
) -> Result<u16, String> {
if let Some(local_port) = self.local_port(connection_id).await {
return Ok(local_port);
}
let local_port = portpicker::pick_unused_port().ok_or("No available port")?;
let listener = TcpListener::bind(("127.0.0.1", local_port))
.await
@@ -45,7 +49,14 @@ impl ProxyTunnelManager {
};
let remote = RemoteEndpoint { host: remote_host.to_string(), port: remote_port };
let handle = tokio::spawn(proxy_forward_loop(listener, proxy, remote));
self.tunnels.lock().await.insert(connection_id.to_string(), (handle, local_port));
let mut tunnels = self.tunnels.lock().await;
if let Some((_, existing_port)) = tunnels.get(connection_id) {
handle.abort();
return Ok(*existing_port);
}
tunnels.insert(connection_id.to_string(), (handle, local_port));
Ok(local_port)
}
@@ -211,3 +222,28 @@ async fn socks5_authenticate(stream: &mut TcpStream, proxy: &ProxyEndpoint) -> R
Err("SOCKS proxy authentication failed".to_string())
}
}
#[cfg(test)]
mod tests {
use super::ProxyTunnelManager;
use crate::models::connection::ProxyType;
#[tokio::test]
async fn start_tunnel_reuses_existing_local_port() {
let manager = ProxyTunnelManager::new();
let first_port = manager
.start_tunnel("connection", ProxyType::Http, "127.0.0.1", 8080, "", "", "db.internal", 5432)
.await
.expect("first proxy tunnel should start");
let second_port = manager
.start_tunnel("connection", ProxyType::Http, "127.0.0.1", 8081, "", "", "other-db.internal", 5433)
.await
.expect("existing proxy tunnel should be reused");
assert_eq!(second_port, first_port);
assert_eq!(manager.local_port("connection").await, Some(first_port));
manager.stop_tunnel("connection").await;
}
}
+1
View File
@@ -161,6 +161,7 @@ pub fn is_memory_database_path(path: &str) -> bool {
}
#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
use super::*;
@@ -0,0 +1,241 @@
use crate::models::connection::TransportLayerConfig;
use super::proxy_tunnel::ProxyTunnelManager;
use super::ssh_tunnel::TunnelManager;
#[derive(Debug, Clone, PartialEq, Eq)]
struct LayerEndpoint {
host: String,
port: u16,
}
impl LayerEndpoint {
fn localhost(port: u16) -> Self {
Self { host: "127.0.0.1".to_string(), port }
}
}
/// Starts an ordered transport layer chain and returns the final local port.
///
/// Each layer listens on a local port. The next layer connects to that local
/// port, and the last layer forwards to `remote_host:remote_port`.
pub async fn start_transport_layers(
connection_id: &str,
layers: &[TransportLayerConfig],
remote_host: &str,
remote_port: u16,
ssh_tunnels: &TunnelManager,
proxy_tunnels: &ProxyTunnelManager,
) -> Result<u16, String> {
if layers.is_empty() {
return Err("No transport layers configured".to_string());
}
let mut next_connect_endpoint: Option<LayerEndpoint> = None;
let mut final_local_port = 0;
for (index, layer) in layers.iter().enumerate() {
let layer_id = layer_id(connection_id, index);
let is_last = index + 1 == layers.len();
let (layer_host, layer_port) = layer.endpoint();
let connect_endpoint = next_connect_endpoint
.clone()
.unwrap_or_else(|| LayerEndpoint { host: layer_host.to_string(), port: layer_port });
let target_endpoint = if is_last {
LayerEndpoint { host: remote_host.to_string(), port: remote_port }
} else {
let (next_host, next_port) = layers[index + 1].endpoint();
LayerEndpoint { host: next_host.to_string(), port: next_port }
};
let local_port = match layer {
TransportLayerConfig::Ssh(ssh) => ssh_tunnels
.start_tunnel(
&layer_id,
&connect_endpoint.host,
connect_endpoint.port,
&ssh.user,
&ssh.password,
&ssh.key_path,
&ssh.key_passphrase,
effective_ssh_connect_timeout_secs(ssh.connect_timeout_secs),
&target_endpoint.host,
target_endpoint.port,
is_last && ssh.expose_lan,
)
.await
.map_err(|err| format!("SSH layer {} failed: {err}", index + 1))?,
TransportLayerConfig::Proxy(proxy) => proxy_tunnels
.start_tunnel(
&layer_id,
proxy.proxy_type,
&connect_endpoint.host,
connect_endpoint.port,
&proxy.username,
&proxy.password,
&target_endpoint.host,
target_endpoint.port,
)
.await
.map_err(|err| format!("Proxy layer {} failed: {err}", index + 1))?,
};
final_local_port = local_port;
next_connect_endpoint = Some(LayerEndpoint::localhost(local_port));
}
Ok(final_local_port)
}
pub async fn stop_transport_layers(
connection_id: &str,
layer_count: usize,
ssh_tunnels: &TunnelManager,
proxy_tunnels: &ProxyTunnelManager,
) {
for index in 0..layer_count {
let layer_id = layer_id(connection_id, index);
ssh_tunnels.stop_tunnel(&layer_id).await;
proxy_tunnels.stop_tunnel(&layer_id).await;
}
}
fn layer_id(connection_id: &str, index: usize) -> String {
format!("{connection_id}:transport:{index}")
}
fn effective_ssh_connect_timeout_secs(value: u64) -> u64 {
if value == 0 {
crate::models::connection::default_ssh_connect_timeout_secs()
} else {
value
}
}
#[cfg(test)]
#[derive(Debug, Clone, PartialEq, Eq)]
enum PlannedLayerType {
Ssh,
Proxy,
}
#[cfg(test)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct PlannedTransportLayer {
layer_type: PlannedLayerType,
connect_host: String,
connect_port: u16,
remote_host: String,
remote_port: u16,
}
#[cfg(test)]
fn plan_transport_layers(
layers: &[TransportLayerConfig],
remote_host: &str,
remote_port: u16,
local_ports: &[u16],
) -> Vec<PlannedTransportLayer> {
let mut planned = Vec::new();
let mut next_connect_endpoint: Option<(String, u16)> = None;
for (index, layer) in layers.iter().enumerate() {
let is_last = index + 1 == layers.len();
let (layer_host, layer_port) = layer.endpoint();
let (connect_host, connect_port) =
next_connect_endpoint.clone().unwrap_or_else(|| (layer_host.to_string(), layer_port));
let (target_host, target_port) = if is_last {
(remote_host.to_string(), remote_port)
} else {
let (next_host, next_port) = layers[index + 1].endpoint();
(next_host.to_string(), next_port)
};
let layer_type = match layer {
TransportLayerConfig::Ssh(_) => PlannedLayerType::Ssh,
TransportLayerConfig::Proxy(_) => PlannedLayerType::Proxy,
};
planned.push(PlannedTransportLayer {
layer_type,
connect_host,
connect_port,
remote_host: target_host,
remote_port: target_port,
});
if let Some(local_port) = local_ports.get(index) {
next_connect_endpoint = Some(("127.0.0.1".to_string(), *local_port));
}
}
planned
}
#[cfg(test)]
mod tests {
use super::{plan_transport_layers, PlannedLayerType, PlannedTransportLayer};
use crate::models::connection::{ProxyTunnelConfig, ProxyType, SshTunnelConfig, TransportLayerConfig};
fn ssh_layer(id: &str, host: &str, port: u16) -> TransportLayerConfig {
TransportLayerConfig::Ssh(SshTunnelConfig {
id: id.to_string(),
name: String::new(),
enabled: true,
host: host.to_string(),
port,
user: "user".to_string(),
password: "secret".to_string(),
key_path: String::new(),
key_passphrase: String::new(),
connect_timeout_secs: 5,
expose_lan: false,
})
}
fn proxy_layer(id: &str, host: &str, port: u16) -> TransportLayerConfig {
TransportLayerConfig::Proxy(ProxyTunnelConfig {
id: id.to_string(),
name: String::new(),
enabled: true,
proxy_type: ProxyType::Socks5,
host: host.to_string(),
port,
username: String::new(),
password: String::new(),
})
}
#[test]
fn mixed_transport_plan_routes_layers_in_configured_order() {
let layers = vec![
ssh_layer("ssh-a", "bastion-a", 22),
proxy_layer("proxy", "proxy.internal", 1080),
ssh_layer("ssh-b", "bastion-b", 2200),
];
let planned = plan_transport_layers(&layers, "db.internal", 5432, &[41001, 41002, 41003]);
assert_eq!(
planned,
vec![
PlannedTransportLayer {
layer_type: PlannedLayerType::Ssh,
connect_host: "bastion-a".to_string(),
connect_port: 22,
remote_host: "proxy.internal".to_string(),
remote_port: 1080,
},
PlannedTransportLayer {
layer_type: PlannedLayerType::Proxy,
connect_host: "127.0.0.1".to_string(),
connect_port: 41001,
remote_host: "bastion-b".to_string(),
remote_port: 2200,
},
PlannedTransportLayer {
layer_type: PlannedLayerType::Ssh,
connect_host: "127.0.0.1".to_string(),
connect_port: 41002,
remote_host: "db.internal".to_string(),
remote_port: 5432,
},
]
);
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ pub fn load_snapshot_to_duckdb(con: &duckdb::Connection, snapshot: &ExternalTabl
format!(
"\"{}\" {}{}",
c.name.replace('"', "\"\""),
&c.duckdb_type,
c.duckdb_type,
if c.is_nullable { "" } else { " NOT NULL" }
)
})
+388 -258
View File
@@ -1,7 +1,8 @@
use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize)]
pub struct ConnectionConfig {
pub id: String,
pub name: String,
@@ -23,43 +24,13 @@ pub struct ConnectionConfig {
pub attached_databases: Vec<AttachedDatabaseConfig>,
#[serde(default)]
pub color: Option<String>,
#[serde(default)]
pub ssh_enabled: bool,
#[serde(default)]
pub ssh_host: String,
#[serde(default = "default_ssh_port")]
pub ssh_port: u16,
#[serde(default)]
pub ssh_user: String,
#[serde(default)]
pub ssh_password: String,
#[serde(default)]
pub ssh_key_path: String,
#[serde(default)]
pub ssh_key_passphrase: String,
#[serde(default)]
pub ssh_expose_lan: bool,
#[serde(default = "default_ssh_connect_timeout_secs")]
pub ssh_connect_timeout_secs: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ssh_tunnels: Vec<SshTunnelConfig>,
pub transport_layers: Vec<TransportLayerConfig>,
#[serde(default = "default_connect_timeout_secs")]
pub connect_timeout_secs: u64,
#[serde(default = "default_query_timeout_secs")]
pub query_timeout_secs: u64,
#[serde(default)]
pub proxy_enabled: bool,
#[serde(default)]
pub proxy_type: ProxyType,
#[serde(default)]
pub proxy_host: String,
#[serde(default = "default_proxy_port")]
pub proxy_port: u16,
#[serde(default)]
pub proxy_username: String,
#[serde(default)]
pub proxy_password: String,
#[serde(default)]
pub ssl: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub ca_cert_path: String,
@@ -94,6 +65,43 @@ pub struct ConnectionConfig {
pub one_time: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum TransportLayerConfig {
Ssh(SshTunnelConfig),
Proxy(ProxyTunnelConfig),
}
impl TransportLayerConfig {
pub fn id(&self) -> &str {
match self {
TransportLayerConfig::Ssh(layer) => &layer.id,
TransportLayerConfig::Proxy(layer) => &layer.id,
}
}
pub fn name(&self) -> &str {
match self {
TransportLayerConfig::Ssh(layer) => &layer.name,
TransportLayerConfig::Proxy(layer) => &layer.name,
}
}
pub fn enabled(&self) -> bool {
match self {
TransportLayerConfig::Ssh(layer) => layer.enabled,
TransportLayerConfig::Proxy(layer) => layer.enabled,
}
}
pub fn endpoint(&self) -> (&str, u16) {
match self {
TransportLayerConfig::Ssh(layer) => (&layer.host, layer.port),
TransportLayerConfig::Proxy(layer) => (&layer.host, layer.port),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SshTunnelConfig {
#[serde(default)]
@@ -120,6 +128,26 @@ pub struct SshTunnelConfig {
pub expose_lan: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProxyTunnelConfig {
#[serde(default)]
pub id: String,
#[serde(default)]
pub name: String,
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(default)]
pub proxy_type: ProxyType,
#[serde(default)]
pub host: String,
#[serde(default = "default_proxy_port")]
pub port: u16,
#[serde(default)]
pub username: String,
#[serde(default)]
pub password: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AttachedDatabaseConfig {
pub name: String,
@@ -154,7 +182,7 @@ fn is_false(value: &bool) -> bool {
!*value
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ProxyType {
@@ -230,45 +258,241 @@ pub enum DatabaseType {
Jdbc,
}
impl ConnectionConfig {
pub fn effective_ssh_connect_timeout_secs(&self) -> u64 {
if self.ssh_connect_timeout_secs == 0 {
default_ssh_connect_timeout_secs()
} else {
self.ssh_connect_timeout_secs
#[derive(Deserialize)]
struct ConnectionConfigData {
pub id: String,
pub name: String,
pub db_type: DatabaseType,
#[serde(default)]
pub driver_profile: Option<String>,
#[serde(default)]
pub driver_label: Option<String>,
#[serde(default)]
pub url_params: Option<String>,
pub host: String,
pub port: u16,
pub username: String,
pub password: String,
pub database: Option<String>,
#[serde(default)]
pub visible_databases: Option<Vec<String>>,
#[serde(default)]
pub attached_databases: Vec<AttachedDatabaseConfig>,
#[serde(default)]
pub color: Option<String>,
#[serde(default)]
pub transport_layers: Vec<TransportLayerConfig>,
#[serde(default = "default_connect_timeout_secs")]
pub connect_timeout_secs: u64,
#[serde(default = "default_query_timeout_secs")]
pub query_timeout_secs: u64,
#[serde(default)]
pub ssl: bool,
#[serde(default)]
pub ca_cert_path: String,
#[serde(default)]
pub sysdba: bool,
#[serde(default)]
pub oracle_connection_type: Option<String>,
#[serde(default)]
pub connection_string: Option<String>,
#[serde(default)]
pub redis_connection_mode: Option<String>,
#[serde(default)]
pub redis_sentinel_master: String,
#[serde(default)]
pub redis_sentinel_nodes: String,
#[serde(default)]
pub redis_sentinel_username: String,
#[serde(default)]
pub redis_sentinel_password: String,
#[serde(default)]
pub redis_sentinel_tls: bool,
#[serde(default)]
pub redis_cluster_nodes: String,
#[serde(default)]
pub external_config: Option<serde_json::Value>,
#[serde(default)]
pub jdbc_driver_class: Option<String>,
#[serde(default)]
pub jdbc_driver_paths: Vec<String>,
#[serde(default)]
pub one_time: bool,
}
impl From<ConnectionConfigData> for ConnectionConfig {
fn from(data: ConnectionConfigData) -> Self {
Self {
id: data.id,
name: data.name,
db_type: data.db_type,
driver_profile: data.driver_profile,
driver_label: data.driver_label,
url_params: data.url_params,
host: data.host,
port: data.port,
username: data.username,
password: data.password,
database: data.database,
visible_databases: data.visible_databases,
attached_databases: data.attached_databases,
color: data.color,
transport_layers: data.transport_layers,
connect_timeout_secs: data.connect_timeout_secs,
query_timeout_secs: data.query_timeout_secs,
ssl: data.ssl,
ca_cert_path: data.ca_cert_path,
sysdba: data.sysdba,
oracle_connection_type: data.oracle_connection_type,
connection_string: data.connection_string,
redis_connection_mode: data.redis_connection_mode,
redis_sentinel_master: data.redis_sentinel_master,
redis_sentinel_nodes: data.redis_sentinel_nodes,
redis_sentinel_username: data.redis_sentinel_username,
redis_sentinel_password: data.redis_sentinel_password,
redis_sentinel_tls: data.redis_sentinel_tls,
redis_cluster_nodes: data.redis_cluster_nodes,
external_config: data.external_config,
jdbc_driver_class: data.jdbc_driver_class,
jdbc_driver_paths: data.jdbc_driver_paths,
one_time: data.one_time,
}
}
}
impl<'de> Deserialize<'de> for ConnectionConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let mut value = Value::deserialize(deserializer)?;
migrate_legacy_transport_layers(&mut value);
let data = ConnectionConfigData::deserialize(value).map_err(serde::de::Error::custom)?;
Ok(data.into())
}
}
fn migrate_legacy_transport_layers(value: &mut Value) {
let Some(object) = value.as_object_mut() else {
return;
};
if object.get("transport_layers").and_then(Value::as_array).is_some_and(|layers| !layers.is_empty()) {
return;
}
let mut layers = Vec::new();
let ssh_enabled = object.get("ssh_enabled").and_then(Value::as_bool).unwrap_or(false);
if ssh_enabled {
if let Some(ssh_tunnels) = object.get("ssh_tunnels").and_then(Value::as_array) {
for hop in ssh_tunnels {
let mut layer = hop.clone();
if let Some(layer_object) = layer.as_object_mut() {
layer_object.insert("type".to_string(), Value::String("ssh".to_string()));
}
layers.push(layer);
}
}
if layers.is_empty() && string_field(object, "ssh_host").is_some() {
let mut layer = serde_json::Map::new();
layer.insert("type".to_string(), Value::String("ssh".to_string()));
layer.insert("id".to_string(), Value::String("legacy".to_string()));
layer.insert("enabled".to_string(), Value::Bool(true));
copy_string(object, &mut layer, "ssh_host", "host");
copy_u64(object, &mut layer, "ssh_port", "port", default_ssh_port() as u64);
copy_string(object, &mut layer, "ssh_user", "user");
copy_string(object, &mut layer, "ssh_password", "password");
copy_string(object, &mut layer, "ssh_key_path", "key_path");
copy_string(object, &mut layer, "ssh_key_passphrase", "key_passphrase");
copy_u64(
object,
&mut layer,
"ssh_connect_timeout_secs",
"connect_timeout_secs",
default_ssh_connect_timeout_secs(),
);
copy_bool(object, &mut layer, "ssh_expose_lan", "expose_lan");
layers.push(Value::Object(layer));
}
}
let proxy_enabled = object.get("proxy_enabled").and_then(Value::as_bool).unwrap_or(false);
if proxy_enabled && string_field(object, "proxy_host").is_some() {
let mut layer = serde_json::Map::new();
layer.insert("type".to_string(), Value::String("proxy".to_string()));
layer.insert("id".to_string(), Value::String("legacy-proxy".to_string()));
layer.insert("enabled".to_string(), Value::Bool(true));
copy_string(object, &mut layer, "proxy_type", "proxy_type");
copy_string(object, &mut layer, "proxy_host", "host");
copy_u64(object, &mut layer, "proxy_port", "port", default_proxy_port() as u64);
copy_string(object, &mut layer, "proxy_username", "username");
copy_string(object, &mut layer, "proxy_password", "password");
layers.push(Value::Object(layer));
}
if !layers.is_empty() {
object.insert("transport_layers".to_string(), Value::Array(layers));
}
}
fn string_field(object: &serde_json::Map<String, Value>, key: &str) -> Option<String> {
object.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty()).map(str::to_string)
}
fn copy_string(
object: &serde_json::Map<String, Value>,
target: &mut serde_json::Map<String, Value>,
from: &str,
to: &str,
) {
if let Some(value) = object.get(from).and_then(Value::as_str) {
target.insert(to.to_string(), Value::String(value.to_string()));
}
}
fn copy_bool(
object: &serde_json::Map<String, Value>,
target: &mut serde_json::Map<String, Value>,
from: &str,
to: &str,
) {
if let Some(value) = object.get(from).and_then(Value::as_bool) {
target.insert(to.to_string(), Value::Bool(value));
}
}
fn copy_u64(
object: &serde_json::Map<String, Value>,
target: &mut serde_json::Map<String, Value>,
from: &str,
to: &str,
default: u64,
) {
let value = object.get(from).and_then(Value::as_u64).filter(|value| *value > 0).unwrap_or(default);
target.insert(to.to_string(), Value::Number(value.into()));
}
impl ConnectionConfig {
pub fn effective_transport_layers(&self) -> Vec<TransportLayerConfig> {
self.transport_layers.iter().filter(|layer| layer.enabled()).cloned().collect()
}
pub fn effective_ssh_tunnels(&self) -> Vec<SshTunnelConfig> {
if !self.ssh_enabled {
return Vec::new();
}
self.effective_transport_layers()
.into_iter()
.filter_map(|layer| match layer {
TransportLayerConfig::Ssh(ssh) => Some(ssh),
TransportLayerConfig::Proxy(_) => None,
})
.collect()
}
if !self.ssh_tunnels.is_empty() {
return self.ssh_tunnels.iter().filter(|hop| hop.enabled).cloned().collect();
}
if self.ssh_host.trim().is_empty() {
return Vec::new();
}
vec![SshTunnelConfig {
id: "legacy".to_string(),
name: String::new(),
enabled: true,
host: self.ssh_host.clone(),
port: self.ssh_port,
user: self.ssh_user.clone(),
password: self.ssh_password.clone(),
key_path: self.ssh_key_path.clone(),
key_passphrase: self.ssh_key_passphrase.clone(),
connect_timeout_secs: self.effective_ssh_connect_timeout_secs(),
expose_lan: self.ssh_expose_lan,
}]
pub fn has_effective_transport_layers(&self) -> bool {
!self.effective_transport_layers().is_empty()
}
pub fn has_effective_ssh_tunnels(&self) -> bool {
!self.effective_ssh_tunnels().is_empty()
self.effective_transport_layers().iter().any(|layer| matches!(layer, TransportLayerConfig::Ssh(_)))
}
pub fn effective_connect_timeout_secs(&self) -> u64 {
@@ -1018,8 +1242,8 @@ fn bracket_ipv6(host: &str) -> String {
#[cfg(test)]
mod tests {
use super::{
default_query_timeout_secs, default_ssh_connect_timeout_secs, ConnectionConfig, DatabaseType, ProxyType,
SshTunnelConfig,
default_query_timeout_secs, default_ssh_connect_timeout_secs, ConnectionConfig, DatabaseType,
ProxyTunnelConfig, ProxyType, TransportLayerConfig,
};
use std::str::FromStr;
@@ -1039,24 +1263,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: default_ssh_connect_timeout_secs(),
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: super::default_connect_timeout_secs(),
query_timeout_secs: default_query_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -1084,49 +1293,7 @@ mod tests {
}
#[test]
fn ssh_connect_timeout_defaults_for_legacy_config() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "name",
"db_type": "mysql",
"host": "10.1.2.3",
"port": 3306,
"username": "root",
"password": "",
"database": null
}))
.unwrap();
assert_eq!(config.ssh_connect_timeout_secs, default_ssh_connect_timeout_secs());
assert_eq!(config.effective_ssh_connect_timeout_secs(), default_ssh_connect_timeout_secs());
assert_eq!(config.query_timeout_secs, default_query_timeout_secs());
assert_eq!(config.effective_query_timeout_secs(), default_query_timeout_secs());
}
#[test]
fn proxy_fields_default_for_legacy_config() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "name",
"db_type": "mysql",
"host": "10.1.2.3",
"port": 3306,
"username": "root",
"password": "",
"database": null
}))
.unwrap();
assert_eq!(config.proxy_enabled, false);
assert_eq!(config.proxy_type, ProxyType::Socks5);
assert_eq!(config.proxy_host, "");
assert_eq!(config.proxy_port, 1080);
assert_eq!(config.proxy_username, "");
assert_eq!(config.proxy_password, "");
}
#[test]
fn visible_databases_round_trips_through_connection_config() {
fn legacy_single_ssh_config_migrates_to_transport_layer() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "name",
@@ -1136,59 +1303,17 @@ mod tests {
"username": "root",
"password": "",
"database": null,
"visible_databases": ["app", "billing"]
"ssh_enabled": true,
"ssh_host": "bastion.example.com",
"ssh_port": 2200,
"ssh_user": "deploy",
"ssh_password": "secret",
"ssh_connect_timeout_secs": 0,
"ssh_expose_lan": true
}))
.unwrap();
let saved = serde_json::to_value(config).unwrap();
assert_eq!(saved["visible_databases"], serde_json::json!(["app", "billing"]));
}
#[test]
fn duckdb_attached_databases_round_trip_through_connection_config() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "DuckDB",
"db_type": "duckdb",
"host": "/tmp/main.duckdb",
"port": 0,
"username": "",
"password": "",
"database": null,
"attached_databases": [{ "name": "analytics", "path": "/tmp/analytics.duckdb" }]
}))
.unwrap();
let saved = serde_json::to_value(config).unwrap();
assert_eq!(
saved["attached_databases"],
serde_json::json!([{ "name": "analytics", "path": "/tmp/analytics.duckdb" }])
);
}
#[test]
fn ssh_connect_timeout_zero_uses_default() {
let mut config = mysql_config("root", "", None);
config.ssh_connect_timeout_secs = 0;
assert_eq!(config.effective_ssh_connect_timeout_secs(), default_ssh_connect_timeout_secs());
}
#[test]
fn effective_ssh_tunnels_adapts_legacy_single_hop() {
let mut config = mysql_config("root", "", None);
config.ssh_enabled = true;
config.ssh_host = "bastion.example.com".to_string();
config.ssh_port = 2200;
config.ssh_user = "deploy".to_string();
config.ssh_password = "secret".to_string();
config.ssh_connect_timeout_secs = 0;
config.ssh_expose_lan = true;
let hops = config.effective_ssh_tunnels();
assert_eq!(hops.len(), 1);
assert_eq!(hops[0].id, "legacy");
assert_eq!(hops[0].host, "bastion.example.com");
@@ -1200,98 +1325,103 @@ mod tests {
}
#[test]
fn effective_ssh_tunnels_prefers_explicit_hops() {
let mut config = mysql_config("root", "", None);
config.ssh_enabled = true;
config.ssh_host = "legacy.example.com".to_string();
config.ssh_tunnels = vec![SshTunnelConfig {
id: "hop-1".to_string(),
name: "Bastion".to_string(),
enabled: true,
host: "new.example.com".to_string(),
port: 22,
user: "alice".to_string(),
password: String::new(),
key_path: "~/.ssh/id_ed25519".to_string(),
key_passphrase: String::new(),
connect_timeout_secs: 7,
expose_lan: false,
}];
fn legacy_ssh_tunnels_migrate_to_ordered_transport_layers() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "name",
"db_type": "mysql",
"host": "10.1.2.3",
"port": 3306,
"username": "root",
"password": "",
"database": null,
"ssh_enabled": true,
"ssh_tunnels": [
{ "id": "first", "host": "a", "port": 22, "user": "u" },
{ "id": "second", "host": "b", "port": 2200, "user": "u" }
]
}))
.unwrap();
let hops = config.effective_ssh_tunnels();
assert_eq!(hops.len(), 1);
assert_eq!(hops[0].id, "hop-1");
assert_eq!(hops[0].host, "new.example.com");
assert_eq!(hops.iter().map(|hop| hop.id.as_str()).collect::<Vec<_>>(), vec!["first", "second"]);
}
#[test]
fn effective_ssh_tunnels_filters_disabled_explicit_hops() {
fn legacy_proxy_config_migrates_to_transport_layer() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "name",
"db_type": "mysql",
"host": "10.1.2.3",
"port": 3306,
"username": "root",
"password": "",
"database": null,
"proxy_enabled": true,
"proxy_type": "http",
"proxy_host": "proxy.example.com",
"proxy_port": 8080,
"proxy_username": "alice",
"proxy_password": "secret"
}))
.unwrap();
assert_eq!(config.transport_layers.len(), 1);
match &config.transport_layers[0] {
TransportLayerConfig::Proxy(proxy) => {
assert_eq!(proxy.id, "legacy-proxy");
assert_eq!(proxy.proxy_type, ProxyType::Http);
assert_eq!(proxy.host, "proxy.example.com");
assert_eq!(proxy.port, 8080);
assert_eq!(proxy.username, "alice");
assert_eq!(proxy.password, "secret");
}
TransportLayerConfig::Ssh(_) => panic!("expected proxy layer"),
}
}
#[test]
fn existing_transport_layers_take_precedence_over_legacy_fields() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "id",
"name": "name",
"db_type": "mysql",
"host": "10.1.2.3",
"port": 3306,
"username": "root",
"password": "",
"database": null,
"ssh_enabled": true,
"ssh_host": "legacy.example.com",
"transport_layers": [{ "type": "proxy", "id": "proxy", "host": "proxy", "port": 1080 }]
}))
.unwrap();
assert_eq!(config.transport_layers.len(), 1);
assert!(matches!(&config.transport_layers[0], TransportLayerConfig::Proxy(proxy) if proxy.id == "proxy"));
}
#[test]
fn serialized_connection_config_omits_legacy_transport_fields() {
let mut config = mysql_config("root", "", None);
config.ssh_enabled = true;
config.ssh_tunnels = vec![
SshTunnelConfig {
id: "disabled".to_string(),
name: String::new(),
enabled: false,
host: "disabled.example.com".to_string(),
port: 22,
user: "alice".to_string(),
password: "secret".to_string(),
key_path: String::new(),
key_passphrase: String::new(),
connect_timeout_secs: 5,
expose_lan: false,
},
SshTunnelConfig {
id: "enabled".to_string(),
name: String::new(),
enabled: true,
host: "enabled.example.com".to_string(),
port: 22,
user: "alice".to_string(),
password: "secret".to_string(),
key_path: String::new(),
key_passphrase: String::new(),
connect_timeout_secs: 5,
expose_lan: false,
},
];
let hops = config.effective_ssh_tunnels();
assert_eq!(hops.len(), 1);
assert_eq!(hops[0].id, "enabled");
}
#[test]
fn effective_ssh_tunnels_empty_without_explicit_or_legacy_ssh() {
let config = mysql_config("root", "", None);
assert!(config.effective_ssh_tunnels().is_empty());
assert!(!config.has_effective_ssh_tunnels());
}
#[test]
fn effective_ssh_tunnels_does_not_fall_back_when_explicit_list_is_disabled() {
let mut config = mysql_config("root", "", None);
config.ssh_enabled = true;
config.ssh_host = "legacy.example.com".to_string();
config.ssh_tunnels = vec![SshTunnelConfig {
id: "disabled".to_string(),
config.transport_layers = vec![TransportLayerConfig::Proxy(ProxyTunnelConfig {
id: "proxy".to_string(),
name: String::new(),
enabled: false,
host: "disabled.example.com".to_string(),
port: 22,
user: "alice".to_string(),
password: "secret".to_string(),
key_path: String::new(),
key_passphrase: String::new(),
connect_timeout_secs: 5,
expose_lan: false,
}];
enabled: true,
proxy_type: ProxyType::Socks5,
host: "proxy".to_string(),
port: 1080,
username: String::new(),
password: String::new(),
})];
assert!(config.effective_ssh_tunnels().is_empty());
let saved = serde_json::to_value(config).unwrap();
assert!(saved.get("transport_layers").is_some());
for key in ["ssh_tunnels", "ssh_host", "ssh_password", "proxy_host", "proxy_password", "proxy_enabled"] {
assert!(saved.get(key).is_none(), "legacy key {key} should not serialize");
}
}
#[test]
+3 -17
View File
@@ -479,6 +479,7 @@ fn resolve_query_timeout(timeout_secs: Option<u64>) -> Option<Duration> {
}
}
#[allow(clippy::too_many_arguments)]
pub async fn do_execute(
state: &AppState,
pool_key: &str,
@@ -1392,7 +1393,7 @@ async fn exec_tx_none_inner(
#[cfg(test)]
mod tests {
use super::*;
use crate::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use crate::models::connection::{ConnectionConfig, DatabaseType};
#[tokio::test]
async fn wait_for_query_returns_cancelled_when_token_is_cancelled() {
@@ -1594,24 +1595,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: 5,
query_timeout_secs: 30,
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
+9 -9
View File
@@ -627,7 +627,7 @@ mod tests {
offset: 200,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(result.sql.unwrap(), "SELECT id, name FROM users LIMIT 100 OFFSET 200;");
}
@@ -640,7 +640,7 @@ mod tests {
offset: 0,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(result.sql.unwrap(), "SELECT TOP (100) id FROM users ORDER BY id DESC");
}
@@ -653,7 +653,7 @@ mod tests {
offset: 0,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(result.sql.unwrap(), "SELECT TOP (100) COUNT(*) FROM TicketInfo");
}
@@ -666,7 +666,7 @@ mod tests {
offset: 0,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(
result.sql.unwrap(),
"SELECT DISTINCT TOP (100) ProjectType FROM JDDR_sys_BasicConfig_ProjectInfo_Data"
@@ -682,7 +682,7 @@ mod tests {
offset: 0,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(result.sql.unwrap(), "SELECT ALL TOP (100) ProjectType FROM JDDR_sys_BasicConfig_ProjectInfo_Data");
}
@@ -695,7 +695,7 @@ mod tests {
offset: 0,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(result.sql.unwrap(), "SELECT TOP (100) AllProjectType FROM JDDR_sys_BasicConfig_ProjectInfo_Data");
}
@@ -708,7 +708,7 @@ mod tests {
offset: 0,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(result.sql.unwrap(), "SELECT TOP 1000 * FROM TicketInfo");
}
@@ -737,7 +737,7 @@ mod tests {
database_type: Some(DatabaseType::SqlServer),
});
assert_eq!(result.ok, false);
assert!(!result.ok);
assert!(result.sql.is_none());
}
@@ -750,7 +750,7 @@ mod tests {
offset: 0,
});
assert_eq!(result.ok, true);
assert!(result.ok);
assert_eq!(result.sql.unwrap(), "SELECT TOP (100) @@version");
}
+3 -18
View File
@@ -557,7 +557,7 @@ mod tests {
clickhouse_metadata_database, deduplicate_column_infos, duckdb_attach_database, duckdb_list_databases,
duckdb_query_tables_in_database, is_agent_postgres_metadata_fallback_config,
};
use crate::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use crate::models::connection::{ConnectionConfig, DatabaseType};
fn test_column(name: &str, comment: Option<&str>, is_primary_key: bool) -> super::db::ColumnInfo {
super::db::ColumnInfo {
@@ -590,24 +590,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: 5,
query_timeout_secs: 30,
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -1160,7 +1145,7 @@ fn merge_optional_string(target: &mut Option<String>, candidate: Option<String>)
}
return;
}
if target.as_ref().map_or(true, |value| value.trim().is_empty()) {
if target.as_ref().is_none_or(|value| value.trim().is_empty()) {
*target = Some(candidate);
}
}
+4 -2
View File
@@ -825,8 +825,10 @@ pub fn generate_schema_sync_sql(diffs: &[TableDiff], db_type: DatabaseType, sche
if let Some(foreign_keys) = &diff.foreign_keys {
for fk in foreign_keys {
if (fk.diff_type == "added" || fk.diff_type == "modified") && fk.source.is_some() {
lines.push(add_foreign_key_sql(&diff.name, fk.source.as_ref().unwrap(), db_type, schema));
if fk.diff_type == "added" || fk.diff_type == "modified" {
if let Some(source) = fk.source.as_ref() {
lines.push(add_foreign_key_sql(&diff.name, source, db_type, schema));
}
}
}
}
+3 -3
View File
@@ -633,7 +633,7 @@ mod tests {
let result =
analyze_editable_query_editability("select u.id, o.total from users u join orders o on o.user_id = u.id");
assert_eq!(result.editable, false);
assert!(!result.editable);
assert_eq!(result.reason, Some(QueryEditabilityReason::ComplexSource));
}
@@ -641,7 +641,7 @@ mod tests {
fn reports_external_file_scan_as_external_source() {
let result = analyze_editable_query_editability("SELECT * FROM '/tmp/duckdb_excel_extension_test.xlsx'");
assert_eq!(result.editable, false);
assert!(!result.editable);
assert_eq!(result.reason, Some(QueryEditabilityReason::ExternalSource));
}
@@ -649,7 +649,7 @@ mod tests {
fn reports_grouped_query_as_aggregation() {
let result = analyze_editable_query_editability("select id, count(*) as total from users group by id");
assert_eq!(result.editable, false);
assert!(!result.editable);
assert_eq!(result.reason, Some(QueryEditabilityReason::Aggregation));
}
+4
View File
@@ -99,6 +99,7 @@ pub async fn execute_sql_file_content(
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn sql_file_progress(
execution_id: &str,
status: SqlFileStatus,
@@ -134,6 +135,7 @@ async fn sql_file_import_target(state: &AppState, connection_id: &str) -> Option
.map(|config| SqlFileImportTarget { db_type: config.db_type, driver_profile: config.driver_profile.clone() })
}
#[allow(clippy::too_many_arguments)]
async fn execute_statement_with_progress(
state: &AppState,
request: &SqlFileRequest,
@@ -268,6 +270,7 @@ async fn execute_statement_with_progress(
}
}
#[allow(clippy::too_many_arguments)]
async fn execute_merged_statement_fallback_with_progress(
state: &AppState,
request: &SqlFileRequest,
@@ -363,6 +366,7 @@ async fn execute_merged_statement_fallback_with_progress(
Ok(false)
}
#[allow(clippy::too_many_arguments)]
fn statement_error_decision(
execution_id: &str,
token: &CancellationToken,
+110 -32
View File
@@ -8,10 +8,11 @@ use uuid::Uuid;
use crate::ai::{AiChatMessage, AiConfig, AiConversation};
use crate::db::sqlite::{connect_path_create_if_missing, SqliteHandle};
use crate::history::{HistoryEntry, MAX_HISTORY};
use crate::models::connection::ConnectionConfig;
use crate::models::connection::{ConnectionConfig, TransportLayerConfig};
use crate::saved_sql::{SavedSqlFile, SavedSqlFolder, SavedSqlLibrary};
const SSH_TUNNEL_SECRET_PREFIX: &str = "ssh_tunnels.";
const TRANSPORT_LAYER_SECRET_PREFIX: &str = "transport_layers.";
pub struct Storage {
db: SqliteHandle,
@@ -209,10 +210,38 @@ fn ssh_tunnel_key_passphrase_key(index: usize, hop: &crate::models::connection::
format!("{}{}.key_passphrase", SSH_TUNNEL_SECRET_PREFIX, ssh_tunnel_secret_segment(index, hop))
}
fn scrub_ssh_tunnel_secrets(config: &mut ConnectionConfig) {
for hop in &mut config.ssh_tunnels {
hop.password.clear();
hop.key_passphrase.clear();
fn transport_layer_secret_segment(index: usize, layer: &TransportLayerConfig) -> String {
let id = layer.id().trim();
if id.is_empty() {
index.to_string()
} else {
id.to_string()
}
}
fn transport_layer_ssh_password_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.ssh_password", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn transport_layer_ssh_key_passphrase_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.ssh_key_passphrase", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn transport_layer_proxy_password_key(index: usize, layer: &TransportLayerConfig) -> String {
format!("{}{}.proxy_password", TRANSPORT_LAYER_SECRET_PREFIX, transport_layer_secret_segment(index, layer))
}
fn scrub_transport_layer_secrets(config: &mut ConnectionConfig) {
for layer in &mut config.transport_layers {
match layer {
TransportLayerConfig::Ssh(ssh) => {
ssh.password.clear();
ssh.key_passphrase.clear();
}
TransportLayerConfig::Proxy(proxy) => {
proxy.password.clear();
}
}
}
}
@@ -566,10 +595,7 @@ impl Storage {
let config_id = config.id.clone();
let mut sanitized = config;
sanitized.password = String::new();
sanitized.ssh_password = String::new();
sanitized.ssh_key_passphrase = String::new();
scrub_ssh_tunnel_secrets(&mut sanitized);
sanitized.proxy_password = String::new();
scrub_transport_layer_secrets(&mut sanitized);
sanitized.redis_sentinel_password = String::new();
sanitized.connection_string = None;
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
@@ -603,10 +629,7 @@ impl Storage {
let config_id = config.id.clone();
let mut sanitized = config.clone();
sanitized.password = String::new();
sanitized.ssh_password = String::new();
sanitized.ssh_key_passphrase = String::new();
scrub_ssh_tunnel_secrets(&mut sanitized);
sanitized.proxy_password = String::new();
scrub_transport_layer_secrets(&mut sanitized);
sanitized.redis_sentinel_password = String::new();
sanitized.connection_string = None;
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
@@ -615,20 +638,38 @@ impl Storage {
.map_err(|e| e.to_string())?;
persist_secret_in_tx(&tx, &config.id, "password", &config.password)?;
persist_secret_in_tx(&tx, &config.id, "ssh_password", &config.ssh_password)?;
persist_secret_in_tx(&tx, &config.id, "ssh_key_passphrase", &config.ssh_key_passphrase)?;
delete_secret_prefix_in_tx(&tx, &config.id, SSH_TUNNEL_SECRET_PREFIX)?;
for (index, hop) in config.ssh_tunnels.iter().enumerate() {
persist_secret_in_tx(&tx, &config.id, &ssh_tunnel_password_key(index, hop), &hop.password)?;
persist_secret_in_tx(
&tx,
&config.id,
&ssh_tunnel_key_passphrase_key(index, hop),
&hop.key_passphrase,
)?;
delete_secret_prefix_in_tx(&tx, &config.id, TRANSPORT_LAYER_SECRET_PREFIX)?;
for (index, layer) in config.transport_layers.iter().enumerate() {
match layer {
TransportLayerConfig::Ssh(ssh) => {
persist_secret_in_tx(
&tx,
&config.id,
&transport_layer_ssh_password_key(index, layer),
&ssh.password,
)?;
persist_secret_in_tx(
&tx,
&config.id,
&transport_layer_ssh_key_passphrase_key(index, layer),
&ssh.key_passphrase,
)?;
}
TransportLayerConfig::Proxy(proxy) => {
persist_secret_in_tx(
&tx,
&config.id,
&transport_layer_proxy_password_key(index, layer),
&proxy.password,
)?;
}
}
}
persist_secret_in_tx(&tx, &config.id, "proxy_password", &config.proxy_password)?;
persist_secret_in_tx(&tx, &config.id, "redis_sentinel_password", &config.redis_sentinel_password)?;
persist_secret_in_tx(&tx, &config.id, "ssh_password", "")?;
persist_secret_in_tx(&tx, &config.id, "ssh_key_passphrase", "")?;
persist_secret_in_tx(&tx, &config.id, "proxy_password", "")?;
delete_secret_prefix_in_tx(&tx, &config.id, SSH_TUNNEL_SECRET_PREFIX)?;
if let Some(cs) = &config.connection_string {
persist_secret_in_tx(&tx, &config.id, "connection_string", cs)?;
} else {
@@ -669,14 +710,51 @@ impl Storage {
for (id, json) in rows {
let mut config: ConnectionConfig = serde_json::from_str(&json).map_err(|e| e.to_string())?;
config.password = self.get_secret(&id, "password").await?.unwrap_or_default();
config.ssh_password = self.get_secret(&id, "ssh_password").await?.unwrap_or_default();
config.ssh_key_passphrase = self.get_secret(&id, "ssh_key_passphrase").await?.unwrap_or_default();
for (index, hop) in config.ssh_tunnels.iter_mut().enumerate() {
hop.password = self.get_secret(&id, &ssh_tunnel_password_key(index, hop)).await?.unwrap_or_default();
hop.key_passphrase =
self.get_secret(&id, &ssh_tunnel_key_passphrase_key(index, hop)).await?.unwrap_or_default();
for index in 0..config.transport_layers.len() {
let layer_for_key = config.transport_layers[index].clone();
match &mut config.transport_layers[index] {
TransportLayerConfig::Ssh(ssh) => {
ssh.password = self
.get_secret(&id, &transport_layer_ssh_password_key(index, &layer_for_key))
.await?
.or(match &layer_for_key {
TransportLayerConfig::Ssh(layer) if layer.id == "legacy" => {
self.get_secret(&id, "ssh_password").await?
}
TransportLayerConfig::Ssh(layer) => {
self.get_secret(&id, &ssh_tunnel_password_key(index, layer)).await?
}
TransportLayerConfig::Proxy(_) => None,
})
.unwrap_or_default();
ssh.key_passphrase = self
.get_secret(&id, &transport_layer_ssh_key_passphrase_key(index, &layer_for_key))
.await?
.or(match &layer_for_key {
TransportLayerConfig::Ssh(layer) if layer.id == "legacy" => {
self.get_secret(&id, "ssh_key_passphrase").await?
}
TransportLayerConfig::Ssh(layer) => {
self.get_secret(&id, &ssh_tunnel_key_passphrase_key(index, layer)).await?
}
TransportLayerConfig::Proxy(_) => None,
})
.unwrap_or_default();
}
TransportLayerConfig::Proxy(proxy) => {
proxy.password = self
.get_secret(&id, &transport_layer_proxy_password_key(index, &layer_for_key))
.await?
.or(match &layer_for_key {
TransportLayerConfig::Proxy(layer) if layer.id == "legacy-proxy" => {
self.get_secret(&id, "proxy_password").await?
}
_ => None,
})
.unwrap_or_default();
}
}
}
config.proxy_password = self.get_secret(&id, "proxy_password").await?.unwrap_or_default();
config.redis_sentinel_password = self.get_secret(&id, "redis_sentinel_password").await?.unwrap_or_default();
config.connection_string = self.get_secret(&id, "connection_string").await?;
configs.push(config.canonicalized());
+1
View File
@@ -111,6 +111,7 @@ fn format_markdown_rows(rows: &[Vec<Value>]) -> String {
.join("\n")
}
#[allow(clippy::too_many_arguments)]
fn table_page_sql(
request: &TableExportRequest,
db_type: &crate::models::connection::DatabaseType,
+4 -16
View File
@@ -1183,6 +1183,7 @@ fn max_transfer_write_rows(db_type: &DatabaseType, mode: &TransferMode) -> usize
}
}
#[allow(clippy::too_many_arguments)]
fn generate_transfer_write_sql(
mode: &TransferMode,
columns: &[String],
@@ -1199,6 +1200,7 @@ fn generate_transfer_write_sql(
}
}
#[allow(clippy::too_many_arguments)]
fn generate_transfer_write_sql_batches(
mode: &TransferMode,
columns: &[String],
@@ -1307,6 +1309,7 @@ pub fn pagination_sql_with_order(
}
}
#[allow(clippy::too_many_arguments)]
pub fn pagination_sql_with_filter_order(
columns: &[String],
table: &str,
@@ -3085,24 +3088,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: 5,
query_timeout_secs: 30,
proxy_enabled: false,
proxy_type: crate::models::connection::ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -1,6 +1,6 @@
use dbx_core::connection::{AppState, PoolKind};
use dbx_core::db::postgres;
use dbx_core::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
use dbx_core::storage::Storage;
use dbx_core::transfer::{
get_db_type, transfer_postgres_schema_dependencies, transfer_postgres_schema_objects, transfer_table, TransferMode,
@@ -24,24 +24,9 @@ fn postgres_test_config(id: &str, database: &str) -> ConnectionConfig {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: 5,
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: 5,
query_timeout_secs: 30,
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -81,7 +66,7 @@ async fn live_postgres_transfer_preserves_data_and_schema_objects() {
let source_schema = format!("dbx_src_{}", &suffix[..8]);
let target_schema = format!("dbx_dst_{}", &suffix[..8]);
let cleanup_sql = vec![
let cleanup_sql = [
format!("DROP SCHEMA IF EXISTS \"{}\" CASCADE", source_schema),
format!("DROP SCHEMA IF EXISTS \"{}\" CASCADE", target_schema),
];
+1 -1
View File
@@ -62,7 +62,7 @@ async fn main() {
};
// Password hash: env var takes priority, then database
let password_hash = if let Some(pw) = std::env::var("DBX_PASSWORD").ok() {
let password_hash = if let Ok(pw) = std::env::var("DBX_PASSWORD") {
let salt = SaltString::generate(&mut OsRng);
Some(Argon2::default().hash_password(pw.as_bytes(), &salt).expect("Failed to hash password").to_string())
} else {
+2 -17
View File
@@ -137,7 +137,7 @@ mod tests {
use axum::extract::State;
use axum::Json;
use dbx_core::connection::{AppState, PoolKind};
use dbx_core::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
use dbx_core::storage::Storage;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -159,24 +159,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: dbx_core::models::connection::default_ssh_connect_timeout_secs(),
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: dbx_core::models::connection::default_connect_timeout_secs(),
query_timeout_secs: dbx_core::models::connection::default_query_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
+8 -9
View File
@@ -11,7 +11,7 @@ use crate::state::WebState;
pub async fn list_jdbc_drivers(State(state): State<Arc<WebState>>) -> Result<Json<Vec<JdbcDriverInfo>>, AppError> {
let root = state.app.plugins.root_dir();
Ok(Json(jdbc::list_jdbc_drivers(&root).map_err(AppError::internal)?))
Ok(Json(jdbc::list_jdbc_drivers(root).map_err(AppError::internal)?))
}
pub async fn import_jdbc_drivers(
@@ -34,7 +34,7 @@ pub async fn import_jdbc_drivers(
imported.push(target);
}
jdbc::list_jdbc_drivers(&root).map(Json).map_err(|e| AppError::internal(e))
jdbc::list_jdbc_drivers(root).map(Json).map_err(AppError::internal)
}
pub async fn delete_jdbc_driver(
@@ -47,19 +47,19 @@ pub async fn delete_jdbc_driver(
let root = state.app.plugins.root_dir();
let driver_path = root.join("jdbc").join("drivers").join(&name);
let path_str = driver_path.to_string_lossy().to_string();
Ok(Json(jdbc::delete_jdbc_driver(&root, &path_str).map_err(AppError::internal)?))
Ok(Json(jdbc::delete_jdbc_driver(root, &path_str).map_err(AppError::internal)?))
}
// ---- JDBC Plugin ----
pub async fn get_jdbc_plugin_status(State(state): State<Arc<WebState>>) -> Result<Json<JdbcPluginStatus>, AppError> {
let root = state.app.plugins.root_dir();
Ok(Json(jdbc::get_jdbc_plugin_status(&root).await.map_err(AppError::internal)?))
Ok(Json(jdbc::get_jdbc_plugin_status(root).await.map_err(AppError::internal)?))
}
pub async fn install_jdbc_plugin(State(state): State<Arc<WebState>>) -> Result<Json<JdbcPluginStatus>, AppError> {
let root = state.app.plugins.root_dir();
Ok(Json(jdbc::install_jdbc_plugin(&root).await.map_err(AppError::internal)?))
Ok(Json(jdbc::install_jdbc_plugin(root).await.map_err(AppError::internal)?))
}
pub async fn install_jdbc_plugin_local(
@@ -78,9 +78,8 @@ pub async fn install_jdbc_plugin_local(
let data = field.bytes().await.map_err(|e| AppError::internal(e.to_string()))?;
let tmp_path = temp_dir.join(&file_name);
std::fs::write(&tmp_path, &data).map_err(|e| AppError::internal(e.to_string()))?;
let result = jdbc::install_jdbc_plugin_from_file(&root, &tmp_path.to_string_lossy())
.await
.map_err(AppError::internal)?;
let result =
jdbc::install_jdbc_plugin_from_file(root, &tmp_path.to_string_lossy()).await.map_err(AppError::internal)?;
let _ = std::fs::remove_dir_all(&temp_dir);
return Ok(Json(result));
}
@@ -90,7 +89,7 @@ pub async fn install_jdbc_plugin_local(
pub async fn uninstall_jdbc_plugin(State(state): State<Arc<WebState>>) -> Result<Json<JdbcPluginStatus>, AppError> {
let root = state.app.plugins.root_dir();
Ok(Json(jdbc::uninstall_jdbc_plugin(&root).map_err(AppError::internal)?))
Ok(Json(jdbc::uninstall_jdbc_plugin(root).map_err(AppError::internal)?))
}
// ---- System Fonts ----
+1 -2
View File
@@ -143,8 +143,7 @@ async fn cleanup_sql_file_execution(state: &WebState, execution_id: &str) {
}
fn safe_uploaded_sql_path(tmp_dir: &Path, file_name: &str) -> Result<PathBuf, AppError> {
let base_name =
file_name.rsplit(|ch| ch == '/' || ch == '\\').find(|part| !part.is_empty()).unwrap_or("upload.sql").trim();
let base_name = file_name.rsplit(['/', '\\']).find(|part| !part.is_empty()).unwrap_or("upload.sql").trim();
if base_name.is_empty() || base_name == "." || base_name == ".." {
return Err(AppError("Invalid SQL file name".to_string()));
}
+2 -2
View File
@@ -149,10 +149,10 @@ pub async fn table_export_download(
let filename = format!("table_export_{export_id}.{file_ext}");
Ok(Response::builder()
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{filename}\""))
.body(Body::from(data))
.map_err(|e| AppError(e.to_string()))?)
.map_err(|e| AppError(e.to_string()))
}
@@ -20,9 +20,7 @@ test("honors slower SSH tunnel connection timeouts", () => {
assert.equal(
connectionAttemptTimeoutMs({
connect_timeout_secs: 5,
ssh_enabled: true,
ssh_connect_timeout_secs: 12,
ssh_tunnels: [{ id: "hop-1", host: "bastion", port: 22, user: "dbx", connect_timeout_secs: 20 }],
transport_layers: [{ type: "ssh", id: "hop-1", host: "bastion", port: 22, user: "dbx", connect_timeout_secs: 20 }],
}),
20_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS,
);
+133 -31
View File
@@ -15,14 +15,7 @@ export interface ConnectionConfig {
password: string;
database?: string;
url_params?: string;
ssh_enabled: boolean;
ssh_tunnels?: SshTunnelConfig[];
proxy_enabled?: boolean;
proxy_type?: "socks5" | "http";
proxy_host?: string;
proxy_port?: number;
proxy_username?: string;
proxy_password?: string;
transport_layers?: TransportLayerConfig[];
ssl: boolean;
ca_cert_path?: string;
oracle_connection_type?: "service_name" | "sid";
@@ -34,6 +27,8 @@ export interface ConnectionConfig {
redis_sentinel_tls?: boolean;
}
export type TransportLayerConfig = ({ type: "ssh" } & SshTunnelConfig) | ({ type: "proxy" } & ProxyTunnelConfig);
export interface SshTunnelConfig {
id: string;
name?: string;
@@ -48,6 +43,17 @@ export interface SshTunnelConfig {
expose_lan?: boolean;
}
export interface ProxyTunnelConfig {
id: string;
name?: string;
enabled?: boolean;
proxy_type?: "socks5" | "http";
host: string;
port: number;
username?: string;
password?: string;
}
export interface ConnectionStoreOptions {
path?: string;
}
@@ -103,6 +109,96 @@ function getSecret(db: Database.Database, connectionId: string, key: string): st
return row?.secret ?? "";
}
function transportLayerSecretSegment(index: number, layer: TransportLayerConfig): string {
return layer.id?.trim() || String(index);
}
function transportLayerSshPasswordKey(index: number, layer: TransportLayerConfig): string {
return `transport_layers.${transportLayerSecretSegment(index, layer)}.ssh_password`;
}
function transportLayerSshKeyPassphraseKey(index: number, layer: TransportLayerConfig): string {
return `transport_layers.${transportLayerSecretSegment(index, layer)}.ssh_key_passphrase`;
}
function transportLayerProxyPasswordKey(index: number, layer: TransportLayerConfig): string {
return `transport_layers.${transportLayerSecretSegment(index, layer)}.proxy_password`;
}
type LegacyConnectionConfig = ConnectionConfig & {
ssh_enabled?: boolean;
ssh_host?: string;
ssh_port?: number;
ssh_user?: string;
ssh_password?: string;
ssh_key_path?: string;
ssh_key_passphrase?: string;
ssh_expose_lan?: boolean;
ssh_connect_timeout_secs?: number;
ssh_tunnels?: SshTunnelConfig[];
proxy_enabled?: boolean;
proxy_type?: "socks5" | "http";
proxy_host?: string;
proxy_port?: number;
proxy_username?: string;
proxy_password?: string;
};
function normalizeTransportLayers(config: LegacyConnectionConfig): TransportLayerConfig[] {
if (Array.isArray(config.transport_layers) && config.transport_layers.length > 0) return config.transport_layers;
const layers: TransportLayerConfig[] = [];
if (config.ssh_enabled && Array.isArray(config.ssh_tunnels) && config.ssh_tunnels.length > 0) {
layers.push(...config.ssh_tunnels.map((hop) => ({ type: "ssh" as const, ...hop })));
} else if (config.ssh_enabled && config.ssh_host) {
layers.push({
type: "ssh",
id: "legacy",
enabled: true,
host: config.ssh_host,
port: config.ssh_port || 22,
user: config.ssh_user || "",
password: config.ssh_password || "",
key_path: config.ssh_key_path || "",
key_passphrase: config.ssh_key_passphrase || "",
connect_timeout_secs: config.ssh_connect_timeout_secs || 5,
expose_lan: !!config.ssh_expose_lan,
});
}
if (config.proxy_enabled && config.proxy_host) {
layers.push({
type: "proxy",
id: "legacy-proxy",
enabled: true,
proxy_type: config.proxy_type || "socks5",
host: config.proxy_host,
port: config.proxy_port || 1080,
username: config.proxy_username || "",
password: config.proxy_password || "",
});
}
return layers;
}
function hydrateTransportLayerSecrets(db: Database.Database, config: ConnectionConfig, connectionId: string) {
config.transport_layers = normalizeTransportLayers(config as LegacyConnectionConfig);
config.transport_layers.forEach((layer, index) => {
if (layer.type === "ssh") {
layer.password ||=
getSecret(db, connectionId, transportLayerSshPasswordKey(index, layer)) ||
(layer.id === "legacy" ? getSecret(db, connectionId, "ssh_password") : getSecret(db, connectionId, `ssh_tunnels.${layer.id || index}.password`));
layer.key_passphrase ||=
getSecret(db, connectionId, transportLayerSshKeyPassphraseKey(index, layer)) ||
(layer.id === "legacy"
? getSecret(db, connectionId, "ssh_key_passphrase")
: getSecret(db, connectionId, `ssh_tunnels.${layer.id || index}.key_passphrase`));
} else {
layer.password ||=
getSecret(db, connectionId, transportLayerProxyPasswordKey(index, layer)) ||
(layer.id === "legacy-proxy" ? getSecret(db, connectionId, "proxy_password") : "");
}
});
}
export async function loadConnections(options: ConnectionStoreOptions = {}): Promise<ConnectionConfig[]> {
const path = options.path ?? defaultDbPath();
if (!existsSync(path)) return [];
@@ -117,7 +213,7 @@ export async function loadConnections(options: ConnectionStoreOptions = {}): Pro
const config: ConnectionConfig = canonicalizeConnection(JSON.parse(row.config_json));
config.id = row.id;
if (!config.password) config.password = getSecret(db, row.id, "password");
if (!config.proxy_password) config.proxy_password = getSecret(db, row.id, "proxy_password");
hydrateTransportLayerSecrets(db, config, row.id);
if (!config.redis_sentinel_password) {
config.redis_sentinel_password = getSecret(db, row.id, "redis_sentinel_password");
}
@@ -204,21 +300,10 @@ export async function addConnection(config: Omit<ConnectionConfig, "id">): Promi
password: "",
database: normalized.database ?? null,
color: null,
ssh_enabled: normalized.ssh_enabled ?? false,
ssh_host: "",
ssh_port: 22,
ssh_user: "",
ssh_password: "",
ssh_key_path: "",
ssh_key_passphrase: "",
ssh_expose_lan: false,
ssh_tunnels: normalized.ssh_tunnels ?? [],
proxy_enabled: normalized.proxy_enabled ?? false,
proxy_type: normalized.proxy_type ?? "socks5",
proxy_host: normalized.proxy_host ?? "",
proxy_port: normalized.proxy_port ?? 1080,
proxy_username: normalized.proxy_username ?? "",
proxy_password: "",
transport_layers: normalizeTransportLayers(normalized as LegacyConnectionConfig).map((layer) => {
if (layer.type === "ssh") return { ...layer, password: "", key_passphrase: "" };
return { ...layer, password: "" };
}),
ssl: normalized.ssl ?? false,
sysdba: false,
oracle_connection_type: normalized.oracle_connection_type ?? null,
@@ -241,13 +326,30 @@ export async function addConnection(config: Omit<ConnectionConfig, "id">): Promi
normalized.password,
);
}
if (normalized.proxy_password) {
db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
id,
"proxy_password",
normalized.proxy_password,
);
}
normalizeTransportLayers(normalized as LegacyConnectionConfig).forEach((layer, index) => {
if (layer.type === "ssh") {
if (layer.password) {
db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
id,
transportLayerSshPasswordKey(index, layer),
layer.password,
);
}
if (layer.key_passphrase) {
db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
id,
transportLayerSshKeyPassphraseKey(index, layer),
layer.key_passphrase,
);
}
} else if (layer.password) {
db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
id,
transportLayerProxyPasswordKey(index, layer),
layer.password,
);
}
});
if (normalized.redis_sentinel_password) {
db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
id,
+22 -15
View File
@@ -1,4 +1,4 @@
import type { ConnectionConfig } from "./connections.js";
import type { ConnectionConfig, ProxyTunnelConfig } from "./connections.js";
import { createServer, connect as netConnect, type Server, type Socket } from "node:net";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
@@ -147,8 +147,15 @@ async function getMysqlPool(config: ConnectionConfig): Promise<import("mysql2/pr
return pool;
}
type ProxyLayer = { type: "proxy" } & ProxyTunnelConfig;
function firstProxyLayer(config: ConnectionConfig): ProxyLayer | undefined {
return config.transport_layers?.find((layer): layer is ProxyLayer => layer.type === "proxy" && layer.enabled !== false && !!layer.host);
}
async function connectionEndpoint(config: ConnectionConfig): Promise<{ host: string; port: number }> {
if (!config.proxy_enabled || !config.proxy_host) return { host: config.host, port: config.port };
const proxy = firstProxyLayer(config);
if (!proxy) return { host: config.host, port: config.port };
const existing = proxyTunnels.get(config.id);
if (existing) return { host: "127.0.0.1", port: existing.port };
@@ -156,7 +163,7 @@ async function connectionEndpoint(config: ConnectionConfig): Promise<{ host: str
const server = createServer((inbound) => {
sockets.add(inbound);
inbound.once("close", () => sockets.delete(inbound));
connectViaProxy(config)
connectViaProxy(config, proxy)
.then((outbound) => {
sockets.add(outbound);
outbound.once("close", () => sockets.delete(outbound));
@@ -187,25 +194,25 @@ function buildConnectionUrl(config: ConnectionConfig, endpoint: { host: string;
return `postgres://${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@${endpoint.host}:${endpoint.port}/${db}${suffix}`;
}
function connectViaProxy(config: ConnectionConfig): Promise<Socket> {
function connectViaProxy(config: ConnectionConfig, proxy: ProxyLayer): Promise<Socket> {
return new Promise((resolve, reject) => {
const socket = netConnect(config.proxy_port || 1080, config.proxy_host || "127.0.0.1");
const socket = netConnect(proxy.port || 1080, proxy.host || "127.0.0.1");
socket.once("error", reject);
socket.once("connect", () => {
if ((config.proxy_type || "socks5") === "http") {
httpConnect(socket, config, resolve, reject);
if ((proxy.proxy_type || "socks5") === "http") {
httpConnect(socket, config, proxy, resolve, reject);
} else {
socks5Connect(socket, config, resolve, reject);
socks5Connect(socket, config, proxy, resolve, reject);
}
});
});
}
function httpConnect(socket: Socket, config: ConnectionConfig, resolve: (socket: Socket) => void, reject: (err: Error) => void) {
function httpConnect(socket: Socket, config: ConnectionConfig, proxy: ProxyLayer, resolve: (socket: Socket) => void, reject: (err: Error) => void) {
const target = `${config.host}:${config.port}`;
const lines = [`CONNECT ${target} HTTP/1.1`, `Host: ${target}`];
if (config.proxy_username || config.proxy_password) {
const token = Buffer.from(`${config.proxy_username || ""}:${config.proxy_password || ""}`).toString("base64");
if (proxy.username || proxy.password) {
const token = Buffer.from(`${proxy.username || ""}:${proxy.password || ""}`).toString("base64");
lines.push(`Proxy-Authorization: Basic ${token}`);
}
socket.write(`${lines.join("\r\n")}\r\n\r\n`);
@@ -227,8 +234,8 @@ function httpConnect(socket: Socket, config: ConnectionConfig, resolve: (socket:
});
}
function socks5Connect(socket: Socket, config: ConnectionConfig, resolve: (socket: Socket) => void, reject: (err: Error) => void) {
const wantsAuth = !!(config.proxy_username || config.proxy_password);
function socks5Connect(socket: Socket, config: ConnectionConfig, proxy: ProxyLayer, resolve: (socket: Socket) => void, reject: (err: Error) => void) {
const wantsAuth = !!(proxy.username || proxy.password);
socket.write(Buffer.from(wantsAuth ? [0x05, 0x02, 0x00, 0x02] : [0x05, 0x01, 0x00]));
socket.once("data", (method) => {
if (method.length < 2 || method[0] !== 0x05) {
@@ -237,8 +244,8 @@ function socks5Connect(socket: Socket, config: ConnectionConfig, resolve: (socke
return;
}
if (method[1] === 0x02) {
const user = Buffer.from(config.proxy_username || "");
const pass = Buffer.from(config.proxy_password || "");
const user = Buffer.from(proxy.username || "");
const pass = Buffer.from(proxy.password || "");
socket.write(Buffer.concat([Buffer.from([0x01, user.length]), user, Buffer.from([pass.length]), pass]));
socket.once("data", (auth) => {
if (auth.length < 2 || auth[1] !== 0x00) {
+7 -25
View File
@@ -152,7 +152,7 @@ async fn connect_agent_pool(
#[cfg(test)]
mod tests {
use super::mongo_legacy_connect_params;
use dbx_core::models::connection::{ConnectionConfig, DatabaseType, ProxyType};
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
fn mongodb_config() -> ConnectionConfig {
ConnectionConfig {
@@ -170,24 +170,9 @@ mod tests {
visible_databases: None,
attached_databases: Vec::new(),
color: None,
ssh_enabled: false,
ssh_host: String::new(),
ssh_port: 22,
ssh_user: String::new(),
ssh_password: String::new(),
ssh_key_path: String::new(),
ssh_key_passphrase: String::new(),
ssh_expose_lan: false,
ssh_connect_timeout_secs: dbx_core::models::connection::default_ssh_connect_timeout_secs(),
ssh_tunnels: Vec::new(),
transport_layers: Vec::new(),
connect_timeout_secs: dbx_core::models::connection::default_connect_timeout_secs(),
query_timeout_secs: dbx_core::models::connection::default_query_timeout_secs(),
proxy_enabled: false,
proxy_type: ProxyType::Socks5,
proxy_host: String::new(),
proxy_port: 1080,
proxy_username: String::new(),
proxy_password: String::new(),
ssl: false,
ca_cert_path: String::new(),
sysdba: false,
@@ -252,8 +237,8 @@ pub async fn load_sidebar_layout(state: State<'_, Arc<AppState>>) -> Result<Opti
#[tauri::command]
pub async fn test_connection(state: State<'_, Arc<AppState>>, config: ConnectionConfig) -> Result<String, String> {
let tunnel_id = format!("{}:test", config.id);
let connection_id =
if config.ssh_enabled && !config.ssh_host.is_empty() { tunnel_id.as_str() } else { config.id.as_str() };
let has_transport_layers = config.has_effective_transport_layers();
let connection_id = if has_transport_layers { tunnel_id.as_str() } else { config.id.as_str() };
let (host, port) = state.connection_host_port(connection_id, &config).await?;
let probe_result = probe_connection_endpoint(&config, &host, port).await;
let url = connection_url_for_endpoint(&config, &host, port);
@@ -426,11 +411,8 @@ pub async fn test_connection(state: State<'_, Arc<AppState>>, config: Connection
},
};
if config.ssh_enabled && !config.ssh_host.is_empty() {
state.tunnels.stop_tunnel(&tunnel_id).await;
}
if config.proxy_enabled && !config.proxy_host.is_empty() {
state.proxy_tunnels.stop_tunnel(&tunnel_id).await;
if has_transport_layers {
state.reset_connection_transport_for_config(&tunnel_id, &config).await;
}
result
@@ -443,7 +425,7 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
let db_config = metadata_connection_config(&config);
state.remove_connection_pools(&id).await;
state.reset_connection_transport(&id).await;
state.reset_connection_transport_for_config(&id, &db_config).await;
let (host, port) = state.connection_host_port(&id, &db_config).await?;
probe_connection_endpoint(&db_config, &host, port).await?;
+1
View File
@@ -22,6 +22,7 @@ pub async fn mongo_list_collections(
}
#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub async fn mongo_find_documents(
state: State<'_, Arc<AppState>>,
connection_id: String,
+7 -7
View File
@@ -13,12 +13,12 @@ pub async fn list_plugins(state: State<'_, Arc<AppState>>) -> Result<Vec<Install
#[tauri::command]
pub async fn jdbc_plugin_status(state: State<'_, Arc<AppState>>) -> Result<JdbcPluginStatus, String> {
jdbc::get_jdbc_plugin_status(&state.plugins.root_dir()).await
jdbc::get_jdbc_plugin_status(state.plugins.root_dir()).await
}
#[tauri::command]
pub async fn install_jdbc_plugin(state: State<'_, Arc<AppState>>) -> Result<JdbcPluginStatus, String> {
jdbc::install_jdbc_plugin(&state.plugins.root_dir()).await
jdbc::install_jdbc_plugin(state.plugins.root_dir()).await
}
#[tauri::command]
@@ -26,17 +26,17 @@ pub async fn install_jdbc_plugin_local(
state: State<'_, Arc<AppState>>,
path: String,
) -> Result<JdbcPluginStatus, String> {
jdbc::install_jdbc_plugin_from_file(&state.plugins.root_dir(), &path).await
jdbc::install_jdbc_plugin_from_file(state.plugins.root_dir(), &path).await
}
#[tauri::command]
pub async fn uninstall_jdbc_plugin(state: State<'_, Arc<AppState>>) -> Result<JdbcPluginStatus, String> {
jdbc::uninstall_jdbc_plugin(&state.plugins.root_dir())
jdbc::uninstall_jdbc_plugin(state.plugins.root_dir())
}
#[tauri::command]
pub async fn list_jdbc_drivers(state: State<'_, Arc<AppState>>) -> Result<Vec<JdbcDriverInfo>, String> {
jdbc::list_jdbc_drivers(&state.plugins.root_dir())
jdbc::list_jdbc_drivers(state.plugins.root_dir())
}
#[tauri::command]
@@ -44,10 +44,10 @@ pub async fn import_jdbc_drivers(
state: State<'_, Arc<AppState>>,
paths: Vec<String>,
) -> Result<Vec<JdbcDriverInfo>, String> {
jdbc::import_jdbc_drivers(&state.plugins.root_dir(), &paths)
jdbc::import_jdbc_drivers(state.plugins.root_dir(), &paths)
}
#[tauri::command]
pub async fn delete_jdbc_driver(state: State<'_, Arc<AppState>>, path: String) -> Result<Vec<JdbcDriverInfo>, String> {
jdbc::delete_jdbc_driver(&state.plugins.root_dir(), &path)
jdbc::delete_jdbc_driver(state.plugins.root_dir(), &path)
}
+2
View File
@@ -8,6 +8,7 @@ use dbx_core::models::connection::DatabaseType;
use dbx_core::sql::split_sql_statements;
#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub async fn execute_query(
state: State<'_, Arc<AppState>>,
connection_id: String,
@@ -47,6 +48,7 @@ pub async fn execute_query(
}
#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub async fn execute_multi(
state: State<'_, Arc<AppState>>,
connection_id: String,
+10 -6
View File
@@ -1,6 +1,6 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use std::time::Instant;
use tauri::{AppHandle, Emitter, State};
@@ -12,8 +12,11 @@ use dbx_core::sql_file_import::{execute_sql_file_content, sql_file_error_progres
pub use dbx_core::sql::{decode_sql_file_bytes, SqlFilePreview, SqlFileRequest, SqlFileStatus};
static SQL_FILE_EXECUTIONS: std::sync::LazyLock<RwLock<HashMap<String, CancellationToken>>> =
std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
static SQL_FILE_EXECUTIONS: OnceLock<RwLock<HashMap<String, CancellationToken>>> = OnceLock::new();
fn sql_file_executions() -> &'static RwLock<HashMap<String, CancellationToken>> {
SQL_FILE_EXECUTIONS.get_or_init(|| RwLock::new(HashMap::new()))
}
#[cfg(test)]
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -47,7 +50,7 @@ pub async fn execute_sql_file(
) -> Result<(), String> {
let token = CancellationToken::new();
{
let mut executions = SQL_FILE_EXECUTIONS.write().await;
let mut executions = sql_file_executions().write().await;
register_sql_file_execution(&mut executions, request.execution_id.clone(), token.clone())?;
}
@@ -56,7 +59,7 @@ pub async fn execute_sql_file(
let result = execute_sql_file_inner(&app, &state, &request, token, started_at).await;
{
let mut executions = SQL_FILE_EXECUTIONS.write().await;
let mut executions = sql_file_executions().write().await;
remove_sql_file_execution(&mut executions, &request.execution_id);
}
result
@@ -64,7 +67,7 @@ pub async fn execute_sql_file(
#[tauri::command]
pub async fn cancel_sql_file_execution(execution_id: String) -> Result<bool, String> {
let executions = SQL_FILE_EXECUTIONS.read().await;
let executions = sql_file_executions().read().await;
if let Some(token) = executions.get(&execution_id) {
token.cancel();
Ok(true)
@@ -119,6 +122,7 @@ fn remove_sql_file_execution(executions: &mut HashMap<String, CancellationToken>
executions.remove(execution_id);
}
#[allow(clippy::too_many_arguments)]
fn emit_progress(
app: &AppHandle,
execution_id: &str,
+9 -6
View File
@@ -1,5 +1,5 @@
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use tauri::{AppHandle, Emitter, State};
use tokio::sync::RwLock;
@@ -10,19 +10,22 @@ use crate::commands::transfer::get_db_type;
// Re-export types for backward compatibility
pub use dbx_core::table_import::{TableImportPreview, TableImportProgress, TableImportRequest, TableImportSummary};
static CANCELLED_IMPORTS: std::sync::LazyLock<RwLock<HashSet<String>>> =
std::sync::LazyLock::new(|| RwLock::new(HashSet::new()));
static CANCELLED_IMPORTS: OnceLock<RwLock<HashSet<String>>> = OnceLock::new();
fn cancelled_imports() -> &'static RwLock<HashSet<String>> {
CANCELLED_IMPORTS.get_or_init(|| RwLock::new(HashSet::new()))
}
fn emit_progress(app: &AppHandle, progress: TableImportProgress) {
let _ = app.emit("table-import-progress", progress);
}
async fn is_cancelled(import_id: &str) -> bool {
CANCELLED_IMPORTS.read().await.contains(import_id)
cancelled_imports().read().await.contains(import_id)
}
async fn clear_cancelled(import_id: &str) {
CANCELLED_IMPORTS.write().await.remove(import_id);
cancelled_imports().write().await.remove(import_id);
}
#[tauri::command]
@@ -60,6 +63,6 @@ pub async fn import_table_file(
#[tauri::command]
pub async fn cancel_table_import(import_id: String) -> Result<bool, String> {
CANCELLED_IMPORTS.write().await.insert(import_id);
cancelled_imports().write().await.insert(import_id);
Ok(true)
}
+1
View File
@@ -166,6 +166,7 @@ pub(crate) fn apply_desktop_settings(app: &tauri::AppHandle, desktop_settings: &
}
#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
use super::{should_hide_window_on_close, should_setup_desktop_tray, should_show_main_window_after_setup};