refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/approval"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/handler/dto"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -81,12 +82,11 @@ func (h *MCPServiceHandler) CreateMCPService(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Redact before echoing so the Create response honors the same
|
||||
// "secrets never leave the server" invariant as List/Get/Update.
|
||||
service.RedactSensitiveData()
|
||||
// Response uses dto.MCPServiceResponse which omits secret fields by
|
||||
// construction — no runtime redaction needed.
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": service,
|
||||
"data": dto.NewMCPServiceResponse(&service),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ func (h *MCPServiceHandler) ListMCPServices(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": services,
|
||||
"data": dto.NewMCPServiceResponses(services),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -154,15 +154,12 @@ func (h *MCPServiceHandler) GetMCPService(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Hide sensitive information for builtin MCP services
|
||||
responseService := service
|
||||
if service.IsBuiltin {
|
||||
responseService = service.HideSensitiveInfo()
|
||||
}
|
||||
|
||||
// dto.NewMCPServiceResponse omits secret fields and additionally strips
|
||||
// transport details (URL/Headers/EnvVars/StdioConfig) for builtin services
|
||||
// so the cross-tenant builtin list does not leak per-tenant config.
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": responseService,
|
||||
"data": dto.NewMCPServiceResponse(service),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -275,26 +272,24 @@ func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) {
|
||||
}
|
||||
if authConfig, ok := updateData["auth_config"].(map[string]interface{}); ok {
|
||||
service.AuthConfig = &types.MCPAuthConfig{}
|
||||
if apiKey, ok := authConfig["api_key"].(string); ok {
|
||||
service.AuthConfig.APIKey = apiKey
|
||||
// Secret fields (api_key, token) are intentionally NOT read from the
|
||||
// main PUT body — they live behind the /credentials subresource so
|
||||
// editing unrelated config (timeout, enabled, etc.) cannot
|
||||
// accidentally clobber a stored credential. Log a warning when a
|
||||
// client still tries to send them so we can spot stale callers.
|
||||
if _, present := authConfig["api_key"]; present {
|
||||
logger.Warnf(ctx,
|
||||
"deprecated: api_key in PUT /mcp-services/%s body is ignored; use PUT /credentials instead",
|
||||
secutils.SanitizeForLog(serviceID))
|
||||
}
|
||||
if token, ok := authConfig["token"].(string); ok {
|
||||
service.AuthConfig.Token = token
|
||||
if _, present := authConfig["token"]; present {
|
||||
logger.Warnf(ctx,
|
||||
"deprecated: token in PUT /mcp-services/%s body is ignored; use PUT /credentials instead",
|
||||
secutils.SanitizeForLog(serviceID))
|
||||
}
|
||||
// Write-only clear flags — must be explicitly pulled off the map
|
||||
// since this handler intentionally uses a manual map-to-struct
|
||||
// projection to support partial updates (see "Use map to handle
|
||||
// partial updates" comment above). A struct-based bind would have
|
||||
// picked these up automatically.
|
||||
if clearAPIKey, ok := authConfig["clear_api_key"].(bool); ok {
|
||||
service.AuthConfig.ClearAPIKey = clearAPIKey
|
||||
}
|
||||
if clearToken, ok := authConfig["clear_token"].(bool); ok {
|
||||
service.AuthConfig.ClearToken = clearToken
|
||||
}
|
||||
// CustomHeaders — nil preserves, non-nil replaces (see
|
||||
// MCPAuthConfig.MergeUpdate). Only copy when the key is present so
|
||||
// the preserve-on-nil branch is reachable.
|
||||
// CustomHeaders is structural (not a secret) — keep accepting it here.
|
||||
// nil preserves existing, non-nil replaces; the service layer treats a
|
||||
// nil CustomHeaders as "no change".
|
||||
if customHeaders, ok := authConfig["custom_headers"].(map[string]interface{}); ok {
|
||||
headers := make(map[string]string, len(customHeaders))
|
||||
for k, v := range customHeaders {
|
||||
@@ -325,13 +320,17 @@ func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) {
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "MCP service updated successfully: %s", secutils.SanitizeForLog(serviceID))
|
||||
// Redact before echoing so the Update response honors the same
|
||||
// "secrets never leave the server" invariant as List/Get/Create, and so
|
||||
// write-only Clear* flags from the request body are never echoed back.
|
||||
service.RedactSensitiveData()
|
||||
|
||||
// Re-fetch to pick up server-side merges (CustomHeaders preserve, etc.)
|
||||
// and respond with the full current state via the secret-free DTO.
|
||||
stored, err := h.mcpServiceService.GetMCPServiceByID(ctx, tenantID, serviceID)
|
||||
if err != nil {
|
||||
c.Error(errors.NewInternalServerError("Failed to fetch updated MCP service: " + err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": service,
|
||||
"data": dto.NewMCPServiceResponse(stored),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user