WeKnora/internal/handler/dto/datasource.go

132 lines
5.2 KiB
Go
Raw Normal View History

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 07:09:30 +00:00
package dto
import (
"encoding/json"
"strings"
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 07:09:30 +00:00
"time"
"github.com/Tencent/WeKnora/internal/types"
)
// DataSourceResponse mirrors types.DataSource for response bodies, with the
// connector Credentials map stripped from the Config jsonb. Credential
// presence is exposed via the dedicated /credentials subresource.
//
// Unlike MCP / Model / WebSearch (which have a flat set of named credential
// fields), DataSource credentials are a per-connector atomic map — an OAuth
// token pair, a Confluence email+token bundle, etc. Splitting them at the
// field level would leave half-configured states that can't actually
// authenticate. The subresource therefore exposes only one logical field,
// "credentials", with PUT replacing the whole map and DELETE wiping it.
type DataSourceResponse struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Name string `json:"name"`
Type string `json:"type"`
Config *DataSourceConfigDTO `json:"config,omitempty"`
SyncSchedule string `json:"sync_schedule"`
SyncMode string `json:"sync_mode"`
Status string `json:"status"`
ConflictStrategy string `json:"conflict_strategy"`
SyncDeletions bool `json:"sync_deletions"`
LastSyncAt *time.Time `json:"last_sync_at"`
LastSyncCursor json.RawMessage `json:"last_sync_cursor,omitempty"`
LastSyncResult json.RawMessage `json:"last_sync_result,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
SyncLogRetentionDays int `json:"sync_log_retention_days"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
TotalItemsSynced int64 `json:"total_items_synced"`
LatestSyncLog *types.SyncLog `json:"latest_sync_log,omitempty"`
// Single logical credential field — DataSource credentials are a
// per-connector atomic map, so "configured?" applies to the whole set.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
}
// DataSourceConfigDTO is types.DataSourceConfig with the Credentials map
// removed by construction. Type, ResourceIDs and Settings remain visible.
type DataSourceConfigDTO struct {
Type string `json:"type"`
ResourceIDs []string `json:"resource_ids,omitempty"`
Settings map[string]interface{} `json:"settings,omitempty"`
}
// NewDataSourceResponse converts a stored entity into its response shape.
// Returns nil for nil input.
func NewDataSourceResponse(ds *types.DataSource) *DataSourceResponse {
if ds == nil {
return nil
}
var cfgDTO *DataSourceConfigDTO
configured := false
if parsed, err := ds.ParseConfig(); err == nil && parsed != nil {
cfgDTO = &DataSourceConfigDTO{
Type: parsed.Type,
ResourceIDs: parsed.ResourceIDs,
Settings: parsed.Settings,
}
enrichRSSFeedURLsInSettings(ds.Type, parsed, cfgDTO)
configured = parsed.HasConfiguredCredentials(ds.Type)
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 07:09:30 +00:00
}
return &DataSourceResponse{
ID: ds.ID,
TenantID: ds.TenantID,
KnowledgeBaseID: ds.KnowledgeBaseID,
Name: ds.Name,
Type: ds.Type,
Config: cfgDTO,
SyncSchedule: ds.SyncSchedule,
SyncMode: ds.SyncMode,
Status: ds.Status,
ConflictStrategy: ds.ConflictStrategy,
SyncDeletions: ds.SyncDeletions,
LastSyncAt: ds.LastSyncAt,
LastSyncCursor: json.RawMessage(ds.LastSyncCursor),
LastSyncResult: json.RawMessage(ds.LastSyncResult),
ErrorMessage: ds.ErrorMessage,
SyncLogRetentionDays: ds.SyncLogRetentionDays,
CreatedAt: ds.CreatedAt,
UpdatedAt: ds.UpdatedAt,
TotalItemsSynced: ds.TotalItemsSynced,
LatestSyncLog: ds.LatestSyncLog,
Credentials: map[string]CredentialFieldMetadata{
"credentials": {Configured: configured},
},
}
}
// enrichRSSFeedURLsInSettings copies feed_urls from credentials into settings
// for API responses. Feed URLs are not secrets but may still live in the
// encrypted credentials blob on rows created before they moved to settings.
func enrichRSSFeedURLsInSettings(dsType string, parsed *types.DataSourceConfig, cfgDTO *DataSourceConfigDTO) {
if dsType != types.ConnectorTypeRSS || parsed == nil || cfgDTO == nil {
return
}
if cfgDTO.Settings != nil {
if v, ok := cfgDTO.Settings["feed_urls"].(string); ok && strings.TrimSpace(v) != "" {
return
}
}
raw, ok := parsed.Credentials["feed_urls"]
if !ok {
return
}
feedURLs, ok := raw.(string)
if !ok || strings.TrimSpace(feedURLs) == "" {
return
}
if cfgDTO.Settings == nil {
cfgDTO.Settings = make(map[string]interface{})
}
cfgDTO.Settings["feed_urls"] = feedURLs
}
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 07:09:30 +00:00
func NewDataSourceResponses(dss []*types.DataSource) []*DataSourceResponse {
out := make([]*DataSourceResponse, 0, len(dss))
for _, d := range dss {
out = append(out, NewDataSourceResponse(d))
}
return out
}