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:
wizardchen
2026-05-17 15:09:30 +08:00
committed by lyingbug
parent f30e9ccd0f
commit 7643dd457e
53 changed files with 3271 additions and 2347 deletions
+19 -20
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/handler/dto"
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -108,10 +109,9 @@ func (h *WebSearchProviderHandler) CreateProvider(c *gin.Context) {
return
}
provider.RedactSensitiveData()
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": provider,
"data": dto.NewWebSearchProviderResponse(provider),
})
}
@@ -132,12 +132,9 @@ func (h *WebSearchProviderHandler) ListProviders(c *gin.Context) {
return
}
for _, p := range providers {
p.RedactSensitiveData()
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": providers,
"data": dto.NewWebSearchProviderResponses(providers),
})
}
@@ -170,10 +167,9 @@ func (h *WebSearchProviderHandler) GetProvider(c *gin.Context) {
return
}
provider.RedactSensitiveData()
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": provider,
"data": dto.NewWebSearchProviderResponse(provider),
})
}
@@ -217,15 +213,22 @@ func (h *WebSearchProviderHandler) UpdateProvider(c *gin.Context) {
return
}
// Merge incoming parameters into the existing ones using write-only
// secret semantics: empty / redacted APIKey preserves the stored value,
// ClearAPIKey explicitly wipes it, any other value replaces. Non-secret
// fields flow through from the request directly.
mergedParams := req.Parameters.MergeUpdate(existing.Parameters)
if req.Parameters.ClearAPIKey {
logger.Infof(ctx, "WebSearchProvider API key cleared by user: id=%s",
// Credentials (api_key) NEVER flow through this endpoint — they live
// behind the /credentials subresource. Force-preserve the stored key
// regardless of what the body says; log a warning if a stale caller
// passes one so we can spot them.
if req.Parameters.APIKey != "" && req.Parameters.APIKey != existing.Parameters.APIKey {
logger.Warnf(ctx,
"deprecated: api_key in PUT /web-search-providers/%s body is ignored; use PUT /credentials instead",
secutils.SanitizeForLog(id))
}
mergedParams := req.Parameters
mergedParams.APIKey = existing.Parameters.APIKey
// Preserve ExtraConfig when the request omits it (nil); otherwise a
// partial PUT would silently drop tenant-configured extras.
if mergedParams.ExtraConfig == nil {
mergedParams.ExtraConfig = existing.Parameters.ExtraConfig
}
// Preserve existing values for top-level metadata fields when the
// request omits them (empty string from the JSON decoder). Without this,
@@ -260,8 +263,7 @@ func (h *WebSearchProviderHandler) UpdateProvider(c *gin.Context) {
// Re-fetch to get the full stored state
updated, _ := h.repo.GetByID(ctx, tenantID, id)
if updated != nil {
updated.RedactSensitiveData()
c.JSON(http.StatusOK, gin.H{"success": true, "data": updated})
c.JSON(http.StatusOK, gin.H{"success": true, "data": dto.NewWebSearchProviderResponse(updated)})
} else {
c.JSON(http.StatusOK, gin.H{"success": true})
}
@@ -408,9 +410,6 @@ func (h *WebSearchProviderHandler) TestProviderRaw(c *gin.Context) {
// user knows they should type a real key or test against the saved config
// via /test instead.
func (h *WebSearchProviderHandler) doTestSearch(ctx context.Context, providerType string, params types.WebSearchProviderParameters) error {
if params.APIKey == types.RedactedSecretPlaceholder {
return fmt.Errorf("api_key looks like the redacted placeholder; enter your real key or call POST /api/v1/web-search-providers/{id}/test to exercise the saved credential")
}
logger.Infof(ctx, "[WebSearch][Test] testing provider type=%s", providerType)
searchProvider, err := h.registry.CreateProvider(providerType, params)
if err != nil {