Files
Enterprise-Knowledge-Base/internal/application/service/web_search_provider.go
T
wizardchen 7643dd457e 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.
2026-05-17 15:27:52 +08:00

187 lines
6.1 KiB
Go

package service
import (
"context"
"fmt"
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// webSearchProviderService implements interfaces.WebSearchProviderService
type webSearchProviderService struct {
repo interfaces.WebSearchProviderRepository
}
// NewWebSearchProviderService creates a new web search provider service
func NewWebSearchProviderService(repo interfaces.WebSearchProviderRepository) interfaces.WebSearchProviderService {
return &webSearchProviderService{repo: repo}
}
// CreateProvider creates a new web search provider configuration.
func (s *webSearchProviderService) CreateProvider(ctx context.Context, provider *types.WebSearchProviderEntity) error {
if provider.TenantID == 0 {
return fmt.Errorf("tenant ID is required")
}
if !isValidProviderType(provider.Provider) {
return fmt.Errorf("invalid provider type: %s", provider.Provider)
}
if err := validateProviderParameters(provider.Provider, provider.Parameters); err != nil {
return err
}
if provider.IsDefault {
if err := s.repo.ClearDefault(ctx, provider.TenantID, ""); err != nil {
logger.Warnf(ctx, "Failed to clear default providers: %v", err)
}
}
logger.Infof(ctx, "Creating web search provider: tenant=%d, name=%s, type=%s", provider.TenantID, provider.Name, provider.Provider)
return s.repo.Create(ctx, provider)
}
// UpdateProvider updates an existing provider.
func (s *webSearchProviderService) UpdateProvider(ctx context.Context, provider *types.WebSearchProviderEntity) error {
if provider.TenantID == 0 {
return fmt.Errorf("tenant ID is required")
}
// Validate provider type if set
if provider.Provider != "" && !isValidProviderType(provider.Provider) {
return fmt.Errorf("invalid provider type: %s", provider.Provider)
}
if provider.IsDefault {
if err := s.repo.ClearDefault(ctx, provider.TenantID, provider.ID); err != nil {
logger.Warnf(ctx, "Failed to clear default providers: %v", err)
}
}
if provider.Provider != "" {
if err := validateProviderParameters(provider.Provider, provider.Parameters); err != nil {
return err
}
}
logger.Infof(ctx, "Updating web search provider: tenant=%d, id=%s", provider.TenantID, provider.ID)
return s.repo.Update(ctx, provider)
}
// UpdateProviderCredentials writes the api_key credential field. Web search
// providers are stateless from our side — every search call rebuilds a
// transport from current Parameters — so no cache invalidation is required.
func (s *webSearchProviderService) UpdateProviderCredentials(
ctx context.Context, tenantID uint64, id string, apiKey *string,
) (*types.WebSearchProviderEntity, error) {
existing, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil {
return nil, err
}
if existing == nil {
return nil, fmt.Errorf("web search provider not found")
}
if apiKey != nil && *apiKey != "" && *apiKey != existing.Parameters.APIKey {
existing.Parameters.APIKey = *apiKey
if err := s.repo.Update(ctx, existing); err != nil {
return nil, err
}
logger.Infof(ctx, "WebSearch provider credentials updated: tenant=%d id=%s", tenantID, id)
}
return existing, nil
}
// ClearProviderCredential clears the api_key credential. Idempotent.
func (s *webSearchProviderService) ClearProviderCredential(
ctx context.Context, tenantID uint64, id, field string,
) error {
if field != "api_key" {
return fmt.Errorf("unknown credential field: %s", field)
}
existing, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil {
return err
}
if existing == nil {
return fmt.Errorf("web search provider not found")
}
if existing.Parameters.APIKey == "" {
return nil
}
existing.Parameters.APIKey = ""
if err := s.repo.Update(ctx, existing); err != nil {
return err
}
logger.Infof(ctx, "WebSearch provider credential cleared by user: tenant=%d id=%s field=%s", tenantID, id, field)
return nil
}
// DeleteProvider deletes a provider by tenant + id.
func (s *webSearchProviderService) DeleteProvider(ctx context.Context, tenantID uint64, id string) error {
logger.Infof(ctx, "Deleting web search provider: tenant=%d, id=%s", tenantID, id)
return s.repo.Delete(ctx, tenantID, id)
}
// isValidProviderType checks if the given provider type is supported
func isValidProviderType(provider types.WebSearchProviderType) bool {
switch provider {
case types.WebSearchProviderTypeBing,
types.WebSearchProviderTypeGoogle,
types.WebSearchProviderTypeDuckDuckGo,
types.WebSearchProviderTypeTavily,
types.WebSearchProviderTypeOllama,
types.WebSearchProviderTypeBaidu,
types.WebSearchProviderTypeSearxng:
return true
default:
return false
}
}
// validateProviderParameters validates required parameters for each provider type
func validateProviderParameters(provider types.WebSearchProviderType, params types.WebSearchProviderParameters) error {
switch provider {
case types.WebSearchProviderTypeBing:
if params.APIKey == "" {
return fmt.Errorf("API key is required for Bing provider")
}
case types.WebSearchProviderTypeGoogle:
if params.APIKey == "" {
return fmt.Errorf("API key is required for Google provider")
}
if params.EngineID == "" {
return fmt.Errorf("engine ID is required for Google provider")
}
case types.WebSearchProviderTypeTavily:
if params.APIKey == "" {
return fmt.Errorf("API key is required for Tavily provider")
}
case types.WebSearchProviderTypeOllama:
if params.APIKey == "" {
return fmt.Errorf("API key is required for Ollama provider")
}
case types.WebSearchProviderTypeBaidu:
if params.APIKey == "" {
return fmt.Errorf("API key is required for Baidu provider")
}
case types.WebSearchProviderTypeDuckDuckGo:
// No API key required
case types.WebSearchProviderTypeSearxng:
if err := infra_web_search.ValidateSearxngBaseURL(params.BaseURL); err != nil {
return err
}
}
if err := validateOptionalProxyURL(params.ProxyURL); err != nil {
return err
}
return nil
}
func validateOptionalProxyURL(proxyURL string) error {
return infra_web_search.ValidateProxyURL(proxyURL)
}