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:
@@ -155,31 +155,27 @@ func (s *DataSourceService) UpdateDataSource(ctx context.Context, ds *types.Data
|
||||
return nil, datasource.ErrDataSourceInvalid
|
||||
}
|
||||
|
||||
// Apply write-only secret merge semantics to the Config jsonb:
|
||||
// empty / redacted credential strings preserve existing values,
|
||||
// ClearCredentials wipes the whole map, other values replace. This
|
||||
// blocks the NELO-1299-style round-trip bug where a frontend that
|
||||
// echoed back the redacted placeholder would overwrite real secrets.
|
||||
//
|
||||
// We also remember the parsed configs for the post-merge "changed?"
|
||||
// comparison — a raw-bytes compare against ds.Config is unreliable
|
||||
// because Go map iteration order makes the re-serialized JSON's key
|
||||
// ordering nondeterministic, causing string(merged) != string(existing)
|
||||
// to spuriously trip every time.
|
||||
// Credentials NEVER flow through this endpoint — they live behind the
|
||||
// /credentials subresource. Force-preserve the stored credentials map
|
||||
// regardless of what the body says. Log a warning if a stale caller
|
||||
// passes one so we can spot them and migrate later. Non-credential
|
||||
// fields of Config (Type / ResourceIDs / Settings) flow through.
|
||||
var mergedCfg, existingParsedCfg *types.DataSourceConfig
|
||||
if len(ds.Config) > 0 {
|
||||
incomingCfg, parseIncErr := ds.ParseConfig()
|
||||
existingCfg, parseExErr := existing.ParseConfig()
|
||||
if parseIncErr == nil && parseExErr == nil && incomingCfg != nil {
|
||||
baseExisting := types.DataSourceConfig{}
|
||||
if existingCfg != nil {
|
||||
baseExisting = *existingCfg
|
||||
}
|
||||
if incomingCfg.ClearCredentials {
|
||||
logger.Infof(ctx, "DataSource credentials cleared by user: id=%s",
|
||||
if incomingCfg.HasCredentials() {
|
||||
logger.Warnf(ctx,
|
||||
"deprecated: credentials in PUT /datasource/%s body are ignored; use PUT /credentials instead",
|
||||
secutils.SanitizeForLog(ds.ID))
|
||||
}
|
||||
merged := incomingCfg.MergeUpdate(baseExisting)
|
||||
merged := *incomingCfg
|
||||
if existingCfg != nil {
|
||||
merged.Credentials = existingCfg.Credentials
|
||||
} else {
|
||||
merged.Credentials = nil
|
||||
}
|
||||
if blob, err := merged.ToJSON(); err == nil {
|
||||
ds.Config = blob
|
||||
}
|
||||
@@ -188,22 +184,16 @@ func (s *DataSourceService) UpdateDataSource(ctx context.Context, ds *types.Data
|
||||
}
|
||||
}
|
||||
|
||||
// Validate new configuration if changed. Compare parsed structures to
|
||||
// avoid re-running (potentially expensive) OAuth / live-connection
|
||||
// validators on every update that only re-orders JSON keys.
|
||||
//
|
||||
// Skip validation entirely when the user is explicitly revoking
|
||||
// credentials (ClearCredentials=true). Live validators (e.g. Notion's
|
||||
// /me API) require a working secret by definition; trying to validate
|
||||
// after a wipe would always fail and leave the row un-cleared, defeating
|
||||
// the whole point of the "Remove all credentials" affordance.
|
||||
// Validate new configuration if non-credential fields changed. Skip
|
||||
// when there are no stored credentials yet (validators would fail with
|
||||
// no token to call the live API) and when the parsed config is
|
||||
// structurally identical.
|
||||
configActuallyChanged := true
|
||||
if mergedCfg != nil && existingParsedCfg != nil {
|
||||
configActuallyChanged = !reflect.DeepEqual(*mergedCfg, *existingParsedCfg)
|
||||
}
|
||||
clearingCredentials := mergedCfg != nil && !mergedCfg.HasCredentials() &&
|
||||
existingParsedCfg != nil && existingParsedCfg.HasCredentials()
|
||||
if !clearingCredentials && (ds.Type != existing.Type || configActuallyChanged) {
|
||||
hasCreds := mergedCfg != nil && mergedCfg.HasCredentials()
|
||||
if hasCreds && (ds.Type != existing.Type || configActuallyChanged) {
|
||||
if err := s.validateDataSourceConfig(ctx, ds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -223,6 +213,78 @@ func (s *DataSourceService) UpdateDataSource(ctx context.Context, ds *types.Data
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
// UpdateDataSourceCredentials replaces the connector credential map. This is
|
||||
// a single atomic write; the previous credential set is discarded entirely
|
||||
// (callers cannot patch individual keys because half-configured connector
|
||||
// auth is meaningless). After persisting, the live connection is validated
|
||||
// so the caller learns immediately if the new credentials are wrong.
|
||||
func (s *DataSourceService) UpdateDataSourceCredentials(
|
||||
ctx context.Context, id string, credentials map[string]interface{},
|
||||
) (*types.DataSource, error) {
|
||||
if id == "" {
|
||||
return nil, datasource.ErrDataSourceInvalid
|
||||
}
|
||||
existing, err := s.dsRepo.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parsed, err := existing.ParseConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parsed == nil {
|
||||
parsed = &types.DataSourceConfig{Type: existing.Type}
|
||||
}
|
||||
parsed.Credentials = credentials
|
||||
blob, err := parsed.ToJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
existing.Config = blob
|
||||
|
||||
// Run live validation now that the credentials are in place — surfaces
|
||||
// "wrong token" feedback immediately to the user instead of waiting for
|
||||
// the next scheduled sync.
|
||||
if err := s.validateDataSourceConfig(ctx, existing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.dsRepo.Update(ctx, existing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "DataSource credentials updated: id=%s", secutils.SanitizeForLog(id))
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// ClearDataSourceCredentials wipes the connector credential map without
|
||||
// touching any other config field. Idempotent.
|
||||
func (s *DataSourceService) ClearDataSourceCredentials(ctx context.Context, id string) error {
|
||||
if id == "" {
|
||||
return datasource.ErrDataSourceInvalid
|
||||
}
|
||||
existing, err := s.dsRepo.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parsed, err := existing.ParseConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if parsed == nil || !parsed.HasCredentials() {
|
||||
return nil
|
||||
}
|
||||
parsed.Credentials = nil
|
||||
blob, err := parsed.ToJSON()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
existing.Config = blob
|
||||
if err := s.dsRepo.Update(ctx, existing); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "DataSource credentials cleared by user: id=%s", secutils.SanitizeForLog(id))
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteDataSource deletes a data source (soft delete)
|
||||
func (s *DataSourceService) DeleteDataSource(ctx context.Context, id string) error {
|
||||
// Verify data source exists
|
||||
|
||||
@@ -57,10 +57,11 @@ func (s *mcpServiceService) CreateMCPService(ctx context.Context, service *types
|
||||
|
||||
// GetMCPServiceByID retrieves an MCP service by ID.
|
||||
//
|
||||
// Sensitive fields are redacted before the service is returned so that the
|
||||
// single-resource GET behaves consistently with the list endpoint. Builtin
|
||||
// services still route through HideSensitiveInfo which clears additional
|
||||
// fields (URL, Headers, EnvVars, StdioConfig) on top of the redaction.
|
||||
// Returns the raw stored entity including any AuthConfig credentials in plain
|
||||
// form. Callers MUST convert to dto.MCPServiceResponse (which strips secret
|
||||
// fields by construction) before serializing to a response body. Internal
|
||||
// callers (e.g. MCP client construction, credential metadata derivation) need
|
||||
// the unredacted form to function correctly.
|
||||
func (s *mcpServiceService) GetMCPServiceByID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
@@ -75,33 +76,19 @@ func (s *mcpServiceService) GetMCPServiceByID(
|
||||
if service == nil {
|
||||
return nil, fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
if service.IsBuiltin {
|
||||
return service.HideSensitiveInfo(), nil
|
||||
}
|
||||
service.RedactSensitiveData()
|
||||
return service, nil
|
||||
}
|
||||
|
||||
// ListMCPServices lists all MCP services for a tenant
|
||||
// ListMCPServices lists all MCP services for a tenant.
|
||||
//
|
||||
// Same contract as GetMCPServiceByID — returns raw entities; handlers MUST
|
||||
// convert to dto.MCPServiceResponse before responding.
|
||||
func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) {
|
||||
services, err := s.mcpServiceRepo.List(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to list MCP services: %v", err)
|
||||
return nil, fmt.Errorf("failed to list MCP services: %w", err)
|
||||
}
|
||||
|
||||
// Redact sensitive data before returning so secrets never leave the server.
|
||||
// Builtin services go through HideSensitiveInfo which clears additional
|
||||
// fields (URL, headers, env_vars, stdio_config) beyond redaction.
|
||||
for i, service := range services {
|
||||
if service.IsBuiltin {
|
||||
services[i] = service.HideSensitiveInfo()
|
||||
} else {
|
||||
service.RedactSensitiveData()
|
||||
}
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
@@ -158,6 +145,11 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
|
||||
// this because the in-place merge below reassigns pointer fields such as
|
||||
// existing.URL = service.URL, after which any post-merge comparison
|
||||
// between service.URL and existing.URL would trivially match.
|
||||
//
|
||||
// AuthConfig is intentionally NOT snapshotted/compared here — credential
|
||||
// changes now flow through the dedicated /credentials subresource which
|
||||
// handles its own CloseClient call. Main PUT does not accept secret
|
||||
// fields (see handler comment on UpdateMCPService).
|
||||
preURL := ""
|
||||
preURLSet := existing.URL != nil
|
||||
if preURLSet {
|
||||
@@ -171,38 +163,19 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
|
||||
preStdioArgs = append([]string(nil), existing.StdioConfig.Args...)
|
||||
}
|
||||
preTransportType := existing.TransportType
|
||||
preAuthSet := existing.AuthConfig != nil
|
||||
var preAuthAPIKey, preAuthToken string
|
||||
var preAuthHeaders map[string]string
|
||||
if preAuthSet {
|
||||
preAuthAPIKey = existing.AuthConfig.APIKey
|
||||
preAuthToken = existing.AuthConfig.Token
|
||||
// Copy the map so subsequent mutations via merged.CustomHeaders don't
|
||||
// alias into the snapshot.
|
||||
if existing.AuthConfig.CustomHeaders != nil {
|
||||
preAuthHeaders = make(map[string]string, len(existing.AuthConfig.CustomHeaders))
|
||||
maps.Copy(preAuthHeaders, existing.AuthConfig.CustomHeaders)
|
||||
}
|
||||
preHeaders := map[string]string{}
|
||||
if existing.AuthConfig != nil && existing.AuthConfig.CustomHeaders != nil {
|
||||
maps.Copy(preHeaders, existing.AuthConfig.CustomHeaders)
|
||||
}
|
||||
|
||||
// AuthConfig merge is applied unconditionally (both partial and full
|
||||
// updates), so a request body like {"clear_token": true} by itself is
|
||||
// honored instead of being silently dropped when Name is empty.
|
||||
// Audit-log explicit clear operations before the merge absorbs the flag.
|
||||
if service.AuthConfig != nil {
|
||||
if service.AuthConfig.ClearAPIKey {
|
||||
logger.GetLogger(ctx).Infof(
|
||||
"MCP auth cleared by user: id=%s field=api_key",
|
||||
secutils.SanitizeForLog(service.ID),
|
||||
)
|
||||
// CustomHeaders flows through main PUT (it's structural, not a secret) —
|
||||
// nil preserves, non-nil replaces. Other AuthConfig fields (APIKey/Token)
|
||||
// are never accepted via main PUT; the handler strips them up front.
|
||||
if service.AuthConfig != nil && service.AuthConfig.CustomHeaders != nil {
|
||||
if existing.AuthConfig == nil {
|
||||
existing.AuthConfig = &types.MCPAuthConfig{}
|
||||
}
|
||||
if service.AuthConfig.ClearToken {
|
||||
logger.GetLogger(ctx).Infof(
|
||||
"MCP auth cleared by user: id=%s field=token",
|
||||
secutils.SanitizeForLog(service.ID),
|
||||
)
|
||||
}
|
||||
existing.AuthConfig = service.AuthConfig.MergeUpdate(existing.AuthConfig)
|
||||
existing.AuthConfig.CustomHeaders = service.AuthConfig.CustomHeaders
|
||||
}
|
||||
|
||||
// Merge updates: only update fields that are provided (non-zero or explicitly set)
|
||||
@@ -212,7 +185,7 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
|
||||
// or if we're updating other fields (indicating full update)
|
||||
// For enabled field, we'll update it if this is a partial update (only enabled) or if it's explicitly set
|
||||
if service.Name == "" {
|
||||
// Partial update - only update enabled field (AuthConfig already merged above).
|
||||
// Partial update - only update enabled field.
|
||||
existing.Enabled = service.Enabled
|
||||
} else {
|
||||
// Full update - update all fields including enabled
|
||||
@@ -250,12 +223,14 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
|
||||
}
|
||||
|
||||
// Check if critical configuration changed (URL / StdioConfig / transport
|
||||
// type / auth config). Comparisons MUST be against the pre-merge
|
||||
// type / custom headers). Comparisons MUST be against the pre-merge
|
||||
// snapshots captured above — after the in-place merge, service.URL and
|
||||
// existing.URL point to the same memory, making any post-merge compare
|
||||
// vacuously equal. Saving the dialog without touching these fields must
|
||||
// not recycle the live MCP client connection (that's the NELO-1299
|
||||
// regression we're preventing).
|
||||
// vacuously equal.
|
||||
//
|
||||
// AuthConfig API key / token changes do NOT go through this path; they
|
||||
// are handled by the /credentials subresource which triggers CloseClient
|
||||
// inline.
|
||||
configChanged := false
|
||||
currURLSet := existing.URL != nil
|
||||
switch {
|
||||
@@ -275,13 +250,11 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
|
||||
if existing.TransportType != preTransportType {
|
||||
configChanged = true
|
||||
}
|
||||
currAuthSet := existing.AuthConfig != nil
|
||||
switch {
|
||||
case currAuthSet != preAuthSet:
|
||||
configChanged = true
|
||||
case currAuthSet && (existing.AuthConfig.APIKey != preAuthAPIKey ||
|
||||
existing.AuthConfig.Token != preAuthToken ||
|
||||
!maps.Equal(existing.AuthConfig.CustomHeaders, preAuthHeaders)):
|
||||
currHeaders := map[string]string{}
|
||||
if existing.AuthConfig != nil && existing.AuthConfig.CustomHeaders != nil {
|
||||
currHeaders = existing.AuthConfig.CustomHeaders
|
||||
}
|
||||
if !maps.Equal(currHeaders, preHeaders) {
|
||||
configChanged = true
|
||||
}
|
||||
name := secutils.SanitizeForLog(existing.Name)
|
||||
@@ -438,6 +411,114 @@ func (s *mcpServiceService) GetMCPServiceTools(
|
||||
return tools, nil
|
||||
}
|
||||
|
||||
// UpdateMCPCredentials writes one or more credential fields and recycles any
|
||||
// active client connection so the next upstream call uses the new credential.
|
||||
//
|
||||
// Implementation notes:
|
||||
// - apiKey == nil and token == nil → no-op, returns current state.
|
||||
// - apiKey == &"" → explicit empty string; treated as no-op because clearing
|
||||
// is the dedicated ClearMCPCredential path. The handler enforces this
|
||||
// contract by accepting empty as no-op too; this is defense-in-depth.
|
||||
// - apiKey == &"sk-..." → replaces stored value.
|
||||
// - Builtin services cannot have credentials updated (mirrors the
|
||||
// UpdateMCPService restriction).
|
||||
// - Always re-fetches existing AuthConfig before merge to avoid clobbering
|
||||
// CustomHeaders or the unrelated credential field.
|
||||
func (s *mcpServiceService) UpdateMCPCredentials(
|
||||
ctx context.Context, tenantID uint64, id string, apiKey *string, token *string,
|
||||
) (*types.MCPService, error) {
|
||||
existing, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
if existing == nil {
|
||||
return nil, fmt.Errorf("MCP service not found")
|
||||
}
|
||||
if existing.IsBuiltin {
|
||||
return nil, fmt.Errorf("builtin MCP services cannot have credentials modified")
|
||||
}
|
||||
|
||||
if existing.AuthConfig == nil {
|
||||
existing.AuthConfig = &types.MCPAuthConfig{}
|
||||
}
|
||||
changed := false
|
||||
if apiKey != nil && *apiKey != "" && *apiKey != existing.AuthConfig.APIKey {
|
||||
existing.AuthConfig.APIKey = *apiKey
|
||||
changed = true
|
||||
}
|
||||
if token != nil && *token != "" && *token != existing.AuthConfig.Token {
|
||||
existing.AuthConfig.Token = *token
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
existing.UpdatedAt = time.Now()
|
||||
if err := s.mcpServiceRepo.Update(ctx, existing); err != nil {
|
||||
return nil, fmt.Errorf("failed to update MCP service: %w", err)
|
||||
}
|
||||
|
||||
// Credential changed → recycle client so the next call reconnects.
|
||||
s.mcpManager.CloseClient(id)
|
||||
logger.GetLogger(ctx).Infof(
|
||||
"MCP credentials updated, connection closed: %s (ID: %s)",
|
||||
secutils.SanitizeForLog(existing.Name), id,
|
||||
)
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// ClearMCPCredential removes a single credential field. Idempotent: clearing
|
||||
// an already-empty field returns nil without writing or reconnecting.
|
||||
func (s *mcpServiceService) ClearMCPCredential(
|
||||
ctx context.Context, tenantID uint64, id, field string,
|
||||
) error {
|
||||
existing, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
if existing == nil {
|
||||
return fmt.Errorf("MCP service not found")
|
||||
}
|
||||
if existing.IsBuiltin {
|
||||
return fmt.Errorf("builtin MCP services cannot have credentials modified")
|
||||
}
|
||||
if existing.AuthConfig == nil {
|
||||
return nil // nothing to clear
|
||||
}
|
||||
|
||||
changed := false
|
||||
switch field {
|
||||
case "api_key":
|
||||
if existing.AuthConfig.APIKey != "" {
|
||||
existing.AuthConfig.APIKey = ""
|
||||
changed = true
|
||||
}
|
||||
case "token":
|
||||
if existing.AuthConfig.Token != "" {
|
||||
existing.AuthConfig.Token = ""
|
||||
changed = true
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown credential field: %s", field)
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
|
||||
existing.UpdatedAt = time.Now()
|
||||
if err := s.mcpServiceRepo.Update(ctx, existing); err != nil {
|
||||
return fmt.Errorf("failed to update MCP service: %w", err)
|
||||
}
|
||||
|
||||
s.mcpManager.CloseClient(id)
|
||||
logger.GetLogger(ctx).Infof(
|
||||
"MCP credential cleared by user: id=%s field=%s, connection closed",
|
||||
secutils.SanitizeForLog(id), field,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMCPServiceResources retrieves the list of resources from an MCP service
|
||||
func (s *mcpServiceService) GetMCPServiceResources(
|
||||
ctx context.Context,
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
@@ -11,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
// fakeMCPRepo is a minimal in-memory implementation of
|
||||
// interfaces.MCPServiceRepository for testing the service-layer merge logic
|
||||
// interfaces.MCPServiceRepository for testing the service-layer logic
|
||||
// without depending on the database.
|
||||
type fakeMCPRepo struct {
|
||||
store map[string]*types.MCPService
|
||||
@@ -22,7 +23,7 @@ func newFakeMCPRepo() *fakeMCPRepo {
|
||||
}
|
||||
|
||||
func (r *fakeMCPRepo) Create(_ context.Context, s *types.MCPService) error {
|
||||
r.store[s.ID] = s
|
||||
r.store[s.ID] = cloneService(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -31,25 +32,21 @@ func (r *fakeMCPRepo) GetByID(_ context.Context, _ uint64, id string) (*types.MC
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
// return a deep-ish copy so service-layer mutations to the returned value
|
||||
// do not leak back into the fake store, mirroring how GORM produces a
|
||||
// fresh struct per query
|
||||
cp := *s
|
||||
if s.AuthConfig != nil {
|
||||
ac := *s.AuthConfig
|
||||
cp.AuthConfig = &ac
|
||||
}
|
||||
if s.AdvancedConfig != nil {
|
||||
adv := *s.AdvancedConfig
|
||||
cp.AdvancedConfig = &adv
|
||||
}
|
||||
return &cp, nil
|
||||
// Return a copy so service-layer mutations don't leak back into the
|
||||
// store, mirroring how GORM returns a fresh struct per query.
|
||||
return cloneService(s), nil
|
||||
}
|
||||
|
||||
func cloneService(s *types.MCPService) *types.MCPService {
|
||||
cp := *s
|
||||
if s.AuthConfig != nil {
|
||||
ac := *s.AuthConfig
|
||||
if s.AuthConfig.CustomHeaders != nil {
|
||||
ac.CustomHeaders = make(map[string]string, len(s.AuthConfig.CustomHeaders))
|
||||
for k, v := range s.AuthConfig.CustomHeaders {
|
||||
ac.CustomHeaders[k] = v
|
||||
}
|
||||
}
|
||||
cp.AuthConfig = &ac
|
||||
}
|
||||
if s.AdvancedConfig != nil {
|
||||
@@ -82,7 +79,7 @@ func (r *fakeMCPRepo) ListByIDs(_ context.Context, _ uint64, ids []string) ([]*t
|
||||
}
|
||||
|
||||
func (r *fakeMCPRepo) Update(_ context.Context, s *types.MCPService) error {
|
||||
r.store[s.ID] = s
|
||||
r.store[s.ID] = cloneService(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -91,8 +88,6 @@ func (r *fakeMCPRepo) Delete(_ context.Context, _ uint64, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// seedService plants a service with the given auth credentials into the fake
|
||||
// repo and returns the service ID. Convenience helper used by every test.
|
||||
func seedService(t *testing.T, repo *fakeMCPRepo, apiKey, token string) string {
|
||||
t.Helper()
|
||||
s := &types.MCPService{
|
||||
@@ -111,8 +106,7 @@ func seedService(t *testing.T, repo *fakeMCPRepo, apiKey, token string) string {
|
||||
}
|
||||
|
||||
// newTestService wires up a mcpServiceService with a fresh fake repo and a
|
||||
// real (empty) MCPManager. CloseClient on an empty manager is a no-op, so
|
||||
// tests can safely exercise the configChanged code paths.
|
||||
// real (empty) MCPManager. CloseClient on an empty manager is a no-op.
|
||||
func newTestService() (*mcpServiceService, *fakeMCPRepo) {
|
||||
repo := newFakeMCPRepo()
|
||||
svc := &mcpServiceService{
|
||||
@@ -122,253 +116,54 @@ func newTestService() (*mcpServiceService, *fakeMCPRepo) {
|
||||
return svc, repo
|
||||
}
|
||||
|
||||
// buildFullUpdate returns an UpdateMCPService input that exercises the
|
||||
// "full update" branch (service.Name is non-empty), which is the branch that
|
||||
// actually merges AuthConfig.
|
||||
func buildFullUpdate(id string, auth *types.MCPAuthConfig) *types.MCPService {
|
||||
return &types.MCPService{
|
||||
// ---- UpdateMCPService: must not touch APIKey/Token even when caller sends them ----
|
||||
|
||||
// The handler now strips api_key/token from the main PUT body, but defense
|
||||
// in depth: if a future caller (CLI / test / misconfigured proxy) still
|
||||
// passes auth_config with secret fields, UpdateMCPService must NOT clobber
|
||||
// the stored credentials. Credentials live behind the dedicated subresource.
|
||||
func TestUpdateMCPService_DoesNotTouchSecretsEvenIfPassed(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := &types.MCPService{
|
||||
ID: id,
|
||||
TenantID: 1,
|
||||
Name: "test", // non-empty → full update branch
|
||||
Name: "renamed",
|
||||
Enabled: true,
|
||||
TransportType: types.MCPTransportSSE,
|
||||
AuthConfig: auth,
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateMCPService_PreservesSecretsOnEmptyOrRedacted(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("nil AuthConfig preserves existing", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, nil)
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey)
|
||||
assert.Equal(t, "stored-token", got.AuthConfig.Token)
|
||||
})
|
||||
|
||||
t.Run("empty string preserves existing", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{APIKey: "", Token: ""})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey)
|
||||
assert.Equal(t, "stored-token", got.AuthConfig.Token)
|
||||
})
|
||||
|
||||
t.Run("redacted placeholder preserves existing (NELO-1299 round-trip)", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
APIKey: types.RedactedSecretPlaceholder,
|
||||
Token: types.RedactedSecretPlaceholder,
|
||||
})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey)
|
||||
assert.Equal(t, "stored-token", got.AuthConfig.Token)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateMCPService_ReplacesOnExplicitValue(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
APIKey: "new-api",
|
||||
Token: "new-token",
|
||||
})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "new-api", got.AuthConfig.APIKey)
|
||||
assert.Equal(t, "new-token", got.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestUpdateMCPService_MixedFields(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
// Replace token only, leave api_key as redacted placeholder → preserve
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
APIKey: types.RedactedSecretPlaceholder,
|
||||
Token: "new-token",
|
||||
})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey, "api_key should be preserved")
|
||||
assert.Equal(t, "new-token", got.AuthConfig.Token, "token should be replaced")
|
||||
}
|
||||
|
||||
func TestUpdateMCPService_ClearFlags(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("ClearToken removes stored token, preserves api_key", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
APIKey: types.RedactedSecretPlaceholder,
|
||||
ClearToken: true,
|
||||
})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey)
|
||||
assert.Empty(t, got.AuthConfig.Token)
|
||||
})
|
||||
|
||||
t.Run("ClearAPIKey removes stored api_key, preserves token", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
ClearAPIKey: true,
|
||||
Token: types.RedactedSecretPlaceholder,
|
||||
})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Empty(t, got.AuthConfig.APIKey)
|
||||
assert.Equal(t, "stored-token", got.AuthConfig.Token)
|
||||
})
|
||||
|
||||
t.Run("ClearToken takes precedence over submitted value", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
Token: "will-be-ignored",
|
||||
ClearToken: true,
|
||||
})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Empty(t, got.AuthConfig.Token)
|
||||
})
|
||||
|
||||
t.Run("clear flags are not persisted", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{ClearToken: true})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
require.NotNil(t, got.AuthConfig)
|
||||
assert.False(t, got.AuthConfig.ClearToken, "ClearToken must not be persisted")
|
||||
assert.False(t, got.AuthConfig.ClearAPIKey, "ClearAPIKey must not be persisted")
|
||||
})
|
||||
|
||||
t.Run("clear on already-empty field is a no-op", func(t *testing.T) {
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "") // token not set
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{ClearToken: true})
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey)
|
||||
assert.Empty(t, got.AuthConfig.Token)
|
||||
})
|
||||
}
|
||||
|
||||
func TestListMCPServices_RedactsSecrets(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
seedService(t, repo, "real-api", "real-token")
|
||||
|
||||
got, err := svc.ListMCPServices(ctx, 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, types.RedactedSecretPlaceholder, got[0].AuthConfig.APIKey)
|
||||
assert.Equal(t, types.RedactedSecretPlaceholder, got[0].AuthConfig.Token)
|
||||
|
||||
// And the underlying store is untouched
|
||||
stored := repo.store["svc-test"]
|
||||
assert.Equal(t, "real-api", stored.AuthConfig.APIKey)
|
||||
assert.Equal(t, "real-token", stored.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestGetMCPServiceByID_RedactsSecrets(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "real-api", "real-token")
|
||||
|
||||
got, err := svc.GetMCPServiceByID(ctx, 1, id)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.AuthConfig)
|
||||
assert.Equal(t, types.RedactedSecretPlaceholder, got.AuthConfig.APIKey)
|
||||
assert.Equal(t, types.RedactedSecretPlaceholder, got.AuthConfig.Token)
|
||||
|
||||
// underlying store unchanged
|
||||
stored := repo.store[id]
|
||||
assert.Equal(t, "real-api", stored.AuthConfig.APIKey)
|
||||
assert.Equal(t, "real-token", stored.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestGetMCPServiceByID_EmptySecretsStayEmpty(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "", "") // both empty
|
||||
|
||||
got, err := svc.GetMCPServiceByID(ctx, 1, id)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.AuthConfig)
|
||||
assert.Empty(t, got.AuthConfig.APIKey, "empty secret must stay empty, not be redacted")
|
||||
assert.Empty(t, got.AuthConfig.Token)
|
||||
}
|
||||
|
||||
// Partial update: service.Name == "" is interpreted as "only touch enabled".
|
||||
// A clear flag sent in such a body was previously dropped; the refactor now
|
||||
// merges AuthConfig unconditionally so single-field clears round-trip.
|
||||
func TestUpdateMCPService_PartialUpdateHonorsClearFlag(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
// Partial update body: no name, enabled flipped, ClearToken set.
|
||||
upd := &types.MCPService{
|
||||
ID: id,
|
||||
TenantID: 1,
|
||||
Enabled: true, // keep enabled, but simulate a "flag only" request
|
||||
// Hostile body: tries to overwrite both secrets via main PUT.
|
||||
AuthConfig: &types.MCPAuthConfig{
|
||||
ClearToken: true,
|
||||
APIKey: "should-not-overwrite",
|
||||
Token: "should-not-overwrite-either",
|
||||
},
|
||||
}
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey, "APIKey preserved in partial update")
|
||||
assert.Empty(t, got.AuthConfig.Token, "ClearToken must clear Token even in partial update")
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey,
|
||||
"main PUT must not overwrite stored APIKey under any circumstance")
|
||||
assert.Equal(t, "stored-token", got.AuthConfig.Token,
|
||||
"main PUT must not overwrite stored Token under any circumstance")
|
||||
assert.Equal(t, "renamed", got.Name, "non-secret field updates still apply")
|
||||
}
|
||||
|
||||
// CustomHeaders: nil means "no change" (preserve existing). Sending a
|
||||
// non-nil (including empty) map replaces. Previously the merge always
|
||||
// overwrote, silently wiping headers on any auth_config-bearing request.
|
||||
func TestUpdateMCPService_CustomHeadersPreserveOnNil(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
// Seed with custom headers.
|
||||
repo.store[id].AuthConfig.CustomHeaders = map[string]string{"X-Tenant": "acme"}
|
||||
|
||||
// Update with AuthConfig but nil CustomHeaders → preserve.
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
Token: "new-token",
|
||||
})
|
||||
upd := &types.MCPService{
|
||||
ID: id,
|
||||
TenantID: 1,
|
||||
Name: "test",
|
||||
Enabled: true,
|
||||
TransportType: types.MCPTransportSSE,
|
||||
// AuthConfig present but CustomHeaders nil → preserve.
|
||||
AuthConfig: &types.MCPAuthConfig{},
|
||||
}
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
@@ -382,14 +177,181 @@ func TestUpdateMCPService_CustomHeadersReplaceOnNonNil(t *testing.T) {
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
repo.store[id].AuthConfig.CustomHeaders = map[string]string{"X-Tenant": "acme"}
|
||||
|
||||
upd := buildFullUpdate(id, &types.MCPAuthConfig{
|
||||
APIKey: types.RedactedSecretPlaceholder,
|
||||
Token: types.RedactedSecretPlaceholder,
|
||||
CustomHeaders: map[string]string{"X-Replaced": "yes"},
|
||||
})
|
||||
upd := &types.MCPService{
|
||||
ID: id,
|
||||
TenantID: 1,
|
||||
Name: "test",
|
||||
Enabled: true,
|
||||
TransportType: types.MCPTransportSSE,
|
||||
AuthConfig: &types.MCPAuthConfig{
|
||||
CustomHeaders: map[string]string{"X-Replaced": "yes"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, svc.UpdateMCPService(ctx, upd))
|
||||
|
||||
got := repo.store[id]
|
||||
assert.Equal(t, map[string]string{"X-Replaced": "yes"}, got.AuthConfig.CustomHeaders,
|
||||
"non-nil CustomHeaders must replace the stored map")
|
||||
}
|
||||
|
||||
// ---- UpdateMCPCredentials: write path ----
|
||||
|
||||
func TestUpdateMCPCredentials_WritesAPIKey(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "", "")
|
||||
|
||||
newKey := "fresh-api-key"
|
||||
got, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.AuthConfig)
|
||||
assert.Equal(t, "fresh-api-key", got.AuthConfig.APIKey)
|
||||
assert.Empty(t, got.AuthConfig.Token, "untouched field stays untouched")
|
||||
|
||||
stored := repo.store[id]
|
||||
assert.Equal(t, "fresh-api-key", stored.AuthConfig.APIKey, "persisted")
|
||||
}
|
||||
|
||||
func TestUpdateMCPCredentials_NilPointerIsNoop(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
got, err := svc.UpdateMCPCredentials(ctx, 1, id, nil, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey)
|
||||
assert.Equal(t, "stored-token", got.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestUpdateMCPCredentials_EmptyStringIsNoop(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
empty := ""
|
||||
got, err := svc.UpdateMCPCredentials(ctx, 1, id, &empty, &empty)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "stored-api", got.AuthConfig.APIKey,
|
||||
"empty string is treated as no-op; clearing goes through ClearMCPCredential")
|
||||
assert.Equal(t, "stored-token", got.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestUpdateMCPCredentials_ReplacesExisting(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "old-api", "old-token")
|
||||
|
||||
newKey, newTok := "new-api", "new-tok"
|
||||
got, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, &newTok)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "new-api", got.AuthConfig.APIKey)
|
||||
assert.Equal(t, "new-tok", got.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestUpdateMCPCredentials_RejectsBuiltin(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "")
|
||||
repo.store[id].IsBuiltin = true
|
||||
|
||||
newKey := "anything"
|
||||
_, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, strings.ToLower(err.Error()), "builtin")
|
||||
}
|
||||
|
||||
func TestUpdateMCPCredentials_ServiceNotFound(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, _ := newTestService()
|
||||
newKey := "x"
|
||||
_, err := svc.UpdateMCPCredentials(ctx, 1, "nope", &newKey, nil)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
// ---- ClearMCPCredential ----
|
||||
|
||||
func TestClearMCPCredential_ClearsAPIKey(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
require.NoError(t, svc.ClearMCPCredential(ctx, 1, id, "api_key"))
|
||||
stored := repo.store[id]
|
||||
assert.Empty(t, stored.AuthConfig.APIKey)
|
||||
assert.Equal(t, "stored-token", stored.AuthConfig.Token, "other field untouched")
|
||||
}
|
||||
|
||||
func TestClearMCPCredential_ClearsToken(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "stored-token")
|
||||
|
||||
require.NoError(t, svc.ClearMCPCredential(ctx, 1, id, "token"))
|
||||
stored := repo.store[id]
|
||||
assert.Equal(t, "stored-api", stored.AuthConfig.APIKey)
|
||||
assert.Empty(t, stored.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestClearMCPCredential_IdempotentOnEmpty(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "") // token already empty
|
||||
|
||||
require.NoError(t, svc.ClearMCPCredential(ctx, 1, id, "token"),
|
||||
"clearing already-empty field must not error")
|
||||
stored := repo.store[id]
|
||||
assert.Equal(t, "stored-api", stored.AuthConfig.APIKey)
|
||||
assert.Empty(t, stored.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestClearMCPCredential_UnknownFieldErrors(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "")
|
||||
|
||||
err := svc.ClearMCPCredential(ctx, 1, id, "bogus")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "unknown")
|
||||
}
|
||||
|
||||
func TestClearMCPCredential_RejectsBuiltin(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "stored-api", "")
|
||||
repo.store[id].IsBuiltin = true
|
||||
|
||||
err := svc.ClearMCPCredential(ctx, 1, id, "api_key")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, strings.ToLower(err.Error()), "builtin")
|
||||
}
|
||||
|
||||
// ---- Service-layer Get/List: returns RAW entity (DTO handles redaction) ----
|
||||
|
||||
// After the credential-subresource refactor, the service-layer Get/List
|
||||
// return the entity unmodified. Handlers MUST convert via
|
||||
// dto.NewMCPServiceResponse, but the credentials handler depends on the
|
||||
// unredacted form to derive metadata (configured: bool).
|
||||
func TestGetMCPServiceByID_ReturnsRawCredentials(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
id := seedService(t, repo, "real-api", "real-token")
|
||||
|
||||
got, err := svc.GetMCPServiceByID(ctx, 1, id)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.AuthConfig)
|
||||
assert.Equal(t, "real-api", got.AuthConfig.APIKey,
|
||||
"service layer returns raw credentials; redaction is the DTO's job")
|
||||
assert.Equal(t, "real-token", got.AuthConfig.Token)
|
||||
}
|
||||
|
||||
func TestListMCPServices_ReturnsRawCredentials(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := newTestService()
|
||||
seedService(t, repo, "real-api", "real-token")
|
||||
|
||||
got, err := svc.ListMCPServices(ctx, 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "real-api", got[0].AuthConfig.APIKey)
|
||||
assert.Equal(t, "real-token", got[0].AuthConfig.Token)
|
||||
}
|
||||
|
||||
@@ -247,6 +247,84 @@ func (s *modelService) UpdateModel(ctx context.Context, model *types.Model) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateModelCredentials writes one or more credential fields on the model's
|
||||
// Parameters jsonb. Models are not pooled per-instance the way MCP clients
|
||||
// are (each call to GetEmbeddingModel/GetChatModel rebuilds the client from
|
||||
// the current Parameters), so no explicit cache invalidation is required —
|
||||
// the next call will pick up the new credential automatically.
|
||||
func (s *modelService) UpdateModelCredentials(
|
||||
ctx context.Context, id string, apiKey, appSecret *string,
|
||||
) (*types.Model, error) {
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
existing, err := s.repo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing == nil {
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
if existing.IsBuiltin {
|
||||
return nil, errors.New("builtin models cannot have credentials modified")
|
||||
}
|
||||
|
||||
changed := false
|
||||
if apiKey != nil && *apiKey != "" && *apiKey != existing.Parameters.APIKey {
|
||||
existing.Parameters.APIKey = *apiKey
|
||||
changed = true
|
||||
}
|
||||
if appSecret != nil && *appSecret != "" && *appSecret != existing.Parameters.AppSecret {
|
||||
existing.Parameters.AppSecret = *appSecret
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return existing, nil
|
||||
}
|
||||
if err := s.repo.Update(ctx, existing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Model credentials updated: id=%s", id)
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// ClearModelCredential removes a single credential field. Idempotent.
|
||||
func (s *modelService) ClearModelCredential(ctx context.Context, id, field string) error {
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
existing, err := s.repo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing == nil {
|
||||
return ErrModelNotFound
|
||||
}
|
||||
if existing.IsBuiltin {
|
||||
return errors.New("builtin models cannot have credentials modified")
|
||||
}
|
||||
|
||||
changed := false
|
||||
switch field {
|
||||
case "api_key":
|
||||
if existing.Parameters.APIKey != "" {
|
||||
existing.Parameters.APIKey = ""
|
||||
changed = true
|
||||
}
|
||||
case "app_secret":
|
||||
if existing.Parameters.AppSecret != "" {
|
||||
existing.Parameters.AppSecret = ""
|
||||
changed = true
|
||||
}
|
||||
default:
|
||||
return errors.New("unknown credential field: " + field)
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
if err := s.repo.Update(ctx, existing); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "Model credential cleared by user: id=%s field=%s", id, field)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteModel removes a model from the repository
|
||||
func (s *modelService) DeleteModel(ctx context.Context, id string) error {
|
||||
logger.Info(ctx, "Start deleting model")
|
||||
|
||||
@@ -71,6 +71,16 @@ func (s *stubModelService) DeleteModel(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubModelService) UpdateModelCredentials(
|
||||
context.Context, string, *string, *string,
|
||||
) (*types.Model, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *stubModelService) ClearModelCredential(context.Context, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubModelService) GetEmbeddingModel(context.Context, string) (embedding.Embedder, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -71,6 +71,55 @@ func (s *webSearchProviderService) UpdateProvider(ctx context.Context, provider
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user