fix: redact sensitive fields and prevent credential loss on edit
Closes #988 Unify the "write-only secrets" pattern across MCP services, Models, WebSearch providers, and DataSources. Fix two related defects: 1. GET responses leaked plaintext credentials — GetMCPServiceByID while List masked, all Model / WebSearchProvider / DataSource GET responses unconditionally. 2. When the frontend echoed a masked placeholder back on save, the update path overwrote the stored secret with the mask — silently wiping the real credential. MCP surfaced this most visibly: ListMCPServices masked Token to "first4****last4" and McpServiceDialog round-tripped that masked string back into the DB. - internal/types/secret.go introduces the shared sentinel RedactedSecretPlaceholder = "***" and two helpers: - IsRedactedOrEmpty(s): true for "" or the sentinel - PreserveIfRedacted(incoming, existing): merge predicate - Each resource adds a RedactSensitiveData (mutates-in-place) or Redacted (returns-a-copy) method and a MergeUpdate contract: empty or placeholder preserves, any other value replaces, and a write-only Clear* bool flag (gorm:"-", json omitempty) wipes with precedence over preserve / replace. Clear* never persists. - Every GET / List / Create / Update response path now redacts. VectorStore's pre-existing "***" literal is refactored onto the shared constant for consistency. All four dialogs — McpServiceDialog, ModelEditorDialog, WebSearchSettings, DataSourceEditorDialog — never pre-fill secret inputs. The stored-state signal is collapsed into the input placeholder: "•••••••• (Enter new value to replace)" when the server reports a stored value, falling back to the connector-specific placeholder otherwise. The input itself carries the "something is there" cue, matching how password dots render. An opt-in "Remove this credential" checkbox appears in edit mode when a value is stored; checking it disables the input and triggers a danger-themed confirmation dialog before submit. DataSource rolls the clear up to a connector-level "Remove all credentials" flag since its credentials are per-connector atomic bundles (e.g. Feishu app_id + app_secret). i18n updates across en-US, zh-CN, ko-KR, ru-RU: secret.storedPlaceholder / clearHint / confirmClearTitle / confirmClearBody. - MCP update handler's manual map-to-struct projection was silently dropping clear_api_key / clear_token / custom_headers on partial updates. Pull them off the map explicitly. - MCP configChanged detection now snapshots URL / StdioConfig / TransportType before the merge so connection recycling still triggers on real transport changes (not just whenever AuthConfig is present). - MCP CustomHeaders: nil preserves existing, non-nil replaces. Was always overwriting, silently wiping headers on any auth-bearing update. - GetMCPServiceByID now redacts (was plaintext while List masked). - WebSearchProvider update preserves Name / Description when empty instead of clobbering them. - WebSearchProvider TestProviderRaw rejects the "***" placeholder up front with an actionable message rather than forwarding it to the upstream provider API as a literal key. - Model builtin hideSensitiveInfo now preserves non-secret metadata (SupportsVision, Provider, ExtraConfig, InterfaceType, ParameterSize, EmbeddingParameters) that were previously zeroed out for builtin model cards. - Replace local equalStringSlices / equalStringMaps helpers with stdlib slices.Equal / maps.Equal (Go 1.21+). - internal/types/{secret,mcp,model,web_search_provider,datasource}_test.go: table-driven coverage of merge, redact, clear, and write-only flag invariants for every resource. - internal/application/service/mcp_service_test.go: full service layer with a fake repo; covers ListMCPServices / GetMCPServiceByID redaction, UpdateMCPService partial-update honoring of Clear*, CustomHeaders preserve-on-nil / replace-on-non-nil, and clear-flag precedence over submitted values. Additive only. No changes to request or response JSON shape beyond the write-only Clear* flags (omitted by default via omitempty). No DB schema changes. No SDK struct field removals. Existing clients that don't know about the new flags continue to function unchanged. - DataSource.Config jsonb at-rest encryption. Pre-existing residual risk; tracked as a follow-up. - Renaming VectorStore.MaskSensitiveFields to match the new RedactSensitiveData / Redacted naming convention. Left alone to minimize diff; a follow-up rename PR can unify.
This commit is contained in:
@@ -13,6 +13,10 @@ export interface MCPService {
|
||||
api_key?: string
|
||||
token?: string
|
||||
custom_headers?: Record<string, string>
|
||||
// Write-only flags — set to true in Update requests to explicitly remove
|
||||
// the corresponding credential. The server never returns these fields.
|
||||
clear_api_key?: boolean
|
||||
clear_token?: boolean
|
||||
}
|
||||
advanced_config?: {
|
||||
timeout?: number
|
||||
|
||||
@@ -26,6 +26,12 @@ export interface ModelConfig {
|
||||
// 会在调用远程模型 API 时附加到每个请求上。Authorization、Content-Type 等保留头会被忽略。
|
||||
custom_headers?: Record<string, string>;
|
||||
supports_vision?: boolean; // Whether the model accepts image/multimodal input
|
||||
app_id?: string;
|
||||
app_secret?: string;
|
||||
// Write-only flags — set to true in Update requests to explicitly remove
|
||||
// the corresponding credential. The server never returns these fields.
|
||||
clear_api_key?: boolean;
|
||||
clear_app_secret?: boolean;
|
||||
};
|
||||
is_default?: boolean;
|
||||
is_builtin?: boolean;
|
||||
|
||||
@@ -13,6 +13,9 @@ export interface WebSearchProviderEntity {
|
||||
base_url?: string
|
||||
proxy_url?: string
|
||||
extra_config?: Record<string, string>
|
||||
// Write-only flag — set to true in Update requests to explicitly remove
|
||||
// the stored API key. The server never returns this field.
|
||||
clear_api_key?: boolean
|
||||
}
|
||||
is_default?: boolean
|
||||
created_at?: string
|
||||
|
||||
@@ -211,8 +211,16 @@
|
||||
<t-input
|
||||
v-model="formData.apiKey"
|
||||
type="password"
|
||||
:placeholder="$t('model.editor.apiKeyPlaceholder')"
|
||||
:disabled="formData.clearApiKey"
|
||||
:placeholder="apiKeyPlaceholder"
|
||||
/>
|
||||
<t-checkbox
|
||||
v-if="isEdit && formData.hasExistingApiKey"
|
||||
v-model="formData.clearApiKey"
|
||||
class="clear-credential"
|
||||
>
|
||||
{{ t('secret.clearHint') }}
|
||||
</t-checkbox>
|
||||
</div>
|
||||
|
||||
<!-- 自定义 HTTP Header(类似 OpenAI Python SDK 的 extra_headers) -->
|
||||
@@ -331,7 +339,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed, onUnmounted, nextTick } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
|
||||
import { checkOllamaModels, checkRemoteModel, testEmbeddingModel, checkRerankModel, checkASRModel, listOllamaModels, downloadOllamaModel, getDownloadProgress, checkOllamaStatus, listModelProviders, type OllamaModelInfo, type ModelProviderOption } from '@/api/initialization'
|
||||
import { getWeKnoraCloudStatus } from '@/api/model'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -352,6 +360,12 @@ interface ModelFormData {
|
||||
modelName: string
|
||||
baseUrl?: string
|
||||
apiKey?: string
|
||||
// True when the server returned '***' for parameters.api_key, meaning a
|
||||
// key is currently stored server-side. Drives the "Set / Not set" badge.
|
||||
hasExistingApiKey?: boolean
|
||||
// Write-only flag set by the user to explicitly remove the stored key on
|
||||
// save. Reset to false on every dialog open.
|
||||
clearApiKey?: boolean
|
||||
dimension?: number
|
||||
interfaceType?: 'ollama' | 'openai'
|
||||
isDefault: boolean
|
||||
@@ -539,6 +553,17 @@ const dialogVisible = computed({
|
||||
|
||||
const isEdit = computed(() => !!props.modelData)
|
||||
|
||||
// Placeholder hint for the API key field. On edit with a stored key, swap
|
||||
// in the shared "bullets + Enter new value to replace" placeholder so the
|
||||
// input itself carries the "something is there" signal. Otherwise fall back
|
||||
// to the generic creation-mode placeholder.
|
||||
const apiKeyPlaceholder = computed(() => {
|
||||
if (isEdit.value && formData.value.hasExistingApiKey) {
|
||||
return t('secret.storedPlaceholder')
|
||||
}
|
||||
return t('model.editor.apiKeyPlaceholder')
|
||||
})
|
||||
|
||||
const formRef = ref()
|
||||
const saving = ref(false)
|
||||
const modelChecked = ref(false)
|
||||
@@ -745,8 +770,14 @@ watch(() => props.visible, (val) => {
|
||||
|
||||
if (props.modelData) {
|
||||
// 编辑:始终用最新的 modelData 覆盖
|
||||
// Always reset apiKey / clearApiKey on every dialog open so the
|
||||
// invariant "non-empty apiKey means the user typed it" holds.
|
||||
// hasExistingApiKey flows through unchanged so the badge keeps showing
|
||||
// "Set" when the server said '***'.
|
||||
formData.value = {
|
||||
...props.modelData,
|
||||
apiKey: '',
|
||||
clearApiKey: false,
|
||||
customHeaders: Array.isArray(props.modelData.customHeaders)
|
||||
? props.modelData.customHeaders.map(h => ({ key: h.key, value: h.value }))
|
||||
: []
|
||||
@@ -781,6 +812,8 @@ const resetForm = () => {
|
||||
modelName: '',
|
||||
baseUrl: '',
|
||||
apiKey: '',
|
||||
hasExistingApiKey: false,
|
||||
clearApiKey: false,
|
||||
dimension: undefined, // 默认不填,让用户手动输入或通过检测按钮获取
|
||||
interfaceType: undefined,
|
||||
isDefault: false,
|
||||
@@ -1117,13 +1150,30 @@ const handleConfirm = async () => {
|
||||
|
||||
// 执行表单验证
|
||||
await formRef.value?.validate()
|
||||
|
||||
// Confirm irrevocable credential removal before emitting.
|
||||
if (formData.value.clearApiKey) {
|
||||
const ok = await new Promise<boolean>((resolve) => {
|
||||
const d = DialogPlugin.confirm({
|
||||
header: t('secret.confirmClearTitle'),
|
||||
body: t('secret.confirmClearBody'),
|
||||
confirmBtn: { content: t('common.confirm'), theme: 'danger' },
|
||||
cancelBtn: t('common.cancel'),
|
||||
onConfirm: () => { d.hide(); resolve(true) },
|
||||
onCancel: () => { d.hide(); resolve(false) },
|
||||
onClose: () => { d.hide(); resolve(false) },
|
||||
})
|
||||
})
|
||||
if (!ok) return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
|
||||
|
||||
// 如果是新增且没有 id,生成一个
|
||||
if (!formData.value.id) {
|
||||
formData.value.id = generateId()
|
||||
}
|
||||
|
||||
|
||||
emit('confirm', { ...formData.value })
|
||||
dialogVisible.value = false
|
||||
// 保存成功后重置草稿,下次打开新增模型时是空白
|
||||
@@ -1658,6 +1708,18 @@ const handleCancel = () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Destructive-action checkbox for "Remove this credential". Styled to match
|
||||
// the pattern used in McpServiceDialog so the two dialogs read identically.
|
||||
.clear-credential {
|
||||
display: inline-flex;
|
||||
margin-top: 8px;
|
||||
|
||||
:deep(.t-checkbox__label) {
|
||||
color: var(--td-error-color);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- 非 scoped 样式:t-select popup 渲染到 body 下,scoped 样式无法覆盖 -->
|
||||
|
||||
@@ -4284,4 +4284,15 @@ export default {
|
||||
createdAt: 'Created at',
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
// Placeholder shown inside a credential input when a value is currently
|
||||
// stored server-side. The bullet run doubles as a visual "something is
|
||||
// there" cue (matching how the password type renders dots); the
|
||||
// parenthetical tells the user what typing will do.
|
||||
storedPlaceholder: '•••••••• (Enter new value to replace)',
|
||||
clearHint: 'Remove this credential',
|
||||
confirmClearTitle: 'Confirm credential removal',
|
||||
confirmClearBody:
|
||||
'This permanently deletes the stored credential. Integrations using it will stop working. Continue?',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -4347,4 +4347,11 @@ export default {
|
||||
createdAt: "생성 시각",
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
storedPlaceholder: "•••••••• (새 값을 입력하면 교체됩니다)",
|
||||
clearHint: "이 credential 제거",
|
||||
confirmClearTitle: "credential 제거 확인",
|
||||
confirmClearBody:
|
||||
"저장된 credential이 영구 삭제되며, 이를 사용하는 통합이 중단됩니다. 계속할까요?",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4247,4 +4247,11 @@ export default {
|
||||
createdAt: 'Создано',
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
storedPlaceholder: '•••••••• (Введите новое значение для замены)',
|
||||
clearHint: 'Удалить эти учётные данные',
|
||||
confirmClearTitle: 'Подтверждение удаления учётных данных',
|
||||
confirmClearBody:
|
||||
'Это действие безвозвратно удалит сохранённые учётные данные. Интеграции, использующие их, перестанут работать. Продолжить?',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -4280,4 +4280,11 @@ export default {
|
||||
createdAt: "创建时间",
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
storedPlaceholder: "•••••••• (输入新值以替换)",
|
||||
clearHint: "删除此凭据",
|
||||
confirmClearTitle: "确认删除凭据",
|
||||
confirmClearBody:
|
||||
"此操作将永久删除已保存的凭据,依赖它的集成将停止工作。是否继续?",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import {
|
||||
createDataSource,
|
||||
@@ -28,6 +28,38 @@ const isEdit = computed(() => !!props.dataSource)
|
||||
const step = ref(0)
|
||||
const submitting = ref(false)
|
||||
|
||||
// Fixed placeholder returned by the server for redacted credential strings.
|
||||
// Must match internal/types/secret.go → RedactedSecretPlaceholder.
|
||||
const REDACTED_PLACEHOLDER = '***'
|
||||
|
||||
// Per-field: is this specific credential key stored server-side? Drives the
|
||||
// per-input placeholder swap to the "••••••• (Enter new value to replace)"
|
||||
// hint when the server marked it present.
|
||||
function hasFieldCredential(key: string): boolean {
|
||||
return props.dataSource?.config?.credentials?.[key] === REDACTED_PLACEHOLDER
|
||||
}
|
||||
|
||||
// Connector-level rollup: true when any credential key is stored. Used to
|
||||
// decide whether to render the "Remove all credentials" checkbox.
|
||||
const hasExistingCredentials = computed(() => {
|
||||
const creds = props.dataSource?.config?.credentials
|
||||
if (!creds) return false
|
||||
return Object.values(creds).some(v => v === REDACTED_PLACEHOLDER)
|
||||
})
|
||||
|
||||
// Placeholder for a given credential input: stored → shared hint,
|
||||
// otherwise the connector-specific default (e.g. "ntn_xxxx" for Notion).
|
||||
function credentialPlaceholder(field: { key: string; placeholder: string }): string {
|
||||
return hasFieldCredential(field.key)
|
||||
? t('secret.storedPlaceholder')
|
||||
: field.placeholder
|
||||
}
|
||||
|
||||
// Explicit "remove all credentials" flag. Because credentials form an atomic
|
||||
// set per connector (e.g. an OAuth pair) we only support all-or-nothing
|
||||
// clearing, mirroring the backend DataSourceConfig.ClearCredentials contract.
|
||||
const clearCredentials = ref(false)
|
||||
|
||||
// Form data
|
||||
const form = ref({
|
||||
name: '',
|
||||
@@ -213,10 +245,22 @@ watch(visible, (v) => {
|
||||
selectedResourceIds.value = []
|
||||
|
||||
if (isEdit.value && props.dataSource) {
|
||||
// Reset clear intent on every open so an aborted deletion doesn't
|
||||
// carry over to the next edit session.
|
||||
clearCredentials.value = false
|
||||
// Credentials are intentionally NOT pre-filled from the server response
|
||||
// — even though the server returns '***' for stored secrets, the form
|
||||
// holds an empty map. This keeps the "non-empty means user typed it"
|
||||
// invariant that the save path relies on, and the badge reflects the
|
||||
// stored state via hasExistingCredentials instead.
|
||||
form.value = {
|
||||
name: props.dataSource.name,
|
||||
type: props.dataSource.type,
|
||||
config: props.dataSource.config || { credentials: {}, resource_ids: [], settings: {} },
|
||||
config: {
|
||||
credentials: {},
|
||||
resource_ids: props.dataSource.config?.resource_ids || [],
|
||||
settings: props.dataSource.config?.settings || {},
|
||||
},
|
||||
sync_schedule: props.dataSource.sync_schedule,
|
||||
sync_mode: props.dataSource.sync_mode,
|
||||
conflict_strategy: props.dataSource.conflict_strategy,
|
||||
@@ -225,6 +269,7 @@ watch(visible, (v) => {
|
||||
selectedResourceIds.value = form.value.config?.resource_ids || []
|
||||
tempDsId.value = props.dataSource.id
|
||||
} else {
|
||||
clearCredentials.value = false
|
||||
form.value = {
|
||||
name: '',
|
||||
type: '',
|
||||
@@ -405,8 +450,45 @@ function prevStep() {
|
||||
step.value--
|
||||
}
|
||||
|
||||
// Prompt the user before irrevocable credential removal.
|
||||
function confirmClearIfNeeded(): Promise<boolean> {
|
||||
if (!clearCredentials.value) return Promise.resolve(true)
|
||||
return new Promise((resolve) => {
|
||||
const d = DialogPlugin.confirm({
|
||||
header: t('secret.confirmClearTitle'),
|
||||
body: t('secret.confirmClearBody'),
|
||||
confirmBtn: { content: t('common.confirm'), theme: 'danger' },
|
||||
cancelBtn: t('common.cancel'),
|
||||
onConfirm: () => { d.hide(); resolve(true) },
|
||||
onCancel: () => { d.hide(); resolve(false) },
|
||||
onClose: () => { d.hide(); resolve(false) },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Build the config payload for Create / Update requests. In edit mode this
|
||||
// applies write-only secret semantics:
|
||||
// - clearCredentials checked → send clear_credentials: true (backend wipes)
|
||||
// - user typed credential values → send them as-is
|
||||
// - user left fields blank → send empty credentials map (backend preserves
|
||||
// every existing credential key individually)
|
||||
function buildConfigPayload(): Record<string, unknown> {
|
||||
const cfg: Record<string, unknown> = {
|
||||
credentials: clearCredentials.value ? {} : { ...form.value.config.credentials },
|
||||
resource_ids: form.value.config.resource_ids,
|
||||
settings: form.value.config.settings,
|
||||
}
|
||||
if (clearCredentials.value) {
|
||||
cfg.clear_credentials = true
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// --- Final submit ---
|
||||
async function handleSubmit() {
|
||||
const ok = await confirmClearIfNeeded()
|
||||
if (!ok) return
|
||||
|
||||
form.value.config.resource_ids = selectedResourceIds.value
|
||||
submitting.value = true
|
||||
try {
|
||||
@@ -415,12 +497,14 @@ async function handleSubmit() {
|
||||
if (tempDsId.value) {
|
||||
await updateDataSource(tempDsId.value, {
|
||||
...form.value,
|
||||
config: buildConfigPayload(),
|
||||
knowledge_base_id: props.kbId,
|
||||
status: 'active',
|
||||
} as any)
|
||||
} else {
|
||||
const res = await createDataSource({
|
||||
...form.value,
|
||||
config: buildConfigPayload(),
|
||||
knowledge_base_id: props.kbId,
|
||||
status: 'active',
|
||||
} as any)
|
||||
@@ -575,6 +659,14 @@ const stepTitles = computed(() => [
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!--
|
||||
Credential fields. When the server returned '***' for a field the
|
||||
per-input placeholder swaps to the shared "••••••• (Enter new value
|
||||
to replace)" hint so the input carries the "something is stored"
|
||||
signal without a separate badge. The "Remove all credentials"
|
||||
checkbox below handles the destructive clear for the whole set
|
||||
(DataSource credentials are per-connector atomic bundles).
|
||||
-->
|
||||
<div v-for="field in currentDef?.fields || []" :key="field.key" class="form-item">
|
||||
<label class="form-label">
|
||||
{{ t(field.labelKey) }}
|
||||
@@ -582,12 +674,19 @@ const stepTitles = computed(() => [
|
||||
</label>
|
||||
<t-input
|
||||
v-model="form.config.credentials[field.key]"
|
||||
:placeholder="field.placeholder"
|
||||
:disabled="clearCredentials"
|
||||
:placeholder="credentialPlaceholder(field)"
|
||||
:type="field.secret ? 'password' : 'text'"
|
||||
/>
|
||||
<div v-if="field.hintKey" class="form-hint">{{ t(field.hintKey) }}</div>
|
||||
</div>
|
||||
|
||||
<div v-if="isEdit && hasExistingCredentials" class="form-item">
|
||||
<t-checkbox v-model="clearCredentials" class="clear-credential">
|
||||
{{ t('secret.clearHint') }}
|
||||
</t-checkbox>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<t-button variant="outline" :loading="testing" @click="testConnection">
|
||||
{{ t('datasource.testConnection') }}
|
||||
@@ -886,6 +985,12 @@ const stepTitles = computed(() => [
|
||||
.form-item { margin-bottom: 16px; }
|
||||
.form-label { display: block; font-size: 13px; font-weight: 500; margin-bottom: 6px; color: var(--td-text-color-primary); }
|
||||
.required-mark { color: var(--td-error-color); margin-left: 2px; }
|
||||
|
||||
/* Destructive-action checkbox — red label, matches the other 3 dialogs. */
|
||||
.clear-credential :deep(.t-checkbox__label) {
|
||||
color: var(--td-error-color);
|
||||
font-size: 13px;
|
||||
}
|
||||
.form-tip { font-size: 12px; color: var(--td-text-color-placeholder); margin: 4px 0 12px; }
|
||||
.form-hint { font-size: 12px; color: var(--td-text-color-placeholder); margin-top: 6px; line-height: 1.5; }
|
||||
.form-actions { display: flex; align-items: center; gap: 8px; margin-top: 12px; }
|
||||
|
||||
@@ -138,6 +138,13 @@ const backendTypeToModelType: Record<string, ModelType> = {
|
||||
}
|
||||
|
||||
// 将后端模型格式转换为旧的前端格式(附带 _modelType 便于渲染)
|
||||
// NOTE: apiKey is intentionally NEVER pre-filled from the server response.
|
||||
// The server returns '***' as a redacted placeholder when a key is stored,
|
||||
// and '' when it is not. We expose this as hasExistingApiKey so the editor
|
||||
// dialog can render a "Set / Not set" badge, while the apiKey field starts
|
||||
// blank — this preserves the invariant "non-empty formData.apiKey means the
|
||||
// user typed something" that the save path relies on to decide preserve /
|
||||
// replace / clear.
|
||||
function convertToLegacyFormat(model: ModelConfig) {
|
||||
return {
|
||||
id: model.id!,
|
||||
@@ -145,7 +152,8 @@ function convertToLegacyFormat(model: ModelConfig) {
|
||||
source: model.source,
|
||||
modelName: model.name,
|
||||
baseUrl: model.parameters.base_url || '',
|
||||
apiKey: model.parameters.api_key || '',
|
||||
apiKey: '',
|
||||
hasExistingApiKey: model.parameters.api_key === '***',
|
||||
provider: model.parameters.provider || '',
|
||||
dimension: model.parameters.embedding_parameters?.dimension,
|
||||
isBuiltin: model.is_builtin || false,
|
||||
@@ -283,6 +291,20 @@ const handleModelSave = async (modelData: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 将前端格式转换为后端格式.
|
||||
// Three-state api_key semantics (write-only secrets pattern):
|
||||
// - clearApiKey set → send { clear_api_key: true }
|
||||
// - user typed a value → send { api_key: "..." }
|
||||
// - empty (default on edit) → omit api_key → server preserves
|
||||
// - empty on create → omit api_key → no stored secret
|
||||
const trimmedApiKey = (modelData.apiKey ?? '').trim()
|
||||
const apiKeyFields: { api_key?: string; clear_api_key?: boolean } =
|
||||
modelData.clearApiKey
|
||||
? { clear_api_key: true }
|
||||
: trimmedApiKey
|
||||
? { api_key: trimmedApiKey }
|
||||
: {}
|
||||
|
||||
const apiModelData: ModelConfig = {
|
||||
name: modelData.modelName.trim(),
|
||||
type: getModelType(currentModelType.value),
|
||||
@@ -290,7 +312,7 @@ const handleModelSave = async (modelData: any) => {
|
||||
description: '',
|
||||
parameters: {
|
||||
base_url: modelData.baseUrl?.trim() || '',
|
||||
api_key: modelData.apiKey?.trim() || '',
|
||||
...apiKeyFields,
|
||||
provider: modelData.provider || '',
|
||||
...(Object.keys(customHeadersMap).length > 0 ? { custom_headers: customHeadersMap } : {}),
|
||||
...(currentModelType.value === 'embedding' && modelData.dimension ? {
|
||||
|
||||
@@ -98,13 +98,22 @@
|
||||
:placeholder="t('webSearchSettings.baseUrlPlaceholder')"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="selectedProviderType?.requires_api_key" :label="t('webSearchSettings.apiKeyLabel')" name="parameters.api_key">
|
||||
<!--
|
||||
API key is mandatory for every requires_api_key=true provider
|
||||
(Bing / Google / Tavily / Ollama / Baidu — see
|
||||
validateProviderParameters in service/web_search_provider.go),
|
||||
so the "Remove this credential" affordance shown in the other
|
||||
three dialogs is intentionally omitted here. Revoking access
|
||||
means deleting the whole provider row from the list.
|
||||
-->
|
||||
<div v-if="selectedProviderType?.requires_api_key" class="credential-field">
|
||||
<label class="credential-label">{{ t('webSearchSettings.apiKeyLabel') }}</label>
|
||||
<t-input
|
||||
v-model="providerForm.parameters.api_key"
|
||||
type="password"
|
||||
:placeholder="editingProvider ? t('webSearchSettings.apiKeyUnchanged') : t('webSearchSettings.apiKeyPlaceholder')"
|
||||
:placeholder="apiKeyPlaceholder"
|
||||
/>
|
||||
</t-form-item>
|
||||
</div>
|
||||
<t-form-item v-if="selectedProviderType?.requires_engine_id" :label="t('webSearchSettings.engineIdLabel')" name="parameters.engine_id">
|
||||
<t-input v-model="providerForm.parameters.engine_id" :placeholder="t('webSearchSettings.engineIdLabel')" />
|
||||
</t-form-item>
|
||||
@@ -179,6 +188,10 @@ const testingId = ref<string | null>(null)
|
||||
const saving = ref(false)
|
||||
const formRef = ref<any>()
|
||||
|
||||
// Fixed placeholder returned by the server for redacted secrets. Must match
|
||||
// internal/types/secret.go → RedactedSecretPlaceholder.
|
||||
const REDACTED_PLACEHOLDER = '***'
|
||||
|
||||
const providerForm = ref<{
|
||||
name: string
|
||||
provider: string
|
||||
@@ -198,6 +211,23 @@ const selectedProviderType = computed(() => {
|
||||
return providerTypes.value.find(pt => pt.id === providerForm.value.provider)
|
||||
})
|
||||
|
||||
// "Is an API key currently stored?" is signaled by the server returning the
|
||||
// fixed REDACTED_PLACEHOLDER in the response. Drive the label badge from this.
|
||||
const hasExistingApiKey = computed(() => {
|
||||
return editingProvider.value?.parameters?.api_key === REDACTED_PLACEHOLDER
|
||||
})
|
||||
|
||||
// In edit mode with a stored key, swap the placeholder to the shared
|
||||
// "bullets + Enter new value to replace" hint. Otherwise fall back to the
|
||||
// provider-specific placeholder (creation) or the "leave blank to keep"
|
||||
// copy used when no key is stored yet.
|
||||
const apiKeyPlaceholder = computed(() => {
|
||||
if (!editingProvider.value) return t('webSearchSettings.apiKeyPlaceholder')
|
||||
return hasExistingApiKey.value
|
||||
? t('secret.storedPlaceholder')
|
||||
: t('webSearchSettings.apiKeyUnchanged')
|
||||
})
|
||||
|
||||
const isProviderFree = (providerType: WebSearchProviderTypeInfo) => {
|
||||
// "Free" here means no upstream-paid credentials are required. Self-hosted
|
||||
// providers (requires_base_url) are still free to use even though they need
|
||||
@@ -253,6 +283,8 @@ const editProvider = (entity: WebSearchProviderEntity) => {
|
||||
provider: entity.provider,
|
||||
description: entity.description || '',
|
||||
parameters: {
|
||||
// Never pre-fill the api_key — even the redacted placeholder from the
|
||||
// server is ignored so that "non-empty means user typed it" holds.
|
||||
api_key: '',
|
||||
engine_id: entity.parameters?.engine_id || '',
|
||||
base_url: entity.parameters?.base_url || '',
|
||||
@@ -273,18 +305,29 @@ const saveProvider = async () => {
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
// Build the parameters payload using two-state semantics:
|
||||
// - user typed a value → send api_key (replaces stored)
|
||||
// - empty + editing → omit api_key (server preserves stored value)
|
||||
// - empty + creating → omit api_key (no secret to store yet)
|
||||
// No clear path: every requires_api_key provider mandates a value, so
|
||||
// "revoke" means deleting the provider row, not zeroing the key.
|
||||
const paramsOut: WebSearchProviderEntity['parameters'] = {
|
||||
engine_id: providerForm.value.parameters.engine_id,
|
||||
base_url: providerForm.value.parameters.base_url,
|
||||
proxy_url: providerForm.value.parameters.proxy_url,
|
||||
}
|
||||
if (providerForm.value.parameters.api_key) {
|
||||
paramsOut.api_key = providerForm.value.parameters.api_key
|
||||
}
|
||||
|
||||
const data: Partial<WebSearchProviderEntity> = {
|
||||
name: providerForm.value.name.trim() || selectedProviderType.value?.name || providerForm.value.provider,
|
||||
provider: providerForm.value.provider as any,
|
||||
description: providerForm.value.description,
|
||||
parameters: { ...providerForm.value.parameters },
|
||||
parameters: paramsOut,
|
||||
is_default: providerForm.value.is_default,
|
||||
}
|
||||
|
||||
if (editingProvider.value && !data.parameters!.api_key) {
|
||||
delete data.parameters!.api_key
|
||||
}
|
||||
|
||||
if (editingProvider.value) {
|
||||
await updateWebSearchProvider(editingProvider.value.id!, data)
|
||||
MessagePlugin.success(t('webSearchSettings.toasts.providerUpdated'))
|
||||
@@ -471,6 +514,31 @@ onMounted(async () => {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Credential field: stacks the label row, password input, and the optional
|
||||
* "Remove this credential" checkbox vertically. Matches the pattern in
|
||||
* McpServiceDialog and ModelEditorDialog so the whole UI reads consistently.
|
||||
*/
|
||||
.credential-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.credential-label {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.clear-credential {
|
||||
:deep(.t-checkbox__label) {
|
||||
color: var(--td-error-color);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.credentials-hint {
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
|
||||
@@ -34,8 +34,8 @@
|
||||
</t-form-item>
|
||||
|
||||
<!-- URL for SSE/HTTP Streamable -->
|
||||
<t-form-item
|
||||
:label="t('mcpServiceDialog.serviceUrl')"
|
||||
<t-form-item
|
||||
:label="t('mcpServiceDialog.serviceUrl')"
|
||||
name="url"
|
||||
>
|
||||
<t-input v-model="formData.url" :placeholder="t('mcpServiceDialog.serviceUrlPlaceholder')" />
|
||||
@@ -50,20 +50,47 @@
|
||||
<!-- Authentication Config -->
|
||||
<t-collapse :default-value="[]">
|
||||
<t-collapse-panel :header="t('mcpServiceDialog.authConfig')" value="auth">
|
||||
<t-form-item :label="t('mcpServiceDialog.apiKey')">
|
||||
<!--
|
||||
Credential fields follow the "write-only secrets" pattern.
|
||||
When a value is currently stored on the server the placeholder
|
||||
is swapped for a bullet run + "Enter new value to replace"
|
||||
hint, so the visual "something is there" signal is carried by
|
||||
the input itself rather than by a separate Set/Not-set badge.
|
||||
The Remove checkbox still offers an explicit clear path.
|
||||
-->
|
||||
<div class="credential-field">
|
||||
<label class="credential-label">{{ t('mcpServiceDialog.apiKey') }}</label>
|
||||
<t-input
|
||||
v-model="formData.auth_config.api_key"
|
||||
type="password"
|
||||
:placeholder="t('mcpServiceDialog.optional')"
|
||||
:disabled="clearApiKey"
|
||||
:placeholder="apiKeyPlaceholder"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item :label="t('mcpServiceDialog.bearerToken')">
|
||||
<t-checkbox
|
||||
v-if="mode === 'edit' && hasExistingApiKey"
|
||||
v-model="clearApiKey"
|
||||
class="clear-credential"
|
||||
>
|
||||
{{ t('secret.clearHint') }}
|
||||
</t-checkbox>
|
||||
</div>
|
||||
|
||||
<div class="credential-field">
|
||||
<label class="credential-label">{{ t('mcpServiceDialog.bearerToken') }}</label>
|
||||
<t-input
|
||||
v-model="formData.auth_config.token"
|
||||
type="password"
|
||||
:placeholder="t('mcpServiceDialog.optional')"
|
||||
:disabled="clearToken"
|
||||
:placeholder="tokenPlaceholder"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-checkbox
|
||||
v-if="mode === 'edit' && hasExistingToken"
|
||||
v-model="clearToken"
|
||||
class="clear-credential"
|
||||
>
|
||||
{{ t('secret.clearHint') }}
|
||||
</t-checkbox>
|
||||
</div>
|
||||
</t-collapse-panel>
|
||||
|
||||
<!-- Advanced Config -->
|
||||
@@ -100,7 +127,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
|
||||
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import {
|
||||
@@ -128,6 +155,10 @@ const formRef = ref<FormInstanceFunctions>()
|
||||
const submitting = ref(false)
|
||||
const { t } = useI18n()
|
||||
|
||||
// Fixed placeholder returned by the server for sensitive fields whose values
|
||||
// are withheld. Must match internal/types/secret.go → RedactedSecretPlaceholder.
|
||||
const REDACTED_PLACEHOLDER = '***'
|
||||
|
||||
const formData = ref({
|
||||
name: '',
|
||||
description: '',
|
||||
@@ -145,11 +176,40 @@ const formData = ref({
|
||||
}
|
||||
})
|
||||
|
||||
// Explicit "remove stored credential" flags. Reset to false on every open/reset.
|
||||
const clearApiKey = ref(false)
|
||||
const clearToken = ref(false)
|
||||
|
||||
// "Is a credential currently stored?" is signaled by the server returning the
|
||||
// fixed REDACTED_PLACEHOLDER instead of an empty string. Drive the label
|
||||
// badge and placeholder hint from this signal.
|
||||
const hasExistingApiKey = computed(
|
||||
() => props.service?.auth_config?.api_key === REDACTED_PLACEHOLDER
|
||||
)
|
||||
const hasExistingToken = computed(
|
||||
() => props.service?.auth_config?.token === REDACTED_PLACEHOLDER
|
||||
)
|
||||
|
||||
// Placeholders swap to the shared "stored credential" hint when the server
|
||||
// signals a value is present (parameters come back as '***'). Otherwise
|
||||
// the field is genuinely empty and we fall through to the normal
|
||||
// "Optional" placeholder that appears in add mode too.
|
||||
const apiKeyPlaceholder = computed(() =>
|
||||
hasExistingApiKey.value
|
||||
? t('secret.storedPlaceholder')
|
||||
: t('mcpServiceDialog.optional')
|
||||
)
|
||||
const tokenPlaceholder = computed(() =>
|
||||
hasExistingToken.value
|
||||
? t('secret.storedPlaceholder')
|
||||
: t('mcpServiceDialog.optional')
|
||||
)
|
||||
|
||||
const rules: Record<string, FormRule[]> = {
|
||||
name: [{ required: true, message: t('mcpServiceDialog.rules.nameRequired') as string, type: 'error' }],
|
||||
transport_type: [{ required: true, message: t('mcpServiceDialog.rules.transportRequired') as string, type: 'error' }],
|
||||
url: [
|
||||
{
|
||||
{
|
||||
validator: (val: string) => {
|
||||
if (!val || val.trim() === '') {
|
||||
return { result: false, message: t('mcpServiceDialog.rules.urlRequired') as string, type: 'error' }
|
||||
@@ -171,7 +231,10 @@ const dialogVisible = computed({
|
||||
set: (value) => emit('update:visible', value)
|
||||
})
|
||||
|
||||
// Reset form function - defined before watch to avoid hoisting issues
|
||||
// Reset form function — defined before watch to avoid hoisting issues.
|
||||
// Sensitive fields are always blank: the watch below does not copy the
|
||||
// server-provided redacted placeholder into formData, and clear flags are
|
||||
// reset so a reopen does not carry over an aborted deletion intent.
|
||||
const resetForm = () => {
|
||||
formData.value = {
|
||||
name: '',
|
||||
@@ -189,10 +252,16 @@ const resetForm = () => {
|
||||
retry_delay: 1
|
||||
}
|
||||
}
|
||||
clearApiKey.value = false
|
||||
clearToken.value = false
|
||||
formRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
// Watch service prop to initialize form
|
||||
// Watch service prop to initialize form.
|
||||
// Sensitive fields (api_key, token) are NEVER pre-filled from the server
|
||||
// response — even when the server returns '***' indicating a stored value.
|
||||
// This keeps the "non-empty means user typed it" invariant that the submit
|
||||
// logic relies on to decide between preserve and replace.
|
||||
watch(
|
||||
() => props.service,
|
||||
(service) => {
|
||||
@@ -206,8 +275,8 @@ watch(
|
||||
transport_type: transportType as 'sse' | 'http-streamable',
|
||||
url: service.url || '',
|
||||
auth_config: {
|
||||
api_key: service.auth_config?.api_key || '',
|
||||
token: service.auth_config?.token || ''
|
||||
api_key: '',
|
||||
token: ''
|
||||
},
|
||||
advanced_config: {
|
||||
timeout: service.advanced_config?.timeout || 30,
|
||||
@@ -215,6 +284,8 @@ watch(
|
||||
retry_delay: service.advanced_config?.retry_delay || 1
|
||||
}
|
||||
}
|
||||
clearApiKey.value = false
|
||||
clearToken.value = false
|
||||
} else {
|
||||
resetForm()
|
||||
}
|
||||
@@ -222,24 +293,67 @@ watch(
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
// Handle submit
|
||||
// Prompt the user before irrevocable credential removal.
|
||||
const confirmClearIfNeeded = (): Promise<boolean> => {
|
||||
if (!clearApiKey.value && !clearToken.value) return Promise.resolve(true)
|
||||
return new Promise((resolve) => {
|
||||
const d = DialogPlugin.confirm({
|
||||
header: t('secret.confirmClearTitle'),
|
||||
body: t('secret.confirmClearBody'),
|
||||
confirmBtn: { content: t('common.confirm'), theme: 'danger' },
|
||||
cancelBtn: t('common.cancel'),
|
||||
onConfirm: () => {
|
||||
d.hide()
|
||||
resolve(true)
|
||||
},
|
||||
onCancel: () => {
|
||||
d.hide()
|
||||
resolve(false)
|
||||
},
|
||||
onClose: () => {
|
||||
d.hide()
|
||||
resolve(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Handle submit — three-state auth_config payload:
|
||||
// - clear flag set → send { clear_api_key: true } / { clear_token: true }
|
||||
// - user typed a value → send the value
|
||||
// - otherwise → omit the field, server preserves the stored value
|
||||
// If auth_config would be empty, omit the key entirely.
|
||||
const handleSubmit = async () => {
|
||||
const valid = await formRef.value?.validate()
|
||||
if (!valid) return
|
||||
|
||||
const proceed = await confirmClearIfNeeded()
|
||||
if (!proceed) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const authPayload: Record<string, unknown> = {}
|
||||
if (clearApiKey.value) {
|
||||
authPayload.clear_api_key = true
|
||||
} else if (formData.value.auth_config.api_key) {
|
||||
authPayload.api_key = formData.value.auth_config.api_key
|
||||
}
|
||||
if (clearToken.value) {
|
||||
authPayload.clear_token = true
|
||||
} else if (formData.value.auth_config.token) {
|
||||
authPayload.token = formData.value.auth_config.token
|
||||
}
|
||||
|
||||
const data: Partial<MCPService> = {
|
||||
name: formData.value.name,
|
||||
description: formData.value.description,
|
||||
enabled: formData.value.enabled,
|
||||
transport_type: formData.value.transport_type,
|
||||
auth_config: {
|
||||
api_key: formData.value.auth_config.api_key || undefined,
|
||||
token: formData.value.auth_config.token || undefined
|
||||
},
|
||||
advanced_config: formData.value.advanced_config,
|
||||
url: formData.value.url || undefined
|
||||
url: formData.value.url || undefined,
|
||||
}
|
||||
if (Object.keys(authPayload).length > 0) {
|
||||
data.auth_config = authPayload as MCPService['auth_config']
|
||||
}
|
||||
|
||||
if (props.mode === 'add') {
|
||||
@@ -269,5 +383,37 @@ const handleClose = () => {
|
||||
|
||||
<style scoped lang="less">
|
||||
/* Stdio-related styles removed as stdio transport is disabled for security reasons */
|
||||
|
||||
/**
|
||||
* Credential field: stacks the label row, the password input, and the
|
||||
* optional "Remove this credential" checkbox vertically. Replaces the
|
||||
* t-form-item-based layout for the auth-config fields so the inline badge
|
||||
* doesn't get clipped by the form's 120px label-width and the clear
|
||||
* checkbox doesn't sit alongside the input.
|
||||
*/
|
||||
.credential-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.credential-label {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
color: var(--td-text-color-primary);
|
||||
line-height: 22px;
|
||||
}
|
||||
|
||||
.clear-credential {
|
||||
:deep(.t-checkbox__label) {
|
||||
color: var(--td-error-color);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user