feat(plugins): add interactive prompts and richer connection forms

This commit is contained in:
Jinpy authored and GitHub committed 2026-09-17 19:29:28 +08:00
1 parent fac270fc8a
commit e4bda693fb
42 files changed
+3922 -200

No files matched your search

@@ -3610,7 +3610,7 @@ const connectionLabelSmallPaddedClass = `${connectionLabelClass} pt-2 text-xs`;
function pluginFieldValue(field: PluginFormField): PluginFormFieldValue { function pluginFieldValue(field: PluginFormField): PluginFormFieldValue {
if (field.binding === "name") return form.value.name; if (field.binding === "name") return form.value.name;
return pluginFormValues.value[field.key] ?? field.default; return pluginFormValues.value[field.key] ?? field.default ?? undefined;
} }
function pluginFieldHasValue(field: PluginFormField): boolean { function pluginFieldHasValue(field: PluginFormField): boolean {
@@ -4,9 +4,19 @@ import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n"; import i18n from "@/i18n";
import PluginConnectionFields from "./PluginConnectionFields.vue"; import PluginConnectionFields from "./PluginConnectionFields.vue";
import type { PluginConnectionProviderContribution, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database"; import type { PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
const invokePluginMock = vi.fn(); const invokePluginMock = vi.fn();
const { pickPluginFieldFileMock, tauriRuntime } = vi.hoisted(() => ({
pickPluginFieldFileMock: vi.fn(),
tauriRuntime: { value: false },
}));
vi.mock("@/lib/plugins/pluginFieldPicker", () => ({
PLUGIN_PICKER_MAX_BYTES: 1_048_576,
pickPluginFieldFile: (...args: unknown[]) => pickPluginFieldFileMock(...args),
}));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => tauriRuntime.value }));
vi.mock("@/lib/backend/api", () => ({ vi.mock("@/lib/backend/api", () => ({
listLocalSshKeys: vi.fn(async () => [ listLocalSshKeys: vi.fn(async () => [
@@ -56,6 +66,72 @@ async function mountFields(initialValues: Record<string, PluginFormFieldValue> =
return state; return state;
} }
describe("PluginConnectionFields file picker", () => {
const pickerContribution = (picker: PluginFormField["picker"], contentField = true): PluginConnectionProviderContribution => ({
type: "connection-provider",
id: "ssh.connection",
label: "SSH",
database_type: "ssh",
fields: [{ key: "private_key_path", label: "Private key path", type: "text", picker }, ...(contentField ? [{ key: "private_key", label: "Private key", type: "textarea" as const, binding: "secret" as const }] : [])],
});
it("stores the chosen client path on desktop and drops a stale uploaded copy", async () => {
tauriRuntime.value = true;
pickPluginFieldFileMock.mockReset().mockResolvedValue({ path: "/Users/dev/.ssh/id_rsa", name: "id_rsa" });
const provider = pickerContribution({ kind: "file", accept: [".pem"], content_field: "private_key" });
const state = await mountContribution(provider, { private_key: "OLD-UPLOADED-KEY" });
const browse = document.querySelector<HTMLButtonElement>("#ssh-connection-private_key_path-picker");
expect(browse?.textContent).toContain("Choose file");
browse?.click();
await vi.waitFor(() => expect(state.values.private_key_path).toBe("/Users/dev/.ssh/id_rsa"));
// The plugin prefers content over a path, so picking a path must clear the
// previously uploaded key or the stale one would keep winning.
expect(state.values.private_key).toBeUndefined();
});
it("uploads the file content into the paired field on browser hosts", async () => {
tauriRuntime.value = false;
pickPluginFieldFileMock.mockReset().mockResolvedValue({ content: "UPLOADED-KEY", name: "id_rsa" });
const provider = pickerContribution({ kind: "file", accept: [".pem"], content_field: "private_key" });
const state = await mountContribution(provider, { private_key_path: "/Users/dev/.ssh/id_rsa" });
const upload = document.querySelector<HTMLButtonElement>("#ssh-connection-private_key_path-picker");
expect(upload?.textContent).toContain("Upload file");
upload?.click();
await vi.waitFor(() => expect(state.values.private_key).toBe("UPLOADED-KEY"));
// A browser path would point at the user's machine, not the host's.
expect(state.values.private_key_path).toBeUndefined();
});
it("hides a browser-unsupported picker and keeps the desktop one available", async () => {
const provider = pickerContribution({ kind: "file" }, false);
tauriRuntime.value = false;
await mountContribution(provider, {});
expect(document.querySelector("#ssh-connection-private_key_path-picker")).toBeNull();
tauriRuntime.value = true;
await mountContribution(provider, {});
expect(document.querySelector("#ssh-connection-private_key_path-picker")).not.toBeNull();
});
it("surfaces a picker failure without touching the form", async () => {
tauriRuntime.value = false;
pickPluginFieldFileMock.mockReset().mockRejectedValue(new Error("File is larger than 1024 KiB"));
const provider = pickerContribution({ kind: "file", content_field: "private_key" });
const state = await mountContribution(provider, { private_key: "KEEP-ME" });
document.querySelector<HTMLButtonElement>("#ssh-connection-private_key_path-picker")?.click();
await vi.waitFor(() => expect(pickPluginFieldFileMock).toHaveBeenCalled());
await nextTick();
expect(state.values).toEqual({ private_key: "KEEP-ME" });
});
});
afterEach(() => { afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount(); for (const app of mountedApps.splice(0)) app.unmount();
document.body.innerHTML = ""; document.body.innerHTML = "";
@@ -111,6 +187,39 @@ describe("PluginConnectionFields", () => {
expect(state.values).toEqual({ password: "secret", host: "db.internal" }); expect(state.values).toEqual({ password: "secret", host: "db.internal" });
}); });
it('renders a null value as an empty field instead of the text "null"', async () => {
// Hosts before the manifest serialization fix hydrated untouched fields with
// `null`, and a null reaching an <input> is coerced to the string "null" by
// the DOM — a password field then looked non-empty without any user input.
const provider: PluginConnectionProviderContribution = {
type: "connection-provider",
id: "null.connection",
label: "Nulls",
database_type: "nulls",
fields: [
{ key: "sudo_password", label: "Sudo password", type: "password", binding: "secret" },
{ key: "sudo_command", label: "Sudo command", type: "text", binding: "config" },
{ key: "set_env", label: "Env", type: "textarea", binding: "config" },
],
};
const state = await mountContribution(provider, {
sudo_password: null,
sudo_command: null,
set_env: null,
} as unknown as Record<string, PluginFormFieldValue>);
expect(document.querySelector<HTMLInputElement>("#null-connection-sudo_password")?.value).toBe("");
expect(document.querySelector<HTMLInputElement>("#null-connection-sudo_command")?.value).toBe("");
expect(document.querySelector<HTMLTextAreaElement>("#null-connection-set_env")?.value).toBe("");
// Editing still emits a real value, so a null never survives the dialog.
const command = document.querySelector<HTMLInputElement>("#null-connection-sudo_command")!;
command.value = "sudo -n true";
command.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
expect(state.values.sudo_command).toBe("sudo -n true");
});
it("can hide host-owned common bindings", async () => { it("can hide host-owned common bindings", async () => {
contribution.fields[0].binding = "host"; contribution.fields[0].binding = "host";
await mountFields({}, ["host"]); await mountFields({}, ["host"]);
@@ -222,6 +331,69 @@ describe("PluginConnectionFields", () => {
expect(document.querySelector("#kafka-connection-msk_region")).toBeNull(); expect(document.querySelector("#kafka-connection-msk_region")).toBeNull();
}); });
it("renders a field only while every clause of an all_of condition holds (sudo_source + read_only)", async () => {
// The SSH plugin cannot express "sudo_source = custom AND read_only =
// false" with one clause per field; all_of + a boolean literal covers it.
const ssh: PluginConnectionProviderContribution = {
type: "connection-provider",
id: "ssh.connection",
label: "SSH",
database_type: "ssh",
fields: [
{
key: "read_only",
label: "Read only",
type: "boolean",
default: false,
},
{
key: "sudo_source",
label: "Sudo source",
type: "select",
default: "none",
options: [
{ label: "None", value: "none" },
{ label: "Custom", value: "custom" },
],
},
{
key: "sudo_command",
label: "Sudo command",
type: "text",
visible_when: {
all_of: [
{ field: "sudo_source", one_of: ["custom"] },
{ field: "read_only", one_of: [false] },
],
},
required_when: {
all_of: [
{ field: "sudo_source", one_of: ["custom"] },
{ field: "read_only", one_of: [false] },
],
},
},
],
};
const state = await mountContribution(ssh, {});
expect(document.querySelector("#ssh-connection-sudo_command")).toBeNull();
state.values = { sudo_source: "custom", read_only: false };
await nextTick();
expect(document.querySelector("#ssh-connection-sudo_command")).not.toBeNull();
expect(document.querySelector('label[for="ssh-connection-sudo_command"]')?.textContent).toContain("*");
// Read-only sessions ignore the sudo block entirely.
state.values = { sudo_source: "custom", read_only: true };
await nextTick();
expect(document.querySelector("#ssh-connection-sudo_command")).toBeNull();
state.values = { sudo_source: "none", read_only: false };
await nextTick();
expect(document.querySelector("#ssh-connection-sudo_command")).toBeNull();
});
it("offers local SSH keys on private_key_path fields and fills the chosen path", async () => { it("offers local SSH keys on private_key_path fields and fills the chosen path", async () => {
const withKey: PluginConnectionProviderContribution = { const withKey: PluginConnectionProviderContribution = {
type: "connection-provider", type: "connection-provider",
@@ -1,14 +1,19 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from "vue"; import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import { FolderOpen } from "@lucide/vue";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import PasswordInput from "@/components/ui/PasswordInput.vue"; import PasswordInput from "@/components/ui/PasswordInput.vue";
import PasswordTextarea from "@/components/ui/PasswordTextarea.vue"; import PasswordTextarea from "@/components/ui/PasswordTextarea.vue";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { useToast } from "@/composables/useToast";
import { pluginFieldIsRequired, pluginFieldIsVisible, type PluginFieldResolver } from "@/lib/plugins/pluginFieldConditions"; import { pluginFieldIsRequired, pluginFieldIsVisible, type PluginFieldResolver } from "@/lib/plugins/pluginFieldConditions";
import { pickPluginFieldFile } from "@/lib/plugins/pluginFieldPicker";
import { invokePlugin, listLocalSshKeys } from "@/lib/backend/api"; import { invokePlugin, listLocalSshKeys } from "@/lib/backend/api";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import type { LocalSshKey, PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldOption, PluginFormFieldValue } from "@/types/database"; import type { LocalSshKey, PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldOption, PluginFormFieldValue } from "@/types/database";
const props = defineProps<{ const props = defineProps<{
@@ -24,12 +29,13 @@ const emit = defineEmits<{
}>(); }>();
const { t } = useI18n(); const { t } = useI18n();
const { toast } = useToast();
const formValues = computed(() => props.modelValue); const formValues = computed(() => props.modelValue);
/** Value of any sibling field by key (condition evaluation reads current form values). */ /** Value of any sibling field by key (condition evaluation reads current form values). */
function readFieldValue(key: string): PluginFormFieldValue { function readFieldValue(key: string): PluginFormFieldValue {
const field = props.contribution.fields.find((candidate) => candidate.key === key); const field = props.contribution.fields.find((candidate) => candidate.key === key);
return field ? (formValues.value[key] ?? field.default) : undefined; return field ? (formValues.value[key] ?? field.default ?? undefined) : undefined;
} }
const resolveSiblingField: PluginFieldResolver = (key) => props.contribution.fields.find((candidate) => candidate.key === key); const resolveSiblingField: PluginFieldResolver = (key) => props.contribution.fields.find((candidate) => candidate.key === key);
function fieldVisible(field: PluginFormField): boolean { function fieldVisible(field: PluginFormField): boolean {
@@ -43,7 +49,18 @@ const visibleFields = computed(() => props.contribution.fields.filter((field) =>
const isConnectionDialogLayout = computed(() => props.layout === "connection-dialog"); const isConnectionDialogLayout = computed(() => props.layout === "connection-dialog");
function fieldValue(field: PluginFormField): PluginFormFieldValue { function fieldValue(field: PluginFormField): PluginFormFieldValue {
return formValues.value[field.key] ?? field.default ?? defaultValueFor(field); // `null` is "unset": hosts used to hydrate untouched fields with a null
// default, and a null reaching an input must not look like a stored value.
const raw = formValues.value[field.key];
const value = raw ?? field.default ?? defaultValueFor(field);
return value === null ? undefined : value;
}
/** Text/number inputs render any primitive as text; `null` stays empty. */
function fieldInputValue(field: PluginFormField): string | number {
const value = fieldValue(field);
if (typeof value === "boolean") return String(value);
return value ?? "";
} }
function updateField(field: PluginFormField, value: PluginFormFieldValue) { function updateField(field: PluginFormField, value: PluginFormFieldValue) {
@@ -174,7 +191,74 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
const selected = localSshKeys.value.find((key) => key.path === select.value); const selected = localSshKeys.value.find((key) => key.path === select.value);
select.value = ""; select.value = "";
if (!selected) return; if (!selected) return;
updateField(field, selected.path); pickPluginFieldPath(field, selected.path);
}
// ---------------------------------------------------------------------------
// Manifest-declared local file action (`picker`, Host API 1.1)
// ---------------------------------------------------------------------------
/** Fields whose picker acts on the working copy; the plugin reads the file. */
function pickerField(field: PluginFormField) {
return field.picker;
}
/**
* Browser hosts cannot hand a path to the plugin, so the picker uploads the
* file content into the declared `content_field` instead. A picker without a
* `content_field` is desktop-only and stays hidden in the browser.
*/
function pickerVisible(field: PluginFormField): boolean {
const picker = pickerField(field);
if (!picker) return false;
if (isTauriRuntime()) return true;
return picker.kind === "file" && Boolean(picker.content_field);
}
const pickerBusyField = ref<string | null>(null);
function pickerLabelKey(field: PluginFormField): string {
const picker = pickerField(field);
if (picker?.kind === "directory") return isTauriRuntime() ? "connection.pluginFieldSelectDirectory" : "connection.pluginFieldSelectFile";
return isTauriRuntime() ? "connection.pluginFieldSelectFile" : "connection.pluginFieldUploadFile";
}
/** Path selection (desktop) and the SSH key dropdown share this entry point. */
function pickPluginFieldPath(field: PluginFormField, path: string) {
const picker = pickerField(field);
const next = { ...formValues.value, [field.key]: path };
// The plugin treats content as more specific than a path, so selecting a path
// must clear the uploaded copy — otherwise a stale upload keeps winning.
if (picker?.content_field) delete next[picker.content_field];
emit("update:modelValue", next);
}
/** Upload content into the paired field and clear the (meaningless) path. */
function pickPluginFieldContent(field: PluginFormField, contentKey: string, content: string) {
const next = { ...formValues.value, [contentKey]: content };
delete next[field.key];
emit("update:modelValue", next);
}
async function runPluginFieldPicker(field: PluginFormField) {
const picker = pickerField(field);
if (!picker || pickerBusyField.value) return;
pickerBusyField.value = field.key;
try {
const picked = await pickPluginFieldFile(picker);
if (!picked) return;
if (picked.path !== undefined) {
pickPluginFieldPath(field, picked.path);
return;
}
if (picked.content !== undefined && picker.content_field) {
pickPluginFieldContent(field, picker.content_field, picked.content);
}
} catch (error) {
toast(error instanceof Error ? error.message : String(error));
} finally {
pickerBusyField.value = null;
}
} }
</script> </script>
@@ -207,7 +291,7 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
</SelectContent> </SelectContent>
</Select> </Select>
<div v-else-if="isLocalSshKeyField(field)" class="flex items-center gap-1.5"> <div v-else-if="isLocalSshKeyField(field)" class="flex items-center gap-1.5">
<Input :id="fieldId(field)" type="text" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" class="min-w-0 flex-1" @update:model-value="updateTextField(field, $event)" /> <Input :id="fieldId(field)" type="text" :model-value="fieldInputValue(field)" :placeholder="field.placeholder" class="min-w-0 flex-1" @update:model-value="updateTextField(field, $event)" />
<select <select
class="h-9 w-40 shrink-0 rounded-md border border-input bg-transparent px-2 text-xs outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50" class="h-9 w-40 shrink-0 rounded-md border border-input bg-transparent px-2 text-xs outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="localSshKeys.length === 0" :disabled="localSshKeys.length === 0"
@@ -219,7 +303,7 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
<option v-for="key in localSshKeys" :key="key.path" :value="key.path" :title="key.path">{{ localSshKeyLabel(key) }}</option> <option v-for="key in localSshKeys" :key="key.path" :value="key.path" :title="key.path">{{ localSshKeyLabel(key) }}</option>
</select> </select>
</div> </div>
<Input v-else :id="fieldId(field)" :type="field.type === 'number' ? 'number' : 'text'" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" @update:model-value="updateTextField(field, $event)" /> <Input v-else :id="fieldId(field)" :type="field.type === 'number' ? 'number' : 'text'" :model-value="fieldInputValue(field)" :placeholder="field.placeholder" @update:model-value="updateTextField(field, $event)" />
</template> </template>
<PasswordInput v-else-if="field.type === 'password'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" /> <PasswordInput v-else-if="field.type === 'password'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
<PasswordTextarea v-else-if="field.type === 'textarea' && field.binding === 'secret'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" /> <PasswordTextarea v-else-if="field.type === 'textarea' && field.binding === 'secret'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
@@ -244,6 +328,12 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
<div v-else-if="field.type === 'boolean'" class="flex h-9 items-center"> <div v-else-if="field.type === 'boolean'" class="flex h-9 items-center">
<Switch :id="fieldId(field)" :model-value="Boolean(fieldValue(field))" size="sm" @update:model-value="updateBooleanField(field, $event)" /> <Switch :id="fieldId(field)" :model-value="Boolean(fieldValue(field))" size="sm" @update:model-value="updateBooleanField(field, $event)" />
</div> </div>
<div v-if="pickerVisible(field)" class="flex items-center gap-2">
<Button :id="`${fieldId(field)}-picker`" variant="outline" size="sm" class="h-8 gap-1.5 text-xs" :disabled="pickerBusyField === field.key" @click="runPluginFieldPicker(field)">
<FolderOpen class="size-3.5" aria-hidden="true" />
{{ t(pickerLabelKey(field)) }}
</Button>
</div>
<div v-if="field.description" class="text-[11px] leading-5 text-muted-foreground">{{ field.description }}</div> <div v-if="field.description" class="text-[11px] leading-5 text-muted-foreground">{{ field.description }}</div>
</div> </div>
</div> </div>
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from "vue"; import { ref, computed, watch, onMounted, onBeforeUnmount } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { TriangleAlert } from "@lucide/vue"; import { TriangleAlert } from "@lucide/vue";
@@ -12,7 +12,7 @@ import { apiUrl } from "@/lib/common/webPath";
interface SshPromptRequest { interface SshPromptRequest {
id: string; id: string;
kind: "HostKeyVerify" | "HostKeyChanged" | "SecretInput" | "WorkerUploadConsent"; kind: "HostKeyVerify" | "HostKeyChanged" | "SecretInput" | "WorkerUploadConsent" | "UserInput";
host: string; host: string;
port: number; port: number;
key_type?: string | null; key_type?: string | null;
@@ -20,6 +20,14 @@ interface SshPromptRequest {
previous_fingerprint?: string | null; previous_fingerprint?: string | null;
prompt?: string | null; prompt?: string | null;
echo?: boolean; echo?: boolean;
/** UserInput: who asked (plugin display name). */
source?: string | null;
/** UserInput: caller-provided heading, already localized by the caller. */
title?: string | null;
/** UserInput: preset answer offered in the input. */
default_value?: string | null;
/** UserInput: fixed answers; empty means free-form input. */
options?: Array<{ value: string; label: string }> | null;
} }
interface SshHostKeyNotice { interface SshHostKeyNotice {
@@ -39,20 +47,39 @@ const { toast } = useToast();
const queue = ref<SshPromptRequest[]>([]); const queue = ref<SshPromptRequest[]>([]);
const current = computed<SshPromptRequest | null>(() => queue.value[0] ?? null); const current = computed<SshPromptRequest | null>(() => queue.value[0] ?? null);
const isSecretPrompt = computed(() => current.value?.kind === "SecretInput"); const isSecretPrompt = computed(() => current.value?.kind === "SecretInput");
const isPluginInputPrompt = computed(() => current.value?.kind === "UserInput");
const isTextPrompt = computed(() => isSecretPrompt.value || isPluginInputPrompt.value);
const isWorkerUploadPrompt = computed(() => current.value?.kind === "WorkerUploadConsent"); const isWorkerUploadPrompt = computed(() => current.value?.kind === "WorkerUploadConsent");
const isHostKeyChanged = computed(() => current.value?.kind === "HostKeyChanged"); const isHostKeyChanged = computed(() => current.value?.kind === "HostKeyChanged");
const promptOptions = computed(() => current.value?.options ?? []);
const titleKey = computed(() => { const titleKey = computed(() => {
if (isSecretPrompt.value) return "connection.sshInteractiveTitle"; if (isSecretPrompt.value) return "connection.sshInteractiveTitle";
if (isPluginInputPrompt.value) return "connection.sshPluginInputTitle";
if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentTitle"; if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentTitle";
if (isHostKeyChanged.value) return "connection.sshHostKeyChangedTitle"; if (isHostKeyChanged.value) return "connection.sshHostKeyChangedTitle";
return "connection.sshHostKeyVerifyTitle"; return "connection.sshHostKeyVerifyTitle";
}); });
const messageKey = computed(() => { const messageKey = computed(() => {
if (isSecretPrompt.value) return "connection.sshInteractiveMessage"; if (isSecretPrompt.value) return "connection.sshInteractiveMessage";
if (isPluginInputPrompt.value) return "connection.sshPluginInputMessage";
if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentMessage"; if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentMessage";
if (isHostKeyChanged.value) return "connection.sshHostKeyChangedMessage"; if (isHostKeyChanged.value) return "connection.sshHostKeyChangedMessage";
return "connection.sshHostKeyVerifyMessage"; return "connection.sshHostKeyVerifyMessage";
}); });
/**
* A plugin's question carries its own heading and body, so the dialog shows
* what was asked instead of the host's SSH wording. The origin line names the
* plugin so a bastion MFA prompt is never mistaken for a host-owned one.
*/
const dialogTitle = computed(() => current.value?.title?.trim() || t(titleKey.value));
const dialogDescription = computed(() => {
if (isPluginInputPrompt.value) {
const source = current.value?.source?.trim();
return source ? t("connection.sshPluginInputMessage", { source }) : t("connection.sshPluginInputMessageNoSource");
}
return t(messageKey.value, { host: current.value?.host ?? "", port: current.value?.port ?? "" });
});
const promptBody = computed(() => (isPluginInputPrompt.value ? current.value?.prompt?.trim() || t("connection.sshInteractiveDefaultPrompt") : ""));
const visible = ref(false); const visible = ref(false);
const remember = ref(true); const remember = ref(true);
@@ -236,7 +263,9 @@ function dismissPrompt(id: string) {
function resetPromptState() { function resetPromptState() {
remember.value = true; remember.value = true;
secretCode.value = ""; // A caller may suggest an answer (e.g. a remembered bastion account); the
// user still has to submit it.
secretCode.value = current.value?.kind === "UserInput" ? (current.value?.default_value ?? "") : "";
} }
function fingerprintBody(value: string | null | undefined): string { function fingerprintBody(value: string | null | undefined): string {
@@ -264,6 +293,19 @@ function reject() {
function submitSecret() { function submitSecret() {
void resolve("secret"); void resolve("secret");
} }
/** A fixed-choice plugin prompt is answered by picking an option. */
function submitOption(value: string) {
secretCode.value = value;
void resolve("secret");
}
// Every prompt gets a clean slate (and its own preset answer) when it reaches
// the front of the queue.
watch(
() => current.value?.id,
() => resetPromptState(),
);
</script> </script>
<template> <template>
@@ -279,9 +321,9 @@ function submitSecret() {
100). --> 100). -->
<DialogContent class="flex max-h-[min(36rem,calc(var(--dbx-viewport-height)-2rem))] w-full max-w-[32rem] flex-col gap-4 overflow-hidden" overlay-class="z-[200]" portal-class="z-[200]" :show-close-button="false" @interact-outside.prevent @escape-key-down.prevent> <DialogContent class="flex max-h-[min(36rem,calc(var(--dbx-viewport-height)-2rem))] w-full max-w-[32rem] flex-col gap-4 overflow-hidden" overlay-class="z-[200]" portal-class="z-[200]" :show-close-button="false" @interact-outside.prevent @escape-key-down.prevent>
<DialogHeader class="shrink-0"> <DialogHeader class="shrink-0">
<DialogTitle>{{ t(titleKey) }}</DialogTitle> <DialogTitle>{{ dialogTitle }}</DialogTitle>
<DialogDescription class="text-muted-foreground"> <DialogDescription class="text-muted-foreground">
{{ t(messageKey, { host: current?.host ?? "", port: current?.port ?? "" }) }} {{ dialogDescription }}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
@@ -323,6 +365,24 @@ function submitSecret() {
<span>{{ current.kind === "WorkerUploadConsent" ? t("connection.sshWorkerUploadConsentRemember") : t("connection.sshHostKeyVerifyRemember") }}</span> <span>{{ current.kind === "WorkerUploadConsent" ? t("connection.sshWorkerUploadConsentRemember") : t("connection.sshHostKeyVerifyRemember") }}</span>
</label> </label>
<div v-else-if="isPluginInputPrompt" class="space-y-3">
<p class="whitespace-pre-wrap text-sm text-muted-foreground">{{ promptBody }}</p>
<div v-if="promptOptions.length" class="flex flex-col gap-2">
<Button v-for="option in promptOptions" :key="option.value" variant="outline" class="h-auto w-full justify-start py-2 text-left whitespace-normal" :disabled="resolving" @click="submitOption(option.value)">
{{ option.label }}
</Button>
</div>
<input
v-else
v-model="secretCode"
:type="current.echo ? 'text' : 'password'"
autocomplete="one-time-code"
class="w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-sm outline-none focus:ring-2 focus:ring-ring"
:placeholder="t('connection.sshInteractivePlaceholder')"
@keydown.enter="submitSecret"
/>
</div>
<div v-else-if="current.kind === 'SecretInput'" class="space-y-2"> <div v-else-if="current.kind === 'SecretInput'" class="space-y-2">
<p class="whitespace-pre-wrap text-sm text-muted-foreground"> <p class="whitespace-pre-wrap text-sm text-muted-foreground">
{{ current.prompt || t("connection.sshInteractiveDefaultPrompt") }} {{ current.prompt || t("connection.sshInteractiveDefaultPrompt") }}
@@ -340,7 +400,7 @@ function submitSecret() {
<DialogFooter class="shrink-0"> <DialogFooter class="shrink-0">
<Button variant="outline" :disabled="resolving" @click="reject"> <Button variant="outline" :disabled="resolving" @click="reject">
{{ t(isSecretPrompt ? "connection.sshInteractiveCancel" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentReject" : isHostKeyChanged ? "connection.sshHostKeyChangedClose" : "connection.sshHostKeyVerifyReject") }} {{ t(isTextPrompt ? "connection.sshInteractiveCancel" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentReject" : isHostKeyChanged ? "connection.sshHostKeyChangedClose" : "connection.sshHostKeyVerifyReject") }}
</Button> </Button>
<template v-if="isHostKeyChanged"> <template v-if="isHostKeyChanged">
<Button variant="outline" :disabled="resolving" @click="acceptSessionOnly"> <Button variant="outline" :disabled="resolving" @click="acceptSessionOnly">
@@ -350,11 +410,13 @@ function submitSecret() {
{{ t("connection.sshHostKeyChangedUpdate") }} {{ t("connection.sshHostKeyChangedUpdate") }}
</Button> </Button>
</template> </template>
<Button v-else-if="current?.kind !== 'SecretInput'" :disabled="resolving" @click="accept"> <!-- A fixed-choice plugin prompt is answered by the option buttons in
{{ t(isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentAccept" : "connection.sshHostKeyVerifyAccept") }} the body, so it needs no submit button here. -->
<Button v-else-if="isTextPrompt && !(isPluginInputPrompt && promptOptions.length)" :disabled="resolving || !secretCode" @click="submitSecret">
{{ t(isSecretPrompt ? "connection.sshInteractiveSubmit" : "connection.sshPluginInputSubmit") }}
</Button> </Button>
<Button v-else :disabled="resolving || !secretCode" @click="submitSecret"> <Button v-else-if="!isTextPrompt" :disabled="resolving" @click="accept">
{{ t("connection.sshInteractiveSubmit") }} {{ t(isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentAccept" : "connection.sshHostKeyVerifyAccept") }}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -432,4 +432,122 @@ describe("SshHostKeyPromptDialog web bridge", () => {
}); });
}); });
}); });
it("relays a plugin question and submits the typed answer", async () => {
// Host API `host/requestUserInput`: a plugin backend (e.g. the SSH plugin
// answering a bastion's keyboard-interactive MFA) asks through the same
// dialog, and the host only carries the question and the typed value.
await mountDialog();
const eventSource = MockEventSource.instances[0];
eventSource?.emit({
type: "prompt",
request: {
id: "plugin-input-1",
kind: "UserInput",
host: "",
port: 0,
prompt: "Verification code (6 digits)",
title: "JumpServer login",
source: "SSH Terminal",
echo: false,
default_value: "12",
},
});
await nextTick();
expect(document.body.textContent).toContain("JumpServer login");
expect(document.body.textContent).toContain("SSH Terminal needs input before it can continue.");
expect(document.body.textContent).toContain("Verification code (6 digits)");
const input = document.body.querySelector<HTMLInputElement>("input");
expect(input?.type).toBe("password");
// A caller-provided default is offered but still has to be submitted.
expect(input?.value).toBe("12");
if (!input) throw new Error("plugin prompt input was not rendered");
input.value = "654321";
input.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
const buttons = [...document.body.querySelectorAll<HTMLButtonElement>("button")];
expect(buttons.map((button) => button.textContent?.trim())).toEqual(["Cancel", "Submit"]);
buttons[buttons.length - 1].click();
await vi.waitFor(() => {
expect(resolveSshPromptMock).toHaveBeenCalledWith({
id: "plugin-input-1",
action: "secret",
remember: undefined,
secret: "654321",
});
});
});
it("answers a fixed-choice plugin question by picking an option", async () => {
await mountDialog();
const eventSource = MockEventSource.instances[0];
eventSource?.emit({
type: "prompt",
request: {
id: "plugin-choice-1",
kind: "UserInput",
host: "",
port: 0,
title: "Select account",
prompt: "Which bastion account should be used?",
source: "LDAP Directory",
options: [
{ value: "jinpy", label: "jinpy (admin)" },
{ value: "deploy", label: "deploy (read-only)" },
],
},
});
await nextTick();
expect(document.body.textContent).toContain("Which bastion account should be used?");
const buttons = [...document.body.querySelectorAll<HTMLButtonElement>("button")];
// Options replace the free-form input, so only the choices plus Cancel show.
expect(buttons.map((button) => button.textContent?.trim())).toEqual(["jinpy (admin)", "deploy (read-only)", "Cancel"]);
expect(document.body.querySelector("input")).toBeNull();
buttons.find((button) => button.textContent?.trim() === "deploy (read-only)")?.click();
await vi.waitFor(() => {
expect(resolveSshPromptMock).toHaveBeenCalledWith({
id: "plugin-choice-1",
action: "secret",
remember: undefined,
secret: "deploy",
});
});
});
it("cancels a plugin question without answering it", async () => {
await mountDialog();
const eventSource = MockEventSource.instances[0];
eventSource?.emit({
type: "prompt",
request: {
id: "plugin-input-cancel",
kind: "UserInput",
host: "",
port: 0,
prompt: "Verification code",
source: "SSH Terminal",
},
});
await nextTick();
const cancel = [...document.body.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "Cancel");
cancel?.click();
await vi.waitFor(() => {
expect(resolveSshPromptMock).toHaveBeenCalledWith({
id: "plugin-input-cancel",
action: "reject",
remember: undefined,
secret: undefined,
});
});
});
}); });
+7
View File
@@ -1183,6 +1183,13 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Yoxlama kodunu daxil edin", sshInteractivePlaceholder: "Yoxlama kodunu daxil edin",
sshInteractiveSubmit: "Yoxla", sshInteractiveSubmit: "Yoxla",
sshInteractiveCancel: "Ləğv et", sshInteractiveCancel: "Ləğv et",
pluginFieldSelectFile: "Fayl seç…",
pluginFieldUploadFile: "Fayl yüklə…",
pluginFieldSelectDirectory: "Qovluq seç…",
sshPluginInputTitle: "Giriş tələb olunur",
sshPluginInputMessage: "Davam etmək üçün {source} giriş tələb edir.",
sshPluginInputMessageNoSource: "Davam etmək üçün plagin giriş tələb edir.",
sshPluginInputSubmit: "Göndər",
sshHostKeyNoticeChanged: "{host}:{port} üçün host açarı dəyişib — bu, araya girən tərəfin hücumuna işarə edə bilər. Yalnız bu dəyişikliyi gözləyirsinizsə, köhnə qeydi silin və yenidən əlaqə qurun.", sshHostKeyNoticeChanged: "{host}:{port} üçün host açarı dəyişib — bu, araya girən tərəfin hücumuna işarə edə bilər. Yalnız bu dəyişikliyi gözləyirsinizsə, köhnə qeydi silin və yenidən əlaqə qurun.",
sshHostKeyNoticeRejected: "{host}:{port} üçün host açarını rədd etdiniz; əlaqə dayandırıldı və kimlik məlumatları göndərilmədi.", sshHostKeyNoticeRejected: "{host}:{port} üçün host açarını rədd etdiniz; əlaqə dayandırıldı və kimlik məlumatları göndərilmədi.",
sshHostKeyNoticeLearnFailed: "{host}:{port} üçün host açarını yadda saxlamaq mümkün olmadı — hosta yalnız bu sessiya üçün etibar edilir və növbəti dəfə onu yenidən yoxlamağınız istəniləcək.", sshHostKeyNoticeLearnFailed: "{host}:{port} üçün host açarını yadda saxlamaq mümkün olmadı — hosta yalnız bu sessiya üçün etibar edilir və növbəti dəfə onu yenidən yoxlamağınız istəniləcək.",
+7
View File
@@ -1146,6 +1146,9 @@ export default {
pluginProviderUnavailable: "This plugin connection provider is unavailable. Reinstall or enable the plugin, then try again.", pluginProviderUnavailable: "This plugin connection provider is unavailable. Reinstall or enable the plugin, then try again.",
pluginRequiredField: "{field} is required", pluginRequiredField: "{field} is required",
pluginSshKeyPickerPlaceholder: "Pick local SSH key…", pluginSshKeyPickerPlaceholder: "Pick local SSH key…",
pluginFieldSelectFile: "Choose file…",
pluginFieldUploadFile: "Upload file…",
pluginFieldSelectDirectory: "Choose folder…",
pluginSshKeyPickerEmpty: "No local SSH keys found", pluginSshKeyPickerEmpty: "No local SSH keys found",
pluginSshKeyEncrypted: "encrypted", pluginSshKeyEncrypted: "encrypted",
jdbcConnection: "JDBC connection", jdbcConnection: "JDBC connection",
@@ -1328,6 +1331,10 @@ export default {
sshInteractivePlaceholder: "Enter verification code", sshInteractivePlaceholder: "Enter verification code",
sshInteractiveSubmit: "Verify", sshInteractiveSubmit: "Verify",
sshInteractiveCancel: "Cancel", sshInteractiveCancel: "Cancel",
sshPluginInputTitle: "Input Required",
sshPluginInputMessage: "{source} needs input before it can continue.",
sshPluginInputMessageNoSource: "A plugin needs input before it can continue.",
sshPluginInputSubmit: "Submit",
sshHostKeyNoticeChanged: "Host key for {host}:{port} changed — this may indicate a man-in-the-middle attack. Remove the old entry and reconnect only if you expect this change.", sshHostKeyNoticeChanged: "Host key for {host}:{port} changed — this may indicate a man-in-the-middle attack. Remove the old entry and reconnect only if you expect this change.",
sshHostKeyNoticeRejected: "You rejected the host key for {host}:{port}; the connection was aborted and no credentials were sent.", sshHostKeyNoticeRejected: "You rejected the host key for {host}:{port}; the connection was aborted and no credentials were sent.",
sshHostKeyNoticeLearnFailed: "Could not save the host key for {host}:{port} — the host is trusted for this session only and you will be asked to verify it again next time.", sshHostKeyNoticeLearnFailed: "Could not save the host key for {host}:{port} — the host is trusted for this session only and you will be asked to verify it again next time.",
+7
View File
@@ -1298,6 +1298,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Introducir código de verificación", sshInteractivePlaceholder: "Introducir código de verificación",
sshInteractiveSubmit: "Verificar", sshInteractiveSubmit: "Verificar",
sshInteractiveCancel: "Cancelar", sshInteractiveCancel: "Cancelar",
sshPluginInputTitle: "Se requiere entrada",
sshPluginInputMessage: "{source} necesita una entrada para continuar.",
sshPluginInputMessageNoSource: "Un complemento necesita una entrada para continuar.",
sshPluginInputSubmit: "Enviar",
sshHostKeyNoticeChanged: "La clave del host {host}:{port} ha cambiado, puede haber un ataque de intermediario. Si es esperado, elimine el registro antiguo y vuelva a conectar.", sshHostKeyNoticeChanged: "La clave del host {host}:{port} ha cambiado, puede haber un ataque de intermediario. Si es esperado, elimine el registro antiguo y vuelva a conectar.",
sshHostKeyNoticeRejected: "Ha rechazado la verificación de la clave del host {host}:{port}. La conexión se ha abortado, no se enviaron credenciales.", sshHostKeyNoticeRejected: "Ha rechazado la verificación de la clave del host {host}:{port}. La conexión se ha abortado, no se enviaron credenciales.",
sshHostKeyNoticeGeneric: "Falló la verificación de la clave del host SSH {host}:{port}.", sshHostKeyNoticeGeneric: "Falló la verificación de la clave del host SSH {host}:{port}.",
@@ -1416,6 +1420,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "Muestra las tablas integradas de control de versiones de Dolt en la lista de tablas de la conexión actual.", doltShowSystemTablesHint: "Muestra las tablas integradas de control de versiones de Dolt en la lista de tablas de la conexión actual.",
clientCertHint: "Cuando se requiere mTLS, el certificado de cliente y la clave privada deben completarse juntos.", clientCertHint: "Cuando se requiere mTLS, el certificado de cliente y la clave privada deben completarse juntos.",
pluginSshKeyPickerPlaceholder: "Seleccionar clave SSH local…", pluginSshKeyPickerPlaceholder: "Seleccionar clave SSH local…",
pluginFieldSelectFile: "Elegir archivo…",
pluginFieldUploadFile: "Subir archivo…",
pluginFieldSelectDirectory: "Elegir carpeta…",
pluginSshKeyPickerEmpty: "No se encontraron claves", pluginSshKeyPickerEmpty: "No se encontraron claves",
pluginSshKeyEncrypted: "Cifrado", pluginSshKeyEncrypted: "Cifrado",
objectCacheRefreshFailed: "Error al actualizar la caché de objetos: {message}", objectCacheRefreshFailed: "Error al actualizar la caché de objetos: {message}",
+7
View File
@@ -1296,6 +1296,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Inserisci il codice di verifica", sshInteractivePlaceholder: "Inserisci il codice di verifica",
sshInteractiveSubmit: "Verifica", sshInteractiveSubmit: "Verifica",
sshInteractiveCancel: "Annulla", sshInteractiveCancel: "Annulla",
sshPluginInputTitle: "Input richiesto",
sshPluginInputMessage: "{source} richiede un input per continuare.",
sshPluginInputMessageNoSource: "Un plugin richiede un input per continuare.",
sshPluginInputSubmit: "Invia",
sshHostKeyNoticeChanged: "La chiave dell'host {host}:{port} è cambiata, potrebbe esserci un attacco man-in-the-middle. Se il cambiamento è previsto, elimina il vecchio record e riconnettiti.", sshHostKeyNoticeChanged: "La chiave dell'host {host}:{port} è cambiata, potrebbe esserci un attacco man-in-the-middle. Se il cambiamento è previsto, elimina il vecchio record e riconnettiti.",
sshHostKeyNoticeRejected: "Hai rifiutato la verifica della chiave host di {host}:{port}, la connessione è stata interrotta e le credenziali non sono state inviate.", sshHostKeyNoticeRejected: "Hai rifiutato la verifica della chiave host di {host}:{port}, la connessione è stata interrotta e le credenziali non sono state inviate.",
sshHostKeyNoticeGeneric: "Verifica della chiave host SSH {host}:{port} fallita.", sshHostKeyNoticeGeneric: "Verifica della chiave host SSH {host}:{port} fallita.",
@@ -1414,6 +1418,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "Mostra le tabelle di controllo versione integrate di Dolt nell'elenco delle tabelle della connessione corrente.", doltShowSystemTablesHint: "Mostra le tabelle di controllo versione integrate di Dolt nell'elenco delle tabelle della connessione corrente.",
clientCertHint: "Quando è richiesto mTLS, il certificato client e la chiave privata devono essere inseriti insieme.", clientCertHint: "Quando è richiesto mTLS, il certificato client e la chiave privata devono essere inseriti insieme.",
pluginSshKeyPickerPlaceholder: "Seleziona chiave SSH locale…", pluginSshKeyPickerPlaceholder: "Seleziona chiave SSH locale…",
pluginFieldSelectFile: "Scegli file…",
pluginFieldUploadFile: "Carica file…",
pluginFieldSelectDirectory: "Scegli cartella…",
pluginSshKeyPickerEmpty: "Nessuna chiave trovata", pluginSshKeyPickerEmpty: "Nessuna chiave trovata",
pluginSshKeyEncrypted: "Crittografata", pluginSshKeyEncrypted: "Crittografata",
objectCacheRefreshFailed: "Aggiornamento della cache degli oggetti non riuscito: {message}", objectCacheRefreshFailed: "Aggiornamento della cache degli oggetti non riuscito: {message}",
+7
View File
@@ -1296,6 +1296,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "検証コードを入力", sshInteractivePlaceholder: "検証コードを入力",
sshInteractiveSubmit: "検証", sshInteractiveSubmit: "検証",
sshInteractiveCancel: "キャンセル", sshInteractiveCancel: "キャンセル",
sshPluginInputTitle: "入力が必要です",
sshPluginInputMessage: "続行するには {source} への入力が必要です。",
sshPluginInputMessageNoSource: "続行するにはプラグインへの入力が必要です。",
sshPluginInputSubmit: "送信",
sshHostKeyNoticeChanged: "ホスト {host}:{port} のキーが変更されました。中間者攻撃の可能性があります。予期された変更である場合は、古いレコードを削除して再接続してください。", sshHostKeyNoticeChanged: "ホスト {host}:{port} のキーが変更されました。中間者攻撃の可能性があります。予期された変更である場合は、古いレコードを削除して再接続してください。",
sshHostKeyNoticeRejected: "ホスト {host}:{port} のホストキー検証を拒否しました。接続は中止され、資格情報は送信されませんでした。", sshHostKeyNoticeRejected: "ホスト {host}:{port} のホストキー検証を拒否しました。接続は中止され、資格情報は送信されませんでした。",
sshHostKeyNoticeGeneric: "SSHホスト {host}:{port} のキー検証に失敗しました。", sshHostKeyNoticeGeneric: "SSHホスト {host}:{port} のキー検証に失敗しました。",
@@ -1435,6 +1439,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "現在の接続のテーブルリストに Dolt 組み込みのバージョン管理テーブルを表示します。", doltShowSystemTablesHint: "現在の接続のテーブルリストに Dolt 組み込みのバージョン管理テーブルを表示します。",
clientCertHint: "mTLS が要求される場合、クライアント証明書と秘密鍵は一緒に入力する必要があります。", clientCertHint: "mTLS が要求される場合、クライアント証明書と秘密鍵は一緒に入力する必要があります。",
pluginSshKeyPickerPlaceholder: "ローカルの SSH キーを選択…", pluginSshKeyPickerPlaceholder: "ローカルの SSH キーを選択…",
pluginFieldSelectFile: "ファイルを選択…",
pluginFieldUploadFile: "ファイルをアップロード…",
pluginFieldSelectDirectory: "フォルダーを選択…",
pluginSshKeyPickerEmpty: "キーが見つかりません", pluginSshKeyPickerEmpty: "キーが見つかりません",
pluginSshKeyEncrypted: "暗号化済み", pluginSshKeyEncrypted: "暗号化済み",
objectCacheRefreshFailed: "オブジェクトキャッシュの更新に失敗しました:{message}", objectCacheRefreshFailed: "オブジェクトキャッシュの更新に失敗しました:{message}",
+7
View File
@@ -1212,6 +1212,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "인증 코드 입력", sshInteractivePlaceholder: "인증 코드 입력",
sshInteractiveSubmit: "인증", sshInteractiveSubmit: "인증",
sshInteractiveCancel: "취소", sshInteractiveCancel: "취소",
sshPluginInputTitle: "입력 필요",
sshPluginInputMessage: "계속하려면 {source}에 입력해야 합니다.",
sshPluginInputMessageNoSource: "계속하려면 플러그인에 입력해야 합니다.",
sshPluginInputSubmit: "제출",
sshHostKeyNoticeChanged: "{host}:{port}의 호스트 키가 변경되었습니다 — 이는 중간자 공격을 나타낼 수 있습니다. 이 변경을 예상한 경우에만 이전 항목을 제거하고 다시 연결하세요.", sshHostKeyNoticeChanged: "{host}:{port}의 호스트 키가 변경되었습니다 — 이는 중간자 공격을 나타낼 수 있습니다. 이 변경을 예상한 경우에만 이전 항목을 제거하고 다시 연결하세요.",
sshHostKeyNoticeRejected: "{host}:{port}의 호스트 키를 거부했습니다. 연결이 중단되고 자격 증명이 전송되지 않았습니다.", sshHostKeyNoticeRejected: "{host}:{port}의 호스트 키를 거부했습니다. 연결이 중단되고 자격 증명이 전송되지 않았습니다.",
sshHostKeyNoticeLearnFailed: "{host}:{port}의 호스트 키를 저장할 수 없습니다 — 이 호스트는 이 세션에만 신뢰되며 다음에 다시 확인을 요청받습니다.", sshHostKeyNoticeLearnFailed: "{host}:{port}의 호스트 키를 저장할 수 없습니다 — 이 호스트는 이 세션에만 신뢰되며 다음에 다시 확인을 요청받습니다.",
@@ -1333,6 +1337,9 @@ export default withEnglishFallback({
pluginProviderUnavailable: "이 플러그인 연결 제공자를 사용할 수 없습니다. 플러그인을 다시 설치하거나 활성화한 후 다시 시도하세요.", pluginProviderUnavailable: "이 플러그인 연결 제공자를 사용할 수 없습니다. 플러그인을 다시 설치하거나 활성화한 후 다시 시도하세요.",
pluginRequiredField: "{field}을(를) 입력하세요.", pluginRequiredField: "{field}을(를) 입력하세요.",
pluginSshKeyPickerPlaceholder: "로컬 SSH 키 선택…", pluginSshKeyPickerPlaceholder: "로컬 SSH 키 선택…",
pluginFieldSelectFile: "파일 선택…",
pluginFieldUploadFile: "파일 업로드…",
pluginFieldSelectDirectory: "폴더 선택…",
pluginSshKeyPickerEmpty: "키를 찾을 수 없음", pluginSshKeyPickerEmpty: "키를 찾을 수 없음",
pluginSshKeyEncrypted: "암호화됨", pluginSshKeyEncrypted: "암호화됨",
objectCacheRefreshFailed: "개체 캐시 새로 고침 실패: {message}", objectCacheRefreshFailed: "개체 캐시 새로 고침 실패: {message}",
+7
View File
@@ -1297,6 +1297,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Digite o código de verificação", sshInteractivePlaceholder: "Digite o código de verificação",
sshInteractiveSubmit: "Verificar", sshInteractiveSubmit: "Verificar",
sshInteractiveCancel: "Cancelar", sshInteractiveCancel: "Cancelar",
sshPluginInputTitle: "Entrada necessária",
sshPluginInputMessage: "{source} precisa de uma entrada para continuar.",
sshPluginInputMessageNoSource: "Um plugin precisa de uma entrada para continuar.",
sshPluginInputSubmit: "Enviar",
sshHostKeyNoticeChanged: "A chave do host {host}:{port} foi alterada, pode haver um ataque man-in-the-middle. Se esta alteração era esperada, exclua o registro antigo e reconecte.", sshHostKeyNoticeChanged: "A chave do host {host}:{port} foi alterada, pode haver um ataque man-in-the-middle. Se esta alteração era esperada, exclua o registro antigo e reconecte.",
sshHostKeyNoticeRejected: "Você rejeitou a verificação da chave do host {host}:{port}. A conexão foi abortada e as credenciais não foram enviadas.", sshHostKeyNoticeRejected: "Você rejeitou a verificação da chave do host {host}:{port}. A conexão foi abortada e as credenciais não foram enviadas.",
sshHostKeyNoticeGeneric: "Falha na verificação da chave do host SSH {host}:{port}.", sshHostKeyNoticeGeneric: "Falha na verificação da chave do host SSH {host}:{port}.",
@@ -1415,6 +1419,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "Exibir as tabelas de controle de versão internas do Dolt na lista de tabelas da conexão atual.", doltShowSystemTablesHint: "Exibir as tabelas de controle de versão internas do Dolt na lista de tabelas da conexão atual.",
clientCertHint: "Quando o mTLS for exigido, o certificado do cliente e a chave privada devem ser preenchidos juntos.", clientCertHint: "Quando o mTLS for exigido, o certificado do cliente e a chave privada devem ser preenchidos juntos.",
pluginSshKeyPickerPlaceholder: "Selecionar chave SSH local…", pluginSshKeyPickerPlaceholder: "Selecionar chave SSH local…",
pluginFieldSelectFile: "Escolher arquivo…",
pluginFieldUploadFile: "Enviar arquivo…",
pluginFieldSelectDirectory: "Escolher pasta…",
pluginSshKeyPickerEmpty: "Nenhuma chave encontrada", pluginSshKeyPickerEmpty: "Nenhuma chave encontrada",
pluginSshKeyEncrypted: "Criptografada", pluginSshKeyEncrypted: "Criptografada",
objectCacheRefreshFailed: "Falha ao atualizar o cache de objetos: {message}", objectCacheRefreshFailed: "Falha ao atualizar o cache de objetos: {message}",
+7
View File
@@ -1185,6 +1185,13 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Doğrulama kodunu girin", sshInteractivePlaceholder: "Doğrulama kodunu girin",
sshInteractiveSubmit: "Doğrula", sshInteractiveSubmit: "Doğrula",
sshInteractiveCancel: "İptal", sshInteractiveCancel: "İptal",
pluginFieldSelectFile: "Dosya seç…",
pluginFieldUploadFile: "Dosya yükle…",
pluginFieldSelectDirectory: "Klasör seç…",
sshPluginInputTitle: "Girdi gerekli",
sshPluginInputMessage: "Devam etmek için {source} bir girdi bekliyor.",
sshPluginInputMessageNoSource: "Devam etmek için bir eklenti girdi bekliyor.",
sshPluginInputSubmit: "Gönder",
sshHostKeyNoticeChanged: "{host}:{port} için sunucu anahtarı değişti — bu, ortadaki adam saldırısına işaret edebilir. Yalnızca bu değişikliği bekliyorsanız eski kaydı silip yeniden bağlanın.", sshHostKeyNoticeChanged: "{host}:{port} için sunucu anahtarı değişti — bu, ortadaki adam saldırısına işaret edebilir. Yalnızca bu değişikliği bekliyorsanız eski kaydı silip yeniden bağlanın.",
sshHostKeyNoticeRejected: "{host}:{port} için sunucu anahtarını reddettiniz; bağlantı iptal edildi ve hiçbir kimlik bilgisi gönderilmedi.", sshHostKeyNoticeRejected: "{host}:{port} için sunucu anahtarını reddettiniz; bağlantı iptal edildi ve hiçbir kimlik bilgisi gönderilmedi.",
sshHostKeyNoticeLearnFailed: "{host}:{port} için sunucu anahtarı kaydedilemedi — sunucuya yalnızca bu oturum için güvenilecek ve bir sonraki seferde yeniden doğrulamanız istenecek.", sshHostKeyNoticeLearnFailed: "{host}:{port} için sunucu anahtarı kaydedilemedi — sunucuya yalnızca bu oturum için güvenilecek ve bir sonraki seferde yeniden doğrulamanız istenecek.",
+7
View File
@@ -1061,6 +1061,9 @@ export default withEnglishFallback({
pluginProviderUnavailable: "此插件连接提供者不可用,请重新安装或启用插件后再试。", pluginProviderUnavailable: "此插件连接提供者不可用,请重新安装或启用插件后再试。",
pluginRequiredField: "请填写{field}", pluginRequiredField: "请填写{field}",
pluginSshKeyPickerPlaceholder: "选择本机 SSH 密钥…", pluginSshKeyPickerPlaceholder: "选择本机 SSH 密钥…",
pluginFieldSelectFile: "选择文件…",
pluginFieldUploadFile: "上传文件…",
pluginFieldSelectDirectory: "选择文件夹…",
pluginSshKeyPickerEmpty: "未发现密钥", pluginSshKeyPickerEmpty: "未发现密钥",
pluginSshKeyEncrypted: "已加密", pluginSshKeyEncrypted: "已加密",
jdbcConnection: "JDBC 连接", jdbcConnection: "JDBC 连接",
@@ -1246,6 +1249,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "输入验证码", sshInteractivePlaceholder: "输入验证码",
sshInteractiveSubmit: "验证", sshInteractiveSubmit: "验证",
sshInteractiveCancel: "取消", sshInteractiveCancel: "取消",
sshPluginInputTitle: "需要输入",
sshPluginInputMessage: "{source} 需要你提供输入才能继续。",
sshPluginInputMessageNoSource: "插件需要你提供输入才能继续。",
sshPluginInputSubmit: "提交",
sshHostKeyNoticeChanged: "主机 {host}:{port} 的密钥已变更,可能存在中间人攻击。如确属预期,请删除旧记录后重新连接。", sshHostKeyNoticeChanged: "主机 {host}:{port} 的密钥已变更,可能存在中间人攻击。如确属预期,请删除旧记录后重新连接。",
sshHostKeyNoticeRejected: "你已拒绝 {host}:{port} 的主机密钥验证,连接已中止,凭据未发送。", sshHostKeyNoticeRejected: "你已拒绝 {host}:{port} 的主机密钥验证,连接已中止,凭据未发送。",
sshHostKeyNoticeLearnFailed: "无法保存 {host}:{port} 的主机密钥 — 该主机仅在本次会话内受信任,下次连接仍需重新确认。", sshHostKeyNoticeLearnFailed: "无法保存 {host}:{port} 的主机密钥 — 该主机仅在本次会话内受信任,下次连接仍需重新确认。",
+7
View File
@@ -946,6 +946,9 @@ export default withEnglishFallback({
pluginProviderUnavailable: "此外掛連線提供者不可用,請重新安裝或啟用外掛後再試。", pluginProviderUnavailable: "此外掛連線提供者不可用,請重新安裝或啟用外掛後再試。",
pluginRequiredField: "請填寫{field}", pluginRequiredField: "請填寫{field}",
pluginSshKeyPickerPlaceholder: "選擇本機 SSH 金鑰…", pluginSshKeyPickerPlaceholder: "選擇本機 SSH 金鑰…",
pluginFieldSelectFile: "選擇檔案…",
pluginFieldUploadFile: "上傳檔案…",
pluginFieldSelectDirectory: "選擇資料夾…",
pluginSshKeyPickerEmpty: "未發現金鑰", pluginSshKeyPickerEmpty: "未發現金鑰",
pluginSshKeyEncrypted: "已加密", pluginSshKeyEncrypted: "已加密",
jdbcConnection: "JDBC 連線", jdbcConnection: "JDBC 連線",
@@ -1302,6 +1305,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "輸入驗證碼", sshInteractivePlaceholder: "輸入驗證碼",
sshInteractiveSubmit: "驗證", sshInteractiveSubmit: "驗證",
sshInteractiveCancel: "取消", sshInteractiveCancel: "取消",
sshPluginInputTitle: "需要輸入",
sshPluginInputMessage: "{source} 需要你提供輸入才能繼續。",
sshPluginInputMessageNoSource: "外掛需要你提供輸入才能繼續。",
sshPluginInputSubmit: "提交",
sshHostKeyNoticeChanged: "主機 {host}:{port} 的金鑰已變更,可能存在中間人攻擊。如確屬預期,請刪除舊記錄後重新連線。", sshHostKeyNoticeChanged: "主機 {host}:{port} 的金鑰已變更,可能存在中間人攻擊。如確屬預期,請刪除舊記錄後重新連線。",
sshHostKeyNoticeRejected: "您已拒絕 {host}:{port} 的主機金鑰驗證,連線已中止,憑證未發送。", sshHostKeyNoticeRejected: "您已拒絕 {host}:{port} 的主機金鑰驗證,連線已中止,憑證未發送。",
sshHostKeyNoticeGeneric: "SSH 主機 {host}:{port} 的金鑰驗證失敗。", sshHostKeyNoticeGeneric: "SSH 主機 {host}:{port} 的金鑰驗證失敗。",
@@ -46,7 +46,7 @@ export function pluginConnectionNeedsPasswordPrompt(fields: readonly PluginFormF
if (!passwordFields.length) return false; if (!passwordFields.length) return false;
const readValue = (key: string): PluginFormFieldValue => { const readValue = (key: string): PluginFormFieldValue => {
const stored = isRecord(externalConfig) ? (externalConfig[key] as PluginFormFieldValue) : undefined; const stored = isRecord(externalConfig) ? (externalConfig[key] as PluginFormFieldValue) : undefined;
return stored !== undefined ? stored : fields.find((candidate) => candidate.key === key)?.default; return stored !== undefined ? stored : (fields.find((candidate) => candidate.key === key)?.default ?? undefined);
}; };
return passwordFields.some((field) => pluginFieldIsRequired(field, readValue)); return passwordFields.some((field) => pluginFieldIsRequired(field, readValue));
} }
+86 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import type { InstalledPlugin, PluginConnectionProviderContribution } from "@/types/database"; import type { InstalledPlugin, PluginConnectionProviderContribution, PluginFormFieldValue } from "@/types/database";
import { buildPluginConnectionConfig, createFrontendPluginRegistry, initialPluginFormValues, parsePluginConnectionProviderOptionValue, pluginConnectionActionsForDialog, pluginConnectionFormValues, pluginConnectionProviderIcon, pluginConnectionProviderOptionValue } from "./frontendPlugin"; import { buildPluginConnectionConfig, createFrontendPluginRegistry, initialPluginFormValues, parsePluginConnectionProviderOptionValue, pluginConnectionActionsForDialog, pluginConnectionFormValues, pluginConnectionProviderIcon, pluginConnectionProviderOptionValue } from "./frontendPlugin";
function installedPlugin(id: string, contributions: InstalledPlugin["manifest"]["contributions"] = []): InstalledPlugin { function installedPlugin(id: string, contributions: InstalledPlugin["manifest"]["contributions"] = []): InstalledPlugin {
@@ -324,6 +324,91 @@ describe("FrontendPluginRegistry", () => {
expect(values).not.toHaveProperty("host"); expect(values).not.toHaveProperty("host");
}); });
it("treats a host-serialized null default as unset instead of a value", () => {
// Hosts before the manifest serialization fix sent `"default": null` for
// every field that declares no default, so an untouched password field
// turned into the four-character string "null" once it was saved.
const provider = connectionProvider({
fields: [
{ key: "sudo_password", label: "Sudo password", type: "password", binding: "secret", default: null },
{ key: "mode", label: "Mode", type: "text", binding: "config", default: null },
{ key: "read_only", label: "Read only", type: "boolean", binding: "config", default: false },
],
});
expect(initialPluginFormValues(provider)).toEqual({ read_only: false });
const config = buildPluginConnectionConfig("io.dbx.ssh", provider, {
sudo_password: null,
mode: null,
read_only: false,
} as unknown as Record<string, string>);
expect(config.connection_secrets?.sudo_password).toBeUndefined();
expect(config.external_config).toEqual({ read_only: false });
});
it("preserves opaque 'null' credentials when reopening and saving connections", () => {
const provider = connectionProvider({
fields: [
{ key: "sudo_password", label: "Sudo password", type: "password", binding: "secret" },
{ key: "totp_secret", label: "TOTP secret", type: "textarea", binding: "secret" },
{ key: "sudo_source", label: "Sudo source", type: "text", binding: "config" },
],
});
const existing = buildPluginConnectionConfig("io.dbx.ssh", provider, {});
existing.connection_secrets = { sudo_password: "null", totp_secret: "JBSWY3DPEHPK3PXP" };
existing.external_config = { sudo_source: "custom", stale: null };
const values = pluginConnectionFormValues(provider, existing);
expect(values.sudo_password).toBe("null");
expect(values.totp_secret).toBe("JBSWY3DPEHPK3PXP");
expect(values.stale).toBeUndefined();
expect(values.sudo_source).toBe("custom");
const saved = buildPluginConnectionConfig("io.dbx.ssh", provider, values, existing);
expect(saved.connection_secrets?.sudo_password).toBe("null");
expect(saved.connection_secrets?.totp_secret).toBe("JBSWY3DPEHPK3PXP");
});
it.each([undefined, "secret", "password"] as const)("round-trips explicit 'null' credentials with binding %s", (binding) => {
const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password", binding }] });
const saved = buildPluginConnectionConfig("example.plugin", provider, { credential: "null" });
expect(binding === "password" ? saved.password : saved.connection_secrets?.credential).toBe("null");
expect(pluginConnectionFormValues(provider, saved)).toEqual({ credential: "null" });
const reopened = buildPluginConnectionConfig("example.plugin", provider, pluginConnectionFormValues(provider, saved), saved);
expect(pluginConnectionFormValues(provider, reopened)).toEqual({ credential: "null" });
});
it("migrates an opaque 'null' credential from config to secret storage without losing it", () => {
const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password" }] });
const existing = buildPluginConnectionConfig("example.plugin", provider, {});
existing.external_config = { credential: "null" };
const values = pluginConnectionFormValues(provider, existing);
expect(values).toEqual({ credential: "null" });
const saved = buildPluginConnectionConfig("example.plugin", provider, values, existing);
expect(saved.connection_secrets).toEqual({ credential: "null" });
expect(saved.external_config).toEqual({});
});
it.each([null, undefined, ""])("keeps an unset credential %s absent without a default", (credential) => {
const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password" }] });
const existing = buildPluginConnectionConfig("example.plugin", provider, {});
existing.connection_secrets = { credential: "old-secret" };
const saved = buildPluginConnectionConfig("example.plugin", provider, { credential } as unknown as Record<string, PluginFormFieldValue>, existing);
expect(saved.connection_secrets).toEqual({});
expect(pluginConnectionFormValues(provider, saved)).toEqual({});
});
it("uses an explicit string default only for missing input, not a cleared input", () => {
const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password", default: "null" }] });
expect(initialPluginFormValues(provider)).toEqual({ credential: "null" });
expect(buildPluginConnectionConfig("example.plugin", provider, {}).connection_secrets).toEqual({ credential: "null" });
expect(buildPluginConnectionConfig("example.plugin", provider, { credential: null } as unknown as Record<string, PluginFormFieldValue>).connection_secrets).toEqual({});
expect(buildPluginConnectionConfig("example.plugin", provider, { credential: "" }).connection_secrets).toEqual({});
});
it("maps provider fields into common, config, and secret storage", () => { it("maps provider fields into common, config, and secret storage", () => {
const provider: PluginConnectionProviderContribution = { const provider: PluginConnectionProviderContribution = {
type: "connection-provider", type: "connection-provider",
+10 -17
View File
@@ -115,7 +115,9 @@ export function pluginConnectionActionsForDialog(contribution: PluginConnectionP
} }
export function initialPluginFormValues(contribution: PluginConnectionProviderContribution): Record<string, PluginFormFieldValue> { export function initialPluginFormValues(contribution: PluginConnectionProviderContribution): Record<string, PluginFormFieldValue> {
return Object.fromEntries(contribution.fields.filter((field) => field.default !== undefined).map((field) => [field.key, field.default])) as Record<string, PluginFormFieldValue>; // `null` means "no default" (older hosts serialized the absent case that way),
// so it must not seed the form with a value the user never typed.
return Object.fromEntries(contribution.fields.filter((field) => field.default !== undefined && field.default !== null).map((field) => [field.key, field.default])) as Record<string, PluginFormFieldValue>;
} }
export function pluginConnectionFormValues(contribution: PluginConnectionProviderContribution, config?: ConnectionConfig): Record<string, PluginFormFieldValue> { export function pluginConnectionFormValues(contribution: PluginConnectionProviderContribution, config?: ConnectionConfig): Record<string, PluginFormFieldValue> {
@@ -125,22 +127,9 @@ export function pluginConnectionFormValues(contribution: PluginConnectionProvide
const secrets = config.connection_secrets || {}; const secrets = config.connection_secrets || {};
for (const field of contribution.fields) { for (const field of contribution.fields) {
const binding = effectiveFieldBinding(field); const binding = effectiveFieldBinding(field);
const secret = secrets[field.key] ?? externalConfig[field.key];
const value = const value =
binding === "name" binding === "name" ? config.name : binding === "host" ? config.host : binding === "port" ? config.port : binding === "username" ? config.username : binding === "password" ? config.password : binding === "database" ? config.database : binding === "secret" ? secret : externalConfig[field.key];
? config.name
: binding === "host"
? config.host
: binding === "port"
? config.port
: binding === "username"
? config.username
: binding === "password"
? config.password
: binding === "database"
? config.database
: binding === "secret"
? (secrets[field.key] ?? externalConfig[field.key])
: externalConfig[field.key];
// Port 0 is the stored representation of an optional, automatic port. // Port 0 is the stored representation of an optional, automatic port.
// Keep that input empty on reopen so its protocol-default hint remains visible. // Keep that input empty on reopen so its protocol-default hint remains visible.
if (binding === "port" && value === 0 && field.default === undefined) delete values[field.key]; if (binding === "port" && value === 0 && field.default === undefined) delete values[field.key];
@@ -180,7 +169,11 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
production_databases: existing?.production_databases || [], production_databases: existing?.production_databases || [],
}; };
for (const field of contribution.fields) { for (const field of contribution.fields) {
const value = values[field.key] ?? field.default; // A `null` coming from the form (or from a host that hydrated absent
// defaults as `null`) means "unset": fall back to the declared default and
// otherwise clear the stored value instead of persisting a null.
const raw = values[field.key];
const value = raw === null ? undefined : (raw ?? field.default ?? undefined);
const binding = effectiveFieldBinding(field); const binding = effectiveFieldBinding(field);
if (binding === "config") { if (binding === "config") {
if (value === undefined) delete externalConfig[field.key]; if (value === undefined) delete externalConfig[field.key];
+173 -9
View File
@@ -1,22 +1,84 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { pluginFieldConditionMatches, pluginFieldIsRequired, pluginFieldIsVisible } from "./pluginFieldConditions"; import { pluginConditionValueText, pluginFieldConditionMatches, pluginFieldConditionReferencedFields, pluginFieldIsRequired, pluginFieldIsVisible } from "./pluginFieldConditions";
import type { PluginFormField, PluginFormFieldValue } from "@/types/database"; import type { PluginFieldCondition, PluginFormField, PluginFormFieldValue } from "@/types/database";
function field(overrides: Partial<PluginFormField>): PluginFormField { function field(overrides: Partial<PluginFormField>): PluginFormField {
return { key: "demo", label: "Demo", type: "text", ...overrides } as PluginFormField; return { key: "demo", label: "Demo", type: "text", ...overrides } as PluginFormField;
} }
const readValue = (key: string) => (key === "mode" ? "custom" : undefined); const readValue = (key: string): PluginFormFieldValue => (key === "mode" ? "custom" : undefined);
/** Reads a fixed map, so a condition can be evaluated against known values. */
function reader(values: Record<string, PluginFormFieldValue>): (key: string) => PluginFormFieldValue {
return (key) => values[key];
}
describe("pluginFieldConditionMatches", () => { describe("pluginFieldConditionMatches", () => {
it("matches a missing condition and a listed value", () => { it("matches a missing condition and a listed value", () => {
expect(pluginFieldConditionMatches(undefined, undefined)).toBe(true); expect(pluginFieldConditionMatches(undefined, () => undefined)).toBe(true);
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "custom")).toBe(true); expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({ mode: "custom" }))).toBe(true);
}); });
it("rejects an unlisted or empty value", () => { it("rejects an unlisted or empty value", () => {
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "direct")).toBe(false); expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({ mode: "direct" }))).toBe(false);
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, undefined)).toBe(false); expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({}))).toBe(false);
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({ mode: " " }))).toBe(false);
});
it("compares boolean and number literals by canonical string form", () => {
// `read_only = false` is the composite-condition driver the SSH plugin needs.
const readOnly = { field: "read_only", one_of: [false] } as PluginFieldCondition;
expect(pluginFieldConditionMatches(readOnly, reader({ read_only: false }))).toBe(true);
expect(pluginFieldConditionMatches(readOnly, reader({ read_only: true }))).toBe(false);
expect(pluginFieldConditionMatches({ field: "read_only", one_of: ["false"] }, reader({ read_only: false }))).toBe(true);
expect(pluginFieldConditionMatches({ field: "port", one_of: [2222] }, reader({ port: 2222 }))).toBe(true);
expect(pluginFieldConditionMatches({ field: "port", one_of: [2222.0] }, reader({ port: 2222 }))).toBe(true);
expect(pluginConditionValueText(false)).toBe("false");
expect(pluginConditionValueText(22)).toBe("22");
});
it("composes clauses with all_of, any_of and not", () => {
const allOf = {
all_of: [
{ field: "sudo_source", one_of: ["custom"] },
{ field: "read_only", one_of: [false] },
],
} as PluginFieldCondition;
expect(pluginFieldConditionMatches(allOf, reader({ sudo_source: "custom", read_only: false }))).toBe(true);
expect(pluginFieldConditionMatches(allOf, reader({ sudo_source: "custom", read_only: true }))).toBe(false);
expect(pluginFieldConditionMatches(allOf, reader({ sudo_source: "default", read_only: false }))).toBe(false);
const anyOf = {
any_of: [
{ field: "authentication", one_of: ["password"] },
{ field: "authentication", one_of: ["keyboard-interactive"] },
],
} as PluginFieldCondition;
expect(pluginFieldConditionMatches(anyOf, reader({ authentication: "keyboard-interactive" }))).toBe(true);
expect(pluginFieldConditionMatches(anyOf, reader({ authentication: "agent" }))).toBe(false);
const not = { not: { field: "read_only", one_of: [true] } } as PluginFieldCondition;
expect(pluginFieldConditionMatches(not, reader({ read_only: false }))).toBe(true);
expect(pluginFieldConditionMatches(not, reader({ read_only: true }))).toBe(false);
const nested = { all_of: [anyOf, not, { any_of: [{ all_of: [{ field: "read_only", one_of: [false] }] }] }] } as PluginFieldCondition;
expect(pluginFieldConditionMatches(nested, reader({ authentication: "password", read_only: false }))).toBe(true);
expect(pluginFieldConditionMatches(nested, reader({ authentication: "password", read_only: true }))).toBe(false);
});
it("lists every referenced field of a nested expression", () => {
expect(
pluginFieldConditionReferencedFields({
all_of: [
{
any_of: [
{ field: "a", one_of: ["1"] },
{ field: "b", one_of: ["1"] },
],
},
{ not: { field: "c", one_of: ["1"] } },
],
}),
).toEqual(["a", "b", "c"]);
}); });
}); });
@@ -35,6 +97,19 @@ describe("pluginFieldIsRequired", () => {
expect(pluginFieldIsRequired(conditional, () => "direct")).toBe(false); expect(pluginFieldIsRequired(conditional, () => "direct")).toBe(false);
expect(pluginFieldIsRequired(conditional, () => undefined)).toBe(false); expect(pluginFieldIsRequired(conditional, () => undefined)).toBe(false);
}); });
it("requires a field only while every clause of an all_of required_when matches", () => {
const conditional = field({
required_when: {
all_of: [
{ field: "sudo_source", one_of: ["custom"] },
{ field: "read_only", one_of: [false] },
],
},
});
expect(pluginFieldIsRequired(conditional, reader({ sudo_source: "custom", read_only: false }))).toBe(true);
expect(pluginFieldIsRequired(conditional, reader({ sudo_source: "custom", read_only: true }))).toBe(false);
});
}); });
describe("pluginFieldIsVisible", () => { describe("pluginFieldIsVisible", () => {
@@ -45,6 +120,62 @@ describe("pluginFieldIsVisible", () => {
expect(pluginFieldIsVisible(conditional, () => "direct")).toBe(false); expect(pluginFieldIsVisible(conditional, () => "direct")).toBe(false);
}); });
it("renders a field only while every clause of an all_of visible_when matches", () => {
const conditional = field({
visible_when: {
all_of: [
{ field: "sudo_source", one_of: ["custom"] },
{ field: "read_only", one_of: [false] },
],
},
});
expect(pluginFieldIsVisible(conditional, reader({ sudo_source: "custom", read_only: false }))).toBe(true);
expect(pluginFieldIsVisible(conditional, reader({ sudo_source: "custom", read_only: true }))).toBe(false);
expect(pluginFieldIsVisible(conditional, reader({ read_only: false }))).toBe(false);
});
it("keeps an unused any_of branch from hiding a matching field", () => {
// `visible_when.any_of` matches through the first clause; the second clause
// references a sibling that is itself hidden, and that must not matter.
const fields: Record<string, PluginFormField> = {
source: field({ key: "source", default: "custom" }),
hidden_controller: field({ key: "hidden_controller", default: "on", visible_when: { field: "source", one_of: ["remote"] } }),
target: field({
key: "target",
visible_when: {
any_of: [
{ field: "source", one_of: ["custom"] },
{ field: "hidden_controller", one_of: ["on"] },
],
},
}),
};
const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default ?? undefined;
const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
expect(pluginFieldIsVisible(fields.target, read, resolve)).toBe(true);
// ...while a match that *depends* on the hidden controller stays dormant.
const onlyHidden = field({
key: "only_hidden",
visible_when: { any_of: [{ field: "hidden_controller", one_of: ["on"] }] },
});
expect(pluginFieldIsVisible(onlyHidden, read, resolve)).toBe(false);
});
it("treats a hidden operand of `not` as dormant instead of lighting the field up", () => {
const fields: Record<string, PluginFormField> = {
mode: field({ key: "mode", default: "remote" }),
read_only: field({ key: "read_only", default: false, visible_when: { field: "mode", one_of: ["local"] } }),
writable_options: field({ key: "writable_options", visible_when: { not: { field: "read_only", one_of: [true] } } }),
};
const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default ?? undefined;
const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
expect(pluginFieldIsVisible(fields.writable_options, read, resolve)).toBe(false);
const localRead = reader({ mode: "local", read_only: false });
expect(pluginFieldIsVisible(fields.writable_options, localRead, resolve)).toBe(true);
});
it("keeps a condition dormant while its referenced sibling is hidden, even when the sibling default would match", () => { it("keeps a condition dormant while its referenced sibling is hidden, even when the sibling default would match", () => {
// kafka-shaped chain: sasl_mechanism (default PLAIN, hidden) → // kafka-shaped chain: sasl_mechanism (default PLAIN, hidden) →
// oauth_token_source (visible only for OAUTHBEARER, defaults msk_iam) → // oauth_token_source (visible only for OAUTHBEARER, defaults msk_iam) →
@@ -56,16 +187,49 @@ describe("pluginFieldIsVisible", () => {
oauth_token_source: field({ key: "oauth_token_source", default: "msk_iam", visible_when: { field: "sasl_mechanism", one_of: ["OAUTHBEARER"] } }), oauth_token_source: field({ key: "oauth_token_source", default: "msk_iam", visible_when: { field: "sasl_mechanism", one_of: ["OAUTHBEARER"] } }),
msk_region: field({ key: "msk_region", visible_when: { field: "oauth_token_source", one_of: ["msk_iam"] } }), msk_region: field({ key: "msk_region", visible_when: { field: "oauth_token_source", one_of: ["msk_iam"] } }),
}; };
const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default; const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default ?? undefined;
const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key]; const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
expect(pluginFieldIsVisible(fields.msk_region, read, resolve)).toBe(false); expect(pluginFieldIsVisible(fields.msk_region, read, resolve)).toBe(false);
// Turning OAUTHBEARER on makes the whole chain visible again. // Turning OAUTHBEARER on makes the whole chain visible again.
const readOauth: (key: string) => PluginFormFieldValue = (key) => (key === "sasl_mechanism" ? "OAUTHBEARER" : key === "security_protocol" ? "SASL_SSL" : fields[key]?.default); const readOauth: (key: string) => PluginFormFieldValue = (key) => (key === "sasl_mechanism" ? "OAUTHBEARER" : key === "security_protocol" ? "SASL_SSL" : (fields[key]?.default ?? undefined));
expect(pluginFieldIsVisible(fields.oauth_token_source, readOauth, resolve)).toBe(true); expect(pluginFieldIsVisible(fields.oauth_token_source, readOauth, resolve)).toBe(true);
expect(pluginFieldIsVisible(fields.msk_region, readOauth, resolve)).toBe(true); expect(pluginFieldIsVisible(fields.msk_region, readOauth, resolve)).toBe(true);
}); });
it.each([false, true])("keeps sibling branches path-local with reverse order %s", (reverse) => {
const fields: Record<string, PluginFormField> = {
mode: field({ key: "mode" }),
auth: field({ key: "auth", visible_when: { field: "mode", one_of: ["enabled"] } }),
};
const clause: PluginFieldCondition = { field: "auth", one_of: ["password"] };
const branches: PluginFieldCondition[] = [{ all_of: [clause, { field: "flag", one_of: [true] }] }, { all_of: [{ field: "flag", one_of: [false] }, clause] }];
if (reverse) branches.reverse();
const resolve = (key: string) => fields[key];
for (const flag of [false, true]) {
const hidden = reader({ mode: "disabled", auth: "password", flag });
const visible = reader({ mode: "enabled", auth: "password", flag });
for (const condition of [clause, { any_of: [clause, clause] }, { any_of: branches }, { all_of: [clause, clause] }] satisfies PluginFieldCondition[]) {
const target = field({ key: "target", visible_when: condition });
expect(pluginFieldIsVisible(target, hidden, resolve)).toBe(false);
expect(pluginFieldIsVisible(target, visible, resolve)).toBe(true);
}
const negated = field({ visible_when: { not: { any_of: [clause, clause] } } });
expect(pluginFieldIsVisible(negated, hidden, resolve)).toBe(false);
expect(pluginFieldIsVisible(negated, reader({ mode: "enabled", auth: "token", flag }), resolve)).toBe(true);
}
});
it("preserves true mutual-cycle compatibility without bypassing value checks", () => {
const fields: Record<string, PluginFormField> = {
first: field({ key: "first", visible_when: { field: "second", one_of: ["on"] } }),
second: field({ key: "second", visible_when: { field: "first", one_of: ["on"] } }),
};
const resolve = (key: string) => fields[key];
expect(pluginFieldIsVisible(fields.first, reader({ first: "on", second: "on" }), resolve)).toBe(true);
expect(pluginFieldIsVisible(fields.first, reader({ first: "off", second: "on" }), resolve)).toBe(false);
});
it("ignores unknown condition fields and survives self-referencing cycles", () => { it("ignores unknown condition fields and survives self-referencing cycles", () => {
const unknown = field({ visible_when: { field: "missing", one_of: ["x"] } }); const unknown = field({ visible_when: { field: "missing", one_of: ["x"] } });
expect( expect(
@@ -1,14 +1,67 @@
import type { PluginFieldCondition, PluginFormField, PluginFormFieldValue } from "@/types/database"; import type { PluginFieldCondition, PluginFormField, PluginFormFieldValue } from "@/types/database";
/** /**
* Evaluates a plugin manifest field condition (`visible_when` / `required_when`, * Canonical string form of a form value, matching the Rust host
* Host API 1.1). A condition matches when the current value of the referenced * (`condition_value_text` in `crates/dbx-core/src/plugins/manifest.rs`).
* sibling field is listed in `one_of`. Missing conditions always match. * `false` renders as `"false"` and `22.0` as `"22"`.
*/ */
export function pluginFieldConditionMatches(condition: PluginFieldCondition | undefined, value: PluginFormFieldValue): boolean { export function pluginConditionValueText(value: PluginFormFieldValue): string {
if (!condition) return true; if (value === undefined || value === null) return "";
return String(value);
}
/** Reads the current value of a sibling form field by key. */
export type PluginFieldValueReader = (key: string) => PluginFormFieldValue;
/** A leaf clause matches when the sibling value equals one of its literals. */
function conditionClauseMatches(clause: { field: string; one_of: readonly (string | number | boolean)[] }, value: PluginFormFieldValue): boolean {
if (value === undefined || value === null || (typeof value === "string" && value.trim().length === 0)) return false; if (value === undefined || value === null || (typeof value === "string" && value.trim().length === 0)) return false;
return condition.one_of.includes(String(value)); const text = pluginConditionValueText(value);
return clause.one_of.some((literal) => pluginConditionValueText(literal) === text);
}
/**
* Evaluates a plugin manifest field condition (`visible_when` / `required_when`,
* Host API 1.1+). A leaf matches when the current value of the referenced
* sibling field is listed in `one_of`; `all_of` / `any_of` / `not` compose
* clauses, so a manifest can express `sudo_source = custom AND read_only =
* false`. Missing conditions always match; a missing or empty sibling value
* never matches.
*/
export function pluginFieldConditionMatches(condition: PluginFieldCondition | undefined, readValue: PluginFieldValueReader): boolean {
if (!condition) return true;
return conditionExpressionMatches(condition, readValue);
}
function conditionExpressionMatches(condition: PluginFieldCondition, readValue: PluginFieldValueReader): boolean {
if (isConditionClause(condition)) return conditionClauseMatches(condition, readValue(condition.field));
if (isConditionAllOf(condition)) {
return condition.all_of.every((child) => conditionExpressionMatches(child, readValue));
}
if (isConditionAnyOf(condition)) {
return condition.any_of.some((child) => conditionExpressionMatches(child, readValue));
}
return !conditionExpressionMatches(condition.not, readValue);
}
/** Field keys the expression reads, in evaluation order (duplicates kept). */
export function pluginFieldConditionReferencedFields(condition: PluginFieldCondition): string[] {
if (isConditionClause(condition)) return [condition.field];
if (isConditionAllOf(condition)) return condition.all_of.flatMap(pluginFieldConditionReferencedFields);
if (isConditionAnyOf(condition)) return condition.any_of.flatMap(pluginFieldConditionReferencedFields);
return pluginFieldConditionReferencedFields(condition.not);
}
function isConditionClause(condition: PluginFieldCondition): condition is { field: string; one_of: (string | number | boolean)[] } {
return typeof (condition as { field?: unknown }).field === "string";
}
function isConditionAllOf(condition: PluginFieldCondition): condition is { all_of: PluginFieldCondition[] } {
return Array.isArray((condition as { all_of?: unknown }).all_of);
}
function isConditionAnyOf(condition: PluginFieldCondition): condition is { any_of: PluginFieldCondition[] } {
return Array.isArray((condition as { any_of?: unknown }).any_of);
} }
/** Looks a sibling field up by key; returns undefined when the key is unknown. */ /** Looks a sibling field up by key; returns undefined when the key is unknown. */
@@ -28,11 +81,40 @@ export function pluginFieldIsVisible(field: PluginFormField, readValue: (key: st
function pluginFieldIsVisibleCached(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean { function pluginFieldIsVisibleCached(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
const condition = field.visible_when; const condition = field.visible_when;
if (!condition) return true; if (!condition) return true;
if (!pluginFieldConditionMatches(condition, readValue(condition.field))) return false; return conditionExpressionVisible(condition, readValue, resolveField, seen);
const target = resolveField?.(condition.field); }
/**
* Visibility-aware evaluation of one condition expression.
*
* A clause only counts while the sibling it reads is visible *and* its own
* `visible_when` chain is satisfied, so a hidden controller's stored default
* cannot light a field up. `not` additionally requires every operand to be
* visible: an inverted hidden value is not a usable answer.
*/
function conditionExpressionVisible(condition: PluginFieldCondition, readValue: PluginFieldValueReader, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
if (isConditionClause(condition)) {
if (!conditionClauseMatches(condition, readValue(condition.field))) return false;
return conditionOperandVisible(condition.field, readValue, resolveField, seen);
}
if (isConditionAllOf(condition)) {
return condition.all_of.every((child) => conditionExpressionVisible(child, readValue, resolveField, seen));
}
if (isConditionAnyOf(condition)) {
return condition.any_of.some((child) => conditionExpressionVisible(child, readValue, resolveField, seen));
}
const operandsVisible = pluginFieldConditionReferencedFields(condition.not).every((key) => conditionOperandVisible(key, readValue, resolveField, seen));
return operandsVisible && !conditionExpressionMatches(condition.not, readValue);
}
/** Whether the sibling behind one clause is itself rendered. Cycles count as visible. */
function conditionOperandVisible(key: string, readValue: PluginFieldValueReader, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
const target = resolveField?.(key);
if (!target || seen.has(target.key)) return true; if (!target || seen.has(target.key)) return true;
seen.add(target.key); seen.add(target.key);
return pluginFieldIsVisibleCached(target, readValue, resolveField, seen); const visible = pluginFieldIsVisibleCached(target, readValue, resolveField, seen);
seen.delete(target.key);
return visible;
} }
/** Effective required = static `required` OR a matching `required_when`. */ /** Effective required = static `required` OR a matching `required_when`. */
@@ -43,5 +125,5 @@ export function pluginFieldIsRequired(field: PluginFormField, readValue: (key: s
// for visibility), so it must not be consulted here — that used to mark // for visibility), so it must not be consulted here — that used to mark
// every plugin field required and dead-locked the connection footer. // every plugin field required and dead-locked the connection footer.
if (!field.required_when) return false; if (!field.required_when) return false;
return pluginFieldConditionMatches(field.required_when, readValue(field.required_when.field)); return pluginFieldConditionMatches(field.required_when, readValue);
} }
+86
View File
@@ -0,0 +1,86 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from "vitest";
const { tauriRuntime, openMock } = vi.hoisted(() => ({ tauriRuntime: { value: false }, openMock: vi.fn() }));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => tauriRuntime.value }));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: openMock }));
import { PLUGIN_PICKER_MAX_BYTES, pickPluginFieldFile } from "./pluginFieldPicker";
/** Captures the hidden `<input type="file">` the browser path creates. */
function stubFileSelection(files: File[]) {
const original = document.createElement.bind(document);
const created: HTMLInputElement[] = [];
const spy = vi.spyOn(document, "createElement").mockImplementation(((tag: string, options?: ElementCreationOptions) => {
const element = original(tag, options as never);
if (tag === "input") {
created.push(element as HTMLInputElement);
setTimeout(() => {
Object.defineProperty(element, "files", { value: files, configurable: true });
element.dispatchEvent(new Event("change"));
}, 0);
}
return element;
}) as typeof document.createElement);
return { created, restore: () => spy.mockRestore() };
}
beforeEach(() => {
tauriRuntime.value = false;
openMock.mockReset();
});
describe("pickPluginFieldFile", () => {
it("returns the client path on desktop so the plugin can read the file itself", async () => {
tauriRuntime.value = true;
openMock.mockResolvedValue("/Users/dev/.ssh/id_rsa");
const picked = await pickPluginFieldFile({ kind: "file", accept: [".pem", ".key"] });
expect(picked).toEqual({ path: "/Users/dev/.ssh/id_rsa", name: "id_rsa" });
expect(openMock).toHaveBeenCalledWith({
directory: false,
multiple: false,
filters: [{ name: "Files", extensions: ["pem", "key"] }],
});
});
it("offers a folder dialog for directory pickers and ignores a dismissal", async () => {
tauriRuntime.value = true;
openMock.mockResolvedValue(null);
expect(await pickPluginFieldFile({ kind: "directory" })).toBeNull();
expect(openMock).toHaveBeenCalledWith({ directory: true, multiple: false, filters: undefined });
});
it("reads the file content on browser hosts, which cannot hand over a path", async () => {
const files = [new File(["-----BEGIN PRIVATE KEY-----\nkey\n"], "id_rsa", { type: "text/plain" })];
const selection = stubFileSelection(files);
try {
const picked = await pickPluginFieldFile({ kind: "file", accept: [".pem", "text/plain"] });
expect(picked).toEqual({ content: "-----BEGIN PRIVATE KEY-----\nkey\n", name: "id_rsa" });
expect(selection.created[0]?.accept).toBe(".pem,text/plain");
expect(selection.created[0]?.multiple).toBe(false);
} finally {
selection.restore();
}
});
it("has no browser equivalent for a folder picker", async () => {
expect(await pickPluginFieldFile({ kind: "directory" })).toBeNull();
});
it("rejects an oversized upload instead of loading it", async () => {
const oversized = new File(["x"], "big.key", { type: "text/plain" });
Object.defineProperty(oversized, "size", { value: PLUGIN_PICKER_MAX_BYTES + 1 });
const selection = stubFileSelection([oversized]);
try {
await expect(pickPluginFieldFile({ kind: "file" })).rejects.toThrow(/larger than 1024 KiB/);
} finally {
selection.restore();
}
});
});
@@ -0,0 +1,69 @@
import type { PluginFormFieldPicker } from "@/types/database";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
/** Uploads larger than this are rejected instead of being held in memory. */
export const PLUGIN_PICKER_MAX_BYTES = 1_048_576;
export interface PluginPickedFile {
/** Absolute path of the selected file; desktop hosts only. */
path?: string;
/** File content; browser hosts only (they cannot produce a usable path). */
content?: string;
/** File name, for messages. */
name: string;
}
/**
* Runs the manifest's picker action for one field.
*
* Desktop hosts (Tauri) open the native dialog and return the absolute path, so
* the plugin — which runs on the same machine — can read the file itself.
* Browser hosts have no client filesystem: they read the selected file and hand
* back its content, which the form stores in the declared `content_field`
* (the browser build cannot hand the server a path to a client file).
*
* Returns `null` when the user cancels.
*/
export async function pickPluginFieldFile(picker: PluginFormFieldPicker): Promise<PluginPickedFile | null> {
const accepted = (picker.accept || []).slice();
if (isTauriRuntime()) {
const { open } = await import("@tauri-apps/plugin-dialog");
const extensions = accepted.filter((entry) => entry.startsWith(".")).map((entry) => entry.replace(/^\./, ""));
const selected = await open({
directory: picker.kind === "directory",
multiple: false,
filters: extensions.length ? [{ name: picker.kind === "directory" ? "Folders" : "Files", extensions }] : undefined,
});
if (typeof selected !== "string" || !selected) return null;
return { path: selected, name: selected.replaceAll("\\", "/").split("/").pop() || selected };
}
if (picker.kind === "directory") return null;
const file = await selectBrowserFile(accepted);
if (!file) return null;
if (file.size > PLUGIN_PICKER_MAX_BYTES) {
throw new Error(`File is larger than ${Math.round(PLUGIN_PICKER_MAX_BYTES / 1024)} KiB`);
}
return { content: await file.text(), name: file.name };
}
function selectBrowserFile(accept: string[]): Promise<File | null> {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.multiple = false;
if (accept.length) input.accept = accept.join(",");
// Chrome fires `cancel` when the dialog is dismissed; older engines only
// fire `change` without files, which the handler below already treats as a
// cancellation.
input.addEventListener("cancel", () => resolve(null), { once: true });
input.addEventListener(
"change",
() => {
resolve(input.files?.[0] ?? null);
},
{ once: true },
);
input.click();
});
}
+49 -5
View File
@@ -295,13 +295,53 @@ export interface PluginFormFieldOption {
value: string; value: string;
} }
export interface PluginFieldCondition { /** A literal a `one_of` clause may list; compared by canonical string form. */
/** Key of another plugin form field whose current value drives the condition. */ export type PluginFieldConditionLiteral = string | number | boolean;
/** Legacy single-field clause: `{ field, one_of }`. */
export interface PluginFieldConditionClause {
/** Key of another plugin form field whose current value drives the clause. */
field: string; field: string;
/** The condition matches when the referenced field's value is in this list. */ /** The clause matches when the referenced field's value is in this list. */
one_of: string[]; one_of: PluginFieldConditionLiteral[];
} }
/** Every nested condition must match. */
export interface PluginFieldConditionAllOf {
all_of: PluginFieldCondition[];
}
/** At least one nested condition must match. */
export interface PluginFieldConditionAnyOf {
any_of: PluginFieldCondition[];
}
/** Inverts the nested condition. */
export interface PluginFieldConditionNot {
not: PluginFieldCondition;
}
/** Host API 1.1: local-file action on a plugin connection field. */
export interface PluginFormFieldPicker {
/** `directory` is desktop-only. */
kind: "file" | "directory";
/** Extensions (`.pem`) or MIME types (`text/plain`) offered by the picker. */
accept?: string[];
/**
* Declared sibling field that receives the file content on hosts without a
* client filesystem (the browser build). Desktop hosts store the chosen path
* in the declaring field and clear this one instead.
*/
content_field?: string;
}
/**
* `visible_when` / `required_when` expression. The legacy `{ field, one_of }`
* clause keeps its exact meaning; `all_of` / `any_of` / `not` compose clauses
* (e.g. `sudo_source = custom AND read_only = false`).
*/
export type PluginFieldCondition = PluginFieldConditionClause | PluginFieldConditionAllOf | PluginFieldConditionAnyOf | PluginFieldConditionNot;
export interface PluginFormField { export interface PluginFormField {
key: string; key: string;
label: string; label: string;
@@ -309,11 +349,15 @@ export interface PluginFormField {
description?: string; description?: string;
placeholder?: string; placeholder?: string;
required?: boolean; required?: boolean;
default?: PluginFormFieldValue; /** Declared default. Hosts older than the manifest serialization fix send
* `null` for "no default", which the form treats as unset. */
default?: PluginFormFieldValue | null;
options?: PluginFormFieldOption[]; options?: PluginFormFieldOption[];
/** Plugin method returning `{ options: [{ value, label }] }` for dynamic /** Plugin method returning `{ options: [{ value, label }] }` for dynamic
* select rendering; falls back to the declared type when unavailable. */ * select rendering; falls back to the declared type when unavailable. */
options_action?: string; options_action?: string;
/** Host API 1.1: offer a local-file action on this field. */
picker?: PluginFormFieldPicker;
binding?: PluginFormFieldBinding; binding?: PluginFormFieldBinding;
visible_when?: PluginFieldCondition; visible_when?: PluginFieldCondition;
required_when?: PluginFieldCondition; required_when?: PluginFieldCondition;
+56
View File
@@ -1606,4 +1606,60 @@ mod tests {
let loaded = load_connections_from_file(&path, &store).unwrap(); let loaded = load_connections_from_file(&path, &store).unwrap();
assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret")); assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret"));
} }
#[test]
fn load_connections_preserves_opaque_null_plugin_secrets() {
let path = temp_connections_file("plugin-null-secret");
let store = MemorySecretStore::default();
let mut config = connection("plugin-connection", "", "");
config.db_type = DatabaseType::Plugin;
config.plugin_id = Some("io.dbx.ssh".to_string());
config.plugin_connection_provider = Some("ssh.connection".to_string());
config.plugin_connection_type = Some("ssh".to_string());
config.external_config = Some(serde_json::json!({ "sudo_source": "custom" }));
config.connection_secrets.insert("sudo_password".to_string(), "null".to_string());
config.connection_secrets.insert("totp_secret".to_string(), "".to_string());
config.connection_secrets.insert("private_key_passphrase".to_string(), "real-passphrase".to_string());
save_connections_to_file(&path, &[config], &store).unwrap();
store.set_existing("plugin-connection", &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}totp_secret"), "null");
let stored = store.values.borrow().clone();
let deleted = store.deleted.borrow().clone();
let raw_config = std::fs::read(&path).unwrap();
let loaded = load_connections_from_file(&path, &store).unwrap();
let secrets = &loaded[0].connection_secrets;
assert_eq!(secrets.get("sudo_password").map(String::as_str), Some("null"));
assert_eq!(secrets.get("totp_secret").map(String::as_str), Some("null"));
assert_eq!(secrets.get("private_key_passphrase").map(String::as_str), Some("real-passphrase"));
assert_eq!(load_connections_from_file(&path, &store).unwrap()[0].connection_secrets, *secrets);
assert_eq!(*store.values.borrow(), stored);
assert_eq!(*store.deleted.borrow(), deleted);
assert_eq!(std::fs::read(&path).unwrap(), raw_config);
save_connections_to_file(&path, &loaded, &store).unwrap();
assert_eq!(load_connections_from_file(&path, &store).unwrap()[0].connection_secrets, *secrets);
assert_eq!(*store.values.borrow(), stored);
}
#[test]
fn file_secret_store_preserves_opaque_null_credentials() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("connections.json");
let secret_path = dir.path().join("secrets.json");
let store = super::FileSecretStore::new(secret_path.clone());
let mut config = connection("plugin-connection", "", "");
config.db_type = DatabaseType::Plugin;
config.connection_secrets.insert("credential".to_string(), "null".to_string());
save_connections_to_file(&path, &[config], &store).unwrap();
let raw_config = std::fs::read(&path).unwrap();
let raw_secrets = std::fs::read(&secret_path).unwrap();
for _ in 0..2 {
let reopened_store = super::FileSecretStore::new(secret_path.clone());
let loaded = load_connections_from_file(&path, &reopened_store).unwrap();
assert_eq!(loaded[0].connection_secrets.get("credential").map(String::as_str), Some("null"));
assert_eq!(std::fs::read(&path).unwrap(), raw_config);
assert_eq!(std::fs::read(&secret_path).unwrap(), raw_secrets);
}
}
} }
+4
View File
@@ -437,6 +437,10 @@ async fn ensure_worker_consent(data_dir: &Path, identity: &str, dest: &str, dige
previous_fingerprint: None, previous_fingerprint: None,
prompt: Some(dest.to_string()), prompt: Some(dest.to_string()),
echo: false, echo: false,
source: None,
title: None,
default_value: None,
options: Vec::new(),
}; };
let Some(rx) = ssh_prompt::request_ssh_prompt(request) else { let Some(rx) = ssh_prompt::request_ssh_prompt(request) else {
return Err("Uploading a SQLite worker requires explicit consent in the Desktop UI".to_string()); return Err("Uploading a SQLite worker requires explicit consent in the Desktop UI".to_string());
+143 -2
View File
@@ -8,6 +8,12 @@
//! suspend on a `oneshot` while the Tauri layer forwards the request to the UI //! suspend on a `oneshot` while the Tauri layer forwards the request to the UI
//! and the UI answers through a command. //! and the UI answers through a command.
//! //!
//! The same gateway carries generic [`SshPromptKind::UserInput`] questions that
//! are not part of a host-owned SSH transport, e.g. a plugin backend asking for
//! a bastion MFA code through the `host/requestUserInput` Host API method. The
//! channel is intentionally transport-agnostic: the host only relays a question
//! and the typed answer, and it never answers on the user's behalf.
//!
//! The gateway is installed once at app startup by the Tauri layer //! The gateway is installed once at app startup by the Tauri layer
//! (`install_ssh_prompt_gateway`). In headless / test contexts where no //! (`install_ssh_prompt_gateway`). In headless / test contexts where no
//! gateway is installed, `request_ssh_prompt` returns `None` and callers MUST //! gateway is installed, `request_ssh_prompt` returns `None` and callers MUST
@@ -30,6 +36,20 @@ pub enum SshPromptKind {
SecretInput, SecretInput,
/// Confirm uploading the SQLite worker binary onto the file host. /// Confirm uploading the SQLite worker binary onto the file host.
WorkerUploadConsent, WorkerUploadConsent,
/// A caller that is not a host-owned transport (today: a plugin backend
/// through the `host/requestUserInput` Host API method) needs a value typed
/// by the user. Unlike [`SshPromptKind::SecretInput`] the host never
/// synthesizes or auto-answers it: without a user there is no answer.
UserInput,
}
/// A fixed answer a [`SshPromptKind::UserInput`] request offers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SshPromptOption {
/// Value returned to the caller when the user picks this option.
pub value: String,
/// Text the dialog shows.
pub label: String,
} }
/// A request for user input, sent from the backend to the UI. /// A request for user input, sent from the backend to the UI.
@@ -56,19 +76,52 @@ pub struct SshPromptRequest {
/// Passwords and verification codes normally set this to false. /// Passwords and verification codes normally set this to false.
#[serde(default)] #[serde(default)]
pub echo: bool, pub echo: bool,
/// UserInput: who is asking (e.g. the plugin display name), shown so the
/// user can tell a bastion login prompt from a host-owned one.
#[serde(default)]
pub source: Option<String>,
/// UserInput: heading above `prompt`, already localized by the caller.
#[serde(default)]
pub title: Option<String>,
/// UserInput: preset answer offered in the input.
#[serde(default)]
pub default_value: Option<String>,
/// UserInput: fixed answers; empty means free-form input.
#[serde(default)]
pub options: Vec<SshPromptOption>,
} }
/// The user's answer, sent from the UI back to the backend. /// The user's answer, sent from the UI back to the backend.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SshPromptAnswer { pub enum SshPromptAnswer {
/// Accept and (for HostKeyVerify) optionally persist the key. /// Accept and (for HostKeyVerify) optionally persist the key.
Accept { remember: bool }, Accept { remember: bool },
/// Reject. /// Reject.
Reject, Reject,
/// A typed secret (SecretInput). /// A typed value (SecretInput / UserInput).
Secret(String), Secret(String),
} }
impl Default for SshPromptRequest {
fn default() -> Self {
Self {
id: String::new(),
kind: SshPromptKind::HostKeyVerify,
host: String::new(),
port: 0,
key_type: None,
fingerprint: None,
previous_fingerprint: None,
prompt: None,
echo: false,
source: None,
title: None,
default_value: None,
options: Vec::new(),
}
}
}
/// Internal envelope: the request plus the channel to deliver the answer on. /// Internal envelope: the request plus the channel to deliver the answer on.
pub struct SshPromptEnvelope { pub struct SshPromptEnvelope {
pub request: SshPromptRequest, pub request: SshPromptRequest,
@@ -88,6 +141,18 @@ pub fn clear_ssh_prompt_gateway() {
*PROMPT_GATEWAY.lock().unwrap() = None; *PROMPT_GATEWAY.lock().unwrap() = None;
} }
/// Serializes every test that mutates the process-global prompt gateway.
///
/// One gateway serves the host's SSH transports, the SQLite worker consent
/// prompt and plugin Host API questions, so tests in any module must hold this
/// lock while a gateway is installed — otherwise one test's gateway (or the
/// fail-closed checks that rely on *no* gateway) clobbers another's.
#[cfg(test)]
pub fn prompt_gateway_test_lock() -> &'static tokio::sync::Mutex<()> {
static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
&LOCK
}
/// Request input from the UI. Returns the receiver the caller should await, or /// Request input from the UI. Returns the receiver the caller should await, or
/// `None` if no gateway is installed (caller must fail closed). /// `None` if no gateway is installed (caller must fail closed).
pub fn request_ssh_prompt(request: SshPromptRequest) -> Option<oneshot::Receiver<SshPromptAnswer>> { pub fn request_ssh_prompt(request: SshPromptRequest) -> Option<oneshot::Receiver<SshPromptAnswer>> {
@@ -117,6 +182,10 @@ pub fn host_key_verify_request(
previous_fingerprint: None, previous_fingerprint: None,
prompt: None, prompt: None,
echo: false, echo: false,
source: None,
title: None,
default_value: None,
options: Vec::new(),
} }
} }
@@ -138,6 +207,10 @@ pub fn host_key_changed_request(
previous_fingerprint, previous_fingerprint,
prompt: None, prompt: None,
echo: false, echo: false,
source: None,
title: None,
default_value: None,
options: Vec::new(),
} }
} }
@@ -153,6 +226,74 @@ pub fn secret_input_request(host: &str, port: u16, prompt: String, echo: bool) -
previous_fingerprint: None, previous_fingerprint: None,
prompt: Some(prompt), prompt: Some(prompt),
echo, echo,
source: None,
title: None,
default_value: None,
options: Vec::new(),
}
}
/// A generic question from a caller the host does not own (today: a plugin
/// backend). Built through [`UserInputRequest::into_request`], which allocates
/// the prompt id the UI answers with.
#[derive(Debug, Clone)]
pub struct UserInputRequest {
pub prompt: String,
pub echo: bool,
pub title: Option<String>,
pub source: Option<String>,
pub default_value: Option<String>,
pub options: Vec<SshPromptOption>,
}
impl UserInputRequest {
pub fn new(prompt: impl Into<String>) -> Self {
Self { prompt: prompt.into(), echo: false, title: None, source: None, default_value: None, options: Vec::new() }
}
pub fn with_title(mut self, title: Option<String>) -> Self {
self.title = title;
self
}
pub fn with_source(mut self, source: Option<String>) -> Self {
self.source = source;
self
}
pub fn with_default(mut self, default_value: Option<String>) -> Self {
self.default_value = default_value;
self
}
pub fn with_options(mut self, options: Vec<SshPromptOption>) -> Self {
self.options = options;
self
}
pub fn with_echo(mut self, echo: bool) -> Self {
self.echo = echo;
self
}
/// Turn the question into a prompt request. `host`/`port` are display-only
/// context a caller outside the host's own transports usually leaves empty.
pub fn into_request(self, host: &str, port: u16) -> SshPromptRequest {
SshPromptRequest {
id: Uuid::new_v4().to_string(),
kind: SshPromptKind::UserInput,
host: host.to_string(),
port,
key_type: None,
fingerprint: None,
previous_fingerprint: None,
prompt: Some(self.prompt),
echo: self.echo,
source: self.source,
title: self.title,
default_value: self.default_value,
options: self.options,
}
} }
} }
+26 -24
View File
@@ -1877,11 +1877,13 @@ pub(crate) fn effective_hop_timeout(hop: &SshTunnelConfig) -> u64 {
} }
} }
/// Serializes every test that mutates the process-global SSH prompt gateway so /// Serializes every test that mutates the process-global prompt gateway. The
/// they cannot clobber each other's gateway (or the MITM fail-closed test, /// lock lives in `db::ssh_prompt` because the gateway is shared with the plugin
/// which relies on *no* gateway being installed). Test-only. /// Host API, so prompt tests in other modules must take the same lock. Test-only.
#[cfg(test)] #[cfg(test)]
static PROMPT_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); fn prompt_test_lock() -> &'static tokio::sync::Mutex<()> {
crate::db::ssh_prompt::prompt_gateway_test_lock()
}
#[cfg(test)] #[cfg(test)]
fn plan_chain( fn plan_chain(
@@ -1918,10 +1920,10 @@ fn plan_chain(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::prompt_test_lock;
#[cfg(unix)] #[cfg(unix)]
use super::resolve_ssh_agent_socket_path; use super::resolve_ssh_agent_socket_path;
use super::SshClient; use super::SshClient;
use super::PROMPT_TEST_LOCK;
use super::{ use super::{
bind_tunnel_listener, connect_and_authenticate, describe_terminal_auth_failure, effective_hop_timeout, bind_tunnel_listener, connect_and_authenticate, describe_terminal_auth_failure, effective_hop_timeout,
netcat_proxy_command, openssh_padding_len, plan_chain, read_ssh_string, netcat_proxy_command, openssh_padding_len, plan_chain, read_ssh_string,
@@ -2404,7 +2406,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn unknown_host_prompt_accept_learns_key() { async fn unknown_host_prompt_accept_learns_key() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts"); let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path.clone()); let verifier = HostKeyVerifier::new(path.clone());
@@ -2428,7 +2430,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn unknown_host_prompt_accept_without_remember_is_session_only() { async fn unknown_host_prompt_accept_without_remember_is_session_only() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts"); let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path.clone()); let verifier = HostKeyVerifier::new(path.clone());
@@ -2454,7 +2456,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn unknown_host_prompt_reject_aborts_handshake() { async fn unknown_host_prompt_reject_aborts_handshake() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts"); let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path.clone()); let verifier = HostKeyVerifier::new(path.clone());
@@ -2480,7 +2482,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn unknown_host_without_gateway_fails_closed() { async fn unknown_host_without_gateway_fails_closed() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
// Ensure no gateway is installed so request_ssh_prompt returns None. // Ensure no gateway is installed so request_ssh_prompt returns None.
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -2501,7 +2503,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn trusted_host_skips_prompt() { async fn trusted_host_skips_prompt() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts"); let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path); let verifier = HostKeyVerifier::new(path);
@@ -2531,7 +2533,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn changed_host_prompt_update_replaces_key() { async fn changed_host_prompt_update_replaces_key() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts"); let path = dir.path().join("known_hosts");
seed_changed_host_key(&path); seed_changed_host_key(&path);
@@ -2559,7 +2561,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn changed_host_prompt_continue_is_session_only() { async fn changed_host_prompt_continue_is_session_only() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts"); let path = dir.path().join("known_hosts");
seed_changed_host_key(&path); seed_changed_host_key(&path);
@@ -2587,7 +2589,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn changed_host_prompt_reject_aborts_handshake() { async fn changed_host_prompt_reject_aborts_handshake() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts"); let path = dir.path().join("known_hosts");
seed_changed_host_key(&path); seed_changed_host_key(&path);
@@ -2735,7 +2737,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn password_auth_continues_with_keyboard_interactive_totp() { async fn password_auth_continues_with_keyboard_interactive_totp() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let (port, server_task) = start_password_then_totp_server().await; let (port, server_task) = start_password_then_totp_server().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -2781,7 +2783,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn public_key_auth_continues_with_keyboard_interactive_totp() { async fn public_key_auth_continues_with_keyboard_interactive_totp() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let (port, server_task) = start_password_then_totp_server().await; let (port, server_task) = start_password_then_totp_server().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -2901,7 +2903,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn socks5_proxy_forwards_requested_target_over_ssh() { async fn socks5_proxy_forwards_requested_target_over_ssh() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key"); let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
let server_config = server::Config { keys: vec![server_key], ..Default::default() }; let server_config = server::Config { keys: vec![server_key], ..Default::default() };
@@ -3052,7 +3054,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn tunnel_falls_back_to_netcat_when_direct_tcpip_is_prohibited() { async fn tunnel_falls_back_to_netcat_when_direct_tcpip_is_prohibited() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key"); let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
let server_config = server::Config { keys: vec![server_key], ..Default::default() }; let server_config = server::Config { keys: vec![server_key], ..Default::default() };
@@ -3107,7 +3109,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn prohibited_direct_tcpip_does_not_run_netcat_by_default() { async fn prohibited_direct_tcpip_does_not_run_netcat_by_default() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key"); let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
let server_config = server::Config { keys: vec![server_key], ..Default::default() }; let server_config = server::Config { keys: vec![server_key], ..Default::default() };
@@ -3157,7 +3159,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn forwarded_connection_checks_logical_host_identity() { async fn forwarded_connection_checks_logical_host_identity() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let (connect_port, server_task) = start_accept_none_server().await; let (connect_port, server_task) = start_accept_none_server().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -3205,7 +3207,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
/// wait must not be charged against `connect_timeout_secs`. /// wait must not be charged against `connect_timeout_secs`.
#[tokio::test] #[tokio::test]
async fn slow_host_key_acceptance_does_not_time_out_the_connection() { async fn slow_host_key_acceptance_does_not_time_out_the_connection() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let (connect_port, server_task) = start_accept_none_server().await; let (connect_port, server_task) = start_accept_none_server().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -3248,7 +3250,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn concurrent_tunnel_starts_share_one_handshake() { async fn concurrent_tunnel_starts_share_one_handshake() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let (connect_port, server_task) = start_accept_none_server().await; let (connect_port, server_task) = start_accept_none_server().await;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -3342,7 +3344,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn unknown_host_without_persist_permission_does_not_leak_password() { async fn unknown_host_without_persist_permission_does_not_leak_password() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
// This test proves the client never sends a password to an untrusted // This test proves the client never sends a password to an untrusted
// host. It must run with NO prompt gateway installed so the handshake // host. It must run with NO prompt gateway installed so the handshake
// fails closed (no UI to confirm the key -> reject before auth). // fails closed (no UI to confirm the key -> reject before auth).
@@ -3479,7 +3481,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn reconnect_auth_failure_is_reported_instead_of_a_dead_local_port() { async fn reconnect_auth_failure_is_reported_instead_of_a_dead_local_port() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
let publickey_attempts = Arc::new(AtomicUsize::new(0)); let publickey_attempts = Arc::new(AtomicUsize::new(0));
@@ -3573,7 +3575,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test] #[tokio::test]
async fn rejected_public_key_reports_what_the_server_refused() { async fn rejected_public_key_reports_what_the_server_refused() {
let _guard = PROMPT_TEST_LOCK.lock().await; let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway(); ssh_prompt::clear_ssh_prompt_gateway();
// Every publickey attempt is refused, so this exercises the initial // Every publickey attempt is refused, so this exercises the initial
+6 -5
View File
@@ -40,16 +40,17 @@ pub use manifest::{
current_plugin_target, resolve_safe_plugin_path, PluginBackendEntrypoint, PluginBackendTransport, current_plugin_target, resolve_safe_plugin_path, PluginBackendEntrypoint, PluginBackendTransport,
PluginCompatibility, PluginConnectionActionContribution, PluginConnectionActionVariant, PluginConnectionActionWhen, PluginCompatibility, PluginConnectionActionContribution, PluginConnectionActionVariant, PluginConnectionActionWhen,
PluginConnectionCapability, PluginConnectionProviderContribution, PluginContribution, PluginDriverManifest, PluginConnectionCapability, PluginConnectionProviderContribution, PluginContribution, PluginDriverManifest,
PluginEngines, PluginEntrypoints, PluginFieldCondition, PluginFilesystemCapability, PluginEngines, PluginEntrypoints, PluginFieldCondition, PluginFieldConditionClause, PluginFieldConditionLiteral,
PluginFilesystemProviderContribution, PluginFormFieldBinding, PluginFormFieldDefinition, PluginFormFieldOption, PluginFilesystemCapability, PluginFilesystemProviderContribution, PluginFormFieldBinding,
PluginFormFieldDefinition, PluginFormFieldOption, PluginFormFieldPicker, PluginFormFieldPickerKind,
PluginFormFieldType, PluginManifest, PluginUiEntrypoint, PluginWorkbenchContribution, PluginFormFieldType, PluginManifest, PluginUiEntrypoint, PluginWorkbenchContribution,
PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD, PLUGIN_CONNECTION_DISCONNECT_METHOD, PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD, PLUGIN_CONNECTION_DISCONNECT_METHOD,
PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_MANIFEST_VERSION, PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_HOST_FEATURES,
SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION, SUPPORTED_PLUGIN_MANIFEST_VERSION, SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
}; };
pub use runtime::{ pub use runtime::{
PluginBinaryMessage, PluginEvent, PluginHandshake, PluginHandshakeIdentity, PluginSessionState, PluginBinaryMessage, PluginEvent, PluginHandshake, PluginHandshakeIdentity, PluginSessionState,
PluginSessionStatus, PluginSidecarSession, PLUGIN_REQUEST_TIMEOUT, PluginSessionStatus, PluginSidecarSession, PLUGIN_REQUEST_TIMEOUT, PLUGIN_REQUEST_USER_INPUT_METHOD,
}; };
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
+255 -31
View File
@@ -546,39 +546,36 @@ fn plugin_field_value_is_empty(value: Option<&serde_json::Value>) -> bool {
} }
} }
/// Resolves the stored value of one plugin form field (a condition's operand).
fn plugin_condition_field_value(
key: &str,
config: &ConnectionConfig,
provider: &PluginConnectionProviderContribution,
) -> Option<serde_json::Value> {
let sibling = provider.fields.iter().find(|field| field.key == key)?;
plugin_connection_field_value(config, sibling)
}
/// Evaluates a plugin manifest field condition (`visible_when` / `required_when`, /// Evaluates a plugin manifest field condition (`visible_when` / `required_when`,
/// Host API 1.1) against the stored connection values. Mirrors the frontend /// Host API 1.1) against the stored connection values. Mirrors the frontend
/// `pluginFieldConditions.ts` semantics: the condition matches when the current /// `pluginFieldConditions.ts` semantics: a leaf matches when the current value
/// value of the referenced sibling field is listed in `one_of`; a missing /// of the referenced sibling field is listed in `one_of`, and a missing sibling
/// sibling field or an unset/empty value never matches. /// field or an unset/empty value never matches; `all_of` / `any_of` / `not`
/// compose those clauses.
fn plugin_field_condition_matches( fn plugin_field_condition_matches(
condition: &super::PluginFieldCondition, condition: &super::PluginFieldCondition,
config: &ConnectionConfig, config: &ConnectionConfig,
provider: &PluginConnectionProviderContribution, provider: &PluginConnectionProviderContribution,
) -> bool { ) -> bool {
let Some(sibling) = provider.fields.iter().find(|field| field.key == condition.field) else { condition.matches(&|key| plugin_condition_field_value(key, config, provider))
return false;
};
let Some(value) = plugin_connection_field_value(config, sibling) else {
return false;
};
let text = match value {
serde_json::Value::Null => return false,
serde_json::Value::String(text) => text,
other => other.to_string(),
};
if text.trim().is_empty() {
return false;
}
condition.one_of.iter().any(|option| option == &text)
} }
/// A field participates in the form when its `visible_when` (if any) matches. /// A field participates in the form when its `visible_when` (if any) matches.
/// Mirrors the frontend cascade (`pluginFieldConditions.ts`): once the raw /// Mirrors the frontend cascade (`pluginFieldConditions.ts`): a clause only
/// condition matches, the referenced sibling must itself be visible — a hidden /// counts while the sibling it reads is itself visible — a hidden container
/// container field's stored default (e.g. `krb_credential_type: "password"` /// field's stored default (e.g. `krb_credential_type: "password"` while auth is
/// while auth is simple) must not mark grandchild fields visible + required, /// simple) must not mark grandchild fields visible + required, otherwise
/// otherwise non-dialog write paths reject connections the dialog accepts. /// non-dialog write paths reject connections the dialog accepts.
fn plugin_field_is_visible( fn plugin_field_is_visible(
field: &PluginFormFieldDefinition, field: &PluginFormFieldDefinition,
config: &ConnectionConfig, config: &ConnectionConfig,
@@ -598,19 +595,59 @@ fn plugin_field_is_visible_cached(
let Some(condition) = &field.visible_when else { let Some(condition) = &field.visible_when else {
return true; return true;
}; };
if !plugin_field_condition_matches(condition, config, provider) { plugin_field_condition_is_visible(condition, config, provider, seen)
return false; }
/// Visibility-aware evaluation of one condition expression, mirroring the
/// frontend `conditionExpressionVisible`: a clause only counts while the field
/// it reads is itself visible, `any_of`/`all_of` compose those verdicts, and
/// `not` additionally requires every operand to be visible (an inverted hidden
/// value is not a usable answer).
fn plugin_field_condition_is_visible(
condition: &super::PluginFieldCondition,
config: &ConnectionConfig,
provider: &PluginConnectionProviderContribution,
seen: &mut HashSet<String>,
) -> bool {
match condition {
super::PluginFieldCondition::Field(clause) => {
if !plugin_field_condition_matches(condition, config, provider) {
return false;
}
plugin_field_key_is_visible(&clause.field, config, provider, seen)
}
super::PluginFieldCondition::AllOf { all_of } => {
all_of.iter().all(|child| plugin_field_condition_is_visible(child, config, provider, seen))
}
super::PluginFieldCondition::AnyOf { any_of } => {
any_of.iter().any(|child| plugin_field_condition_is_visible(child, config, provider, seen))
}
super::PluginFieldCondition::Not { not } => {
let operands_visible =
not.referenced_fields().iter().all(|key| plugin_field_key_is_visible(key, config, provider, seen));
operands_visible && !plugin_field_condition_matches(not, config, provider)
}
} }
// The condition matched, so the sibling exists (its value was readable); }
// guard cycles anyway and fall through to visible, mirroring the frontend.
let Some(sibling) = provider.fields.iter().find(|candidate| candidate.key == condition.field) else { /// Whether the sibling field behind one referenced key is itself rendered.
/// Cycles count as visible, mirroring the frontend's `seen` guard.
fn plugin_field_key_is_visible(
key: &str,
config: &ConnectionConfig,
provider: &PluginConnectionProviderContribution,
seen: &mut HashSet<String>,
) -> bool {
let Some(sibling) = provider.fields.iter().find(|candidate| candidate.key == key) else {
return true; return true;
}; };
if seen.contains(&sibling.key) { if seen.contains(&sibling.key) {
return true; return true;
} }
seen.insert(sibling.key.clone()); seen.insert(sibling.key.clone());
plugin_field_is_visible_cached(sibling, config, provider, seen) let visible = plugin_field_is_visible_cached(sibling, config, provider, seen);
seen.remove(&sibling.key);
visible
} }
/// Effective required = static `required` OR a matching `required_when` /// Effective required = static `required` OR a matching `required_when`
@@ -695,8 +732,8 @@ fn ensure_permission(plugin: &super::InstalledPlugin, required_permission: Optio
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{ use super::{
plugin_connection_action_result, plugin_invoke_connection_action, validate_plugin_connection_values, plugin_connection_action_result, plugin_field_is_visible, plugin_invoke_connection_action,
validate_plugin_connection_values_for_action, validate_plugin_connection_values, validate_plugin_connection_values_for_action,
}; };
use crate::models::connection::ConnectionConfig; use crate::models::connection::ConnectionConfig;
use crate::plugins::PluginConnectionProviderContribution; use crate::plugins::PluginConnectionProviderContribution;
@@ -1117,4 +1154,191 @@ mod tests {
let cyclic_config = config_for(serde_json::json!({ "a": "x", "b": "x" })); let cyclic_config = config_for(serde_json::json!({ "a": "x", "b": "x" }));
assert!(validate_plugin_connection_values(&cyclic_config, &cyclic).is_ok()); assert!(validate_plugin_connection_values(&cyclic_config, &cyclic).is_ok());
} }
#[test]
fn condition_sibling_branches_keep_cycle_detection_path_local() {
let mut provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
"id": "test.connection",
"database_type": "test",
"fields": [
{ "key": "mode", "label": "Mode", "type": "text" },
{
"key": "auth", "label": "Auth", "type": "text",
"visible_when": { "field": "mode", "one_of": ["enabled"] }
},
{ "key": "flag", "label": "Flag", "type": "boolean" },
{ "key": "target", "label": "Target", "type": "text", "required": true }
]
}))
.unwrap();
let mut config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "plugin-connection", "name": "Test", "db_type": "plugin",
"host": "", "port": 0, "username": "", "password": ""
}))
.unwrap();
let clause = serde_json::json!({ "field": "auth", "one_of": ["password"] });
let branches = [
serde_json::json!({ "all_of": [clause, { "field": "flag", "one_of": [true] }] }),
serde_json::json!({ "all_of": [{ "field": "flag", "one_of": [false] }, clause] }),
];
for condition in [
clause.clone(),
serde_json::json!({ "any_of": [clause, clause] }),
serde_json::json!({ "all_of": [clause, clause] }),
serde_json::json!({ "any_of": [branches[0], branches[1]] }),
serde_json::json!({ "any_of": [branches[1], branches[0]] }),
] {
provider.fields[3].visible_when = Some(serde_json::from_value(condition.clone()).unwrap());
for flag in [false, true] {
for (mode, expected) in [("disabled", false), ("enabled", true)] {
config.external_config =
Some(serde_json::json!({ "mode": mode, "auth": "password", "flag": flag }));
assert_eq!(
plugin_field_is_visible(&provider.fields[3], &config, &provider),
expected,
"{condition}"
);
assert_eq!(validate_plugin_connection_values(&config, &provider).is_err(), expected, "{condition}");
}
}
}
provider.fields[3].visible_when = Some(
serde_json::from_value(serde_json::json!({
"not": { "any_of": [clause, clause] }
}))
.unwrap(),
);
for (mode, expected) in [("disabled", false), ("enabled", true)] {
config.external_config = Some(serde_json::json!({ "mode": mode, "auth": "token" }));
assert_eq!(plugin_field_is_visible(&provider.fields[3], &config, &provider), expected);
}
}
#[test]
fn condition_cycles_still_require_matching_values() {
let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
"id": "test.connection",
"database_type": "test",
"fields": [
{ "key": "first", "label": "First", "type": "text", "visible_when": { "field": "second", "one_of": ["on"] } },
{ "key": "second", "label": "Second", "type": "text", "visible_when": { "field": "first", "one_of": ["on"] } },
{ "key": "self", "label": "Self", "type": "text", "visible_when": { "field": "self", "one_of": ["on"] } },
{ "key": "unknown", "label": "Unknown", "type": "text", "visible_when": { "field": "missing", "one_of": ["on"] } }
]
}))
.unwrap();
let mut config: ConnectionConfig = serde_json::from_value(serde_json::json!({
"id": "plugin-connection", "name": "Test", "db_type": "plugin",
"host": "", "port": 0, "username": "", "password": ""
}))
.unwrap();
for (value, expected) in [("on", true), ("off", false)] {
config.external_config =
Some(serde_json::json!({ "first": value, "second": "on", "self": value, "missing": value }));
for field in &provider.fields {
assert_eq!(
plugin_field_is_visible(field, &config, &provider),
expected && field.key != "unknown",
"{}",
field.key
);
}
}
}
/// Mirrors the SSH plugin shape the composite contract was added for:
/// `sudo_command` is required only while `sudo_source = custom` **and**
/// `read_only = false`, which the single-clause contract could not express.
#[test]
fn composite_condition_gates_required_fields_like_the_dialog() {
let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
"id": "ssh.connection",
"label": "SSH",
"database_type": "ssh",
"fields": [
{
"key": "read_only",
"label": "Read only",
"type": "boolean",
"binding": "config",
"default": false
},
{
"key": "sudo_source",
"label": "Sudo source",
"type": "select",
"binding": "config",
"default": "none",
"options": [
{ "value": "none", "label": "None" },
{ "value": "custom", "label": "Custom" }
]
},
{
"key": "sudo_command",
"label": "Sudo command",
"type": "text",
"binding": "config",
"visible_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "field": "read_only", "one_of": [false] }
]
},
"required_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "not": { "field": "read_only", "one_of": [true] } }
]
}
}
]
}))
.unwrap();
let config_for = |external: serde_json::Value| -> ConnectionConfig {
serde_json::from_value(serde_json::json!({
"id": "plugin-connection",
"name": "Prod SSH",
"db_type": "plugin",
"host": "ssh.example.com",
"port": 22,
"username": "root",
"password": "",
"database": null,
"plugin_id": "io.dbx.ssh",
"plugin_connection_provider": "ssh.connection",
"plugin_connection_type": "ssh",
"external_config": external
}))
.unwrap()
};
// Read-only sessions ignore the sudo block: nothing is required.
assert!(validate_plugin_connection_values(
&config_for(serde_json::json!({ "sudo_source": "custom", "read_only": true })),
&provider
)
.is_ok());
// Sudo stays off: nothing is required either.
assert!(validate_plugin_connection_values(
&config_for(serde_json::json!({ "sudo_source": "none", "read_only": false })),
&provider
)
.is_ok());
// Custom sudo on a writable connection: the command becomes required.
assert!(validate_plugin_connection_values(
&config_for(serde_json::json!({ "sudo_source": "custom", "read_only": false })),
&provider
)
.unwrap_err()
.contains("Sudo command' is required"));
// ...and passes once it is filled in.
assert!(validate_plugin_connection_values(
&config_for(
serde_json::json!({ "sudo_source": "custom", "read_only": false, "sudo_command": "sudo -n true" })
),
&provider
)
.is_ok());
}
} }
+618 -43
View File
@@ -5,7 +5,15 @@ use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub const SUPPORTED_PLUGIN_MANIFEST_VERSION: u32 = 1; pub const SUPPORTED_PLUGIN_MANIFEST_VERSION: u32 = 1;
pub const SUPPORTED_PLUGIN_HOST_API_VERSION: &str = "1.0.0"; /// Host API version the host advertises at `plugin/initialize`.
///
/// 1.1 adds the plugin-initiated `host/requestUserInput` method (see
/// `plugins/runtime.rs`). It is additive: 1.0 plugins keep working, and a
/// plugin that wants the capability must check the advertised version (or the
/// `host.requestUserInput` entry in `host.features`) before calling it.
pub const SUPPORTED_PLUGIN_HOST_API_VERSION: &str = "1.1.0";
/// Capabilities the host advertises to a plugin backend at `plugin/initialize`.
pub const SUPPORTED_PLUGIN_HOST_FEATURES: &[&str] = &["host.requestUserInput"];
pub const SUPPORTED_PLUGIN_PROTOCOL_VERSION: u32 = 1; pub const SUPPORTED_PLUGIN_PROTOCOL_VERSION: u32 = 1;
pub const PLUGIN_CONNECTION_TEST_METHOD: &str = "connection/test"; pub const PLUGIN_CONNECTION_TEST_METHOD: &str = "connection/test";
pub const PLUGIN_CONNECTION_CONNECT_METHOD: &str = "connection/connect"; pub const PLUGIN_CONNECTION_CONNECT_METHOD: &str = "connection/connect";
@@ -16,6 +24,13 @@ pub const SUPPORTED_PLUGIN_PERMISSIONS: &[&str] = &["host.events", "host.binary"
/// Cap the number of `host.network:<origin>` entries so a manifest cannot bloat /// Cap the number of `host.network:<origin>` entries so a manifest cannot bloat
/// the sandbox CSP or enumerate large origin lists. /// the sandbox CSP or enumerate large origin lists.
pub const MAX_PLUGIN_NETWORK_ORIGINS: usize = 8; pub const MAX_PLUGIN_NETWORK_ORIGINS: usize = 8;
/// Bound the `visible_when` / `required_when` expression tree so a hostile
/// manifest cannot make the host or the dialog evaluator do unbounded work.
pub const MAX_PLUGIN_FIELD_CONDITION_DEPTH: usize = 8;
pub const MAX_PLUGIN_FIELD_CONDITION_NODES: usize = 64;
/// Cap the file filters a picker may declare so one manifest cannot bloat the
/// native dialog or the browser `accept` attribute.
pub const MAX_PLUGIN_PICKER_FILTERS: usize = 16;
const HOST_NETWORK_PERMISSION_PREFIX: &str = "host.network:"; const HOST_NETWORK_PERMISSION_PREFIX: &str = "host.network:";
/// Parse a `host.network:https://host[:port]` permission into the origin that /// Parse a `host.network:https://host[:port]` permission into the origin that
@@ -104,9 +119,9 @@ pub struct PluginEngines {
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct PluginEntrypoints { pub struct PluginEntrypoints {
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<PluginBackendEntrypoint>, pub backend: Option<PluginBackendEntrypoint>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub ui: Option<PluginUiEntrypoint>, pub ui: Option<PluginUiEntrypoint>,
} }
@@ -157,7 +172,7 @@ pub struct PluginDriverManifest {
pub id: String, pub id: String,
pub label: String, pub label: String,
pub kind: String, pub kind: String,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub database_type: Option<String>, pub database_type: Option<String>,
} }
@@ -236,18 +251,27 @@ pub struct PluginFormFieldDefinition {
pub label: String, pub label: String,
#[serde(rename = "type")] #[serde(rename = "type")]
pub field_type: PluginFormFieldType, pub field_type: PluginFormFieldType,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>, pub description: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub placeholder: Option<String>, pub placeholder: Option<String>,
#[serde(default)] #[serde(default)]
pub required: bool, pub required: bool,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub default: Option<serde_json::Value>, pub default: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub options: Vec<PluginFormFieldOption>, pub options: Vec<PluginFormFieldOption>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub binding: Option<PluginFormFieldBinding>, pub binding: Option<PluginFormFieldBinding>,
/// Optional local-file action on a text/password/textarea field.
///
/// Desktop (client-side) hosts open a native picker and store the chosen
/// **absolute path** in this field. Browser hosts cannot read a client
/// path, so the same action becomes an **upload**: the host reads the file
/// and stores its content in `content_field` instead. Contract documented
/// in `plugins/README.md`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub picker: Option<PluginFormFieldPicker>,
/// Plugin method returning `{ options: [{ value, label }] }`; the host /// Plugin method returning `{ options: [{ value, label }] }`; the host
/// connection form fetches it and renders the field as a dynamic select. /// connection form fetches it and renders the field as a dynamic select.
/// Optional and forward/backward compatible: older hosts reject the /// Optional and forward/backward compatible: older hosts reject the
@@ -260,11 +284,189 @@ pub struct PluginFormFieldDefinition {
pub required_when: Option<PluginFieldCondition>, pub required_when: Option<PluginFieldCondition>,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] /// A `visible_when` / `required_when` expression.
///
/// The legacy single-field form `{ "field": "mode", "one_of": ["custom"] }`
/// keeps its exact meaning. Composite forms (`all_of`, `any_of`, `not`) let a
/// manifest express combinations such as
/// `sudo_source = custom AND read_only = false`, which a single-field
/// condition cannot. Composite nodes nest arbitrarily; [`MAX_PLUGIN_FIELD_CONDITION_DEPTH`]
/// bounds the evaluation cost of a hostile manifest.
///
/// Semantics are shared with the frontend evaluator
/// (`apps/desktop/src/lib/plugins/pluginFieldConditions.ts`): a leaf matches
/// when the referenced sibling field holds a non-empty value that equals one of
/// the listed literals (compared by canonical string form, so the boolean
/// `false` matches both the literal `false` and the literal `"false"`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged, deny_unknown_fields)]
pub enum PluginFieldCondition {
/// Legacy single-field clause: `{ "field": "...", "one_of": [...] }`.
Field(PluginFieldConditionClause),
/// Every nested condition must match.
AllOf { all_of: Vec<PluginFieldCondition> },
/// At least one nested condition must match.
AnyOf { any_of: Vec<PluginFieldCondition> },
/// Inverts the nested condition.
Not { not: Box<PluginFieldCondition> },
}
/// The legacy single-field clause of a [`PluginFieldCondition`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct PluginFieldCondition { pub struct PluginFieldConditionClause {
pub field: String, pub field: String,
pub one_of: Vec<String>, pub one_of: Vec<PluginFieldConditionLiteral>,
}
/// A value a manifest may list in `one_of`. Plugins mostly compare strings,
/// but booleans and numbers are allowed so a condition can be written exactly
/// like the value the form produces (`"read_only": [false]` instead of
/// `["false"]`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PluginFieldConditionLiteral {
String(String),
Bool(bool),
Number(serde_json::Number),
}
impl PluginFieldConditionLiteral {
/// Canonical string form used for comparison. This is the rule the
/// frontend has always applied (`String(value)`), so every manifest written
/// against the string-only contract keeps matching.
pub fn canonical(&self) -> String {
match self {
Self::String(value) => value.clone(),
Self::Bool(value) => value.to_string(),
// `serde_json::Number` prints `22.0` for a float that JavaScript
// renders as `22`; normalize integral floats so the two sides agree.
Self::Number(value) => normalize_condition_number(value),
}
}
}
fn normalize_condition_number(number: &serde_json::Number) -> String {
if let Some(value) = number.as_i64() {
return value.to_string();
}
if let Some(value) = number.as_u64() {
return value.to_string();
}
if let Some(value) = number.as_f64() {
if value.fract() == 0.0 && value.abs() < 9_007_199_254_740_992.0 {
return format!("{}", value as i64);
}
}
number.to_string()
}
impl PluginFieldCondition {
/// Every sibling field key the expression reads, in declaration order.
/// Duplicates are preserved; callers de-duplicate when they need to.
pub fn referenced_fields(&self) -> Vec<&str> {
let mut fields = Vec::new();
self.collect_referenced_fields(&mut fields);
fields
}
fn collect_referenced_fields<'a>(&'a self, fields: &mut Vec<&'a str>) {
match self {
Self::Field(clause) => fields.push(clause.field.as_str()),
Self::AllOf { all_of } => all_of.iter().for_each(|child| child.collect_referenced_fields(fields)),
Self::AnyOf { any_of } => any_of.iter().for_each(|child| child.collect_referenced_fields(fields)),
Self::Not { not } => not.collect_referenced_fields(fields),
}
}
/// Structural validation shared by every condition site. Returns
/// human-readable problems without a location prefix.
pub fn validate(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.node_count() > MAX_PLUGIN_FIELD_CONDITION_NODES {
errors.push(format!("condition uses more than {MAX_PLUGIN_FIELD_CONDITION_NODES} nodes"));
return errors;
}
self.validate_at_depth(0, &mut errors);
errors
}
fn validate_at_depth(&self, depth: usize, errors: &mut Vec<String>) {
if depth > MAX_PLUGIN_FIELD_CONDITION_DEPTH {
errors.push(format!("condition nesting exceeds {MAX_PLUGIN_FIELD_CONDITION_DEPTH} levels"));
return;
}
match self {
Self::Field(clause) => {
if clause.field.trim().is_empty() {
errors.push("condition field cannot be empty".to_string());
}
if clause.one_of.is_empty() {
errors.push("condition one_of cannot be empty".to_string());
}
}
Self::AllOf { all_of } => {
if all_of.is_empty() {
errors.push("condition all_of cannot be empty".to_string());
}
for child in all_of {
child.validate_at_depth(depth + 1, errors);
}
}
Self::AnyOf { any_of } => {
if any_of.is_empty() {
errors.push("condition any_of cannot be empty".to_string());
}
for child in any_of {
child.validate_at_depth(depth + 1, errors);
}
}
Self::Not { not } => not.validate_at_depth(depth + 1, errors),
}
}
/// Number of nodes in this expression tree (including this one).
pub fn node_count(&self) -> usize {
match self {
Self::Field(_) => 1,
Self::AllOf { all_of } => 1 + all_of.iter().map(Self::node_count).sum::<usize>(),
Self::AnyOf { any_of } => 1 + any_of.iter().map(Self::node_count).sum::<usize>(),
Self::Not { not } => 1 + not.node_count(),
}
}
/// Raw expression evaluation against a field-value reader. Visibility
/// cascade handling (a referenced field that is itself hidden) is applied
/// by callers, exactly like the single-field contract behaved.
pub fn matches(&self, read: &impl Fn(&str) -> Option<serde_json::Value>) -> bool {
match self {
Self::Field(clause) => {
let Some(value) = read(&clause.field) else {
return false;
};
let text = condition_value_text(&value);
if text.trim().is_empty() {
return false;
}
clause.one_of.iter().any(|literal| literal.canonical() == text)
}
Self::AllOf { all_of } => all_of.iter().all(|child| child.matches(read)),
Self::AnyOf { any_of } => any_of.iter().any(|child| child.matches(read)),
Self::Not { not } => !not.matches(read),
}
}
}
/// Canonical string form of a stored field value, mirroring the frontend
/// (`String(value)`) so a boolean `false` and the literal `"false"` agree.
pub fn condition_value_text(value: &serde_json::Value) -> String {
match value {
serde_json::Value::Null => String::new(),
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Bool(value) => value.to_string(),
serde_json::Value::Number(value) => normalize_condition_number(value),
other => other.to_string(),
}
} }
impl PluginFormFieldDefinition { impl PluginFormFieldDefinition {
@@ -309,22 +511,50 @@ pub struct PluginFormFieldOption {
pub value: String, pub value: String,
} }
/// A file action on a plugin connection field (see
/// [`PluginFormFieldDefinition::picker`]).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginFormFieldPicker {
pub kind: PluginFormFieldPickerKind,
/// File filters offered by the picker, e.g. `[".pem", ".key"]`. Entries are
/// extensions (`.ext`) or MIME types (`text/plain`); non-empty entries only.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub accept: Vec<String>,
/// Field that receives the file **content** on hosts without a client
/// filesystem (the browser build), which cannot produce a usable path.
/// Required for the picker to appear in the browser; on desktop the chosen
/// path goes into the declaring field and this field is cleared so the two
/// sources cannot disagree.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_field: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PluginFormFieldPickerKind {
/// Pick one existing file.
File,
/// Pick one existing directory (desktop only; no browser equivalent).
Directory,
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct PluginConnectionProviderContribution { pub struct PluginConnectionProviderContribution {
pub id: String, pub id: String,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>, pub label: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>, pub icon: Option<String>,
pub database_type: String, pub database_type: String,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>, pub description: Option<String>,
#[serde(default)] #[serde(default)]
pub fields: Vec<PluginFormFieldDefinition>, pub fields: Vec<PluginFormFieldDefinition>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub workbench: Option<String>, pub workbench: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub filesystem_provider: Option<String>, pub filesystem_provider: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capabilities: Vec<PluginConnectionCapability>, pub capabilities: Vec<PluginConnectionCapability>,
@@ -351,17 +581,17 @@ pub enum PluginConnectionCapability {
pub struct PluginConnectionActionContribution { pub struct PluginConnectionActionContribution {
pub id: String, pub id: String,
pub label: String, pub label: String,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>, pub description: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub variant: Option<PluginConnectionActionVariant>, pub variant: Option<PluginConnectionActionVariant>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub when: Option<PluginConnectionActionWhen>, pub when: Option<PluginConnectionActionWhen>,
#[serde(default, skip_serializing_if = "is_false")] #[serde(default, skip_serializing_if = "is_false")]
pub close_on_success: bool, pub close_on_success: bool,
#[serde(default = "default_action_requires_valid_form", skip_serializing_if = "is_true")] #[serde(default = "default_action_requires_valid_form", skip_serializing_if = "is_true")]
pub requires_valid_form: bool, pub requires_valid_form: bool,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_ms: Option<u64>, pub timeout_ms: Option<u64>,
} }
@@ -400,9 +630,9 @@ pub enum PluginConnectionActionWhen {
pub struct PluginWorkbenchContribution { pub struct PluginWorkbenchContribution {
pub id: String, pub id: String,
pub label: String, pub label: String,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>, pub description: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>, pub icon: Option<String>,
} }
@@ -414,9 +644,9 @@ pub struct PluginWorkbenchContribution {
pub struct PluginContextMenuContribution { pub struct PluginContextMenuContribution {
pub id: String, pub id: String,
pub label: String, pub label: String,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>, pub description: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>, pub icon: Option<String>,
/// Menu surface the item belongs to; currently only `connection`. /// Menu surface the item belongs to; currently only `connection`.
#[serde(default)] #[serde(default)]
@@ -430,9 +660,9 @@ pub struct PluginContextMenuContribution {
pub struct PluginResultViewContribution { pub struct PluginResultViewContribution {
pub id: String, pub id: String,
pub label: String, pub label: String,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>, pub description: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>, pub icon: Option<String>,
} }
@@ -442,13 +672,13 @@ pub struct PluginFilesystemProviderContribution {
pub id: String, pub id: String,
pub label: String, pub label: String,
pub schemes: Vec<String>, pub schemes: Vec<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>, pub description: Option<String>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>, pub icon: Option<String>,
#[serde(default)] #[serde(default)]
pub capabilities: Vec<PluginFilesystemCapability>, pub capabilities: Vec<PluginFilesystemCapability>,
#[serde(default)] #[serde(default, skip_serializing_if = "Option::is_none")]
pub root_uri: Option<String>, pub root_uri: Option<String>,
} }
@@ -979,6 +1209,78 @@ fn validate_connection_actions(
} }
} }
/// A picker action only makes sense on a field the user can type into, and the
/// field that receives uploaded content must be a declared sibling.
fn validate_form_field_picker(
field: &PluginFormFieldDefinition,
fields: &[PluginFormFieldDefinition],
contribution_index: usize,
field_index: usize,
errors: &mut Vec<String>,
) {
let Some(picker) = &field.picker else {
return;
};
let location = format!("Contribution at index {contribution_index} field {field_index} picker");
if !matches!(
field.field_type,
PluginFormFieldType::Text | PluginFormFieldType::Password | PluginFormFieldType::Textarea
) {
errors.push(format!("{location} is only supported on text, password, or textarea fields"));
}
if picker.accept.len() > MAX_PLUGIN_PICKER_FILTERS {
errors.push(format!("{location} declares more than {MAX_PLUGIN_PICKER_FILTERS} filters"));
}
for filter in &picker.accept {
if !valid_picker_filter(filter) {
errors.push(format!("{location} filter '{filter}' must look like '.pem' or 'text/plain'"));
}
}
if picker.kind == PluginFormFieldPickerKind::Directory && picker.content_field.is_some() {
errors.push(format!("{location} cannot upload a directory into a content field"));
}
let Some(content_key) = &picker.content_field else {
return;
};
match fields.iter().find(|candidate| candidate.key == *content_key) {
None => errors.push(format!("{location} content_field references unknown field '{content_key}'")),
Some(content) => {
if content.key == field.key {
errors.push(format!("{location} content_field cannot be the declaring field"));
}
if !matches!(
content.field_type,
PluginFormFieldType::Text | PluginFormFieldType::Password | PluginFormFieldType::Textarea
) {
errors.push(format!("{location} content_field '{content_key}' must be a text or textarea field"));
}
}
}
}
/// Accept entries are file extensions (`.pem`) or MIME types (`text/plain`), so
/// the browser `<input accept>` attribute and the native dialog filters can use
/// them directly. Anything else is rejected instead of silently ignored.
fn valid_picker_filter(filter: &str) -> bool {
if let Some(extension) = filter.strip_prefix('.') {
return !extension.is_empty()
&& extension.len() <= 16
&& extension.chars().all(|character| character.is_ascii_alphanumeric());
}
let mut parts = filter.split('/');
let (Some(kind), Some(subtype), None) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
let valid_part = |part: &str| {
!part.is_empty()
&& part.len() <= 64
&& part
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '+' | '-' | '.' | '_' | '*'))
};
valid_part(kind) && valid_part(subtype)
}
fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index: usize, errors: &mut Vec<String>) { fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index: usize, errors: &mut Vec<String>) {
let mut seen_keys = HashSet::new(); let mut seen_keys = HashSet::new();
let field_keys = fields.iter().map(|field| field.key.as_str()).collect::<HashSet<_>>(); let field_keys = fields.iter().map(|field| field.key.as_str()).collect::<HashSet<_>>();
@@ -993,6 +1295,7 @@ fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index
&format!("Contribution at index {contribution_index} field {field_index} label"), &format!("Contribution at index {contribution_index} field {field_index} label"),
errors, errors,
); );
validate_form_field_picker(field, fields, contribution_index, field_index, errors);
for (name, condition) in for (name, condition) in
[("visible_when", field.visible_when.as_ref()), ("required_when", field.required_when.as_ref())] [("visible_when", field.visible_when.as_ref()), ("required_when", field.required_when.as_ref())]
@@ -1000,16 +1303,15 @@ fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index
let Some(condition) = condition else { let Some(condition) = condition else {
continue; continue;
}; };
if condition.one_of.is_empty() { let location = format!("Contribution at index {contribution_index} field {field_index} {name}");
errors.push(format!( errors.extend(condition.validate().into_iter().map(|error| format!("{location} {error}")));
"Contribution at index {contribution_index} field {field_index} {name} one_of cannot be empty" for referenced in condition.referenced_fields() {
)); // Self-references are tolerated for backward compatibility (a
} // single-field manifest could always point a field at itself);
if !field_keys.contains(condition.field.as_str()) { // unknown targets were already rejected by the v1 contract.
errors.push(format!( if !field_keys.contains(referenced) {
"Contribution at index {contribution_index} field {field_index} {name} references unknown field '{}'", errors.push(format!("{location} references unknown field '{referenced}'"));
condition.field }
));
} }
} }
@@ -1713,6 +2015,55 @@ mod tests {
assert!(errors.iter().any(|error| error.contains("timeout_ms must be between"))); assert!(errors.iter().any(|error| error.contains("timeout_ms must be between")));
} }
/// The manifest the frontend receives is a re-serialization of the parsed
/// manifest, so an absent optional must stay absent. Emitting `null`
/// instead made the connection form treat "no default" as a real `null`
/// value: untouched fields showed a literal "null" and a save persisted the
/// four-character string "null" into `connection_secrets`.
#[test]
fn serialized_form_fields_omit_absent_optionals() {
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
"manifest_version": 1,
"id": "io.dbx.nulls",
"name": "Nulls",
"version": "1.0.0",
"publisher": "example",
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
"contributions": [{
"type": "connection-provider",
"id": "nulls.connection",
"label": "Nulls",
"database_type": "nulls",
"fields": [
{ "key": "sudo_password", "label": "Sudo password", "type": "password", "binding": "secret" },
{ "key": "with_default", "label": "With default", "type": "text", "default": "root" },
{ "key": "explicit_null", "label": "Explicit null", "type": "text", "default": null },
{ "key": "mode", "label": "Mode", "type": "text" }
]
}]
}))
.unwrap();
let serialized = serde_json::to_value(&manifest).unwrap();
let fields = serialized["contributions"][0]["fields"].as_array().unwrap();
// A field that declares nothing optional carries none of those keys, so
// the frontend can never mistake "absent" for a `null` value.
for key in ["default", "binding", "description", "placeholder"] {
assert!(fields[3].get(key).is_none(), "bare field must not serialize `{key}`: {}", fields[3]);
}
// Declared values survive the round trip; an explicit `null` default
// means "no default" and normalizes to an absent key rather than a
// value the form would try to render.
assert_eq!(fields[0]["binding"], "secret");
assert_eq!(fields[1]["default"], "root");
assert!(fields[2].get("default").is_none());
// Provider-level optionals follow the same rule.
assert!(serialized["contributions"][0].get("icon").is_none());
assert!(serialized["contributions"][0].get("workbench").is_none());
assert!(serialized["contributions"][0].get("filesystem_provider").is_none());
}
#[test] #[test]
fn parses_form_field_conditions() { fn parses_form_field_conditions() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@@ -1754,9 +2105,21 @@ mod tests {
assert!(compatibility.compatible, "{:?}", compatibility.errors); assert!(compatibility.compatible, "{:?}", compatibility.errors);
let visible_when = provider.fields[1].visible_when.as_ref().unwrap(); let visible_when = provider.fields[1].visible_when.as_ref().unwrap();
assert_eq!(visible_when.field, "mode"); let super::PluginFieldCondition::Field(clause) = visible_when else {
assert_eq!(visible_when.one_of, vec!["custom".to_string()]); panic!("legacy single-field condition must deserialize into the field clause");
assert_eq!(provider.fields[1].required_when.as_ref().unwrap().one_of, vec!["custom".to_string()]); };
assert_eq!(clause.field, "mode");
assert_eq!(clause.one_of, vec![super::PluginFieldConditionLiteral::String("custom".to_string())]);
// Serializing a legacy clause keeps the exact v1 manifest shape.
assert_eq!(
serde_json::to_value(visible_when).unwrap(),
serde_json::json!({ "field": "mode", "one_of": ["custom"] })
);
let required = provider.fields[1].required_when.as_ref().unwrap();
let super::PluginFieldCondition::Field(required_clause) = required else {
panic!("legacy single-field condition must deserialize into the field clause");
};
assert_eq!(required_clause.one_of, vec![super::PluginFieldConditionLiteral::String("custom".to_string())]);
} }
#[test] #[test]
@@ -1815,10 +2178,222 @@ mod tests {
let compatibility = manifest.compatibility(dir.path(), "0.5.68"); let compatibility = manifest.compatibility(dir.path(), "0.5.68");
assert!(!compatibility.compatible); assert!(!compatibility.compatible);
assert!(compatibility.errors.iter().any(|error| error.contains("visible_when one_of cannot be empty"))); assert!(compatibility
.errors
.iter()
.any(|error| error.contains("visible_when condition one_of cannot be empty")));
assert!(compatibility assert!(compatibility
.errors .errors
.iter() .iter()
.any(|error| error.contains("visible_when references unknown field 'missing'"))); .any(|error| error.contains("visible_when references unknown field 'missing'")));
} }
#[test]
fn parses_composite_form_field_conditions() {
let dir = tempfile::tempdir().unwrap();
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
"manifest_version": 1,
"id": "io.dbx.conditions",
"name": "Conditions",
"version": "1.0.0",
"publisher": "example",
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
"contributions": [{
"type": "connection-provider",
"id": "conditions.connection",
"database_type": "conditions",
"fields": [
{ "key": "authentication", "label": "Auth", "type": "text" },
{ "key": "read_only", "label": "Read only", "type": "boolean" },
{ "key": "sudo_source", "label": "Sudo source", "type": "text" },
{
"key": "sudo_command",
"label": "Sudo command",
"type": "text",
"visible_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "field": "read_only", "one_of": [false] }
]
},
"required_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "not": { "field": "read_only", "one_of": [true] } }
]
}
}
]
}]
}))
.unwrap();
let compatibility = manifest.compatibility(dir.path(), "0.6.14");
assert!(compatibility.compatible, "{:?}", compatibility.errors);
let provider = manifest.connection_provider("conditions.connection").unwrap().unwrap();
let visible_when = provider.fields[3].visible_when.as_ref().unwrap();
assert_eq!(visible_when.referenced_fields(), vec!["sudo_source", "read_only"]);
assert_eq!(visible_when.node_count(), 3);
assert!(matches!(visible_when, super::PluginFieldCondition::AllOf { .. }));
}
#[test]
fn rejects_malformed_composite_form_field_conditions() {
let dir = tempfile::tempdir().unwrap();
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
"manifest_version": 1,
"id": "io.dbx.conditions",
"name": "Conditions",
"version": "1.0.0",
"publisher": "example",
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
"contributions": [{
"type": "connection-provider",
"id": "conditions.connection",
"database_type": "conditions",
"fields": [
{ "key": "mode", "label": "Mode", "type": "text" },
{
"key": "empty_all_of",
"label": "Empty",
"type": "text",
"visible_when": { "all_of": [] }
},
{
"key": "unknown_nested",
"label": "Unknown",
"type": "text",
"required_when": { "any_of": [{ "field": "ghost", "one_of": ["x"] }] }
}
]
}]
}))
.unwrap();
let compatibility = manifest.compatibility(dir.path(), "0.6.14");
assert!(!compatibility.compatible);
assert!(compatibility.errors.iter().any(|error| error.contains("condition all_of cannot be empty")));
assert!(compatibility
.errors
.iter()
.any(|error| error.contains("required_when references unknown field 'ghost'")));
}
/// The SSH plugin asks the host for a key file: desktop hosts store the
/// client path, browser hosts upload the content into a paired field.
#[test]
fn parses_and_validates_file_pickers() {
let dir = tempfile::tempdir().unwrap();
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
"manifest_version": 1,
"id": "io.dbx.ssh",
"name": "SSH",
"version": "1.0.0",
"publisher": "example",
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
"contributions": [{
"type": "connection-provider",
"id": "ssh.connection",
"label": "SSH",
"database_type": "ssh",
"fields": [
{
"key": "private_key_path",
"label": "Private key path",
"type": "text",
"binding": "config",
"picker": {
"kind": "file",
"accept": [".pem", ".key", "text/plain"],
"content_field": "private_key"
}
},
{ "key": "private_key", "label": "Private key", "type": "textarea", "binding": "secret" }
]
}]
}))
.unwrap();
let compatibility = manifest.compatibility(dir.path(), "0.6.15");
assert!(compatibility.compatible, "{:?}", compatibility.errors);
let provider = manifest.connection_provider("ssh.connection").unwrap().unwrap();
let picker = provider.fields[0].picker.as_ref().unwrap();
assert_eq!(picker.kind, super::PluginFormFieldPickerKind::File);
assert_eq!(picker.accept, vec![".pem", ".key", "text/plain"]);
assert_eq!(picker.content_field.as_deref(), Some("private_key"));
// The picker round-trips through the manifest the UI receives.
let serialized = serde_json::to_value(&manifest).unwrap();
assert_eq!(serialized["contributions"][0]["fields"][0]["picker"]["kind"], "file");
}
#[test]
fn rejects_invalid_file_pickers() {
let dir = tempfile::tempdir().unwrap();
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
"manifest_version": 1,
"id": "io.dbx.ssh",
"name": "SSH",
"version": "1.0.0",
"publisher": "example",
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
"contributions": [{
"type": "connection-provider",
"id": "ssh.connection",
"label": "SSH",
"database_type": "ssh",
"fields": [
{ "key": "port", "label": "Port", "type": "number", "picker": { "kind": "file" } },
{
"key": "private_key_path",
"label": "Private key path",
"type": "text",
"picker": {
"kind": "file",
"accept": ["pem", ".", "text/"],
"content_field": "missing"
}
},
{
"key": "self_reference",
"label": "Self",
"type": "text",
"picker": { "kind": "file", "content_field": "self_reference" }
},
{
"key": "folder",
"label": "Folder",
"type": "text",
"picker": { "kind": "directory", "content_field": "private_key_path" }
},
{ "key": "private_key", "label": "Private key", "type": "textarea", "binding": "secret" }
]
}]
}))
.unwrap();
let compatibility = manifest.compatibility(dir.path(), "0.6.15");
assert!(!compatibility.compatible);
let errors = compatibility.errors.join("\n");
assert!(errors.contains("picker is only supported on text, password, or textarea fields"), "{errors}");
assert!(errors.contains("filter 'pem' must look like '.pem' or 'text/plain'"), "{errors}");
assert!(errors.contains("filter 'text/' must look like '.pem' or 'text/plain'"), "{errors}");
assert!(errors.contains("content_field references unknown field 'missing'"), "{errors}");
assert!(errors.contains("content_field cannot be the declaring field"), "{errors}");
assert!(errors.contains("cannot upload a directory into a content field"), "{errors}");
}
#[test]
fn rejects_unknown_keys_and_mixed_condition_shapes() {
// A clause may not smuggle composite keys, and a composite node may not
// smuggle `field`/`one_of`; both must fail to deserialize.
assert!(serde_json::from_value::<super::PluginFieldCondition>(serde_json::json!({
"field": "mode",
"one_of": ["custom"],
"all_of": [{ "field": "mode", "one_of": ["custom"] }]
}))
.is_err());
assert!(serde_json::from_value::<super::PluginFieldCondition>(serde_json::json!({})).is_err());
assert!(serde_json::from_value::<super::PluginFieldCondition>(serde_json::json!({ "not": 1 })).is_err());
}
} }
File diff suppressed because it is too large. Load diff
+52
View File
@@ -6730,6 +6730,58 @@ mod tests {
assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret")); assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret"));
} }
#[tokio::test]
async fn load_connections_preserves_opaque_null_plugin_secrets() {
let path = temp_db_path("plugin-null-secret");
let storage = Storage::open(&path).await.unwrap();
let mut config = mq_connection("plugin-connection", "");
config.name = "SSH plugin".to_string();
config.db_type = DatabaseType::Plugin;
config.driver_profile = Some("plugin".to_string());
config.plugin_id = Some("io.dbx.ssh".to_string());
config.plugin_connection_provider = Some("io.dbx.ssh.connection".to_string());
config.plugin_connection_type = Some("ssh".to_string());
config.connection_secrets.insert("sudo_password".to_string(), "null".to_string());
config.connection_secrets.insert("totp_secret".to_string(), "".to_string());
config.connection_secrets.insert("private_key_passphrase".to_string(), "real-passphrase".to_string());
storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
storage
.set_secret("plugin-connection", &plugin_connection_secret_key("totp_secret").unwrap(), "null")
.await
.unwrap();
let loaded = storage.load_connections().await.unwrap();
let secrets = &loaded[0].connection_secrets;
assert_eq!(secrets.len(), 3);
assert_eq!(secrets.get("sudo_password").map(String::as_str), Some("null"));
assert_eq!(secrets.get("totp_secret").map(String::as_str), Some("null"));
assert_eq!(secrets.get("private_key_passphrase").map(String::as_str), Some("real-passphrase"));
assert_eq!(
storage
.get_secret("plugin-connection", &plugin_connection_secret_key("sudo_password").unwrap())
.await
.unwrap()
.as_deref(),
Some("null")
);
assert_eq!(
storage
.get_secret("plugin-connection", &plugin_connection_secret_key("totp_secret").unwrap())
.await
.unwrap()
.as_deref(),
Some("null")
);
assert_eq!(storage.load_connections().await.unwrap()[0].connection_secrets, *secrets);
storage.save_connections(&loaded).await.unwrap();
assert_eq!(storage.load_connections().await.unwrap()[0].connection_secrets, *secrets);
drop(storage);
let reopened = Storage::open(&path).await.unwrap();
assert_eq!(reopened.load_connections().await.unwrap()[0].connection_secrets, *secrets);
let _ = std::fs::remove_file(path);
}
#[tokio::test] #[tokio::test]
async fn metadata_save_scrubs_mq_auth_token_and_preserves_existing_secret() { async fn metadata_save_scrubs_mq_auth_token_and_preserves_existing_secret() {
let path = temp_db_path("mq-token-metadata"); let path = temp_db_path("mq-token-metadata");
+1 -3
View File
@@ -132,9 +132,7 @@ mod tests {
port: 22, port: 22,
key_type: Some("ssh-ed25519".to_string()), key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()), fingerprint: Some("SHA256:test".to_string()),
previous_fingerprint: None, ..Default::default()
prompt: None,
echo: false,
} }
} }
@@ -152,6 +152,51 @@ Manifest 中的路径相对于包根目录,不能以 `/` 开头、不能包含
每个字段必须声明 `key`、`label`、`type`,可选 `description`、`placeholder`、`required`、`default`、`options` 和 `binding`;默认值必须符合字段类型。省略 binding 的 `password` 字段默认按 `secret` 处理。`database_type` 是插件自定义类型标识,不会给 DBX 内置数据库枚举添加成员。 每个字段必须声明 `key`、`label`、`type`,可选 `description`、`placeholder`、`required`、`default`、`options` 和 `binding`;默认值必须符合字段类型。省略 binding 的 `password` 字段默认按 `secret` 处理。`database_type` 是插件自定义类型标识,不会给 DBX 内置数据库枚举添加成员。
字段还支持条件显隐/条件必填。`visible_when` 与 `required_when` 接受单条子句 `{ "field": "mode", "one_of": ["custom"] }`(引用字段取到列表中的值时命中,按字符串比较,因此 `[false]` 与 `["false"]` 都能匹配布尔 `false`),并用 `all_of` / `any_of` / `not` 组合:
```json
{
"key": "sudo_command",
"label": "Sudo command",
"type": "text",
"visible_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "field": "read_only", "one_of": [false] }
]
}
}
```
条件会级联:子句引用的字段自身处于隐藏状态时该子句不参与判定,因此隐藏容器的默认值不会把孙级字段点亮;未填写或空值永不命中;组合树最多 8 层、64 个节点。DBX 在对话框与保存/测试/连接校验中使用同一套求值,不会出现「表单放行、宿主拒绝」的分歧。
`text`、`password`、`textarea` 字段可以用 `picker` 声明**本机文件选择**(例如 SSH 私钥、keystore):
```json
{
"key": "private_key_path",
"label": "Private key path",
"type": "text",
"binding": "config",
"picker": { "kind": "file", "accept": [".pem", ".key"], "content_field": "private_key" }
}
```
桌面端打开系统文件选择器,把选中的**绝对路径**写回该字段(插件后端同机运行,可自行读取文件);网页端拿不到客户端路径,同一操作变成**上传**:DBX 读取文件内容写入声明的 `content_field` 兄弟字段,并清空路径字段。两者互相清除——选了路径就丢弃已上传内容,上传内容就清空路径,避免同时存在两份互相矛盾的来源。`kind` 还支持 `directory`(仅桌面端),`accept` 最多 16 条扩展名或 MIME 过滤,上传上限 1 MiB。
插件在连接过程中需要用户输入时(堡垒机登录期 keyboard-interactive 验证码、主机密钥确认、账号选择等),可以调用 Host API 1.1 新增的 `host/requestUserInput`,通过 DBX 同一个阻塞对话框拿到用户输入,`连接测试` 与真实连接走同一条通道:
```json
{
"jsonrpc": "2.0",
"id": "prompt-1",
"method": "host/requestUserInput",
"params": { "prompt": "Verification code (6 digits)", "title": "JumpServer login", "echo": false, "timeoutSecs": 300 }
}
```
返回值为 `{ "action": "submit", "value": "123456" }`、`{ "action": "cancel" }` 或 `{ "action": "timeout" }`;只有 `submit` 带值,其余必须按「没有答案」处理并失败关闭。插件发起的请求使用字符串 id,DBX 自己的请求与响应继续使用数字 id;提示期间 DBX 会暂停等待该回答的请求超时计时,用户输入验证码不会被误判成连接超时。错误码 `-32001` 表示没有可用的用户界面(headless/MCP),`-32602` 参数非法,`-32601` 宿主不支持该方法,三种情况都要优雅降级。调用前请确认 `plugin/initialize` 通告的 `hostApiVersion` 为 `1.1.0`(或 `host.features` 含 `host.requestUserInput`);Rust SDK 对应 `dbx_plugin_sdk::host_client()` 与 `HostClient::supports("host/requestUserInput")`、`HostClient::request_user_input(&UserInputPrompt::secret("Verification code"))`。
连接生命周期使用固定的 `connection/test`、`connection/connect`、`connection/disconnect`,自定义表单动作使用 `connection/action`,参数包含 `provider`、`connection`、`runtime`;动作额外包含 `action: { id }`。后端使用 `connection.id` 保存会话,并使用 `runtime.host`/`runtime.port` 连接经过 DBX 隧道或代理转换后的端点。仅在后端生命周期请求中接收补齐 Secret 的连接;前端通过 `connectionId` 使用已经建立的会话。 连接生命周期使用固定的 `connection/test`、`connection/connect`、`connection/disconnect`,自定义表单动作使用 `connection/action`,参数包含 `provider`、`connection`、`runtime`;动作额外包含 `action: { id }`。后端使用 `connection.id` 保存会话,并使用 `runtime.host`/`runtime.port` 连接经过 DBX 隧道或代理转换后的端点。仅在后端生命周期请求中接收补齐 Secret 的连接;前端通过 `connectionId` 使用已经建立的会话。
动作的 `when` 可为 `always`、`create`、`edit`;`variant` 可为 `default`、`outline`、`secondary`、`destructive`、`ghost`;`timeout_ms` 为 1–120000。`requires_valid_form` 决定是否要求完整表单,`close_on_success` 决定成功后是否关闭。返回 `{ "success": true, "message": "...", "fieldValues": { "port": 443 } }` 可以更新已声明的字段;返回 `success: false` 表示失败。 动作的 `when` 可为 `always`、`create`、`edit`;`variant` 可为 `default`、`outline`、`secondary`、`destructive`、`ghost`;`timeout_ms` 为 1–120000。`requires_valid_form` 决定是否要求完整表单,`close_on_success` 决定成功后是否关闭。返回 `{ "success": true, "message": "...", "fieldValues": { "port": 443 } }` 可以更新已声明的字段;返回 `success: false` 表示失败。
+45
View File
@@ -152,6 +152,51 @@ Field types are `text`, `password`, `number`, `boolean`, `select`, `radio`, and
Fields require `key`, `label`, and `type`; optional fields are `description`, `placeholder`, `required`, `default`, `options`, and `binding`. Defaults must match the field type. A password field without an explicit binding defaults to `secret`. `database_type` is a plugin-defined identifier, not an extension to DBX's built-in database enum. Fields require `key`, `label`, and `type`; optional fields are `description`, `placeholder`, `required`, `default`, `options`, and `binding`. Defaults must match the field type. A password field without an explicit binding defaults to `secret`. `database_type` is a plugin-defined identifier, not an extension to DBX's built-in database enum.
Fields can also be conditional. `visible_when` and `required_when` take a clause `{ "field": "mode", "one_of": ["custom"] }` — matching when the sibling holds one of the listed values, compared as strings so `[false]` and `["false"]` both match a boolean `false` — and compose clauses with `all_of`, `any_of`, and `not`:
```json
{
"key": "sudo_command",
"label": "Sudo command",
"type": "text",
"visible_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "field": "read_only", "one_of": [false] }
]
}
}
```
Conditions cascade: while the field a clause reads is hidden, the clause does not count, so a hidden option's stored default never surfaces a grandchild field. DBX evaluates the same expression for the dialog and for save/test/connect validation, an unset or empty value never matches, and composite trees are capped at 8 levels and 64 nodes.
Text, password, and textarea fields can offer a **local file action** — for example an SSH private key or a keystore — with `picker`:
```json
{
"key": "private_key_path",
"label": "Private key path",
"type": "text",
"binding": "config",
"picker": { "kind": "file", "accept": [".pem", ".key"], "content_field": "private_key" }
}
```
The desktop app opens a native picker and stores the chosen absolute path, which the plugin backend (same machine) can read. The browser build cannot resolve a client path, so the action becomes an upload: DBX reads the file and stores its content in the declared `content_field` sibling, and clears the path field — picking a path clears the uploaded content and vice versa, so the two alternatives never disagree. `kind` also accepts `directory` (desktop only), `accept` takes up to 16 extension or MIME filters, and uploads are capped at 1 MiB.
When a plugin needs the user mid-flight — a bastion's keyboard-interactive MFA code, a host-key confirmation, a choice of account — it can call the Host API method `host/requestUserInput` (Host API 1.1) and receive the typed answer. The request goes through the same blocking dialog DBX uses for its own prompts, including during `connection/test` and `connection/connect`:
```json
{
"jsonrpc": "2.0",
"id": "prompt-1",
"method": "host/requestUserInput",
"params": { "prompt": "Verification code (6 digits)", "title": "JumpServer login", "echo": false, "timeoutSecs": 300 }
}
```
The result is `{ "action": "submit", "value": "123456" }`, `{ "action": "cancel" }`, or `{ "action": "timeout" }`; only `submit` carries a value and the plugin must fail closed on the other two. Plugin-initiated requests use string ids while DBX keeps numeric ids, and DBX pauses the request deadline of the call waiting on a prompt, so a user typing a code is not mistaken for a connect timeout. An error code of `-32001` means no user interface is attached (headless/MCP), `-32602` invalid params, `-32601` unsupported method — degrade gracefully in every case. Gate the call on `plugin/initialize` advertising `hostApiVersion` `1.1.0` (or `host.requestUserInput` in `host.features`). With the Rust SDK that is `HostClient::supports("host/requestUserInput")` plus `HostClient::request_user_input(&UserInputPrompt::secret("Verification code"))` from `dbx_plugin_sdk::host_client()`.
The fixed lifecycle methods are `connection/test`, `connection/connect`, and `connection/disconnect`; custom form actions use `connection/action`. Parameters include `provider`, `connection`, and `runtime`, plus `action: { id }` for actions. Keep sessions keyed by `connection.id` and connect to `runtime.host`/`runtime.port`, which include DBX tunnel/proxy resolution. Hydrated secrets are provided only to backend lifecycle requests; the frontend uses `connectionId` to access an established session. The fixed lifecycle methods are `connection/test`, `connection/connect`, and `connection/disconnect`; custom form actions use `connection/action`. Parameters include `provider`, `connection`, and `runtime`, plus `action: { id }` for actions. Keep sessions keyed by `connection.id` and connect to `runtime.host`/`runtime.port`, which include DBX tunnel/proxy resolution. Hydrated secrets are provided only to backend lifecycle requests; the frontend uses `connectionId` to access an established session.
Action `when` accepts `always`, `create`, or `edit`; `variant` accepts `default`, `outline`, `secondary`, `destructive`, or `ghost`; `timeout_ms` is 1–120000. `requires_valid_form` requires a complete form and `close_on_success` closes the dialog on success. Return `{ "success": true, "message": "...", "fieldValues": { "port": 443 } }` to update declared fields; `success: false` is a failure. Action `when` accepts `always`, `create`, or `edit`; `variant` accepts `default`, `outline`, `secondary`, `destructive`, or `ghost`; `timeout_ms` is 1–120000. `requires_valid_form` requires a complete form and `close_on_success` closes the dialog on success. Return `{ "success": true, "message": "...", "fieldValues": { "port": 443 } }` to update declared fields; `success: false` is a failure.
+82
View File
@@ -222,6 +222,58 @@ Field bindings:
Password fields default to `secret` when `binding` is omitted. DBX validates required values and value types before calling the plugin. The plugin receives the hydrated connection only in its backend lifecycle request; the workbench UI receives a connection ID and non-secret navigation context. Password fields default to `secret` when `binding` is omitted. DBX validates required values and value types before calling the plugin. The plugin receives the hydrated connection only in its backend lifecycle request; the workbench UI receives a connection ID and non-secret navigation context.
Absent optional fields stay absent: when DBX hands the manifest to its own UI it omits `description`, `placeholder`, `default`, and `binding` for fields that do not declare them, and `"default": null` means "no default" exactly like omitting the key. Treat a missing value as unset — never as an empty string, and never as the literal text `null`, which is not a storable plugin value.
#### Local file fields
A `text`, `password`, or `textarea` field may declare `picker` when the user should choose a local file (private keys, keystores, credential files):
```json
{
"key": "private_key_path",
"label": "Private key path",
"type": "text",
"binding": "config",
"picker": { "kind": "file", "accept": [".pem", ".key", ".ppk"], "content_field": "private_key" }
}
```
- **Desktop hosts** open a native picker and store the chosen **absolute path** in the declaring field. The plugin backend runs on the same machine, so it can read the file itself.
- **Browser hosts** cannot resolve a path on the user's machine, so the same action becomes an **upload**: DBX reads the selected file and stores its **content** in `content_field` (which must be a declared `text` / `password` / `textarea` sibling), and clears the declaring field. A picker without `content_field` is therefore desktop-only and stays hidden in the browser.
- Switching source clears the other one: choosing a path removes the uploaded content and vice versa. This matters for fields that are alternatives — a plugin that prefers `private_key` content over `private_key_path` must not keep serving a stale upload after the user re-picked a path.
- `kind` is `file` (default use case) or `directory` (desktop-only: a browser cannot hand a folder to the plugin). `accept` lists up to 16 filters as extensions (`.pem`) or MIME types (`text/plain`) and is passed to the native dialog and the browser file input unchanged. Uploads are capped at 1 MiB.
`picker` is additive; hosts older than the release that ships it reject the manifest, so keep `engines.dbx` at or above that release when the form relies on it.
#### Conditional fields
A field may declare `visible_when` and `required_when`. A leaf clause matches when the referenced sibling field holds a non-empty value listed in `one_of`; listed values may be strings, numbers, or booleans and are compared by canonical string form, so `false` and `"false"` both match a boolean `false`. Clauses compose with `all_of`, `any_of`, and `not`:
```json
{
"key": "sudo_command",
"label": "Sudo command",
"type": "text",
"visible_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "field": "read_only", "one_of": [false] }
]
},
"required_when": {
"all_of": [
{ "field": "sudo_source", "one_of": ["custom"] },
{ "not": { "field": "read_only", "one_of": [true] } }
]
}
}
```
- `all_of` / `any_of` must contain at least one nested condition, nesting is limited to 8 levels and 64 nodes, and every referenced field must be a sibling declared by the same provider.
- Conditions cascade: while the field a clause reads is itself hidden, the clause does not count. A hidden container's stored default therefore cannot surface a grandchild field, and a hidden operand of `not` keeps the field dormant instead of lighting it up.
- DBX evaluates the same conditions for the dialog and for save/test/connect validation, so a manifest can never produce a form DBX itself rejects.
- Composite conditions were added after the single-clause contract; keep `engines.dbx` at or above the DBX release that ships them if the form relies on them.
Lifecycle methods receive: Lifecycle methods receive:
```json ```json
@@ -385,6 +437,36 @@ Every entry has `name`, canonical `uri`, `kind` (`file`, `directory`, `symlink`,
Mutation methods return `{ success, message?, entry? }` and are rejected unless the provider declares the matching capability. Inline read/write payloads are capped at 4 MiB. The built-in file manager currently owns directory navigation, pagination, and bounded file preview. Large upload/download and PTY/SFTP streams use `stdio-framed` binary channels with plugin-defined transfer methods, chunk acknowledgements, cancellation, and progress events; they must not be encoded as one large JSON value. Mutation methods return `{ success, message?, entry? }` and are rejected unless the provider declares the matching capability. Inline read/write payloads are capped at 4 MiB. The built-in file manager currently owns directory navigation, pagination, and bounded file preview. Large upload/download and PTY/SFTP streams use `stdio-framed` binary channels with plugin-defined transfer methods, chunk acknowledgements, cancellation, and progress events; they must not be encoded as one large JSON value.
### Host API methods a plugin may call
Plugins normally answer requests, but Host API 1.1 adds one method a plugin backend may call back into DBX. Plugin-initiated requests use **string** ids (`"prompt-1"`), while DBX-owned requests and their responses keep numeric ids, so one stream carries both directions and older hosts that only understand numeric ids ignore the new frames instead of failing.
- `host/requestUserInput` asks the user a question through the DBX UI and returns the answer. It is the channel for anything the host cannot answer on the user's behalf: a bastion's keyboard-interactive MFA code, a one-time approval, a host-key confirmation, or a choice between accounts.
```json
{
"jsonrpc": "2.0",
"id": "prompt-1",
"method": "host/requestUserInput",
"params": {
"prompt": "Verification code (6 digits)",
"title": "JumpServer login",
"echo": false,
"default": "000000",
"options": [{ "value": "jinpy", "label": "jinpy (admin)" }],
"timeoutSecs": 300
}
}
```
- `prompt` is required (≤2000 characters). `title` (≤200), `default` (≤1000), and `options` (≤8 entries, unique values, ≤200 characters each) are optional; `echo` defaults to `false`, so the dialog masks input unless the plugin says otherwise. `timeoutSecs` is clamped to 5-600 and defaults to 300.
- The result is `{ "action": "submit", "value": "123456" }`, `{ "action": "cancel" }`, or `{ "action": "timeout" }`. Only `submit` carries a value; treat `cancel` and `timeout` as "no answer" and fail closed — never fall back to a guess.
- The prompt is delivered through the same blocking dialog the host uses for its own host-key and keyboard-interactive prompts, so it also appears for `connection/test` and `connection/connect`. While a prompt is open DBX pauses the request deadline of the call that is waiting on it, so a user typing a code is never mistaken for a connect timeout.
- Errors come back as JSON-RPC errors: `-32001` means no user interface is attached (headless/MCP runs, or the desktop dialog is not mounted), `-32602` means the params are invalid, `-32601` means the host does not implement the method. A plugin must degrade gracefully on all three instead of blocking forever.
- DBX answers only with what the user typed. It never auto-fills, caches, or logs the value, and it allows at most four open prompts per plugin session.
- Capability gating: `plugin/initialize` advertises `host.hostApiVersion` (`1.1.0` or later) and `host.features` (containing `host.requestUserInput` when available). Only call the method when it is advertised; an older host reports `1.0.0` and drops the frame.
- The Rust SDK (`dbx-plugin-sdk`) wraps this: `dbx_plugin_sdk::host_client()`, `HostClient::supports("host/requestUserInput")`, and `HostClient::request_user_input(&UserInputPrompt::secret("Verification code"))`.
## Backend protocol ## Backend protocol
The backend is a persistent child process with stdin/stdout reserved for the DBX protocol. Diagnostics must go to stderr. The backend is a persistent child process with stdin/stdout reserved for the DBX protocol. Diagnostics must go to stderr.
+80 -1
View File
@@ -104,6 +104,32 @@
"value": { "type": "string" } "value": { "type": "string" }
} }
}, },
"fieldPicker": {
"description": "Local-file action on a text/password/textarea field. Desktop hosts store the chosen absolute path in the declaring field; browser hosts cannot read a client path and upload the file content into 'content_field' instead.",
"type": "object",
"additionalProperties": false,
"required": ["kind"],
"properties": {
"kind": {
"description": "'directory' is desktop-only: a browser cannot hand a folder to the plugin.",
"enum": ["file", "directory"]
},
"accept": {
"description": "Filters offered by the picker: file extensions ('.pem') or MIME types ('text/plain').",
"type": "array",
"maxItems": 16,
"uniqueItems": true,
"items": {
"type": "string",
"pattern": "^(\\.[A-Za-z0-9]{1,16}|[A-Za-z0-9+*._-]{1,64}/[A-Za-z0-9+*._-]{1,64})$"
}
},
"content_field": {
"description": "Declared sibling field that receives the file content on hosts without a client filesystem.",
"$ref": "#/$defs/identifier"
}
}
},
"formFieldLocalization": { "formFieldLocalization": {
"type": "object", "type": "object",
"additionalProperties": false, "additionalProperties": false,
@@ -142,12 +168,64 @@
} }
}, },
"fieldCondition": { "fieldCondition": {
"oneOf": [
{ "$ref": "#/$defs/fieldConditionClause" },
{ "$ref": "#/$defs/fieldConditionAllOf" },
{ "$ref": "#/$defs/fieldConditionAnyOf" },
{ "$ref": "#/$defs/fieldConditionNot" }
]
},
"fieldConditionClause": {
"type": "object", "type": "object",
"additionalProperties": false, "additionalProperties": false,
"required": ["field", "one_of"], "required": ["field", "one_of"],
"properties": { "properties": {
"field": { "$ref": "#/$defs/identifier" }, "field": { "$ref": "#/$defs/identifier" },
"one_of": { "type": "array", "items": { "type": "string" }, "minItems": 1 } "one_of": {
"type": "array",
"minItems": 1,
"items": {
"description": "Compared against the referenced field's value by canonical string form, so `false` and `\"false\"` both match a boolean false.",
"type": ["string", "boolean", "number"]
}
}
}
},
"fieldConditionAllOf": {
"type": "object",
"additionalProperties": false,
"required": ["all_of"],
"properties": {
"all_of": {
"description": "Matches only when every nested condition matches.",
"type": "array",
"minItems": 1,
"items": { "$ref": "#/$defs/fieldCondition" }
}
}
},
"fieldConditionAnyOf": {
"type": "object",
"additionalProperties": false,
"required": ["any_of"],
"properties": {
"any_of": {
"description": "Matches when at least one nested condition matches.",
"type": "array",
"minItems": 1,
"items": { "$ref": "#/$defs/fieldCondition" }
}
}
},
"fieldConditionNot": {
"type": "object",
"additionalProperties": false,
"required": ["not"],
"properties": {
"not": {
"description": "Inverts the nested condition.",
"$ref": "#/$defs/fieldCondition"
}
} }
}, },
"formField": { "formField": {
@@ -164,6 +242,7 @@
"default": { "type": ["string", "number", "boolean", "null"] }, "default": { "type": ["string", "number", "boolean", "null"] },
"options": { "type": "array", "items": { "$ref": "#/$defs/selectOption" } }, "options": { "type": "array", "items": { "$ref": "#/$defs/selectOption" } },
"binding": { "enum": ["config", "secret", "name", "host", "port", "username", "password", "database"] }, "binding": { "enum": ["config", "secret", "name", "host", "port", "username", "password", "database"] },
"picker": { "$ref": "#/$defs/fieldPicker" },
"visible_when": { "$ref": "#/$defs/fieldCondition" }, "visible_when": { "$ref": "#/$defs/fieldCondition" },
"required_when": { "$ref": "#/$defs/fieldCondition" } "required_when": { "$ref": "#/$defs/fieldCondition" }
}, },
+20
View File
@@ -113,6 +113,26 @@ export class Sidecar extends EventEmitter {
const message = packet.message; const message = packet.message;
if (message.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC message"); if (message.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC message");
if (message.id !== undefined) { if (message.id !== undefined) {
// Host API 1.1: a plugin may call back into the host with a *string*
// id. The dev host has no user interface, so answer like a headless
// host does and never leave the plugin waiting for a dialog.
if (typeof message.id === "string" && message.method) {
void this.write(
0,
Buffer.from(
JSON.stringify({
jsonrpc: "2.0",
id: message.id,
error: {
code: -32001,
message: `The DBX development host cannot answer '${message.method}': run the plugin in DBX to reach the user interface`,
},
}),
),
).catch(() => undefined);
this.emit("diagnostic", { level: "info", message: "宿主请求无法在开发宿主中应答", details: { method: protocolName(message.method) } });
return;
}
const waiter = this.pending.get(message.id); const waiter = this.pending.get(message.id);
if (!waiter) return; if (!waiter) return;
this.pending.delete(message.id); this.pending.delete(message.id);
@@ -5,8 +5,16 @@ const send = (message) => {
const bytes = Buffer.from(JSON.stringify({ jsonrpc: "2.0", ...message })); const bytes = Buffer.from(JSON.stringify({ jsonrpc: "2.0", ...message }));
process.stdout.write(jsonl ? Buffer.concat([bytes, Buffer.from("\n")]) : frame(0, bytes)); process.stdout.write(jsonl ? Buffer.concat([bytes, Buffer.from("\n")]) : frame(0, bytes));
}; };
let pendingAsk = null;
const decoder = new (jsonl ? JsonLineDecoder : FrameDecoder)((packet) => { const decoder = new (jsonl ? JsonLineDecoder : FrameDecoder)((packet) => {
if (packet.kind === 1) return process.stdout.write(frame(1, binaryPayload(packet.channel, packet.data))); if (packet.kind === 1) return process.stdout.write(frame(1, binaryPayload(packet.channel, packet.data)));
// Host API 1.1: the dev host answers a plugin-initiated (string-id) request
// with an error, which this sidecar forwards as the `ask-user` result.
if (packet.message.id === "plugin-1") {
const waiting = pendingAsk;
pendingAsk = null;
return send({ id: waiting, result: packet.message });
}
const { id, method, params } = packet.message; const { id, method, params } = packet.message;
if (method === "plugin/initialize") return send({ id, result: { protocolVersion: 1, plugin: { id: "example.echo", version: "1.0.0" } } }); if (method === "plugin/initialize") return send({ id, result: { protocolVersion: 1, plugin: { id: "example.echo", version: "1.0.0" } } });
if (method === "die") return process.exit(1); if (method === "die") return process.exit(1);
@@ -18,6 +26,12 @@ const decoder = new (jsonl ? JsonLineDecoder : FrameDecoder)((packet) => {
if (method === "emit") return send({ method: "example/event", params }); if (method === "emit") return send({ method: "example/event", params });
if (method === "fail") return send({ id, error: { code: -32000, message: "Example failure", data: { category: "example" } } }); if (method === "fail") return send({ id, error: { code: -32000, message: "Example failure", data: { category: "example" } } });
if (method === "slow") return setTimeout(() => send({ id, result: params }), 80); if (method === "slow") return setTimeout(() => send({ id, result: params }), 80);
// Plugins ask the user through string ids. The dev host has no UI, so it must
// answer instead of leaving the plugin waiting.
if (method === "ask-user") {
pendingAsk = id;
return send({ id: "plugin-1", method: "host/requestUserInput", params: { prompt: "Verification code" } });
}
if (id !== undefined) send({ id, result: method.startsWith("connection/") ? { success: true } : params }); if (id !== undefined) send({ id, result: method.startsWith("connection/") ? { success: true } : params });
}); });
process.stdin.on("data", (data) => decoder.push(data)); process.stdin.on("data", (data) => decoder.push(data));
@@ -130,3 +130,16 @@ test("JSONL supports split lines, concurrent RPC, events and rejects binary chan
assert.equal((await event)[0].params.ok, true); assert.equal((await event)[0].params.ok, true);
await assert.rejects(sidecar.sendBinary("bytes", Buffer.from("data")), /framed/); await assert.rejects(sidecar.sendBinary("bytes", Buffer.from("data")), /framed/);
}); });
test("answers plugin-initiated host requests instead of leaving them pending", async (t) => {
// Host API 1.1 lets a plugin ask the user through `host/requestUserInput`
// (string ids). The dev host has no dialog, so it must fail that call fast
// rather than let the plugin block until its own timeout.
const sidecar = new Sidecar(config);
t.after(() => sidecar.stop());
await sidecar.start();
const answer = await sidecar.request("ask-user");
assert.equal(answer.id, "plugin-1");
assert.equal(answer.error.code, -32001);
assert.match(answer.error.message, /host\/requestUserInput/);
});
+477 -12
View File
@@ -1,6 +1,9 @@
use std::collections::HashMap;
use std::io::{self, BufRead, BufReader, Read, Write}; use std::io::{self, BufRead, BufReader, Read, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{mpsc, Arc, Mutex}; use std::sync::{mpsc, Arc, Mutex};
use std::thread; use std::thread;
use std::time::Duration;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
@@ -11,6 +14,12 @@ const MAX_BINARY_BYTES: usize = 64 * 1024 * 1024;
const FRAME_KIND_JSON: u8 = 0; const FRAME_KIND_JSON: u8 = 0;
const FRAME_KIND_BINARY: u8 = 1; const FRAME_KIND_BINARY: u8 = 1;
const DEFAULT_WORK_QUEUE_CAPACITY: usize = 256; const DEFAULT_WORK_QUEUE_CAPACITY: usize = 256;
/// How long a plugin waits for a host answer before giving up. User prompts are
/// bounded by their own `timeoutSecs`, so the default covers one prompt plus a
/// little slack.
const DEFAULT_HOST_REQUEST_TIMEOUT: Duration = Duration::from_secs(330);
/// Host API method that relays a question to the DBX user interface.
pub const HOST_REQUEST_USER_INPUT_METHOD: &str = "host/requestUserInput";
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginTransport { pub enum PluginTransport {
@@ -124,20 +133,305 @@ impl PluginEmitter {
if payload.len() > MAX_JSON_BYTES { if payload.len() > MAX_JSON_BYTES {
return Err(PluginError::new(-32600, "JSON message is too large")); return Err(PluginError::new(-32600, "JSON message is too large"));
} }
let mut output = self.output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?; write_json_frame(&self.output, self.transport, &payload)
match self.transport { }
PluginTransport::JsonLines => { }
output.write_all(&payload).map_err(io_error)?;
output.write_all(b"\n").map_err(io_error)?; fn write_json_frame(
output: &Arc<Mutex<Box<dyn Write + Send>>>,
transport: PluginTransport,
payload: &[u8],
) -> Result<(), PluginError> {
let mut output = output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?;
match transport {
PluginTransport::JsonLines => {
output.write_all(payload).map_err(io_error)?;
output.write_all(b"\n").map_err(io_error)?;
}
PluginTransport::Framed => {
output.write_all(&[FRAME_KIND_JSON]).map_err(io_error)?;
output.write_all(&(payload.len() as u32).to_be_bytes()).map_err(io_error)?;
output.write_all(payload).map_err(io_error)?;
}
}
output.flush().map_err(io_error)
}
/// A question the plugin asks the user through the host, e.g. a bastion's
/// keyboard-interactive MFA challenge or a host-key confirmation. Serializes
/// into the `host/requestUserInput` params of Host API 1.1.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserInputPrompt {
/// Text the user answers, already localized by the plugin.
pub prompt: String,
/// Optional heading shown above `prompt`.
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
/// Show the typed characters (defaults to masked input).
#[serde(default)]
pub echo: bool,
/// Preset answer the user may keep or replace.
#[serde(rename = "default", skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
/// Fixed answers; leave empty for free-form input (at most 8).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub options: Vec<UserInputOption>,
/// How long the user has to answer, in seconds (host clamps to 5..600).
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_secs: Option<u64>,
}
/// One fixed answer of a [`UserInputPrompt`].
#[derive(Debug, Clone, Serialize)]
pub struct UserInputOption {
pub value: String,
pub label: String,
}
impl UserInputPrompt {
/// A masked free-form question (verification codes, passwords, tokens).
pub fn secret(prompt: impl Into<String>) -> Self {
Self { prompt: prompt.into(), title: None, echo: false, default_value: None, options: Vec::new(), timeout_secs: None }
}
/// A question whose answer is visible while typing (account names, paths).
pub fn text(prompt: impl Into<String>) -> Self {
Self { echo: true, ..Self::secret(prompt) }
}
/// A multiple-choice question; the host shows the options as buttons.
pub fn choice(prompt: impl Into<String>, options: Vec<UserInputOption>) -> Self {
Self { options, ..Self::text(prompt) }
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn with_default(mut self, value: impl Into<String>) -> Self {
self.default_value = Some(value.into());
self
}
pub fn with_timeout_secs(mut self, seconds: u64) -> Self {
self.timeout_secs = Some(seconds);
self
}
}
/// The user's answer to a [`UserInputPrompt`].
#[derive(Debug, Clone, Deserialize)]
pub struct UserInputAnswer {
/// `submit`, `cancel`, or `timeout`.
pub action: String,
/// The typed value or chosen option value; only present on `submit`.
#[serde(default)]
pub value: Option<String>,
}
impl UserInputAnswer {
/// The submitted value, or `None` when the user cancelled and the host gave
/// up waiting. Callers must fail closed on `None`.
pub fn submitted(&self) -> Option<&str> {
if self.action == "submit" {
self.value.as_deref()
} else {
None
}
}
pub fn is_cancelled(&self) -> bool {
self.action == "cancel"
}
pub fn is_timeout(&self) -> bool {
self.action == "timeout"
}
}
/// What the host told the plugin about itself at `plugin/initialize`.
#[derive(Debug, Default, Clone)]
struct HostDescription {
api_version: Option<String>,
features: Vec<String>,
}
/// Client for Host API methods the plugin calls back into DBX. Create it by
/// running a [`PluginServer`]; [`host_client`] returns the running instance.
///
/// Calls block the calling thread until the host answers, so call them from a
/// plugin worker (a `connection/connect` handler is already one) rather than
/// from the thread that runs the server loop. While a user prompt is open the
/// host pauses the deadline of the request that is waiting on it, so a human
/// typing an MFA code is never mistaken for a connect timeout.
#[derive(Clone)]
pub struct HostClient {
output: Arc<Mutex<Box<dyn Write + Send>>>,
transport: PluginTransport,
pending: Arc<Mutex<HashMap<String, mpsc::Sender<Result<Value, PluginError>>>>>,
next_request_id: Arc<AtomicU64>,
host: Arc<Mutex<HostDescription>>,
}
impl HostClient {
fn new(output: Arc<Mutex<Box<dyn Write + Send>>>, transport: PluginTransport) -> Self {
Self {
output,
transport,
pending: Arc::new(Mutex::new(HashMap::new())),
next_request_id: Arc::new(AtomicU64::new(1)),
host: Arc::new(Mutex::new(HostDescription::default())),
}
}
/// Host API version DBX reported at `plugin/initialize`.
pub fn host_api_version(&self) -> Option<String> {
self.host.lock().ok().and_then(|host| host.api_version.clone())
}
/// Whether DBX advertised `method` for this session. Gate optional calls on
/// this (or on [`HostClient::host_api_version`]) so a plugin still works
/// against an older host that predates the capability.
pub fn supports(&self, method: &str) -> bool {
self.host.lock().map(|host| host.features.iter().any(|feature| feature == method)).unwrap_or(false)
}
/// Calls one Host API method and waits for the answer.
pub fn request(&self, method: &str, params: Value) -> Result<Value, PluginError> {
self.request_with_timeout(method, params, DEFAULT_HOST_REQUEST_TIMEOUT)
}
pub fn request_with_timeout(
&self,
method: &str,
params: Value,
timeout: Duration,
) -> Result<Value, PluginError> {
validate_protocol_name(method)?;
let id = format!("plugin-{}", self.next_request_id.fetch_add(1, Ordering::Relaxed));
let (sender, receiver) = mpsc::channel();
self.pending
.lock()
.map_err(|_| PluginError::new(-32000, "Host request lock is poisoned"))?
.insert(id.clone(), sender);
let message = serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
});
if let Err(error) = self.write(&message) {
if let Ok(mut pending) = self.pending.lock() {
pending.remove(&id);
} }
PluginTransport::Framed => { return Err(error);
output.write_all(&[FRAME_KIND_JSON]).map_err(io_error)?; }
output.write_all(&(payload.len() as u32).to_be_bytes()).map_err(io_error)?; match receiver.recv_timeout(timeout) {
output.write_all(&payload).map_err(io_error)?; Ok(result) => result,
Err(mpsc::RecvTimeoutError::Timeout) => {
if let Ok(mut pending) = self.pending.lock() {
pending.remove(&id);
}
Err(PluginError::new(-32001, format!("Host did not answer '{method}' in time")))
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
Err(PluginError::new(-32000, format!("Host dropped the answer to '{method}'")))
} }
} }
output.flush().map_err(io_error)
} }
/// Asks the user a question through the DBX UI. Fails when the host has no
/// user interface attached (headless/MCP runs), so the plugin can fall back
/// to its own behaviour instead of waiting for an answer that cannot come.
pub fn request_user_input(&self, prompt: &UserInputPrompt) -> Result<UserInputAnswer, PluginError> {
let params = serde_json::to_value(prompt).map_err(|error| PluginError::new(-32603, error.to_string()))?;
let answer = self.request(HOST_REQUEST_USER_INPUT_METHOD, params)?;
serde_json::from_value(answer)
.map_err(|error| PluginError::new(-32002, format!("Host returned an invalid input answer: {error}")))
}
fn write(&self, value: &Value) -> Result<(), PluginError> {
let payload = serde_json::to_vec(value).map_err(|error| PluginError::new(-32603, error.to_string()))?;
if payload.len() > MAX_JSON_BYTES {
return Err(PluginError::new(-32600, "JSON message is too large"));
}
write_json_frame(&self.output, self.transport, &payload)
}
/// Remembers what the host advertised at `plugin/initialize`.
fn note_host_description(&self, params: &Value) {
let host = params.get("host");
let api_version = host
.and_then(|host| host.get("hostApiVersion"))
.and_then(Value::as_str)
.map(str::to_string);
let features = host
.and_then(|host| host.get("features"))
.and_then(Value::as_array)
.map(|features| features.iter().filter_map(Value::as_str).map(str::to_string).collect())
.unwrap_or_default();
if let Ok(mut description) = self.host.lock() {
*description = HostDescription { api_version, features };
}
}
/// Routes an answer from the host to the waiting caller. Returns `false`
/// when the message is not a response to a plugin-initiated request, so the
/// server loop can keep handling host -> plugin requests.
fn deliver_response(&self, value: &Value) -> bool {
if value.get("method").is_some() {
return false;
}
let Some(id) = value.get("id").and_then(Value::as_str) else {
return false;
};
let Some(sender) = self.pending.lock().ok().and_then(|mut pending| pending.remove(id)) else {
return false;
};
let result = match value.get("error") {
Some(error) => {
let code = error.get("code").and_then(Value::as_i64).unwrap_or(-32603) as i32;
let message = error
.get("message")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| error.to_string());
Err(PluginError::new(code, message))
}
None => match value.get("result") {
Some(result) => Ok(result.clone()),
None => Err(PluginError::new(-32603, "Host answer has neither result nor error")),
},
};
let _ = sender.send(result);
true
}
}
static HOST_CLIENT: Mutex<Option<HostClient>> = Mutex::new(None);
/// The host client of the running plugin server, if any.
pub fn host_client() -> Option<HostClient> {
HOST_CLIENT.lock().ok().and_then(|client| client.clone())
}
/// Installs the process-wide host client. [`PluginServer::serve`] calls this;
/// tests may replace it.
pub fn install_host_client(client: HostClient) {
if let Ok(mut current) = HOST_CLIENT.lock() {
*current = Some(client);
}
}
/// Convenience wrapper for [`HostClient::request_user_input`] on the running
/// server. Fails when the plugin server is not running.
pub fn request_user_input(prompt: &UserInputPrompt) -> Result<UserInputAnswer, PluginError> {
let Some(client) = host_client() else {
return Err(PluginError::new(-32000, "Host API is unavailable: the plugin server is not running"));
};
client.request_user_input(prompt)
} }
pub struct PluginServer<H> { pub struct PluginServer<H> {
@@ -175,7 +469,11 @@ impl<H: PluginHandler> PluginServer<H> {
} }
pub fn serve(self) -> io::Result<()> { pub fn serve(self) -> io::Result<()> {
let emitter = PluginEmitter { output: Arc::new(Mutex::new(Box::new(io::stdout()))), transport: self.transport }; let output: Arc<Mutex<Box<dyn Write + Send>>> = Arc::new(Mutex::new(Box::new(io::stdout())));
let emitter = PluginEmitter { output: output.clone(), transport: self.transport };
// Publish the client before serving so a handler (including the very
// first request) can call back into the host.
install_host_client(HostClient::new(output, self.transport));
let workers = WorkerPool::new(self.worker_threads, self.work_queue_capacity)?; let workers = WorkerPool::new(self.worker_threads, self.work_queue_capacity)?;
match self.transport { match self.transport {
PluginTransport::JsonLines => self.serve_json_lines(BufReader::new(io::stdin()), emitter, &workers), PluginTransport::JsonLines => self.serve_json_lines(BufReader::new(io::stdin()), emitter, &workers),
@@ -235,13 +533,24 @@ impl<H: PluginHandler> PluginServer<H> {
} }
fn dispatch_json(&self, payload: &[u8], emitter: PluginEmitter, workers: &WorkerPool) -> Result<(), String> { fn dispatch_json(&self, payload: &[u8], emitter: PluginEmitter, workers: &WorkerPool) -> Result<(), String> {
let request: ProtocolRequest = serde_json::from_slice(payload).map_err(|error| error.to_string())?; let value: Value = serde_json::from_slice(payload).map_err(|error| error.to_string())?;
// Answers to Host API calls the plugin made (string ids). Everything
// else is a host -> plugin request, whose ids are numeric.
if let Some(host) = host_client() {
if host.deliver_response(&value) {
return Ok(());
}
}
let request: ProtocolRequest = serde_json::from_value(value).map_err(|error| error.to_string())?;
if request.jsonrpc.as_deref() != Some("2.0") { if request.jsonrpc.as_deref() != Some("2.0") {
return Err("request does not declare jsonrpc 2.0".to_string()); return Err("request does not declare jsonrpc 2.0".to_string());
} }
validate_protocol_name(&request.method).map_err(|error| error.message)?; validate_protocol_name(&request.method).map_err(|error| error.message)?;
if request.method == "plugin/initialize" { if request.method == "plugin/initialize" {
let id = request.id.ok_or("plugin/initialize must be a request")?; let id = request.id.ok_or("plugin/initialize must be a request")?;
if let Some(host) = host_client() {
host.note_host_description(&request.params);
}
let supported = request let supported = request
.params .params
.get("host") .get("host")
@@ -425,6 +734,162 @@ mod tests {
let mut reader = Cursor::new(b"12345\n".to_vec()); let mut reader = Cursor::new(b"12345\n".to_vec());
assert!(read_limited_line(&mut reader, 4).unwrap_err().to_string().contains("too large")); assert!(read_limited_line(&mut reader, 4).unwrap_err().to_string().contains("too large"));
} }
use super::{
host_client, install_host_client, request_user_input, HostClient, PluginTransport, UserInputAnswer,
UserInputOption, UserInputPrompt, HOST_CLIENT, HOST_REQUEST_USER_INPUT_METHOD,
};
use std::thread;
use std::sync::{Arc, Mutex};
/// Output sink that records every frame the plugin writes.
#[derive(Clone, Default)]
struct RecordingOutput(Arc<Mutex<Vec<u8>>>);
impl RecordingOutput {
fn lines(&self) -> Vec<Value> {
let bytes = self.0.lock().unwrap().clone();
String::from_utf8(bytes)
.unwrap()
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| serde_json::from_str(line).unwrap())
.collect()
}
}
impl std::io::Write for RecordingOutput {
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buffer);
Ok(buffer.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn recording_client() -> (HostClient, RecordingOutput) {
let output = RecordingOutput::default();
let sink: Arc<Mutex<Box<dyn std::io::Write + Send>>> = Arc::new(Mutex::new(Box::new(output.clone())));
let client = HostClient::new(sink, PluginTransport::JsonLines);
install_host_client(client.clone());
(client, output)
}
#[test]
fn host_client_routes_answers_and_gates_on_advertised_features() {
let (client, output) = recording_client();
assert!(!client.supports(HOST_REQUEST_USER_INPUT_METHOD));
assert_eq!(client.host_api_version(), None);
client.note_host_description(&serde_json::json!({
"host": { "hostApiVersion": "1.1.0", "features": [HOST_REQUEST_USER_INPUT_METHOD] }
}));
assert_eq!(client.host_api_version().as_deref(), Some("1.1.0"));
assert!(client.supports(HOST_REQUEST_USER_INPUT_METHOD));
let prompt = UserInputPrompt::secret("Verification code")
.with_title("Bastion MFA")
.with_default("000000")
.with_timeout_secs(120);
let caller = {
let client = client.clone();
thread::spawn(move || client.request_user_input(&prompt))
};
// Simulate the host answering the outbound request.
let request = loop {
if let Some(request) = output
.lines()
.into_iter()
.find(|line| line["method"] == HOST_REQUEST_USER_INPUT_METHOD)
{
break request;
}
thread::sleep(Duration::from_millis(5));
};
assert_eq!(request["params"]["prompt"], "Verification code");
assert_eq!(request["params"]["title"], "Bastion MFA");
assert_eq!(request["params"]["default"], "000000");
assert_eq!(request["params"]["timeoutSecs"], 120);
assert_eq!(request["params"]["echo"], false);
assert!(request["params"].get("options").is_none());
assert!(client.deliver_response(&serde_json::json!({
"jsonrpc": "2.0",
"id": request["id"],
"result": { "action": "submit", "value": "123456" }
})));
// Host -> plugin requests and unknown answers stay on the server path.
assert!(!client.deliver_response(&serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "connection/test" })));
assert!(!client.deliver_response(&serde_json::json!({ "jsonrpc": "2.0", "id": "plugin-999", "result": {} })));
let answer = caller.join().unwrap().unwrap();
assert_eq!(answer.submitted(), Some("123456"));
assert!(!answer.is_cancelled());
}
#[test]
fn host_client_surfaces_host_errors_cancels_and_timeouts() {
let (client, output) = recording_client();
let error_call = {
let client = client.clone();
thread::spawn(move || client.request_user_input(&UserInputPrompt::text("Account")))
};
let request = loop {
if let Some(request) = output.lines().into_iter().find(|line| line["method"] == HOST_REQUEST_USER_INPUT_METHOD) {
break request;
}
thread::sleep(Duration::from_millis(5));
};
assert!(client.deliver_response(&serde_json::json!({
"jsonrpc": "2.0",
"id": request["id"],
"error": { "code": -32001, "message": "The DBX host cannot ask the user for input right now" }
})));
let error = error_call.join().unwrap().unwrap_err();
assert_eq!(error.code, -32001);
assert!(error.message.contains("cannot ask the user"));
// A cancel carries no value, so callers fail closed.
let cancel = UserInputAnswer { action: "cancel".to_string(), value: None };
assert_eq!(cancel.submitted(), None);
assert!(cancel.is_cancelled());
let timeout = UserInputAnswer { action: "timeout".to_string(), value: Some("ignored".to_string()) };
assert_eq!(timeout.submitted(), None);
assert!(timeout.is_timeout());
let timed_out = client
.request_with_timeout("host/requestUserInput", serde_json::json!({ "prompt": "x" }), Duration::from_millis(30))
.unwrap_err();
assert!(timed_out.message.contains("did not answer"), "{}", timed_out.message);
}
#[test]
fn user_input_prompt_builders_match_the_host_contract() {
assert_eq!(
serde_json::to_value(UserInputPrompt::secret("Code")).unwrap(),
serde_json::json!({ "prompt": "Code", "echo": false })
);
assert_eq!(
serde_json::to_value(UserInputPrompt::choice(
"Account",
vec![UserInputOption { value: "deploy".to_string(), label: "deploy".to_string() }]
))
.unwrap(),
serde_json::json!({
"prompt": "Account",
"echo": true,
"options": [{ "value": "deploy", "label": "deploy" }]
})
);
// The convenience wrapper needs a running server to talk to.
HOST_CLIENT.lock().unwrap().take();
assert!(request_user_input(&UserInputPrompt::secret("Code")).is_err());
assert!(host_client().is_none());
}
} }
fn io_error(error: io::Error) -> PluginError { fn io_error(error: io::Error) -> PluginError {
+1 -3
View File
@@ -263,9 +263,7 @@ mod tests {
port: 22, port: 22,
key_type: Some("ssh-ed25519".to_string()), key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()), fingerprint: Some("SHA256:test".to_string()),
previous_fingerprint: None, ..Default::default()
prompt: None,
echo: false,
} }
} }