RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix: protect provider instance credentials (#21618)
buua43691a53bc2ddbc
diff --git a/internal/handler/providers.go b/internal/handler/providers.goindex ae12926dc4..a83c5b5fab 100644--- a/internal/handler/providers.go+++ b/internal/handler/providers.go@@ -178,10 +178,47 @@ func (h *ProviderHandler) ListModels(c *gin.Context) {return}- apiKey := strings.TrimSpace(c.Query("api_key"))+ apiKey, apiKeyProvided := c.GetQuery("api_key")+ apiKey = strings.TrimSpace(apiKey)baseURL := strings.TrimSpace(c.Query("base_url"))- if instanceName := strings.TrimSpace(c.Query("instance_name")); instanceName != "" && (apiKey == "" || baseURL == "") {- instanceModels, err := h.modelProviderService.ListSupportedModels(c.Request.Context(), providerName, instanceName, c.GetString("user_id"))+ region := strings.TrimSpace(c.Query("region"))+ instanceName := strings.TrimSpace(c.Query("instance_name"))+ if strings.EqualFold(c.Query("use_saved_credentials"), "true") {+ if instanceName == "" {+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Saved credentials require an instance name")+ return+ }+ var baseURLOverride, regionOverride *string+ if value, ok := c.GetQuery("base_url"); ok {+ baseURLOverride = &value+ }+ if value, ok := c.GetQuery("region"); ok {+ regionOverride = &value+ }+ apiKeyConfig := json.RawMessage(c.Query("api_key_config"))+ instanceModels, err := h.modelProviderService.ListSupportedModels(c.Request.Context(), providerName, instanceName, c.GetString("user_id"), service.ListSupportedModelsOptions{+ APIKeyConfig: apiKeyConfig,+ BaseURL: baseURLOverride,+ Region: regionOverride,+ })+ if err != nil {+ common.ErrorWithCode(c, common.CodeDataError, err.Error())+ return+ }+ for _, model := range instanceModels {+ if _, ok := model["max_tokens"]; !ok {+ if contextLength, ok := model["context_length"]; ok && contextLength != nil {+ model["max_tokens"] = contextLength+ }+ }+ }+ common.SuccessWithData(c, instanceModels, "success")+ return+ }+ _, baseURLProvided := c.GetQuery("base_url")+ _, regionProvided := c.GetQuery("region")+ if instanceName != "" && !apiKeyProvided && !baseURLProvided && !regionProvided {+ instanceModels, err := h.modelProviderService.ListSupportedModels(c.Request.Context(), providerName, instanceName, c.GetString("user_id"), service.ListSupportedModelsOptions{})if err == nil {for _, model := range instanceModels {if _, ok := model["max_tokens"]; !ok {@@ -193,7 +230,7 @@ func (h *ProviderHandler) ListModels(c *gin.Context) {common.SuccessWithData(c, instanceModels, "success")return}- if apiKey == "" && baseURL == "" {+ if apiKey == "" && baseURL == "" && region == "" {common.ErrorWithCode(c, common.CodeDataError, err.Error())return}@@ -589,7 +626,7 @@ func (h *ProviderHandler) CheckConnection(c *gin.Context) {}userID := c.GetString("user_id")- errCode, err := h.modelProviderService.CheckConnection(ctx, providerName, service.NormalizeAPIKey(req.APIKey), req.Region, req.BaseURL, req.InstanceID, userID, req.ModelInfo)+ errCode, err := h.modelProviderService.CheckConnection(ctx, providerName, req, userID)if err != nil {common.ErrorWithCode(c, errCode, err.Error())return@@ -619,12 +656,12 @@ func (h *ProviderHandler) CheckInstanceConnection(c *gin.Context) {return}- apikey, _ := instanceInfo["api_key"].(string)- region, _ := instanceInfo["region"].(string)- baseURL, _ := instanceInfo["base_url"].(string)instanceID, _ := instanceInfo["id"].(string)- errorCode, err := h.modelProviderService.CheckConnection(ctx, providerName, apikey, region, baseURL, instanceID, userID, nil)+ errorCode, err := h.modelProviderService.CheckConnection(ctx, providerName, service.CheckConnectionRequest{+ UseSavedCredentials: true,+ InstanceID: instanceID,+ }, userID)if err != nil {common.ErrorWithCode(c, errorCode, err.Error())return@@ -717,7 +754,7 @@ func (h *ProviderHandler) AlterProviderInstance(c *gin.Context) {return}- code, err := h.modelProviderService.AlterProviderInstance(ctx, userID, providerName, instanceName, req.InstanceName, service.NormalizeAPIKey(req.APIKey), req.BaseURL, req.Region, *req.ModelInfo)+ code, err := h.modelProviderService.AlterProviderInstance(ctx, userID, providerName, instanceName, req.InstanceName, req.APIKey, req.ClearAPIKey, req.BaseURL, req.Region, *req.ModelInfo)if err != nil {common.ErrorWithCode(c, code, err.Error())return@@ -773,7 +810,7 @@ func (h *ProviderHandler) ListInstanceModels(c *gin.Context) {if keywords == "true" {// list supported models- modelList, err := h.modelProviderService.ListSupportedModels(ctx, providerName, instanceName, c.GetString("user_id"))+ modelList, err := h.modelProviderService.ListSupportedModels(ctx, providerName, instanceName, c.GetString("user_id"), service.ListSupportedModelsOptions{})if err != nil {common.ErrorWithCode(c, common.CodeServerError, err.Error())returndiff --git a/internal/service/model_service.go b/internal/service/model_service.goindex 48a0c00491..6b72116655 100644--- a/internal/service/model_service.go+++ b/internal/service/model_service.go@@ -86,8 +86,8 @@ type ModelProviderService struct {modelGroupMapDAO *dao.TenantModelGroupMapDAO}-// CheckConnectionModelInfo CheckConnectionRequest carries the credentials and optional instance selector-// for checking provider connectivity without creating a new model instance.+// CheckConnectionModelInfo describes a model whose provider connectivity is+// being verified.type CheckConnectionModelInfo struct {ModelName string `json:"model_name"`ModelTypes []string `json:"model_type"`@@ -95,12 +95,17 @@ type CheckConnectionModelInfo struct {Extra map[string]interface{} `json:"extra"`}+// CheckConnectionRequest carries credentials and optional instance settings+// for checking provider connectivity without creating a new model instance.type CheckConnectionRequest struct {- APIKey json.RawMessage `json:"api_key"`- Region string `json:"region"`- BaseURL string `json:"base_url"`- InstanceID string `json:"instance_id"`- ModelInfo []CheckConnectionModelInfo `json:"model_info"`+ APIKey json.RawMessage `json:"api_key"`+ ClearAPIKey bool `json:"clear_api_key"`+ UseSavedCredentials bool `json:"use_saved_credentials"`+ APIKeyConfig json.RawMessage `json:"api_key_config"`+ Region string `json:"region"`+ BaseURL string `json:"base_url"`+ InstanceID string `json:"instance_id"`+ ModelInfo []CheckConnectionModelInfo `json:"model_info"`}func (m *ModelProviderService) AddModelProvider(ctx context.Context, providerName, userID string) (common.ErrorCode, error) {@@ -285,7 +290,15 @@ func (m *ModelProviderService) DeleteModelProvider(ctx context.Context, userID,return common.CodeSuccess, nil}-func (m *ModelProviderService) ListSupportedModels(ctx context.Context, providerName, instanceName, userID string) ([]map[string]interface{}, error) {+// ListSupportedModelsOptions contains owner-only overrides for a saved+// provider instance's endpoint and non-secret configuration.+type ListSupportedModelsOptions struct {+ APIKeyConfig json.RawMessage+ BaseURL *string+ Region *string+}++func (m *ModelProviderService) ListSupportedModels(ctx context.Context, providerName, instanceName, userID string, options ListSupportedModelsOptions) ([]map[string]interface{}, error) {providerName = strings.TrimSpace(providerName)provider, err := m.resolveProviderInTenant(ctx, userID, providerName, permission.OperationRead)@@ -304,10 +317,21 @@ func (m *ModelProviderService) ListSupportedModels(ctx context.Context, provider}return nil, err}- if err = checkModelPermission(ctx, userID, permission.ResourceKindModelInstance, instance.ID, permission.OperationUse); err != nil {+ access, err := permission.NewDatabaseChecker(dao.DB).ResolveAccess(ctx, permission.Subject{UserID: userID}, permission.ResourceRef{+ Kind: permission.ResourceKindModelInstance,+ ID: instance.ID,+ })+ if err != nil || !access.Allows(permission.OperationUse) {+ if err == nil {+ err = permission.ErrPermissionDenied+ }_, normalizedErr := normalizeModelPermissionError(err)return nil, normalizedErr}+ if access.Source != permission.AccessSourceOwner && hasSavedProviderInstanceOverrides(options.APIKeyConfig, options.BaseURL, options.Region) {+ _, normalizedErr := normalizeModelPermissionError(permission.ErrPermissionDenied)+ return nil, normalizedErr+ }providerName = provider.ProviderNameproviderInfo := dao.GetModelProviderManager().FindProvider(providerName)@@ -321,19 +345,37 @@ func (m *ModelProviderService) ListSupportedModels(ctx context.Context, providerreturn nil, err}- apiConfig := &modelModule.APIConfig{- ApiKey: nil,- Region: nil,+ apiKey := instance.APIKey+ if len(bytes.TrimSpace(options.APIKeyConfig)) > 0 && !bytes.Equal(bytes.TrimSpace(options.APIKeyConfig), []byte("null")) {+ apiKey, err = mergeSavedProviderAPIKeyConfig(instance.APIKey, options.APIKeyConfig)+ if err != nil {+ return nil, err+ }}-region := extra["region"]- apiConfig.Region = ®ion- apiConfig.ApiKey = &instance.APIKey+ if options.Region != nil {+ region = strings.TrimSpace(*options.Region)+ if region == "" {+ region = "default"+ }+ }+ baseURL := extra["base_url"]+ if options.BaseURL != nil {+ baseURL = strings.TrimSpace(*options.BaseURL)+ }++ apiConfig := &modelModule.APIConfig{+ ApiKey: &apiKey,+ Region: ®ion,+ }+ if options.BaseURL != nil {+ apiConfig.BaseURL = &baseURL+ }driver := providerInfo.ModelDriver// For local deployed models- if baseURL, ok := extra["base_url"]; ok && baseURL != "" {+ if baseURL != "" {driver, err = newModelDriverForBaseURL(driver, providerName, region, baseURL)if err != nil {return nil, err@@ -391,6 +433,7 @@ type CreateProviderInstanceRequest struct {type AlterProviderInstanceRequest struct {InstanceName string `json:"instance_name"`APIKey json.RawMessage `json:"api_key"`+ ClearAPIKey bool `json:"clear_api_key"`BaseURL string `json:"base_url"`Region string `json:"region"`ModelInfo *[]CreateInstanceModelInfo `json:"model_info" binding:"required"`@@ -428,6 +471,277 @@ func NormalizeAPIKey(raw json.RawMessage) string {return compact.String()}+var providerAPIKeyConfigFields = map[string]struct{}{+ "api_version": {},+ "auth_mode": {},+ "aws_role_arn": {},+ "bedrock_region": {},+ "fish_audio_refid": {},+ "google_project_id": {},+ "google_region": {},+ "group_id": {},+ "mineru_apiserver": {},+ "mineru_backend": {},+ "mineru_delete_output": {},+ "mineru_output_dir": {},+ "mineru_server_url": {},+ "opendataloader_apiserver": {},+ "paddleocr_algorithm": {},+ "paddleocr_api_url": {},+ "provider_order": {},+}++var safeProviderAPIKeyConfigFields = map[string]struct{}{+ "api_version": {},+ "auth_mode": {},+ "bedrock_region": {},+ "fish_audio_refid": {},+ "google_project_id": {},+ "google_region": {},+ "group_id": {},+ "mineru_apiserver": {},+ "mineru_backend": {},+ "mineru_delete_output": {},+ "mineru_output_dir": {},+ "mineru_server_url": {},+ "opendataloader_apiserver": {},+ "paddleocr_algorithm": {},+ "paddleocr_api_url": {},+ "provider_order": {},+}++func hasSavedProviderAPIKeyConfig(raw json.RawMessage) bool {+ trimmed := bytes.TrimSpace(raw)+ if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {+ return false+ }+ var config map[string]json.RawMessage+ if err := json.Unmarshal(trimmed, &config); err != nil {+ return true+ }+ return len(config) > 0+}++func hasSavedProviderInstanceOverrides(apiKeyConfig json.RawMessage, baseURL, region *string) bool {+ return baseURL != nil || region != nil || hasSavedProviderAPIKeyConfig(apiKeyConfig)+}++func providerInstanceCredentialMetadata(apiKey string) (bool, map[string]interface{}, map[string]bool, map[string]string) {+ originalAPIKey := apiKey+ apiKey = strings.TrimSpace(apiKey)+ config := make(map[string]interface{})+ status := make(map[string]bool)+ masks := make(map[string]string)+ if apiKey == "" {+ return false, config, status, masks+ }++ var values map[string]interface{}+ if err := json.Unmarshal([]byte(apiKey), &values); err != nil || values == nil {+ status["api_key"] = true+ masks["api_key"] = maskProviderCredentialValue(originalAPIKey)+ return true, config, status, masks+ }++ configured := false+ for key, value := range values {+ if _, safe := safeProviderAPIKeyConfigFields[key]; safe {+ config[key] = value+ }+ if isProviderCredentialField(key) && hasProviderCredentialValue(value) {+ status[key] = true+ masks[key] = maskProviderCredentialValue(value)+ configured = true+ }+ if key == "auth_mode" && value == "assume_role" {+ configured = true+ }+ }+ if roleARN, ok := values["aws_role_arn"].(string); ok && strings.TrimSpace(roleARN) != "" {+ configured = true+ status["aws_role_arn"] = true+ masks["aws_role_arn"] = maskProviderCredentialValue(roleARN)+ }+ return configured, config, status, masks+}++func maskProviderCredentialValue(value interface{}) string {+ secret, ok := value.(string)+ if !ok {+ return "********"+ }+ characters := []rune(secret)+ if len(characters) <= 8 {+ return strings.Repeat("*", len(characters))+ }+ return string(characters[:4]) + strings.Repeat("*", len(characters)-8) + string(characters[len(characters)-4:])+}++func isProviderCredentialField(name string) bool {+ name = strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(name, "-", "_"), ".", "_"))+ for _, marker := range []string{"api_key", "apikey", "secret", "token", "password", "credential", "private", "access_key"} {+ if strings.Contains(name, marker) {+ return true+ }+ }+ return strings.HasSuffix(name, "_ak") || strings.HasSuffix(name, "_sk") || strings.HasSuffix(name, "_sid") || strings.HasSuffix(name, "_key")+}++func hasProviderCredentialValue(value interface{}) bool {+ switch value := value.(type) {+ case string:+ return strings.TrimSpace(value) != ""+ case []interface{}:+ for _, item := range value {+ if hasProviderCredentialValue(item) {+ return true+ }+ }+ case map[string]interface{}:+ return len(value) > 0+ case bool:+ return value+ case float64:+ return value != 0+ }+ return false+}++func mergeProviderAPIKey(existing string, submitted json.RawMessage, clear bool) (string, error) {+ if clear {+ existing = ""+ }++ trimmed := bytes.TrimSpace(submitted)+ if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {+ return existing, nil+ }++ var submittedString string+ if err := json.Unmarshal(trimmed, &submittedString); err == nil {+ if strings.TrimSpace(submittedString) == "" {+ return existing, nil+ }+ return submittedString, nil+ }++ var submittedConfig map[string]json.RawMessage+ if err := json.Unmarshal(trimmed, &submittedConfig); err != nil || submittedConfig == nil {+ var compact bytes.Buffer+ if err := json.Compact(&compact, trimmed); err != nil {+ return "", fmt.Errorf("invalid api_key value: %w", err)+ }+ return compact.String(), nil+ }++ merged := make(map[string]json.RawMessage)+ if !clear && strings.TrimSpace(existing) != "" {+ var existingConfig map[string]json.RawMessage+ if err := json.Unmarshal([]byte(existing), &existingConfig); err == nil && existingConfig != nil {+ for key, value := range existingConfig {+ merged[key] = value+ }+ } else {+ plainKey, _ := json.Marshal(existing)+ merged["api_key"] = plainKey+ }+ }+ for key, value := range submittedConfig {+ if bytes.Equal(bytes.TrimSpace(value), []byte("null")) {+ delete(merged, key)+ continue+ }+ var textValue string+ if err := json.Unmarshal(value, &textValue); err == nil && textValue == "" {+ continue+ }+ merged[key] = value+ }+ if len(merged) == 0 {+ return "", nil+ }+ encoded, err := json.Marshal(merged)+ if err != nil {+ return "", fmt.Errorf("marshal api_key configuration: %w", err)+ }+ return string(encoded), nil+}++func mergeSavedProviderAPIKeyConfig(existing string, submitted json.RawMessage) (string, error) {+ var submittedConfig map[string]json.RawMessage+ if err := json.Unmarshal(submitted, &submittedConfig); err != nil || submittedConfig == nil {+ return "", errors.New("saved credential requests must include a provider configuration object")+ }++ var merged map[string]json.RawMessage+ if err := json.Unmarshal([]byte(existing), &merged); err != nil || merged == nil {+ merged = make(map[string]json.RawMessage)+ if strings.TrimSpace(existing) != "" {+ plainKey, _ := json.Marshal(existing)+ merged["api_key"] = plainKey+ }+ }+ updated := false+ for key, value := range submittedConfig {+ if _, safe := providerAPIKeyConfigFields[key]; safe {+ updated = true+ trimmed := bytes.TrimSpace(value)+ if bytes.Equal(trimmed, []byte("null")) {+ delete(merged, key)+ continue+ }+ var textValue string+ if err := json.Unmarshal(trimmed, &textValue); err == nil && strings.TrimSpace(textValue) == "" {+ delete(merged, key)+ continue+ }+ merged[key] = value+ }+ }+ if !updated {+ return existing, nil+ }+ if len(merged) == 0 {+ return "", nil+ }+ encoded, err := json.Marshal(merged)+ if err != nil {+ return "", fmt.Errorf("marshal provider configuration: %w", err)+ }+ return string(encoded), nil+}++func (m *ModelProviderService) getProviderByIDOrName(ctx context.Context, userID, providerIDOrName string, operation permission.Operation) (*entity.TenantModelProvider, error) {+ providerIDOrName = strings.TrimSpace(providerIDOrName)+ if providerIDOrName == "" {+ return nil, gorm.ErrRecordNotFound+ }+ provider, err := m.modelProviderDAO.GetByID(ctx, dao.DB, providerIDOrName)+ if err == nil {+ if err := checkModelPermission(ctx, userID, permission.ResourceKindModelProvider, provider.ID, operation); err != nil {+ return nil, err+ }+ return provider, nil+ }+ if !errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, err+ }+ providerIDs, scopeErr := accessibleModelResourceIDs(ctx, userID, permission.ResourceKindModelProvider, permission.ResourceRef{}, operation, nil, "")+ if scopeErr != nil {+ return nil, scopeErr+ }+ for _, providerID := range providerIDs {+ candidate, candidateErr := m.modelProviderDAO.GetByID(ctx, dao.DB, providerID)+ if candidateErr != nil {+ return nil, candidateErr+ }+ if strings.EqualFold(candidate.ProviderName, providerIDOrName) {+ return candidate, nil+ }+ }+ return nil, gorm.ErrRecordNotFound+}+func (m *ModelProviderService) findProviderByIDOrNameInTenant(ctx context.Context, tenantID, providerIDOrName string) (*entity.TenantModelProvider, error) {providerIDOrName = strings.TrimSpace(providerIDOrName)if providerIDOrName == "" {@@ -801,6 +1115,7 @@ func (m *ModelProviderService) ListProviderInstances(ctx context.Context, provid"region": extraFields["region"],"status": instance.Status,"operator_permission": access.PermissionMask,+ "is_owner": access.Source == permission.AccessSourceOwner,})}@@ -861,9 +1176,14 @@ func (m *ModelProviderService) ShowProviderInstance(ctx context.Context, provide"region": extraFields["region"],"base_url": extraFields["base_url"],"status": instance.Status,+ "is_owner": access.Source == permission.AccessSourceOwner,}- if access.Source == permission.AccessSourceOwner {- result["api_key"] = instance.APIKey+ if access.Source == permission.AccessSourceOwner || access.Allows(permission.OperationUpdate) {+ configured, config, credentialStatus, credentialMasks := providerInstanceCredentialMetadata(instance.APIKey)+ result["api_key_configured"] = configured+ result["api_key_config"] = config+ result["credential_status"] = credentialStatus+ result["credential_masks"] = credentialMasks}return result, common.CodeSuccess, nil@@ -925,8 +1245,19 @@ func (m *ModelProviderService) ShowInstanceBalance(ctx context.Context, providerreturn result, common.CodeSuccess, nil}-func (m *ModelProviderService) CheckConnection(ctx context.Context, providerName, apiKey, region, baseURL, instanceID, userID string, modelInfo []CheckConnectionModelInfo) (common.ErrorCode, error) {+// CheckConnection verifies provider connectivity. When saved credentials are+// selected, only the instance owner may override their endpoint or config.+func (m *ModelProviderService) CheckConnection(ctx context.Context, providerName string, req CheckConnectionRequest, userID string) (common.ErrorCode, error) {providerName = strings.TrimSpace(providerName)+ apiKey := strings.TrimSpace(NormalizeAPIKey(req.APIKey))+ region := strings.TrimSpace(req.Region)+ baseURL := strings.TrimSpace(req.BaseURL)+ clearAPIKey := req.ClearAPIKey+ useSavedCredentials := req.UseSavedCredentials+ instanceID := strings.TrimSpace(req.InstanceID)+ modelInfo := req.ModelInfo+ var savedInstance *entity.TenantModelInstance+ var instanceAccess permission.Accessif instanceID != "" {instance, err := m.modelInstanceDAO.GetByID(ctx, dao.DB, instanceID)if err != nil {@@ -949,10 +1280,18 @@ func (m *ModelProviderService) CheckConnection(ctx context.Context, providerNamecode, normalizedErr := normalizeModelPermissionError(err)return code, normalizedErr}- if err = checkModelPermission(ctx, userID, permission.ResourceKindModelInstance, instance.ID, permission.OperationUpdate); err != nil {+ instanceAccess, err = permission.NewDatabaseChecker(dao.DB).ResolveAccess(ctx, permission.Subject{UserID: userID}, permission.ResourceRef{+ Kind: permission.ResourceKindModelInstance,+ ID: instance.ID,+ })+ if err != nil || !instanceAccess.Allows(permission.OperationUpdate) {+ if err == nil {+ err = permission.ErrPermissionDenied+ }code, normalizedErr := normalizeModelPermissionError(err)return code, normalizedErr}+ savedInstance = instanceproviderName = provider.ProviderName}@@ -961,9 +1300,51 @@ func (m *ModelProviderService) CheckConnection(ctx context.Context, providerNamereturn common.CodeServerError, fmt.Errorf("provider %s not found", providerName)}- apiKey = strings.TrimSpace(apiKey)- region = strings.TrimSpace(region)- baseURL = strings.TrimSpace(baseURL)+ if savedInstance != nil {+ extra := make(map[string]interface{})+ if savedInstance.Extra != "" {+ if err := json.Unmarshal([]byte(savedInstance.Extra), &extra); err != nil {+ return common.CodeServerError, err+ }+ }+ if useSavedCredentials {+ if clearAPIKey || apiKey != "" {+ return common.CodeBadRequest, errors.New("saved credentials cannot be combined with submitted credentials")+ }+ if instanceAccess.Source != permission.AccessSourceOwner && (region != "" || baseURL != "" || hasSavedProviderAPIKeyConfig(req.APIKeyConfig)) {+ code, normalizedErr := normalizeModelPermissionError(permission.ErrPermissionDenied)+ return code, normalizedErr+ }+ apiKey = savedInstance.APIKey+ if hasSavedProviderAPIKeyConfig(req.APIKeyConfig) {+ var err error+ apiKey, err = mergeSavedProviderAPIKeyConfig(apiKey, req.APIKeyConfig)+ if err != nil {+ return common.CodeBadRequest, err+ }+ }+ if region == "" {+ region, _ = extra["region"].(string)+ }+ if baseURL == "" {+ baseURL, _ = extra["base_url"].(string)+ }+ } else {+ if hasSavedProviderAPIKeyConfig(req.APIKeyConfig) {+ return common.CodeBadRequest, errors.New("api_key_config requires saved credentials")+ }+ if region == "" {+ region, _ = extra["region"].(string)+ }+ if baseURL == "" {+ baseURL, _ = extra["base_url"].(string)+ }+ }+ } else if useSavedCredentials {+ return common.CodeBadRequest, errors.New("saved credentials require an existing model instance")+ } else if hasSavedProviderAPIKeyConfig(req.APIKeyConfig) {+ return common.CodeBadRequest, errors.New("api_key_config requires saved credentials")+ }if region == "" {region = "default"}@@ -987,13 +1368,8 @@ func (m *ModelProviderService) CheckConnection(ctx context.Context, providerNameBaseURL: &baseURL,}- // Mirror Python verify_api_key: verify each model by making a real- // lightweight API request. Returns per-model verify results.modelVerifyResult, verifyErr := verifyProviderModel(ctx, driver, providerInfo.Models, apiConfig, modelInfo)- // When instanceID is provided (frontend passes it), persist the verify- // results to the database — mirrors Python's per-model update_model calls- // inside the /connection/verify REST endpoint.if instanceID != "" && len(modelVerifyResult) > 0 {if dbErr := m.updateModelVerifyResults(ctx, userID, providerName, instanceID, modelVerifyResult); dbErr != nil {if permissionresponse.IsPermissionError(dbErr) {@@ -2037,8 +2413,7 @@ func (m *ModelProviderService) ensureOCRProviderFromEnv(ctx context.Context, usereturn nil}-func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, userID, providerIDOrName, instanceIDOrName, newInstanceName, apiKey, baseURL, region string, modelInfo []CreateInstanceModelInfo) (common.ErrorCode, error) {- apiKey = strings.TrimSpace(apiKey)+func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, userID, providerIDOrName, instanceIDOrName, newInstanceName string, apiKey json.RawMessage, clearAPIKey bool, baseURL, region string, modelInfo []CreateInstanceModelInfo) (common.ErrorCode, error) {baseURL = strings.TrimSpace(baseURL)region = strings.TrimSpace(region)providerIDOrName = strings.TrimSpace(providerIDOrName)@@ -2105,9 +2480,16 @@ func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, userID}}- // Update instance record.- instanceUpdates := map[string]interface{}{- "api_key": apiKey,+ // Update instance record. Empty or omitted credentials keep the existing+ // value; clear_api_key explicitly clears the stored credentials. Structured+ // credential objects merge non-empty submitted fields into the saved config.+ instanceUpdates := make(map[string]interface{})+ if clearAPIKey || len(bytes.TrimSpace(apiKey)) > 0 {+ updatedAPIKey, mergeErr := mergeProviderAPIKey(instance.APIKey, apiKey, clearAPIKey)+ if mergeErr != nil {+ return common.CodeBadRequest, mergeErr+ }+ instanceUpdates["api_key"] = updatedAPIKey}if newInstanceName != "" && newInstanceName != instance.InstanceName {instanceUpdates["instance_name"] = newInstanceNamediff --git a/internal/service/model_service_test.go b/internal/service/model_service_test.goindex bf76c40641..5252788690 100644--- a/internal/service/model_service_test.go+++ b/internal/service/model_service_test.go@@ -6,6 +6,7 @@ import ("errors""net/http""net/http/httptest"+ "reflect""strings""testing"@@ -22,22 +23,34 @@ import (type remoteModelProbeDriver struct {*modelModule.DummyModelremoteModels []modelModule.ListModelResponse+ listCalls int+ listConfig *modelModule.APIConfig+ baseURLs map[string]stringembedCalls intcheckCalls intcheckErr error+ checkConfig *modelModule.APIConfig}-func (d *remoteModelProbeDriver) ListModels(context.Context, *modelModule.APIConfig) ([]modelModule.ListModelResponse, error) {+func (d *remoteModelProbeDriver) ListModels(_ context.Context, apiConfig *modelModule.APIConfig) ([]modelModule.ListModelResponse, error) {+ d.listCalls+++ d.listConfig = apiConfigreturn d.remoteModels, nil}+func (d *remoteModelProbeDriver) NewInstance(baseURLs map[string]string) modelModule.ModelDriver {+ d.baseURLs = baseURLs+ return d+}+func (d *remoteModelProbeDriver) Embed(context.Context, *string, modelModule.EmbedRequest, *modelModule.APIConfig, *modelModule.EmbeddingConfig, *common.ModelUsage) ([]modelModule.EmbeddingData, error) {d.embedCalls++return nil, nil}-func (d *remoteModelProbeDriver) CheckConnection(context.Context, *modelModule.APIConfig) error {+func (d *remoteModelProbeDriver) CheckConnection(_ context.Context, apiConfig *modelModule.APIConfig) error {d.checkCalls+++ d.checkConfig = apiConfigreturn d.checkErr}@@ -534,7 +547,8 @@ func TestBedrockAPIKeyInstancePersistsDiscoveredModelsWithoutRuntimeVerification"Bedrock","api-key-instance","api-key-instance",- apiKey,+ json.RawMessage(apiKey),+ false,"","default",[]CreateInstanceModelInfo{{@@ -703,7 +717,7 @@ func TestProviderModelListingUsesOwnedTenant(t *testing.T) {if _, err = service.ListInstanceModels(serviceTestContext(t, "user-1", "user-1"), "provider-2", "default", "user-1"); !errors.Is(err, gorm.ErrRecordNotFound) {t.Fatalf("ListInstanceModels() for another tenant's provider error = %v, want record not found", err)}- if _, err = service.ListSupportedModels(serviceTestContext(t, "user-1", "user-1"), "provider-2", "default", "user-1"); !errors.Is(err, gorm.ErrRecordNotFound) {+ if _, err = service.ListSupportedModels(serviceTestContext(t, "user-1", "user-1"), "provider-2", "default", "user-1", ListSupportedModelsOptions{}); !errors.Is(err, gorm.ErrRecordNotFound) {t.Fatalf("ListSupportedModels() for another tenant's provider error = %v, want record not found", err)}}@@ -734,8 +748,17 @@ func TestShowProviderInstanceUsesOwnedTenantProvider(t *testing.T) {if instance["id"] != "instance-1" || instance["provider_id"] != "provider-1" {t.Fatalf("ShowProviderInstance() = %v, want user-1's own-tenant instance", instance)}- if instance["api_key"] != "sk-test" {- t.Fatalf("ShowProviderInstance() api_key = %v, want owner credential", instance["api_key"])+ if instance["is_owner"] != true {+ t.Fatalf("ShowProviderInstance() is_owner = %v, want true", instance["is_owner"])+ }+ if _, exists := instance["api_key"]; exists {+ t.Fatalf("ShowProviderInstance() returned the stored API key: %v", instance["api_key"])+ }+ if instance["api_key_configured"] != true {+ t.Fatalf("ShowProviderInstance() api_key_configured = %v, want true", instance["api_key_configured"])+ }+ if status, ok := instance["credential_status"].(map[string]bool); !ok || status["api_key"] != true {+ t.Fatalf("ShowProviderInstance() credential_status = %v, want api_key configured", instance["credential_status"])}if _, code, err = service.ShowProviderInstance(ctx, "provider-2", "instance-2", "user-1"); err == nil || code != common.CodeNotFound {@@ -743,6 +766,149 @@ func TestShowProviderInstanceUsesOwnedTenantProvider(t *testing.T) {}}+func TestProviderInstanceCredentialMetadataDoesNotExposeSecrets(t *testing.T) {+ apiKey := `{"api_key":"sk-secret","group_id":"group-1","auth_mode":"bedrock_api_key","aws_role_arn":"arn:aws:iam::123456789012:role/model","bedrock_api_key":"br-secret","bedrock_region":"us-east-1","google_service_account_key":"google-secret","unknown_secret":"hidden"}`+ configured, config, status, _ := providerInstanceCredentialMetadata(apiKey)+ if !configured {+ t.Fatal("providerInstanceCredentialMetadata() configured = false, want true")+ }+ if config["group_id"] != "group-1" || config["auth_mode"] != "bedrock_api_key" || config["bedrock_region"] != "us-east-1" {+ t.Fatalf("safe config = %v, missing expected fields", config)+ }+ for _, secret := range []string{"api_key", "aws_role_arn", "bedrock_api_key", "unknown_secret"} {+ if _, exists := config[secret]; exists {+ t.Fatalf("safe config contains secret field %q: %v", secret, config)+ }+ }+ if status["api_key"] != true || status["aws_role_arn"] != true || status["bedrock_api_key"] != true || status["google_service_account_key"] != true || status["unknown_secret"] != true {+ t.Fatalf("credential status = %v, want configured secret field names", status)+ }+}++func TestMergeProviderAPIKeyPreservesBlankCredentialsAndSupportsClear(t *testing.T) {+ tests := []struct {+ name string+ existing string+ submitted string+ clear bool+ want map[string]string+ }{+ {+ name: "blank plain key keeps existing",+ existing: "sk-existing",+ submitted: `""`,+ want: map[string]string{"api_key": "sk-existing"},+ },+ {+ name: "structured update keeps blank secrets and updates metadata",+ existing: `{"api_key":"sk-existing","group_id":"old-group","bedrock_sk":"aws-secret"}`,+ submitted: `{"api_key":"","group_id":"new-group"}`,+ want: map[string]string{"api_key": "sk-existing", "group_id": "new-group", "bedrock_sk": "aws-secret"},+ },+ {+ name: "null removes one credential and keeps the rest",+ existing: `{"api_key":"sk-existing","bedrock_api_key":"br-secret","bedrock_region":"us-east-1"}`,+ submitted: `{"bedrock_api_key":null}`,+ want: map[string]string{"api_key": "sk-existing", "bedrock_region": "us-east-1"},+ },+ {+ name: "clear removes old secret fields before applying new config",+ existing: `{"api_key":"sk-existing","bedrock_sk":"aws-secret"}`,+ submitted: `{"auth_mode":"iam_role","aws_role_arn":"arn:aws:iam::1:role/model"}`,+ clear: true,+ want: map[string]string{"auth_mode": "iam_role", "aws_role_arn": "arn:aws:iam::1:role/model"},+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := mergeProviderAPIKey(tt.existing, json.RawMessage(tt.submitted), tt.clear)+ if err != nil {+ t.Fatalf("mergeProviderAPIKey() error = %v", err)+ }+ var gotMap map[string]string+ if err = json.Unmarshal([]byte(got), &gotMap); err != nil {+ gotMap = map[string]string{"api_key": got}+ }+ if !reflect.DeepEqual(gotMap, tt.want) {+ t.Fatalf("mergeProviderAPIKey() = %v, want %v", gotMap, tt.want)+ }+ })+ }+}++func TestListSupportedModelsUsePermissionCannotOverrideSavedEndpoint(t *testing.T) {+ db := setupModelProviderServiceTestDB(t)+ useModelProviderServiceTestDB(t, db)+ seedModelProviderServiceScope(t, db)+ activeStatus := string(entity.TenantMembershipStatusJoined)+ if err := db.Model(&entity.TenantModelProvider{}).Where("id = ?", "provider-1").Update("tenant_id", "tenant-1").Error; err != nil {+ t.Fatalf("move provider into test tenant: %v", err)+ }+ if err := db.Model(&entity.TenantModelInstance{}).Where("id = ?", "instance-1").Updates(map[string]interface{}{+ "api_key": "sk-owner-secret",+ "extra": `{"region":"us-east-1","base_url":"https://stored.example"}`,+ }).Error; err != nil {+ t.Fatalf("update saved instance: %v", err)+ }+ if err := db.Create(&entity.UserTenant{+ ID: "user-tenant-member", UserID: "member-1", TenantID: "tenant-1", Role: string(permission.RoleNormal), Status: &activeStatus,+ }).Error; err != nil {+ t.Fatalf("seed tenant member: %v", err)+ }+ provider := dao.GetModelProviderManager().FindProvider("OpenAI")+ if provider == nil {+ t.Fatal("OpenAI provider is not configured")+ }+ probe := &remoteModelProbeDriver{DummyModel: modelModule.NewDummyModel(nil, modelModule.URLSuffix{})}+ originalDriver := provider.ModelDriver+ provider.ModelDriver = probe+ t.Cleanup(func() { provider.ModelDriver = originalDriver })++ service := NewModelProviderService()+ ctx := serviceTestContext(t, "member-1", "tenant-1")+ if _, err := service.ListSupportedModels(ctx, "OpenAI", "default", "member-1", ListSupportedModelsOptions{}); err != nil {+ t.Fatalf("ListSupportedModels(use saved credentials) error = %v, want success", err)+ }+ if probe.listCalls != 1 || probe.listConfig == nil || probe.listConfig.ApiKey == nil || *probe.listConfig.ApiKey != "sk-owner-secret" {+ t.Fatalf("saved-credential list config = %+v, calls %d; want stored key used once", probe.listConfig, probe.listCalls)+ }+ if probe.baseURLs["us-east-1"] != "https://stored.example" || probe.listConfig.Region == nil || *probe.listConfig.Region != "us-east-1" {+ t.Fatalf("saved endpoint = driver URLs %v, config %+v; want persisted endpoint", probe.baseURLs, probe.listConfig)+ }++ attackerURL := "https://attacker.example"+ _, err := service.ListSupportedModels(ctx, "OpenAI", "default", "member-1", ListSupportedModelsOptions{BaseURL: &attackerURL})+ if err == nil || !errors.Is(err, permission.ErrPermissionDenied) {+ t.Fatalf("ListSupportedModels(use permission with endpoint override) error = %v, want hidden denial", err)+ }+ if probe.listCalls != 1 {+ t.Fatalf("provider was called %d times after rejecting endpoint override, want 1", probe.listCalls)+ }++ _, err = service.ListSupportedModels(ctx, "OpenAI", "default", "member-1", ListSupportedModelsOptions{+ APIKeyConfig: json.RawMessage(`{"paddleocr_api_url":"https://attacker.example"}`),+ })+ if err == nil || !errors.Is(err, permission.ErrPermissionDenied) {+ t.Fatalf("ListSupportedModels(use permission with provider endpoint override) error = %v, want hidden denial", err)+ }+ if probe.listCalls != 1 {+ t.Fatalf("provider was called %d times after rejecting provider config override, want 1", probe.listCalls)+ }++ ownerCtx := serviceTestContext(t, "user-1", "tenant-1")+ ownerInstance, code, err := service.ShowProviderInstance(ownerCtx, "OpenAI", "default", "user-1")+ if err != nil || code != common.CodeSuccess || ownerInstance["is_owner"] != true {+ t.Fatalf("ShowProviderInstance(owner) = (%v, %v, %v), want owner metadata", ownerInstance, code, err)+ }+ ownerURL := "https://owner-override.example"+ if _, err = service.ListSupportedModels(ownerCtx, "OpenAI", "default", "user-1", ListSupportedModelsOptions{BaseURL: &ownerURL}); err != nil {+ t.Fatalf("ListSupportedModels(owner endpoint override) error = %v, want success", err)+ }+ if probe.listCalls != 2 || probe.listConfig == nil || probe.listConfig.BaseURL == nil || *probe.listConfig.BaseURL != ownerURL || probe.listConfig.ApiKey == nil || *probe.listConfig.ApiKey != "sk-owner-secret" {+ t.Fatalf("owner override config = %+v, calls %d; want saved key sent only to owner endpoint", probe.listConfig, probe.listCalls)+ }+}+func TestCheckConnectionDeniesBeforeCallingProvider(t *testing.T) {db := setupModelProviderServiceTestDB(t)useModelProviderServiceTestDB(t, db)@@ -768,7 +934,11 @@ func TestCheckConnectionDeniesBeforeCallingProvider(t *testing.T) {provider.ModelDriver = probet.Cleanup(func() { provider.ModelDriver = originalDriver })- code, err := NewModelProviderService().CheckConnection(serviceTestContext(t, "member-1", "tenant-1", "user-1"), "OpenAI", "sk-test", "default", "", "instance-1", "member-1", nil)+ code, err := NewModelProviderService().CheckConnection(serviceTestContext(t, "member-1", "tenant-1", "user-1"), "OpenAI", CheckConnectionRequest{+ APIKey: json.RawMessage(`"sk-test"`),+ Region: "default",+ InstanceID: "instance-1",+ }, "member-1")if err == nil || code != common.CodeNotFound {t.Fatalf("CheckConnection() = (%v, %v), want hidden update denial", code, err)}@@ -777,6 +947,78 @@ func TestCheckConnectionDeniesBeforeCallingProvider(t *testing.T) {}}+func TestCheckConnectionUsesStoredCredentialsAndAllowsOwnerOverrides(t *testing.T) {+ db := setupModelProviderServiceTestDB(t)+ useModelProviderServiceTestDB(t, db)+ seedModelProviderServiceScope(t, db)+ if err := db.Model(&entity.TenantModelInstance{}).Where("id = ?", "instance-1").Updates(map[string]interface{}{+ "api_key": "sk-stored-secret",+ "extra": `{"region":"us-east-1","base_url":"https://stored.example"}`,+ }).Error; err != nil {+ t.Fatalf("update saved instance: %v", err)+ }++ provider := dao.GetModelProviderManager().FindProvider("OpenAI")+ if provider == nil {+ t.Fatal("OpenAI provider is not configured")+ }+ probe := &remoteModelProbeDriver{DummyModel: modelModule.NewDummyModel(nil, modelModule.URLSuffix{})}+ originalDriver := provider.ModelDriver+ provider.ModelDriver = probe+ t.Cleanup(func() { provider.ModelDriver = originalDriver })++ service := NewModelProviderService()+ ctx := serviceTestContext(t, "user-1", "tenant-1", "user-1")+ modelInfo := []CheckConnectionModelInfo{{ModelName: "gpt-test", ModelTypes: []string{"doc_parse"}}}+ code, err := service.CheckConnection(ctx, "OpenAI", CheckConnectionRequest{+ UseSavedCredentials: true,+ InstanceID: "instance-1",+ ModelInfo: modelInfo,+ }, "user-1")+ if err != nil || code != common.CodeSuccess {+ t.Fatalf("CheckConnection(saved) = (%v, %v), want success", code, err)+ }+ if probe.checkConfig == nil || probe.checkConfig.ApiKey == nil || *probe.checkConfig.ApiKey != "sk-stored-secret" {+ t.Fatalf("saved API key = %+v, want stored credential", probe.checkConfig)+ }+ if probe.checkConfig.BaseURL == nil || *probe.checkConfig.BaseURL != "https://stored.example" || probe.checkConfig.Region == nil || *probe.checkConfig.Region != "us-east-1" {+ t.Fatalf("saved endpoint config = %+v, want persisted endpoint settings", probe.checkConfig)+ }++ code, err = service.CheckConnection(ctx, "OpenAI", CheckConnectionRequest{+ BaseURL: "https://attacker.example",+ InstanceID: "instance-1",+ ModelInfo: modelInfo,+ }, "user-1")+ if err != nil || code != common.CodeSuccess {+ t.Fatalf("CheckConnection(custom endpoint) = (%v, %v), want provider probe success", code, err)+ }+ if probe.checkConfig == nil || probe.checkConfig.ApiKey == nil || *probe.checkConfig.ApiKey != "" {+ t.Fatalf("custom endpoint received saved credential: %+v", probe.checkConfig)+ }+ if probe.checkConfig.BaseURL == nil || *probe.checkConfig.BaseURL != "https://attacker.example" {+ t.Fatalf("custom endpoint = %+v, want caller-supplied URL", probe.checkConfig)+ }++ code, err = service.CheckConnection(ctx, "OpenAI", CheckConnectionRequest{+ UseSavedCredentials: true,+ BaseURL: "https://owner-override.example",+ Region: "eu-west-1",+ APIKeyConfig: json.RawMessage(`{"group_id":"owner-group"}`),+ InstanceID: "instance-1",+ ModelInfo: modelInfo,+ }, "user-1")+ if err != nil || code != common.CodeSuccess {+ t.Fatalf("CheckConnection(owner saved credential overrides) = (%v, %v), want success", code, err)+ }+ if probe.checkConfig == nil || probe.checkConfig.ApiKey == nil || *probe.checkConfig.ApiKey != `{"api_key":"sk-stored-secret","group_id":"owner-group"}` {+ t.Fatalf("owner-saved API key config = %+v, want stored key plus config override", probe.checkConfig)+ }+ if probe.checkConfig.BaseURL == nil || *probe.checkConfig.BaseURL != "https://owner-override.example" || probe.checkConfig.Region == nil || *probe.checkConfig.Region != "eu-west-1" {+ t.Fatalf("owner-saved endpoint override = %+v, want supplied URL and region", probe.checkConfig)+ }+}+func TestModelFactoryResolveModelConfigByID(t *testing.T) {db := setupModelProviderServiceTestDB(t)useModelProviderServiceTestDB(t, db)@@ -1360,7 +1602,8 @@ func TestAlterProviderInstanceUsesActiveTenantProvider(t *testing.T) {"DeepSeek","instance-2","ds",- "sk-tenant-2-updated",+ json.RawMessage(`"sk-tenant-2-updated"`),+ false,"https://api.deepseek.com","default",[]CreateInstanceModelInfo{{ModelName: "deepseek-v4-pro", ModelTypes: []string{"chat"}, MaxTokens: 8192}},@@ -1426,7 +1669,8 @@ func TestAlterProviderInstanceReportsInstanceProviderMismatch(t *testing.T) {"OpenAI","instance-deepseek","ds",- "sk-should-not-be-written",+ json.RawMessage(`"sk-should-not-be-written"`),+ false,"","",[]CreateInstanceModelInfo{{ModelName: "gpt-test", ModelTypes: []string{"chat"}, MaxTokens: 8192}},@@ -1464,14 +1708,14 @@ func TestAlterProviderInstanceScopesToActiveTenant(t *testing.T) {service := NewModelProviderService()if code, err := service.AlterProviderInstance(serviceTestContext(t, "user-1", "tenant-2"),- "user-1", "DeepSeek", "instance-2", "ds", "sk-from-tenant-2", "", "",+ "user-1", "DeepSeek", "instance-2", "ds", json.RawMessage(`"sk-from-tenant-2"`), false, "", "",[]CreateInstanceModelInfo{{ModelName: "model-2", ModelTypes: []string{"chat"}, MaxTokens: 8192}},); err != nil || code != common.CodeSuccess {t.Fatalf("AlterProviderInstance(tenant-2) = (%v, %v), want success", code, err)}if code, err := service.AlterProviderInstance(serviceTestContext(t, "user-1", "tenant-1"),- "user-1", "DeepSeek", "instance-1", "ds", "sk-from-tenant-1", "", "",+ "user-1", "DeepSeek", "instance-1", "ds", json.RawMessage(`"sk-from-tenant-1"`), false, "", "",[]CreateInstanceModelInfo{{ModelName: "model-1", ModelTypes: []string{"chat"}, MaxTokens: 8192}},); err != nil || code != common.CodeSuccess {t.Fatalf("AlterProviderInstance(tenant-1) = (%v, %v), want success", code, err)diff --git a/web/src/hooks/use-llm-request.tsx b/web/src/hooks/use-llm-request.tsxindex 381dc8b086..d8302d6091 100644--- a/web/src/hooks/use-llm-request.tsx+++ b/web/src/hooks/use-llm-request.tsx@@ -358,7 +358,10 @@ export const useVerifyProviderConnection = () => {mutationKey: [LLMApiAction.VerifyProviderConnection],mutationFn: async (params: {provider_name: string;- api_key: string;+ api_key?: string | Record<string, any>;+ clear_api_key?: boolean;+ use_saved_credentials?: boolean;+ api_key_config?: Record<string, unknown>;base_url?: string;region?: string;model_info?: IModelInfo[];@@ -376,22 +379,38 @@ export const useListProviderModels = () => {const { isPending: loading, mutateAsync } = useMutation({mutationKey: [LLMApiAction.ListProviderModels],mutationFn: async (params: IListProviderModelsRequestBody) => {- const { provider_name, api_key, base_url, instance_name } = params;+ const {+ provider_name,+ api_key,+ base_url,+ region,+ use_saved_credentials,+ api_key_config,+ instance_name,+ } = params;// GET /api/v1/providers/<provider_name>/models// The API accepts api_key and base_url as optional query parameters.// api_key is expected as a string; values in {} object form must be// JSON-stringified before being sent.const queryParams: Record<string, string> = {};- if (api_key) {+ if (!use_saved_credentials && api_key !== undefined) {queryParams.api_key =typeof api_key === 'string' ? api_key : JSON.stringify(api_key);}- if (base_url) {+ if (base_url !== undefined) {queryParams.base_url = base_url;}- // Sent for an already-saved instance: the API then uses the stored- // credential and base URL, which is the only way a provider with no- // bundled catalog can be listed after saving.+ if (region !== undefined) {+ queryParams.region = region;+ }+ if (use_saved_credentials) {+ queryParams.use_saved_credentials = 'true';+ if (api_key_config !== undefined) {+ queryParams.api_key_config = JSON.stringify(api_key_config);+ }+ }+ // Identifies the saved instance used for credentials and fallback+ // configuration when the form does not supply a value.if (instance_name) {queryParams.instance_name = instance_name;}diff --git a/web/src/interfaces/database/llm.ts b/web/src/interfaces/database/llm.tsindex 0d487666a7..6ba8a36753 100644--- a/web/src/interfaces/database/llm.ts+++ b/web/src/interfaces/database/llm.ts@@ -55,30 +55,28 @@ export interface IAvailableProvider {}export interface IProviderInstance {- /**- * Usually a plain key string, but the showProviderInstance endpoint- * may return an object `{ api_key, ...nested }` for providers that- * bundle extra credentials (see the nested fields below).- */- api_key: string | Record<string, any>;id: string;instance_name: string;provider_id: string;region: string;status: string;+ /** Whether the current user owns this model instance. */+ is_owner?: boolean;+ /** Whether the server has a credential configured for this instance. */+ api_key_configured?: boolean;+ /** Safe provider configuration values; secret values are never returned. */+ api_key_config?: Record<string, any>;+ /** Names of configured credential fields, without their values. */+ credential_status?: Record<string, boolean>;+ /** Masked credential previews; actual credential values are never returned. */+ credential_masks?: Record<string, string>;/*** Optional: only returned by the showProviderInstance endpoint. Used* to pre-fill the base_url form field when opening a saved* instance.*/base_url?: string;- /**- * Provider-specific credentials that may be returned either at the top- * level or nested inside `api_key`:- * - group_id → MiniMax- * - api_version → Azure OpenAI- * - provider_order → OpenRouter- */+ /** Safe provider-specific settings returned separately from secrets. */group_id?: string;api_version?: string;provider_order?: string;diff --git a/web/src/interfaces/request/llm.ts b/web/src/interfaces/request/llm.tsindex cdcf8a9725..f34f3afdc2 100644--- a/web/src/interfaces/request/llm.ts+++ b/web/src/interfaces/request/llm.ts@@ -98,12 +98,10 @@ export interface IUpdateProviderInstanceRequestBody {provider_name: string;instance_name: string;id: string;- /**- * Either a plain API-key string, or — for providers that need an- * extra credential such as MiniMax's `group_id` — an object bundling- * the key with those fields: `{ api_key, group_id }`.- */+ /** Plain API key or a provider credential/configuration object. Blank+ * credential values keep the saved value; use clear_api_key to remove it. */api_key?: string | Record<string, any>;+ clear_api_key?: boolean;base_url?: string;region?: string;model_info?: IModelInfo[];@@ -151,9 +149,11 @@ export interface IListProviderModelsRequestBody {base_url?: string;region?: string;model_info?: IModelInfo[];+ use_saved_credentials?: boolean;+ api_key_config?: Record<string, unknown>;/**- * An already-saved instance: the server then lists with the stored credential- * and base URL, so the picker works without the browser ever holding the key.+ * Identifies the saved instance whose credentials should be used while the+ * server applies the current form's non-secret configuration and endpoint.*/instance_name?: string;}diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 9fd1ff6bf2..4ce5e2a779 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -2136,6 +2136,8 @@ Example: Virtual Hosted Style`,apiKey: 'API Key',apiKeyMessage: 'Please enter the API Key',apiKeyPlaceholder: 'Please enter the API Key',+ credentialClearToRemove:+ 'Clear this field to remove the saved credential',apiKeyTip:'The API Key can be obtained by registering the corresponding LLM supplier.',aimlapiGetKey: 'Get API key',diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.tsindex 11c1630977..afcd678ae3 100644--- a/web/src/locales/zh.ts+++ b/web/src/locales/zh.ts@@ -1760,6 +1760,7 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 RapiKey: 'API Key',apiKeyMessage: '请输入API Key',apiKeyPlaceholder: '请输入API Key',+ credentialClearToRemove: '清空此字段并保存即可移除已保存的凭据',apiKeyTip: 'API Key可以通过注册相应的LLM供应商来获取。',aimlapiGetKey: '获取 API Key',aimlapiCheckStatus: '检查状态',diff --git a/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx b/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxindex e9a5a002d7..336828d4f0 100644--- a/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx+++ b/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx@@ -14,10 +14,33 @@* limitations under the License.*/-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react';import { createRef } from 'react';import { BedrockInstanceCard } from './bedrock-instance-card';+import {+ applySavedCredentialEdits,+ buildApiKeyValue,+ SAVED_CREDENTIAL_MASK,+} from './hooks';++const originalResizeObserver = global.ResizeObserver;+beforeAll(() => {+ global.ResizeObserver = class {+ observe() {}+ unobserve() {}+ disconnect() {}+ };+});+afterAll(() => {+ global.ResizeObserver = originalResizeObserver;+});type TestCardRef = {validate: () => Promise<boolean>;@@ -46,11 +69,13 @@ const savedInstanceDetails = {provider_id: 'provider-id',region: 'us-east-1',status: 'active',- api_key: JSON.stringify({+ is_owner: true,+ api_key_configured: true,+ api_key_config: {auth_mode: 'bedrock_api_key',- bedrock_api_key: 'old-key',bedrock_region: 'us-east-1',- }),+ },+ credential_status: { bedrock_api_key: true },};jest.mock('react-i18next', () => ({@@ -156,6 +181,44 @@ describe('BedrockInstanceCard', () => {];});+ it('drops unchanged saved masks when another Bedrock credential changes', () => {+ expect(+ applySavedCredentialEdits(+ {+ auth_mode: 'iam_role',+ aws_role_arn: SAVED_CREDENTIAL_MASK,+ bedrock_ak: SAVED_CREDENTIAL_MASK,+ bedrock_sk: SAVED_CREDENTIAL_MASK,+ },+ {+ aws_role_arn: 'arn:aws:iam::123456789012:role/model',+ bedrock_ak: SAVED_CREDENTIAL_MASK,+ bedrock_sk: SAVED_CREDENTIAL_MASK,+ },+ { aws_role_arn: true, bedrock_ak: true, bedrock_sk: true },+ ),+ ).toEqual({+ auth_mode: 'iam_role',+ aws_role_arn: 'arn:aws:iam::123456789012:role/model',+ });+ });++ it('omits unchanged masks and sends null when a saved credential is cleared', () => {+ expect(+ buildApiKeyValue({ api_key: SAVED_CREDENTIAL_MASK }, { api_key: true }),+ ).toBeUndefined();+ expect(buildApiKeyValue({ api_key: '' }, { api_key: true })).toEqual({+ api_key: null,+ });+ expect(+ applySavedCredentialEdits(+ { auth_mode: 'bedrock_api_key', bedrock_api_key: '' },+ { bedrock_api_key: '' },+ { bedrock_api_key: true },+ ),+ ).toEqual({ auth_mode: 'bedrock_api_key', bedrock_api_key: null });+ });+it('creates an API key instance without manual model fields', async () => {const ref = createRef<TestCardRef>();render(@@ -169,7 +232,6 @@ describe('BedrockInstanceCard', () => {provider_id: 'provider-id',region: 'us-east-1',status: 'active',- api_key: '',}}/>,);@@ -226,7 +288,6 @@ describe('BedrockInstanceCard', () => {provider_id: 'provider-id',region: 'us-east-1',status: 'active',- api_key: '',}}/>,);@@ -257,17 +318,24 @@ describe('BedrockInstanceCard', () => {provider_id: 'provider-id',region: 'us-east-1',status: 'active',- api_key: '',}}/>,);- await screen.findByPlaceholderText('apiKeyMessage');+ const credentialInput = await waitFor(() => {+ const input = document.querySelector<HTMLInputElement>(+ 'input[name="bedrock_api_key"]',+ );+ expect(input).not.toBeNull();+ return input!;+ });+ expect(credentialInput.value).toBe(SAVED_CREDENTIAL_MASK);await waitFor(() => expect(ref.current?.getSavePayload()).toBeNull());- fireEvent.click(screen.getByRole('button', { name: 'accessKey' }));- fireEvent.click(screen.getByRole('button', { name: 'apiKey' }));- const input = await screen.findByPlaceholderText('apiKeyMessage');- fireEvent.change(input, { target: { value: 'new-key' } });+ const input = document.querySelector<HTMLInputElement>(+ 'input[name="bedrock_api_key"]',+ );+ expect(input?.value).toBe(SAVED_CREDENTIAL_MASK);+ fireEvent.change(input!, { target: { value: 'new-key' } });await waitFor(() => {const result = ref.current?.getSavePayload();@@ -291,6 +359,52 @@ describe('BedrockInstanceCard', () => {});});+ it('clearing a masked field removes the saved credential on save', async () => {+ const ref = createRef<TestCardRef>();+ render(+ <BedrockInstanceCard+ ref={ref}+ providerName="Bedrock"+ defaultOpen+ instance={{+ id: 'instance-id',+ instance_name: 'saved-instance',+ provider_id: 'provider-id',+ region: 'us-east-1',+ status: 'active',+ }}+ />,+ );++ const input = await waitFor(() => {+ const field = document.querySelector<HTMLInputElement>(+ 'input[name="bedrock_api_key"]',+ );+ expect(field).not.toBeNull();+ return field!;+ });+ expect(input.value).toBe(SAVED_CREDENTIAL_MASK);+ fireEvent.change(input, { target: { value: '' } });++ await waitFor(() => {+ const payload = ref.current?.getSavePayload()?.payload;+ expect(payload?.clear_api_key).toBeUndefined();+ expect(payload?.api_key).toMatchObject({ bedrock_api_key: null });+ });+ expect(+ screen.queryByRole('button', { name: /removeSavedCredentials/i }),+ ).toBeNull();+ let isValid = false;+ await act(async () => {+ isValid = (await ref.current?.validate()) ?? false;+ });+ expect(isValid).toBe(true);+ act(() => ref.current?.markSaved());+ await waitFor(() => {+ expect(ref.current?.getSavePayload()).toBeNull();+ });+ });+it('stops saving when the model snapshot becomes stale', async () => {const ref = createRef<TestCardRef>();const card = (@@ -304,7 +418,6 @@ describe('BedrockInstanceCard', () => {provider_id: 'provider-id',region: 'us-east-1',status: 'active',- api_key: '',}}/>);@@ -320,7 +433,7 @@ describe('BedrockInstanceCard', () => {);});- it('restores saved credentials before model discovery starts', async () => {+ it('restores safe auth metadata without exposing credentials before model discovery starts', async () => {mockFetchProviderInstance.mockReturnValue({data: undefined,refetch: mockRefetchProviderInstance,@@ -335,7 +448,6 @@ describe('BedrockInstanceCard', () => {provider_id: 'provider-id',region: 'us-east-1',status: 'active',- api_key: '',}}/>,);@@ -356,7 +468,6 @@ describe('BedrockInstanceCard', () => {provider_id: 'provider-id',region: 'us-east-1',status: 'active',- api_key: '',}}/>,);@@ -365,7 +476,6 @@ describe('BedrockInstanceCard', () => {expect(mockCatalogCredentials).toHaveBeenCalledWith({apiKey: {auth_mode: 'bedrock_api_key',- bedrock_api_key: 'old-key',bedrock_region: 'us-east-1',},baseUrl: undefined,diff --git a/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx b/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxindex 18f93a73fb..dedbd1bb97 100644--- a/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx+++ b/web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx@@ -59,7 +59,17 @@ import {ProviderInstanceCardProps,ProviderInstanceCardRef,} from './interface';-import { unwrapApiKey } from './hooks';+import {+ applySavedCredentialEdits,+ SAVED_CREDENTIAL_MASK,+ unwrapApiKey,+} from './hooks';+import {+ SavedProviderConfigFieldSet,+ hasUnsavedProviderCredential,+ pickSavedProviderConfigOverrides,+} from './saved-provider-config';+import { SavedCredentialInput } from './saved-credential-input';import { ModelsSection } from './models-section';import VerifyButton from './verify-button';@@ -118,6 +128,12 @@ export const BedrockInstanceCard = forwardRef<}}, [providerName, isDraft]);+ const { data: instanceDetails, refetch: refetchInstanceDetails } =+ useFetchProviderInstance(+ isDraft ? '' : providerName,+ isDraft ? '' : instance.id,+ );+const FormSchema = useMemo(() =>z@@ -168,15 +184,31 @@ export const BedrockInstanceCard = forwardRef<});}}- if (data.auth_mode === 'access_key_secret') {- if (!data.bedrock_ak || !data.bedrock_ak.trim()) {+ const savedConfig = instanceDetails?.api_key_config ?? {};+ const storedAuthMode = savedConfig.auth_mode;+ const credentialStatus = instanceDetails?.credential_status ?? {};+ const mayKeepStoredCredentials =+ !isDraft && data.auth_mode === storedAuthMode;+ const hasStoredBedrockAccessKeys =+ mayKeepStoredCredentials &&+ credentialStatus.bedrock_ak === true &&+ credentialStatus.bedrock_sk === true;+ const removingStoredAccessKeys =+ hasStoredBedrockAccessKeys &&+ data.bedrock_ak === '' &&+ data.bedrock_sk === '';+ if (+ data.auth_mode === 'access_key_secret' &&+ !removingStoredAccessKeys+ ) {+ if (!data.bedrock_ak?.trim()) {ctx.addIssue({code: z.ZodIssueCode.custom,message: tSetting('bedrockAKMessage'),path: ['bedrock_ak'],});}- if (!data.bedrock_sk || !data.bedrock_sk.trim()) {+ if (!data.bedrock_sk?.trim()) {ctx.addIssue({code: z.ZodIssueCode.custom,message: tSetting('bedrockSKMessage'),@@ -185,7 +217,19 @@ export const BedrockInstanceCard = forwardRef<}}if (data.auth_mode === 'iam_role') {- if (!data.aws_role_arn || !data.aws_role_arn.trim()) {+ const canKeepStoredRoleArn =+ mayKeepStoredCredentials &&+ credentialStatus.aws_role_arn === true &&+ data.aws_role_arn === SAVED_CREDENTIAL_MASK;+ const removingStoredRoleArn =+ mayKeepStoredCredentials &&+ credentialStatus.aws_role_arn === true &&+ data.aws_role_arn === '';+ if (+ !data.aws_role_arn?.trim() &&+ !canKeepStoredRoleArn &&+ !removingStoredRoleArn+ ) {ctx.addIssue({code: z.ZodIssueCode.custom,message: tSetting('awsRoleArnMessage'),@@ -195,7 +239,11 @@ export const BedrockInstanceCard = forwardRef<}if (data.auth_mode === 'bedrock_api_key' &&- !data.bedrock_api_key?.trim()+ !data.bedrock_api_key?.trim() &&+ !(+ mayKeepStoredCredentials &&+ credentialStatus.bedrock_api_key === true+ )) {ctx.addIssue({code: z.ZodIssueCode.custom,@@ -204,15 +252,9 @@ export const BedrockInstanceCard = forwardRef<});}}),- [isDraft, tSetting],+ [instanceDetails, isDraft, tSetting],);- const { data: instanceDetails, refetch: refetchInstanceDetails } =- useFetchProviderInstance(- isDraft ? '' : providerName,- isDraft ? '' : instance.id,- );-// Lazily fetch full instance details only when the card is open.// Collapsed cards never hit /providers/<name>/instances/<instance_name>;// expanding one triggers a fresh refetch.@@ -230,13 +272,26 @@ export const BedrockInstanceCard = forwardRef<const initialValues = useMemo<BedrockFormValues>(() => {const merged = { ...instance, ...(instanceDetails ?? {}) } as any;- const { nested: apiKey } = unwrapApiKey(merged.api_key);+ const { nested: apiKey } = unwrapApiKey(merged.api_key_config);+ const credentialStatus = merged.credential_status ?? {};return {auth_mode: (apiKey.auth_mode as AuthMode) ?? 'access_key_secret',- bedrock_ak: apiKey.bedrock_ak ?? '',- bedrock_sk: apiKey.bedrock_sk ?? '',- aws_role_arn: apiKey.aws_role_arn ?? '',- bedrock_api_key: apiKey.bedrock_api_key ?? '',+ bedrock_ak:+ credentialStatus.bedrock_ak === true+ ? SAVED_CREDENTIAL_MASK+ : (apiKey.bedrock_ak ?? ''),+ bedrock_sk:+ credentialStatus.bedrock_sk === true+ ? SAVED_CREDENTIAL_MASK+ : (apiKey.bedrock_sk ?? ''),+ aws_role_arn:+ credentialStatus.aws_role_arn === true+ ? SAVED_CREDENTIAL_MASK+ : (apiKey.aws_role_arn ?? ''),+ bedrock_api_key:+ credentialStatus.bedrock_api_key === true+ ? SAVED_CREDENTIAL_MASK+ : (apiKey.bedrock_api_key ?? ''),bedrock_region:apiKey.bedrock_region ??(merged.region && merged.region !== 'default' ? merged.region : ''),@@ -260,6 +315,18 @@ export const BedrockInstanceCard = forwardRef<}, [initialValues]);const authMode = useWatch({ control: form.control, name: 'auth_mode' });+ const storedCredentialStatus = useMemo(+ () => instanceDetails?.credential_status ?? {},+ [instanceDetails?.credential_status],+ );+ const canKeepStoredCredentials =+ !isDraft && authMode === instanceDetails?.api_key_config?.auth_mode;+ const canKeepStoredBedrockAccessKeys =+ canKeepStoredCredentials &&+ storedCredentialStatus.bedrock_ak === true &&+ storedCredentialStatus.bedrock_sk === true;+ const canKeepStoredBedrockAPIKey =+ canKeepStoredCredentials && storedCredentialStatus.bedrock_api_key === true;const regionOptions = useMemo(() => BedrockRegionList.map((x) => ({ value: x, label: tSetting(x) })),@@ -292,14 +359,24 @@ export const BedrockInstanceCard = forwardRef<model_type: values.model_type,};const { instancePayload, modelPayload } = splitProviderPayload(flat);+ const credentialStatus = instanceDetails?.credential_status ?? {};const payload: Record<string, any> = {instance_name: instanceName,- api_key: instancePayload.api_key,+ api_key: applySavedCredentialEdits(+ instancePayload.api_key,+ values,+ credentialStatus,+ ),base_url: instancePayload.base_url,region: instancePayload.region,};if (forDraft) {payload.llm_factory = providerName;+ } else {+ const storedAuthMode = instanceDetails?.api_key_config?.auth_mode;+ if (storedAuthMode && storedAuthMode !== values.auth_mode) {+ payload.clear_api_key = true;+ }}if (forDraft && values.auth_mode !== 'bedrock_api_key') {payload.max_tokens = modelPayload.max_tokens;@@ -309,7 +386,11 @@ export const BedrockInstanceCard = forwardRef<}return payload;},- [providerName],+ [+ instanceDetails?.api_key_config,+ instanceDetails?.credential_status,+ providerName,+ ],);const transformModelCredentials = useCallback(@@ -353,11 +434,43 @@ export const BedrockInstanceCard = forwardRef<draftName.trim() || instance.instance_name,isDraft,);+ const currentValues = values as Record<string, any>;+ const credentialChanged = Object.entries(storedCredentialStatus).some(+ ([field, configured]) =>+ configured &&+ !SavedProviderConfigFieldSet.has(field) &&+ currentValues[field] !== undefined &&+ currentValues[field] !== SAVED_CREDENTIAL_MASK,+ );+ const useSavedCredentials =+ !isDraft &&+ !payload.clear_api_key &&+ !credentialChanged &&+ !hasUnsavedProviderCredential(payload.api_key);+ const canOverrideSavedCredentials =+ useSavedCredentials && instanceDetails?.is_owner === true;+ const savedConfigOverrides = canOverrideSavedCredentials+ ? pickSavedProviderConfigOverrides(payload.api_key)+ : {};const ret = await verifyProviderConnection({provider_name: providerName,- api_key: JSON.stringify(payload.api_key),- base_url: payload.base_url,- region: payload.region,+ ...(!isDraft ? { instance_id: instance.id } : {}),+ ...(payload.clear_api_key ? { clear_api_key: true } : {}),+ ...(useSavedCredentials+ ? {+ use_saved_credentials: true,+ ...(Object.keys(savedConfigOverrides).length > 0+ ? { api_key_config: savedConfigOverrides }+ : {}),+ ...(canOverrideSavedCredentials+ ? { base_url: payload.base_url, region: payload.region }+ : {}),+ }+ : {+ api_key: JSON.stringify(payload.api_key),+ base_url: payload.base_url,+ region: payload.region,+ }),model_info: payload.model_info,});return {@@ -370,6 +483,9 @@ export const BedrockInstanceCard = forwardRef<buildPayload,draftName,instance.instance_name,+ instance.id,+ instanceDetails?.is_owner,+ storedCredentialStatus,verifyProviderConnection,tSetting,isDraft,@@ -598,16 +714,38 @@ export const BedrockInstanceCard = forwardRef<<RAGFlowFormItemname="bedrock_ak"label={tSetting('awsAccessKeyId')}- required+ required={!canKeepStoredBedrockAccessKeys}>- <Input placeholder={tSetting('bedrockAKMessage')} />+ {(field) => (+ <SavedCredentialInput+ {...field}+ maskedValue={instanceDetails?.credential_masks?.bedrock_ak}+ placeholder={tSetting(+ storedCredentialStatus.bedrock_ak === true+ ? 'credentialClearToRemove'+ : 'bedrockAKMessage',+ )}+ autoComplete="new-password"+ />+ )}</RAGFlowFormItem><RAGFlowFormItemname="bedrock_sk"label={tSetting('awsSecretAccessKey')}- required+ required={!canKeepStoredBedrockAccessKeys}>- <Input placeholder={tSetting('bedrockSKMessage')} />+ {(field) => (+ <SavedCredentialInput+ {...field}+ maskedValue={instanceDetails?.credential_masks?.bedrock_sk}+ placeholder={tSetting(+ storedCredentialStatus.bedrock_sk === true+ ? 'credentialClearToRemove'+ : 'bedrockSKMessage',+ )}+ autoComplete="new-password"+ />+ )}</RAGFlowFormItem></>)}@@ -616,24 +754,49 @@ export const BedrockInstanceCard = forwardRef<<RAGFlowFormItemname="aws_role_arn"label={tSetting('awsRoleArn')}- required+ required={+ !canKeepStoredCredentials ||+ storedCredentialStatus.aws_role_arn !== true+ }>- <Input placeholder={tSetting('awsRoleArnMessage')} />+ {(field) => (+ <SavedCredentialInput+ {...field}+ maskedValue={instanceDetails?.credential_masks?.aws_role_arn}+ autoComplete="new-password"+ placeholder={tSetting(+ storedCredentialStatus.aws_role_arn === true+ ? 'credentialClearToRemove'+ : 'awsRoleArnMessage',+ )}+ />+ )}</RAGFlowFormItem>)}{authMode === 'bedrock_api_key' && (- <RAGFlowFormItem- name="bedrock_api_key"- label={tSetting('apiKey')}- required- >- <Input- type="password"- placeholder={tSetting('apiKeyMessage')}- autoComplete="off"- />- </RAGFlowFormItem>+ <>+ <RAGFlowFormItem+ name="bedrock_api_key"+ label={tSetting('apiKey')}+ required={!canKeepStoredBedrockAPIKey}+ >+ {(field) => (+ <SavedCredentialInput+ {...field}+ maskedValue={+ instanceDetails?.credential_masks?.bedrock_api_key+ }+ placeholder={tSetting(+ storedCredentialStatus.bedrock_api_key === true+ ? 'credentialClearToRemove'+ : 'apiKeyMessage',+ )}+ autoComplete="new-password"+ />+ )}+ </RAGFlowFormItem>+ </>)}{authMode === 'assume_role' && (@@ -800,7 +963,7 @@ export const BedrockInstanceCard = forwardRef<<ModelsSectionproviderName={providerName}instanceName={instance.instance_name || '__draft__'}- instance={instance}+ instance={{ ...instance, ...(instanceDetails ?? {}) }}hideActions={false}hideIfEmpty={false}instanceDetailsLoadeddiff --git a/web/src/pages/user-setting/setting-model/instance-card/hooks.tsx b/web/src/pages/user-setting/setting-model/instance-card/hooks.tsxindex d273fce8a7..c04a1433da 100644--- a/web/src/pages/user-setting/setting-model/instance-card/hooks.tsx+++ b/web/src/pages/user-setting/setting-model/instance-card/hooks.tsx@@ -14,24 +14,37 @@* limitations under the License.*/-import { DynamicFormRef } from '@/components/dynamic-form';+import { DynamicFormRef, FormFieldType } from '@/components/dynamic-form';import {useDeleteProviderInstance,useFetchAvailableProviders,useFetchProviderInstance,useVerifyProviderConnection,} from '@/hooks/use-llm-request';+import { useTranslate } from '@/hooks/common-hooks';import { IProviderInstance } from '@/interfaces/database/llm';import { IModelInfo } from '@/interfaces/request/llm';import { RefObject, useCallback, useEffect, useMemo, useRef } from 'react';import { getProviderConfig } from '../provider-schema/field-config';import { useProviderFields } from '../provider-schema/hooks';import { SelectOption } from '../provider-schema/types';+import type { ControllerRenderProps } from 'react-hook-form';import {API_KEY_NESTED_FIELDS,ApiKeyNestedField,InstanceSavePayload,} from './interface';+import {+ SAVED_CREDENTIAL_MASK,+ SavedCredentialInput,+} from './saved-credential-input';+import {+ SavedProviderConfigFieldSet,+ hasUnsavedProviderCredential,+ pickSavedProviderConfigOverrides,+} from './saved-provider-config';++export { SAVED_CREDENTIAL_MASK } from './saved-credential-input';// ---------------------------------------------------------------------------// Pure helpers - api_key shape normalization@@ -46,26 +59,113 @@ import {*/export function buildApiKeyValue(values: Record<string, any>,+ credentialStatus: Record<string, boolean> = {},): string | Record<string, any> | undefined {- const nested: Record<string, any> = {};+ const config: Record<string, any> = {};+ const apiKey = values.api_key;+ if (credentialStatus.api_key === true) {+ if (apiKey !== SAVED_CREDENTIAL_MASK && apiKey !== undefined) {+ config.api_key = apiKey === '' ? null : apiKey;+ }+ } else if (apiKey !== undefined && apiKey !== '') {+ config.api_key = apiKey;+ }+for (const field of API_KEY_NESTED_FIELDS) {const v = values[field];- if (v !== undefined && v !== '') nested[field] = v;+ if (credentialStatus[field] === true) {+ if (v !== SAVED_CREDENTIAL_MASK && v !== undefined) {+ config[field] = v === '' ? null : v;+ }+ } else if (v !== undefined && v !== '') {+ config[field] = v;+ }+ }++ const keys = Object.keys(config);+ if (keys.length === 0) {+ return apiKey === SAVED_CREDENTIAL_MASK ? undefined : apiKey;+ }+ if (keys.length === 1 && keys[0] === 'api_key' && config.api_key !== null) {+ return config.api_key;+ }+ return config;+}++/**+ * Apply edits to credentials already stored in a provider's structured+ * `api_key` value. Unchanged masks are omitted so the backend preserves those+ * fields; an emptied field is sent as null so the backend removes it.+ */+export function applySavedCredentialEdits(+ apiKey: unknown,+ values: Record<string, any>,+ credentialStatus: Record<string, boolean> = {},+): unknown {+ const changes: Record<string, any> = {};+ for (const [field, configured] of Object.entries(credentialStatus)) {+ if (!configured) continue;+ const value = values[field];+ if (value === undefined || value === SAVED_CREDENTIAL_MASK) continue;+ changes[field] = value === '' || value === null ? null : value;+ }+ if (Object.keys(changes).length === 0) {+ if (+ typeof apiKey === 'string' &&+ credentialStatus.api_key === true &&+ values.api_key === SAVED_CREDENTIAL_MASK+ ) {+ return undefined;+ }+ if (apiKey && typeof apiKey === 'object' && !Array.isArray(apiKey)) {+ const config = { ...(apiKey as Record<string, any>) };+ for (const [field, configured] of Object.entries(credentialStatus)) {+ if (configured && config[field] === SAVED_CREDENTIAL_MASK) {+ delete config[field];+ }+ }+ return config;+ }+ if (typeof apiKey === 'string' && apiKey.trim() === '') {+ return undefined;+ }+ return apiKey;}- if (Object.keys(nested).length === 0) return values.api_key;- return { api_key: values.api_key ?? '', ...nested };++ let config: Record<string, any> = {};+ if (apiKey && typeof apiKey === 'object' && !Array.isArray(apiKey)) {+ config = { ...(apiKey as Record<string, any>) };+ } else if (typeof apiKey === 'string' && apiKey !== '') {+ try {+ const parsed = JSON.parse(apiKey);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ config = parsed;+ } else {+ config.api_key = apiKey;+ }+ } catch {+ config.api_key = apiKey;+ }+ }+ Object.assign(config, changes);+ for (const [field, configured] of Object.entries(credentialStatus)) {+ if (configured && config[field] === SAVED_CREDENTIAL_MASK) {+ delete config[field];+ }+ }+ if (+ Object.keys(config).length === 1 &&+ Object.prototype.hasOwnProperty.call(config, 'api_key') &&+ config.api_key !== null+ ) {+ return config.api_key;+ }+ return config;}/**- * Inverse of `buildApiKeyValue`, used on the echo/prefill path. The- * backend persists the credential bundle as a JSON string (see- * `rag/llm/chat_model.py`, which does `json.loads(key)`), so- * `showProviderInstance` may return `api_key` as:- * 1. a raw JSON string `'{"api_key":"sk-x","group_id":"123"}'`- * 2. an already-parsed object `{ api_key, group_id }`- * 3. a plain bare key string `'sk-x'`- * Normalise all three into the bare key plus the registered nested- * credential fields so provider forms can restore their inputs.+ * Parse provider-specific fields from a safe configuration object. The+ * detail API never returns stored credential values.*/export function unwrapApiKey(raw: unknown): {apiKey: string;@@ -169,14 +269,11 @@ export function useProviderBaseUrlOptions(providerName: string) {** - Draft: empty form, with `base_url` pre-filled from the* provider's `default` URL when available.- * - Saved: prefer `instanceDetails` (which carries api_key / base_url);- * when `echoTransform` is supplied (provider-specific field mapping,- * e.g. Google Cloud's top-level `google_project_id` or XunFei Spark's- * nested `spark_api_password`), use it to reverse the corresponding- * `submitTransform` so the provider-specific credential fields- * pre-fill. Otherwise fall back to the generic `unwrapApiKey` path- * which lifts the bare `api_key` plus the provider-specific fields- * registered in `API_KEY_NESTED_FIELDS`.+ * - Saved: prefer `instanceDetails` (safe config status plus base_url);+ * when `echoTransform` is supplied, use it to restore provider-specific+ * fields from the safe configuration. Otherwise fall back to the generic+ * `unwrapApiKey` path, which lifts settings registered in+ * `API_KEY_NESTED_FIELDS`.*/export function useProviderInitialValues(providerName: string,@@ -210,22 +307,20 @@ export function useProviderInitialValues(};const values: Record<string, any> = {instance_name: merged.instance_name,+ api_key: '',+ api_key_configured: merged.api_key_configured ?? false,+ api_key_config: merged.api_key_config ?? {},+ credential_status: merged.credential_status ?? {},+ credential_masks: merged.credential_masks ?? {},};+ const safeConfig = merged.api_key_config ?? {};+ const { nested } = unwrapApiKey(safeConfig);+ Object.assign(values, nested);if (echoTransform) {// Provider-specific echo: reverse the `submitTransform` mapping so- // credential fields that the backend persists either at the top- // level (Google Cloud, Tencent Cloud, Fish Audio) or nested inside- // `api_key` (XunFei Spark, Baidu YiYan, OpenDataLoader, PaddleOCR,- // MinerU) are restored into their own form inputs.- Object.assign(values, echoTransform(merged));- } else if (merged.api_key) {- // api_key may come back as a JSON string, an already-parsed object,- // or a plain bare key (see `unwrapApiKey`). Normalise it so the- // api_key text field shows the bare key and registered nested- // credentials pre-fill their own form inputs.- const { apiKey, nested } = unwrapApiKey(merged.api_key);- values.api_key = apiKey;- Object.assign(values, nested);+ // provider-specific fields are restored from the safe config or+ // nested `api_key` values.+ Object.assign(values, echoTransform({ ...merged, ...safeConfig }));}if (merged.base_url) {values.base_url = merged.base_url;@@ -236,14 +331,17 @@ export function useProviderInitialValues(// for providers where it applies; surface it so the form / region// submit logic can echo it back.if ((merged as any).region) values.region = (merged as any).region;- // Fallback: some backends may still surface these credential fields- // at the top level rather than nested in api_key - echo any that- // weren't already lifted from the api_key object above.+ // Restore only known non-secret settings from the safe config map.for (const field of API_KEY_NESTED_FIELDS) {- if (values[field] === undefined && (merged as any)[field] !== undefined) {- values[field] = (merged as any)[field];+ if (values[field] === undefined && safeConfig[field] !== undefined) {+ values[field] = safeConfig[field];}}+ for (const [field, configured] of Object.entries(+ values.credential_status,+ )) {+ if (configured === true) values[field] = SAVED_CREDENTIAL_MASK;+ }return values;}, [providerName,@@ -262,8 +360,8 @@ export function useProviderInitialValues(/*** The list endpoint (`useFetchProviderInstances`) does not return* sensitive/heavy fields like `api_key` or `base_url`. Pull the full- * instance via `showProviderInstance` so the form can be pre-filled when- * the user clicks an existing provider on the left. The hook is+ * instance via `showProviderInstance` to get safe config status and URL+ * metadata when the user clicks an existing provider on the left. The hook is* `enabled: false` by default - we trigger it manually here so we* don't change behavior of other call sites.*/@@ -353,6 +451,8 @@ export function useVerifyProvider(formRef: RefObject<DynamicFormRef>,verifyTransform?: VerifyTransform,modelInfoRef?: { current: IModelInfo[] },+ instanceId?: string,+ savedInstance?: IProviderInstance,) {const { verifyProviderConnection } = useVerifyProviderConnection();@@ -372,8 +472,15 @@ export function useVerifyProvider(model_info?: IModelInfo[];region?: string;};+ const credentialStatus = savedInstance?.credential_status ?? {};+ const verifyValues = { ...values };+ for (const [field, configured] of Object.entries(credentialStatus)) {+ if (configured && verifyValues[field] === SAVED_CREDENTIAL_MASK) {+ verifyValues[field] = '';+ }+ }if (verifyTransform) {- const transformed = verifyTransform(values);+ const transformed = verifyTransform(verifyValues);verifyArgs = {api_key: transformed.apiKey,base_url: transformed.baseUrl,@@ -389,9 +496,41 @@ export function useVerifyProvider(model_info: selectedModels ?? values.model_info,};}+ verifyArgs.api_key = applySavedCredentialEdits(+ verifyArgs.api_key,+ values,+ credentialStatus,+ ) as string | object;+ const credentialChanged = Object.keys(credentialStatus).some(+ (field) =>+ credentialStatus[field] === true &&+ !SavedProviderConfigFieldSet.has(field) &&+ values[field] !== undefined &&+ values[field] !== SAVED_CREDENTIAL_MASK,+ );+ const useSavedCredentials =+ Boolean(instanceId) &&+ !credentialChanged &&+ !hasUnsavedProviderCredential(verifyArgs.api_key);+ const canOverrideSavedCredentials =+ useSavedCredentials && savedInstance?.is_owner === true;+ const savedConfigOverrides = canOverrideSavedCredentials+ ? pickSavedProviderConfigOverrides(verifyArgs.api_key)+ : {};const ret = await verifyProviderConnection({provider_name: providerName,- ...(verifyArgs as any),+ ...(instanceId ? { instance_id: instanceId } : {}),+ ...(useSavedCredentials+ ? {+ use_saved_credentials: true,+ ...(Object.keys(savedConfigOverrides).length > 0+ ? { api_key_config: savedConfigOverrides }+ : {}),+ ...(canOverrideSavedCredentials+ ? { base_url: verifyArgs.base_url, region: verifyArgs.region }+ : {}),+ }+ : (verifyArgs as any)),});if (ret.code === 0) {return { isValid: true, logs: ret.message } as {@@ -410,6 +549,8 @@ export function useVerifyProvider(verifyProviderConnection,verifyTransform,modelInfoRef,+ instanceId,+ savedInstance,],);}@@ -462,6 +603,7 @@ interface UseInstanceSaveStateArgs {draftName: string;instanceDetails: IProviderInstance | undefined;initialValues: Record<string, any>;+ baselineValues?: Record<string, any>;modelInfoRef: { current: IModelInfo[] };/*** Optional provider-specific transform that maps form values to the@@ -503,6 +645,7 @@ export function useInstanceSaveState({draftName,instanceDetails,initialValues,+ baselineValues,modelInfoRef,submitTransform,}: UseInstanceSaveStateArgs) {@@ -525,87 +668,130 @@ export function useInstanceSaveState({// via `buildApiKeyValue` so nested credential fields (group_id /// api_version / provider_order) are bundled inside `api_key` as the// backend expects.- const buildPayload = useCallback((): Record<string, any> | null => {- const values = (formRef.current?.getValues?.() ?? {}) as Record<- string,- any- >;- const modelInfo =- modelInfoRef.current.length > 0 ? modelInfoRef.current : [];-- // Provider-specific field mapping (e.g. OpenDataLoader's nested- // `opendataloader_apiserver` / `opendataloader_api_key`). The- // transform produces the canonical submit body shape- // (`instance_name`, `llm_factory`, `api_key`, `base_url`,- // `model_info`); we then layer on the card's own state (typed /- // edited name, model_info ref, update-only fields for saved cards).- if (submitTransform) {- const transformed = submitTransform({- ...values,- model_info: modelInfo,- }) as Record<string, any>;+ const buildPayload = useCallback(+ (+ valuesOverride?: Record<string, any>,+ modelInfoOverride?: IModelInfo[],+ instanceNameOverride?: string,+ instanceIdOverride?: string,+ ): Record<string, any> | null => {+ const values =+ valuesOverride ??+ ((formRef.current?.getValues?.() ?? {}) as Record<string, any>);+ const modelInfo =+ modelInfoOverride ??+ (modelInfoRef.current.length > 0 ? modelInfoRef.current : []);++ // Provider-specific field mapping (e.g. OpenDataLoader's nested+ // `opendataloader_apiserver` / `opendataloader_api_key`). The+ // transform produces the canonical submit body shape+ // (`instance_name`, `llm_factory`, `api_key`, `base_url`,+ // `model_info`); we then layer on the card's own state (typed /+ // edited name, model_info ref, update-only fields for saved cards).+ if (submitTransform) {+ const credentialStatus = initialValues.credential_status ?? {};+ const transformValues = { ...values };+ for (const [field, configured] of Object.entries(credentialStatus)) {+ if (configured && transformValues[field] === SAVED_CREDENTIAL_MASK) {+ transformValues[field] = '';+ }+ }+ const transformed = submitTransform({+ ...transformValues,+ model_info: modelInfo,+ }) as Record<string, any>;+ const updatedAPIKey = applySavedCredentialEdits(+ transformed.api_key,+ values,+ credentialStatus,+ );+ if (updatedAPIKey === undefined) {+ delete transformed.api_key;+ } else {+ transformed.api_key = updatedAPIKey;+ }+ for (const [field, configured] of Object.entries(credentialStatus)) {+ // `api_key` is the canonical credential property in the update body.+ // Other provider-specific credential fields must not leak at the top+ // level, but deleting this one also removes the transformed value.+ if (configured && field !== 'api_key') delete transformed[field];+ }+ if (isDraft) {+ const trimmed = draftNameRef.current.trim();+ if (!trimmed) return null;+ return {+ ...transformed,+ llm_factory: providerName,+ instance_name: trimmed,+ model_info: modelInfo,+ };+ }+ const resolvedId =+ instanceIdOverride || instanceDetails?.id || instanceId;+ return {+ ...transformed,+ provider_name: providerName,+ instance_name: instanceNameOverride ?? editedNameRef.current,+ id: resolvedId,+ base_url: transformed.base_url ?? '',+ region: values.region || 'default',+ model_info: modelInfo,+ verify: false,+ };+ }+if (isDraft) {const trimmed = draftNameRef.current.trim();if (!trimmed) return null;- return {- ...transformed,+ const payload: Record<string, any> = {llm_factory: providerName,- instance_name: trimmed,- model_info: modelInfo,+ instance_name: instanceNameOverride ?? trimmed,+ api_key:+ buildApiKeyValue(values, initialValues.credential_status) ?? '',+ base_url: values.base_url,};+ if (modelInfo.length > 0) {+ payload.model_info = modelInfo;+ }+ return payload;}- const resolvedId = instanceDetails?.id || instanceId;- return {- ...transformed,++ const resolvedId =+ instanceIdOverride || instanceDetails?.id || instanceId;+ const apiKeyValue = buildApiKeyValue(+ values,+ initialValues.credential_status,+ );+ const payload: Record<string, any> = {provider_name: providerName,- instance_name: editedNameRef.current,+ // Use the edited name (may differ from the persisted `instanceName`+ // when the user has renamed the instance via double-click).+ instance_name: instanceNameOverride ?? editedNameRef.current,id: resolvedId,- base_url: transformed.base_url ?? '',+ base_url: values.base_url,region: values.region || 'default',model_info: modelInfo,verify: false,};- }-- if (isDraft) {- const trimmed = draftNameRef.current.trim();- if (!trimmed) return null;- const payload: Record<string, any> = {- llm_factory: providerName,- instance_name: trimmed,- api_key: buildApiKeyValue(values) ?? '',- base_url: values.base_url,- };- if (modelInfoRef.current.length > 0) {- payload.model_info = modelInfoRef.current;+ if (+ apiKeyValue !== undefined &&+ !(typeof apiKeyValue === 'string' && apiKeyValue.trim() === '')+ ) {+ payload.api_key = apiKeyValue;}return payload;- }-- const resolvedId = instanceDetails?.id || instanceId;- const apiKeyValue = buildApiKeyValue(values);- const payload: Record<string, any> = {- provider_name: providerName,- // Use the edited name (may differ from the persisted `instanceName`- // when the user has renamed the instance via double-click).- instance_name: editedNameRef.current,- id: resolvedId,- api_key: apiKeyValue ?? '',- base_url: values.base_url,- region: values.region || 'default',- model_info: modelInfoRef.current.length > 0 ? modelInfoRef.current : [],- verify: false,- };- return payload;- }, [- isDraft,- providerName,- instanceId,- instanceDetails?.id,- formRef,- modelInfoRef,- submitTransform,- ]);+ },+ [+ isDraft,+ providerName,+ instanceId,+ instanceDetails?.id,+ formRef,+ modelInfoRef,+ submitTransform,+ initialValues.credential_status,+ ],+ );// Seed the "last saved" baseline once instance details (or the// draft's empty state) are available, so the first `getSavePayload()`@@ -619,29 +805,24 @@ export function useInstanceSaveState({}const resolvedId = instanceDetails?.id || instanceId;if (!resolvedId) return;- const baseline = {- provider_name: providerName,- instance_name: instanceName,- id: resolvedId,- api_key: buildApiKeyValue(initialValues),- base_url: initialValues.base_url,- region: initialValues.region,- // model_info baseline is `[]`; `markModelsEdited` rewrites it after- // a model PATCH so the next top-save short-circuits. The first- // save after the models initially load may re-send the same- // model_info (idempotent) - acceptable, matches the old- // `lastSavedPayloadRef` seeding behaviour.- model_info: [] as IModelInfo[],- verify: false,- };- baselinePayloadRef.current = JSON.stringify(baseline);+ // Build the baseline through the same provider transform and payload+ // normalization as a save. Hand-assembling it misses provider-specific+ // fields such as llm_factory and can make an untouched card look dirty.+ // Use the form defaults from the loaded instance, including provider+ // defaults, but not the live form values: a refetch must not absorb edits+ // preserved by `keepDirtyValues` into the saved baseline.+ const savedValues = baselineValues ?? initialValues;+ const baseline = buildPayload(savedValues, [], instanceName, resolvedId);+ baselinePayloadRef.current = JSON.stringify(baseline ?? {});}, [isDraft,- providerName,instanceName,instanceId,instanceDetails?.id,initialValues,+ baselineValues,+ formRef,+ buildPayload,]);// `getSavePayload()` is the imperative entry point the parent calls@@ -748,16 +929,17 @@ export function useInstanceSaveState({*/export function useFormFields(providerName: string,- _isDraft: boolean,+ isDraft: boolean,initialValues: Record<string, any>,baseUrlOptions: SelectOption[] | undefined,hideWhenInstanceExists: (values: any) => boolean,urlHint?: string,) {+ const { t: tSetting } = useTranslate('setting');const { fields, defaultValues } = useProviderFields({llmFactory: providerName,// Always seed initial values (drafts need the default base_url;- // saved cards need the persisted api_key / base_url).+ // saved cards need safe persisted settings and the base_url).editMode: true,// Never disable fields - the old name-first lock is gone. Drafts// are fully editable from the start; saved cards are edited via the@@ -769,10 +951,36 @@ export function useFormFields(urlHint,});- const formFields = useMemo(- () => fields.filter((f) => f.name !== 'instance_name'),- [fields],- );+ const formFields = useMemo(() => {+ const credentialStatus = initialValues.credential_status ?? {};+ const credentialMasks = initialValues.credential_masks ?? {};+ return fields+ .filter((field) => field.name !== 'instance_name')+ .map((field) => {+ if (isDraft || credentialStatus[field.name] !== true) return field;+ return {+ ...field,+ type: FormFieldType.Custom,+ required: false,+ placeholder: tSetting('credentialClearToRemove'),+ autoComplete: 'new-password',+ render: (fieldProps: ControllerRenderProps) => (+ <SavedCredentialInput+ {...fieldProps}+ maskedValue={credentialMasks[field.name]}+ placeholder={tSetting('credentialClearToRemove')}+ autoComplete="new-password"+ />+ ),+ };+ });+ }, [+ fields,+ initialValues.credential_masks,+ initialValues.credential_status,+ isDraft,+ tSetting,+ ]);const defaultValuesKey = JSON.stringify(defaultValues);const formDefaultValues = useMemo(() => {diff --git a/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsx b/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsxindex 96a988f430..b36f0d90d5 100644--- a/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsx+++ b/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsx@@ -19,7 +19,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';import { useRef } from 'react';import { modelNameKey } from '@/utils/llm-util';-import { useInstanceSaveState } from '../hooks';+import { SAVED_CREDENTIAL_MASK, useInstanceSaveState } from '../hooks';import {DRAFT_INSTANCE_SENTINEL,useModelMutations,@@ -179,11 +179,10 @@ describe('Bedrock model credentials', () => {provider_id: 'provider-id',region: 'default',status: 'active',- api_key: '',};const { result } = renderHook(() => {- const { resolveCreds } = useResolveCreds(instance, () => ({+ const { resolveCreds } = useResolveCreds('Bedrock', instance, () => ({api_key: apiKey,}));const verify = useModelVerify({@@ -220,6 +219,86 @@ describe('Bedrock model credentials', () => {expect.objectContaining({ api_key: apiKey, region: 'default' }),);});++ it('uses the stored credential for an unchanged mask and clears it when emptied', async () => {+ const model = {+ name: 'anthropic.claude',+ model_types: ['chat'],+ max_tokens: 8192,+ features: [],+ };+ const instance = {+ id: 'instance-id',+ instance_name: 'bedrock-instance',+ provider_id: 'provider-id',+ region: 'default',+ status: 'active',+ api_key_configured: true,+ credential_status: { bedrock_api_key: true },+ };+ const formValues: Record<string, unknown> = {+ auth_mode: 'bedrock_api_key',+ bedrock_api_key: SAVED_CREDENTIAL_MASK,+ bedrock_region: 'us-east-1',+ };++ const { result } = renderHook(() => {+ const { resolveCreds } = useResolveCreds(+ 'Bedrock',+ instance,+ () => formValues,+ );+ const verify = useModelVerify({+ providerName: 'Bedrock',+ resolveCreds,+ instanceModels: [],+ instance,+ getFormValues: () => formValues,+ verifyTransform: (values) => ({+ apiKey: {+ auth_mode: values.auth_mode,+ bedrock_api_key: values.bedrock_api_key,+ bedrock_region: values.bedrock_region,+ },+ region: 'default',+ }),+ });+ return { resolveCreds, verify };+ });++ expect(result.current.resolveCreds()).toMatchObject({+ hasStoredCredentials: true,+ credentialChanged: false,+ apiKey: { auth_mode: 'bedrock_api_key', bedrock_region: 'us-east-1' },+ });+ await act(async () => result.current.verify.handleVerify(model));+ expect(mockVerifyProviderConnection).toHaveBeenLastCalledWith(+ expect.objectContaining({+ instance_id: 'instance-id',+ use_saved_credentials: true,+ }),+ );+ expect(mockVerifyProviderConnection.mock.lastCall?.[0]).not.toHaveProperty(+ 'api_key',+ );++ formValues.bedrock_api_key = '';+ expect(result.current.resolveCreds().credentialChanged).toBe(true);+ await act(async () => result.current.verify.handleVerify(model));+ expect(mockVerifyProviderConnection).toHaveBeenLastCalledWith(+ expect.objectContaining({+ api_key: {+ auth_mode: 'bedrock_api_key',+ bedrock_api_key: null,+ bedrock_region: 'us-east-1',+ },+ instance_id: 'instance-id',+ }),+ );+ expect(mockVerifyProviderConnection.mock.lastCall?.[0]).not.toHaveProperty(+ 'use_saved_credentials',+ );+ });});describe('API-key-gated model listing (SystemOne / RAGcon)', () => {@@ -293,10 +372,11 @@ describe('API-key-gated model listing (SystemOne / RAGcon)', () => {);});- it('auto-fetches a saved RAGcon instance once its stored api_key loads', async () => {+ it('auto-fetches a saved RAGcon instance using server-stored credentials', async () => {let apiKey = '';+ let hasStoredCredentials = false;const baseUrl = 'https://api.ragcon.ai/v1';- const resolveCreds = () => ({ apiKey, baseUrl });+ const resolveCreds = () => ({ apiKey, baseUrl, hasStoredCredentials });const { rerender } = renderHook(({ apiKeyValue, instanceDetailsLoaded }) =>@@ -306,8 +386,10 @@ describe('API-key-gated model listing (SystemOne / RAGcon)', () => {hideActions: false,resolveCreds,instanceModels: undefined,+ instance: { id: 'instance-id', is_owner: true } as any,apiKeyValue,baseUrlValue: baseUrl,+ regionValue: undefined,instanceDetailsLoaded,}),{ initialProps: { apiKeyValue: apiKey, instanceDetailsLoaded: false } },@@ -315,18 +397,51 @@ describe('API-key-gated model listing (SystemOne / RAGcon)', () => {expect(mockListProviderModels).not.toHaveBeenCalled();- apiKey = 'saved-key';+ hasStoredCredentials = true;rerender({ apiKeyValue: apiKey, instanceDetailsLoaded: true });await waitFor(() =>expect(mockListProviderModels).toHaveBeenCalledWith({provider_name: 'RAGcon',- api_key: apiKey,- base_url: baseUrl,+ base_url: 'https://api.ragcon.ai/v1',+ region: undefined,+ use_saved_credentials: true,instance_name: 'ragcon-instance',}),);});++ it('does not send endpoint overrides with saved credentials for a non-owner', async () => {+ const resolveCreds = () => ({+ apiKey: '',+ apiKeyConfig: { paddleocr_api_url: 'https://attacker.example' },+ baseUrl: 'https://attacker.example',+ hasStoredCredentials: true,+ });++ const { result } = renderHook(() =>+ useModelsCatalog({+ providerName: 'RAGcon',+ instanceName: 'ragcon-instance',+ hideActions: false,+ resolveCreds,+ instanceModels: undefined,+ instance: { id: 'instance-id', is_owner: false } as any,+ apiKeyValue: '',+ baseUrlValue: 'https://attacker.example',+ regionValue: 'region-override',+ instanceDetailsLoaded: true,+ }),+ );++ await waitFor(() => expect(mockListProviderModels).toHaveBeenCalled());+ expect(mockListProviderModels).toHaveBeenCalledWith({+ provider_name: 'RAGcon',+ use_saved_credentials: true,+ instance_name: 'ragcon-instance',+ });+ expect(result.current.hasFetched).toBe(true);+ });});describe('saved instance model baseline', () => {diff --git a/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts b/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsindex 8760ff2bff..1ded6d9aac 100644--- a/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts+++ b/web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts@@ -29,6 +29,13 @@ import { IInstanceModel, IProviderInstance } from '@/interfaces/database/llm';import { IModelInfo, IProviderModelItem } from '@/interfaces/request/llm';import llmService from '@/services/llm-service';import { modelNameKey } from '@/utils/llm-util';+import { hasProviderCredentialInput } from '../../provider-schema/field-config/utils';+import { getProviderConfig } from '../../provider-schema/field-config/get-provider-config';+import {+ applySavedCredentialEdits,+ buildApiKeyValue,+ SAVED_CREDENTIAL_MASK,+} from '../hooks';import {Dispatch,SetStateAction,@@ -41,6 +48,11 @@ import {import { sortModelTypes } from '../available-models';import { useCustomModelFields } from '../use-custom-model-fields';import { ModelsSectionProps, VerifyStatus } from './interface';+import {+ SavedProviderConfigFieldSet,+ SavedProviderConfigFields,+ hasUnsavedProviderCredential,+} from '../saved-provider-config';// ---------------------------------------------------------------------------// Constants@@ -117,14 +129,35 @@ export const buildModelInfo = (* empty". */export type ResolvedCreds = {apiKey: string | object;+ apiKeyConfig?: Record<string, unknown>;baseUrl: string | undefined;+ region?: string;+ hasStoredCredentials?: boolean;+ credentialChanged?: boolean;};+function isVisibleSavedConfigField(+ providerName: string,+ field: { name: string; shouldRender?: string | ((values: any) => boolean) },+ values: Record<string, any>,+ hasSavedInstance: boolean,+): boolean {+ const shouldRender = field.shouldRender;+ if (!shouldRender) return true;+ if (typeof shouldRender === 'function') return shouldRender(values);+ if (shouldRender === 'hideWhenInstanceExists') return !hasSavedInstance;+ if (shouldRender === 'showGroupId') {+ return providerName.toLowerCase() === LLMFactory.MiniMax.toLowerCase();+ }+ return true;+}+// ---------------------------------------------------------------------------// 1. useResolveCreds — resolve api_key / base_url from host form or instance// ---------------------------------------------------------------------------export function useResolveCreds(+ providerName: string,instance: IProviderInstance | undefined,getFormValues: ModelsSectionProps['getFormValues'],) {@@ -133,11 +166,85 @@ export function useResolveCreds(// back to the persisted instance fields when no form getter is wired up.const resolveCreds = useCallback((): ResolvedCreds => {const fv = getFormValues?.() ?? {};+ const credentialStatus = instance?.credential_status ?? {};+ const savedConfig = instance?.api_key_config ?? {};+ const providerFields = getProviderConfig(providerName).fields;+ const visibleConfigFields = new Set(+ providerFields+ .filter(+ (field) =>+ SavedProviderConfigFieldSet.has(field.name) &&+ isVisibleSavedConfigField(+ providerName,+ field,+ fv,+ Boolean(instance?.id),+ ),+ )+ .map((field) => field.name),+ );+ const apiKeyConfig: Record<string, unknown> = {};+ for (const field of SavedProviderConfigFields) {+ if (!visibleConfigFields.has(field)) continue;+ if (!Object.prototype.hasOwnProperty.call(fv, field)) continue;+ const value = fv[field];+ if (value === SAVED_CREDENTIAL_MASK) continue;+ if (value === '' || value === undefined || value === null) {+ const savedValue = savedConfig[field];+ if (+ savedValue !== undefined &&+ savedValue !== null &&+ savedValue !== ''+ ) {+ apiKeyConfig[field] = null;+ }+ continue;+ }+ apiKeyConfig[field] = value;+ }+ if (providerName === LLMFactory.Bedrock) {+ let bedrockConfig: unknown = buildApiKeyValue(fv, credentialStatus);+ if (+ bedrockConfig &&+ typeof bedrockConfig === 'object' &&+ 'api_key' in bedrockConfig+ ) {+ bedrockConfig = (bedrockConfig as Record<string, unknown>).api_key;+ }+ if (bedrockConfig && typeof bedrockConfig === 'object') {+ for (const field of ['auth_mode', 'aws_role_arn', 'bedrock_region']) {+ const value = (bedrockConfig as Record<string, unknown>)[field];+ if (value === undefined || value === SAVED_CREDENTIAL_MASK) continue;+ const savedValue = savedConfig[field];+ if (value === '' || value === null) {+ if (+ savedValue !== undefined &&+ savedValue !== null &&+ savedValue !== ''+ ) {+ apiKeyConfig[field] = null;+ }+ continue;+ }+ apiKeyConfig[field] = value;+ }+ }+ }return {- apiKey: (fv.api_key as string | object) ?? instance?.api_key ?? '',+ apiKey: (buildApiKeyValue(fv, credentialStatus) as string | object) ?? '',+ apiKeyConfig,baseUrl: (fv.base_url as string) ?? instance?.base_url,+ region: (fv.region as string) ?? instance?.region,+ hasStoredCredentials: instance?.api_key_configured === true,+ credentialChanged: Object.entries(credentialStatus).some(+ ([field, configured]) =>+ configured &&+ !SavedProviderConfigFieldSet.has(field) &&+ fv[field] !== undefined &&+ fv[field] !== SAVED_CREDENTIAL_MASK,+ ),};- }, [getFormValues, instance]);+ }, [getFormValues, instance, providerName]);return { resolveCreds };}@@ -152,11 +259,14 @@ interface UseModelsCatalogArgs {hideActions: boolean;resolveCreds: () => ResolvedCreds;instanceModels: IInstanceModel[] | undefined;+ instance?: IProviderInstance;apiKeyValue: ResolvedCreds['apiKey'];baseUrlValue: string | undefined;+ regionValue?: ResolvedCreds['region'];+instanceDetailsLoaded?: boolean;/**@@ -174,8 +284,10 @@ export function useModelsCatalog({hideActions,resolveCreds,instanceModels,+ instance,apiKeyValue,baseUrlValue,+ regionValue,instanceDetailsLoaded,onCatalogFetched,}: UseModelsCatalogArgs) {@@ -245,22 +357,43 @@ export function useModelsCatalog({// The result is merged into `catalog`; the displayed list then becomes// the union of catalog + instance models.const handleListModels = async () => {- const { apiKey, baseUrl } = resolveCreds();- if (providerName === LLMFactory.VolcEngine && !apiKey) {+ const {+ apiKey,+ apiKeyConfig,+ baseUrl,+ region,+ hasStoredCredentials,+ credentialChanged,+ } = resolveCreds();+ if (+ providerName === LLMFactory.VolcEngine &&+ !hasUnsavedProviderCredential(apiKey) &&+ !hasStoredCredentials+ ) {setHasFetched(true);return;}setManualListLoading(true);try {+ const useStoredCredentials =+ instanceName &&+ instanceName !== DRAFT_INSTANCE_SENTINEL &&+ !hasUnsavedProviderCredential(apiKey) &&+ !credentialChanged;+ const canOverrideSavedCredentials =+ useStoredCredentials && instance?.is_owner === true;const ret = await listProviderModels({provider_name: providerName,- api_key: apiKey as any,- base_url: baseUrl,- // The saved instance never hands its key back to the browser, but it- // does hand back its base URL — so without this the request would go- // out unauthenticated and the upstream would answer 401 "no API key".- // With the name, the server lists using the stored credential. A draft- // has no stored credential, so it is not named here.+ ...(!useStoredCredentials ? { api_key: apiKey as any } : {}),+ ...(canOverrideSavedCredentials &&+ apiKeyConfig &&+ Object.keys(apiKeyConfig).length > 0+ ? { api_key_config: apiKeyConfig }+ : {}),+ ...(!useStoredCredentials || canOverrideSavedCredentials+ ? { base_url: baseUrl, region }+ : {}),+ ...(useStoredCredentials ? { use_saved_credentials: true } : {}),...(instanceName && instanceName !== DRAFT_INSTANCE_SENTINEL? { instance_name: instanceName }: {}),@@ -291,8 +424,8 @@ export function useModelsCatalog({// mount regardless.//// The credential check is performed INSIDE the effect (not in the deps).- // The host restores saved credentials before passive effects run, so this- // reads the current form snapshot instead of the previous render's values.+ // Saved instances wait for their details and form reset before this reads+ // current endpoint and region values.const hasAutoFetchedRef = useRef(false);useEffect(() => {@@ -315,21 +448,22 @@ export function useModelsCatalog({(providerName === LLMFactory.Bedrock &&apiKeyConfig?.auth_mode === 'bedrock_api_key');const hasApiKey =- providerName === LLMFactory.Bedrock && requiresApiKey- ? Boolean(apiKeyConfig?.bedrock_api_key && apiKeyConfig?.bedrock_region)- : Boolean(creds.apiKey);+ hasProviderCredentialInput(creds.apiKey) ||+ (creds.hasStoredCredentials && !creds.credentialChanged);const waitingForInstanceDetails =- providerName === LLMFactory.Bedrock &&- instanceName !== DRAFT_INSTANCE_SENTINEL &&- !instanceDetailsLoaded;+ instanceName !== DRAFT_INSTANCE_SENTINEL && !instanceDetailsLoaded;const hasBaseUrlField = creds.baseUrl !== undefined;const ready =!waitingForInstanceDetails &&(!requiresApiKey || hasApiKey) &&(!hasBaseUrlField || !!creds.baseUrl);if (!ready) return;- hasAutoFetchedRef.current = true;- handleListModels();+ const frame = requestAnimationFrame(() => {+ if (hasAutoFetchedRef.current) return;+ hasAutoFetchedRef.current = true;+ handleListModels();+ });+ return () => cancelAnimationFrame(frame);// oxlint-disable-next-line react/exhaustive-deps}, [providerName,@@ -337,6 +471,7 @@ export function useModelsCatalog({hideActions,apiKeyValue,baseUrlValue,+ regionValue,instanceDetailsLoaded,]);@@ -495,7 +630,7 @@ export function useModelsDerived({// save payload can include `model_info`.useEffect(() => {onChangeRef.current?.(buildModelInfo(instanceItems, isDraftInstance));- }, [instanceItems]);+ }, [instanceItems, isDraftInstance]);// Saved instance models come from the backend, both after the initial// query and after mutation-driven refetches. Once that authoritative@@ -580,10 +715,22 @@ function buildVerifyArgs(let apiKey: string | object;let baseUrl: string | undefined;let region: string | undefined;+ const formValues = getFormValues?.() ?? {};+ const credentialStatus = instance?.credential_status ?? {};+ const verifyValues = { ...formValues };+ for (const [field, configured] of Object.entries(credentialStatus)) {+ if (configured && verifyValues[field] === SAVED_CREDENTIAL_MASK) {+ verifyValues[field] = '';+ }+ }if (verifyTransform) {- const transformed = verifyTransform(getFormValues?.() ?? {});- apiKey = transformed.apiKey;+ const transformed = verifyTransform(verifyValues);+ apiKey = applySavedCredentialEdits(+ transformed.apiKey,+ formValues,+ credentialStatus,+ ) as string | object;baseUrl = transformed.baseUrl;region = transformed.region;} else {@@ -592,6 +739,22 @@ function buildVerifyArgs(baseUrl = creds.baseUrl;}+ const resolvedCreds = resolveCreds();+ const credentialChanged =+ resolvedCreds.credentialChanged === true ||+ Object.entries(credentialStatus).some(+ ([field, configured]) =>+ configured &&+ !SavedProviderConfigFieldSet.has(field) &&+ formValues[field] !== undefined &&+ formValues[field] !== SAVED_CREDENTIAL_MASK,+ );++ const useSavedCredentials =+ Boolean(instance?.id) &&+ !credentialChanged &&+ !hasUnsavedProviderCredential(apiKey);+// `api_key` is typed `string` on the service signature, but// providers with a `verifyTransform` may legitimately produce an// object (e.g. PaddleOCR's nested config). The backend accepts@@ -599,11 +762,19 @@ function buildVerifyArgs(// verify path in `useVerifyProvider`.return {provider_name: providerName,- api_key: apiKey as any,- base_url: baseUrl,+ ...(!useSavedCredentials ? { api_key: apiKey as any } : {}),+ ...(useSavedCredentials &&+ instance?.is_owner === true &&+ resolvedCreds.apiKeyConfig &&+ Object.keys(resolvedCreds.apiKeyConfig).length > 0+ ? { api_key_config: resolvedCreds.apiKeyConfig }+ : {}),+ ...(!useSavedCredentials || instance?.is_owner === true+ ? { base_url: baseUrl, region }+ : {}),model_info: modelInfo,- ...(region ? { region } : {}),...(instance?.id ? { instance_id: instance.id } : {}),+ ...(useSavedCredentials ? { use_saved_credentials: true } : {}),};}diff --git a/web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx b/web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxindex facc5080c1..fe030a0a42 100644--- a/web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx+++ b/web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx@@ -70,7 +70,11 @@ export function ModelsSection(props: ModelsSectionProps) {!instanceName || instanceName === DRAFT_INSTANCE_SENTINEL;// 1. Credentials for catalog / verify / batch calls.- const { resolveCreds } = useResolveCreds(instance, getFormValues);+ const { resolveCreds } = useResolveCreds(+ providerName,+ instance,+ getFormValues,+ );// Snapshot of the current api_key so `useModelsCatalog` can gate the// auto-fetch for VolcEngine on the user actually having typed one.@@ -147,8 +151,10 @@ export function ModelsSection(props: ModelsSectionProps) {hideActions,resolveCreds,instanceModels,+ instance,apiKeyValue: currentCreds.apiKey,baseUrlValue: currentCreds.baseUrl,+ regionValue: currentCreds.region,instanceDetailsLoaded,onCatalogFetched: isDraftInstance ? mergeCatalogIntoDraft : undefined,});diff --git a/web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts b/web/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsindex aff8af7e76..e69c07ce6e 100644--- a/web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts+++ b/web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts@@ -31,7 +31,7 @@ export interface ModelsSectionProps {*/hideActions?: boolean;/**- * True once the lazy-loaded instance details (which carry `api_key` /+ * True once the lazy-loaded instance details (safe credential status and* `base_url` - the list endpoint omits them) have resolved. Providers* whose upstream model-list endpoint requires an api_key (e.g.* VolcEngine) use this to defer the auto-fetch until the credentialdiff --git a/web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx b/web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsxindex dfe3b01599..480a210c75 100644--- a/web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx+++ b/web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx@@ -162,6 +162,8 @@ const GenericProviderInstanceCard = forwardRef<formRef,providerConfig.verifyTransform,modelInfoRef,+ isDraft ? undefined : instance.id,+ isDraft ? undefined : { ...instance, ...(instanceDetails ?? {}) },);const handleDelete = useDeleteInstance(providerName,@@ -181,6 +183,7 @@ const GenericProviderInstanceCard = forwardRef<draftName,instanceDetails,initialValues,+ baselineValues: formDefaultValues,modelInfoRef,submitTransform: providerConfig.submitTransform,});@@ -259,7 +262,7 @@ const GenericProviderInstanceCard = forwardRef<instanceName={instance.instance_name}editedInstanceName={editedInstanceName}onRename={setEditedInstanceName}- instance={instance}+ instance={{ ...instance, ...(instanceDetails ?? {}) }}instanceDetailsLoaded={Boolean(instanceDetails)}modelInfoRef={modelInfoRef}onInstanceModelsStatusChange={(ready) => {diff --git a/web/src/pages/user-setting/setting-model/instance-card/saved-credential-input.test.tsx b/web/src/pages/user-setting/setting-model/instance-card/saved-credential-input.test.tsxnew file mode 100644index 0000000000..5e0b9c8522--- /dev/null+++ b/web/src/pages/user-setting/setting-model/instance-card/saved-credential-input.test.tsx@@ -0,0 +1,28 @@+import { fireEvent, render, screen } from '@testing-library/react';+import {+ SAVED_CREDENTIAL_MASK,+ SavedCredentialInput,+} from './saved-credential-input';++describe('SavedCredentialInput', () => {+ it('keeps the saved credential mask selected on mouse release', () => {+ render(+ <SavedCredentialInput+ aria-label="API key"+ value={SAVED_CREDENTIAL_MASK}+ maskedValue="sk-a**********z9"+ />,+ );++ const input = screen.getByLabelText('API key') as HTMLInputElement;+ const mouseUp = new MouseEvent('mouseup', {+ bubbles: true,+ cancelable: true,+ });+ fireEvent(input, mouseUp);++ expect(mouseUp.defaultPrevented).toBe(true);+ expect(input.selectionStart).toBe(0);+ expect(input.selectionEnd).toBe(input.value.length);+ });+});diff --git a/web/src/pages/user-setting/setting-model/instance-card/saved-credential-input.tsx b/web/src/pages/user-setting/setting-model/instance-card/saved-credential-input.tsxnew file mode 100644index 0000000000..9444e6089a--- /dev/null+++ b/web/src/pages/user-setting/setting-model/instance-card/saved-credential-input.tsx@@ -0,0 +1,65 @@+/*+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Input } from '@/components/ui/input';+import { forwardRef } from 'react';+import type { ComponentProps, FocusEvent, MouseEvent } from 'react';++export const SAVED_CREDENTIAL_MASK = '********';++type SavedCredentialInputProps = Omit<+ ComponentProps<typeof Input>,+ 'type' | 'value' | 'onFocus' | 'onMouseUp'+> & {+ maskedValue?: string;+ value?: unknown;+};++export const SavedCredentialInput = forwardRef<+ HTMLInputElement,+ SavedCredentialInputProps+>(function SavedCredentialInput({ maskedValue, value, ...inputProps }, ref) {+ const isStoredCredential = value === SAVED_CREDENTIAL_MASK;+ const displayValue = isStoredCredential+ ? maskedValue || SAVED_CREDENTIAL_MASK+ : typeof value === 'string'+ ? value+ : '';+ const handleFocus = (event: FocusEvent<HTMLInputElement>) => {+ if (isStoredCredential) {+ event.currentTarget.select();+ }+ };+ const handleMouseUp = (event: MouseEvent<HTMLInputElement>) => {+ if (isStoredCredential) {+ event.preventDefault();+ event.currentTarget.select();+ }+ };++ return (+ <Input+ ref={ref}+ {...inputProps}+ type={isStoredCredential ? 'text' : 'password'}+ value={displayValue}+ onFocus={handleFocus}+ onMouseUp={handleMouseUp}+ />+ );+});++SavedCredentialInput.displayName = 'SavedCredentialInput';diff --git a/web/src/pages/user-setting/setting-model/instance-card/saved-credential-save.test.tsx b/web/src/pages/user-setting/setting-model/instance-card/saved-credential-save.test.tsxnew file mode 100644index 0000000000..9197e5a607--- /dev/null+++ b/web/src/pages/user-setting/setting-model/instance-card/saved-credential-save.test.tsx@@ -0,0 +1,257 @@+import { renderHook } from '@testing-library/react';+import { useRef } from 'react';++import { LLMFactory } from '@/constants/llm';+import { LocalLlmConfigs } from '../provider-schema/field-config/local-llm-configs';+import { ProviderConfigMap } from '../provider-schema/field-config/provider-config-map';+import { SAVED_CREDENTIAL_MASK, useInstanceSaveState } from './hooks';++jest.mock('@/components/dynamic-form', () => ({+ FormFieldType: new Proxy({}, { get: (_target, key) => String(key) }),+}));++jest.mock('@/hooks/use-llm-request', () => ({}));+jest.mock('@/hooks/common-hooks', () => ({+ useTranslate: () => ({ t: (key: string) => key }),+}));+jest.mock('../provider-schema/hooks', () => ({ useProviderFields: jest.fn() }));++describe('saved provider credential updates', () => {+ it('does not treat an unchanged transformed instance as dirty', () => {+ const instance = {+ id: 'instance-id',+ instance_name: 'openai-compatible',+ };+ const initialValues = {+ api_key: SAVED_CREDENTIAL_MASK,+ credential_status: { api_key: true },+ base_url: 'https://example.com/v1',+ region: 'default',+ };+ const formValues = { ...initialValues };+ const config = LocalLlmConfigs[LLMFactory.OpenAiAPICompatible];++ const { result } = renderHook(() => {+ const formRef = useRef({ getValues: () => formValues } as any);+ const modelInfoRef = useRef<any[]>([]);+ return useInstanceSaveState({+ formRef,+ providerName: LLMFactory.OpenAiAPICompatible,+ instanceName: instance.instance_name,+ instanceId: instance.id,+ isDraft: false,+ draftName: '',+ instanceDetails: instance as any,+ initialValues,+ modelInfoRef,+ submitTransform: config.submitTransform,+ });+ });++ expect(result.current.getSavePayload()).toBeNull();+ });++ it('omits an empty API key when saving another field on a keyless instance', () => {+ const instance = {+ id: 'instance-id',+ instance_name: 'openai-compatible',+ };+ const initialValues = {+ api_key: '',+ credential_status: {},+ base_url: 'https://example.com/v1',+ region: 'default',+ };+ const formValues = { ...initialValues };+ const config = LocalLlmConfigs[LLMFactory.OpenAiAPICompatible];++ const { result } = renderHook(() => {+ const formRef = useRef({ getValues: () => formValues } as any);+ const modelInfoRef = useRef<any[]>([]);+ return useInstanceSaveState({+ formRef,+ providerName: LLMFactory.OpenAiAPICompatible,+ instanceName: instance.instance_name,+ instanceId: instance.id,+ isDraft: false,+ draftName: '',+ instanceDetails: instance as any,+ initialValues,+ modelInfoRef,+ submitTransform: config.submitTransform,+ });+ });++ formValues.base_url = 'https://updated.example.com/v1';+ const save = result.current.getSavePayload();+ expect(save?.payload.base_url).toBe('https://updated.example.com/v1');+ expect(save?.payload).not.toHaveProperty('api_key');+ });++ it('sends safe Google Cloud settings in the api_key config', () => {+ const instance = {+ id: 'instance-id',+ instance_name: 'google-cloud',+ };+ const initialValues = {+ google_project_id: 'project-1',+ google_region: 'us-central1',+ google_service_account_key: SAVED_CREDENTIAL_MASK,+ credential_status: { google_service_account_key: true },+ base_url: '',+ region: 'default',+ };+ const formValues = { ...initialValues };+ const config = ProviderConfigMap[LLMFactory.GoogleCloud];++ const { result } = renderHook(() => {+ const formRef = useRef({ getValues: () => formValues } as any);+ const modelInfoRef = useRef<any[]>([]);+ return useInstanceSaveState({+ formRef,+ providerName: LLMFactory.GoogleCloud,+ instanceName: instance.instance_name,+ instanceId: instance.id,+ isDraft: false,+ draftName: '',+ instanceDetails: instance as any,+ initialValues,+ modelInfoRef,+ submitTransform: config.submitTransform,+ });+ });++ expect(result.current.getSavePayload()).toBeNull();+ formValues.google_region = 'europe-west1';++ const save = result.current.getSavePayload();+ expect(save?.payload.api_key).toEqual({+ google_project_id: 'project-1',+ google_region: 'europe-west1',+ google_service_account_key: '',+ });+ expect(save?.payload).not.toHaveProperty('google_project_id');+ expect(save?.payload).not.toHaveProperty('google_region');+ });++ it('sends changed API keys and keeps later edits dirty', () => {+ const instance = {+ id: 'instance-id',+ instance_name: 'openai-compatible',+ };+ const initialValues = {+ api_key: SAVED_CREDENTIAL_MASK,+ api_key_configured: true,+ credential_status: { api_key: true },+ base_url: 'https://example.com/v1',+ region: 'default',+ };+ const formValues = { ...initialValues };+ const config = LocalLlmConfigs[LLMFactory.OpenAiAPICompatible];++ const { result } = renderHook(() => {+ const formRef = useRef({ getValues: () => formValues } as any);+ const modelInfoRef = useRef<any[]>([]);+ return useInstanceSaveState({+ formRef,+ providerName: LLMFactory.OpenAiAPICompatible,+ instanceName: instance.instance_name,+ instanceId: instance.id,+ isDraft: false,+ draftName: '',+ instanceDetails: instance as any,+ initialValues,+ modelInfoRef,+ submitTransform: config.submitTransform,+ });+ });++ formValues.api_key = 'first-new-key';+ const firstSave = result.current.getSavePayload();+ expect(firstSave?.payload.api_key).toBe('first-new-key');++ result.current.markSaved();+ formValues.api_key = 'second-new-key';+ const secondSave = result.current.getSavePayload();+ expect(secondSave?.payload.api_key).toBe('second-new-key');+ });++ it.each([+ {+ name: 'an unchanged saved credential',+ api_key: SAVED_CREDENTIAL_MASK,+ credential_status: { api_key: true },+ },+ {+ name: 'an instance with no credential',+ api_key: '',+ credential_status: {},+ },+ ])('omits api_key for $name', ({ api_key, credential_status }) => {+ const instance = {+ id: 'instance-id',+ instance_name: 'openai-compatible',+ };+ const initialValues = {+ api_key,+ credential_status,+ base_url: 'https://example.com/v1',+ region: 'default',+ };+ const formValues = { ...initialValues };+ const config = LocalLlmConfigs[LLMFactory.OpenAiAPICompatible];++ const { result } = renderHook(() => {+ const formRef = useRef({ getValues: () => formValues } as any);+ const modelInfoRef = useRef<any[]>([]);+ return useInstanceSaveState({+ formRef,+ providerName: LLMFactory.OpenAiAPICompatible,+ instanceName: instance.instance_name,+ instanceId: instance.id,+ isDraft: false,+ draftName: '',+ instanceDetails: instance as any,+ initialValues,+ modelInfoRef,+ submitTransform: config.submitTransform,+ });+ });++ expect(result.current.buildPayload()).not.toHaveProperty('api_key');+ });++ it('sends an explicit clear only when a saved credential is emptied', () => {+ const instance = {+ id: 'instance-id',+ instance_name: 'openai-compatible',+ };+ const initialValues = {+ api_key: SAVED_CREDENTIAL_MASK,+ credential_status: { api_key: true },+ base_url: 'https://example.com/v1',+ region: 'default',+ };+ const formValues = { ...initialValues, api_key: '' };+ const config = LocalLlmConfigs[LLMFactory.OpenAiAPICompatible];++ const { result } = renderHook(() => {+ const formRef = useRef({ getValues: () => formValues } as any);+ const modelInfoRef = useRef<any[]>([]);+ return useInstanceSaveState({+ formRef,+ providerName: LLMFactory.OpenAiAPICompatible,+ instanceName: instance.instance_name,+ instanceId: instance.id,+ isDraft: false,+ draftName: '',+ instanceDetails: instance as any,+ initialValues,+ modelInfoRef,+ submitTransform: config.submitTransform,+ });+ });++ expect(result.current.buildPayload()?.api_key).toEqual({ api_key: null });+ });+});diff --git a/web/src/pages/user-setting/setting-model/instance-card/saved-provider-config.ts b/web/src/pages/user-setting/setting-model/instance-card/saved-provider-config.tsnew file mode 100644index 0000000000..416427a8e6--- /dev/null+++ b/web/src/pages/user-setting/setting-model/instance-card/saved-provider-config.ts@@ -0,0 +1,88 @@+/*+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { hasProviderCredentialInput } from '../provider-schema/field-config/utils';+import { SAVED_CREDENTIAL_MASK } from './saved-credential-input';++export const SavedProviderConfigFields = [+ 'api_version',+ 'auth_mode',+ 'aws_role_arn',+ 'bedrock_region',+ 'fish_audio_refid',+ 'google_project_id',+ 'google_region',+ 'group_id',+ 'mineru_apiserver',+ 'mineru_backend',+ 'mineru_delete_output',+ 'mineru_output_dir',+ 'mineru_server_url',+ 'opendataloader_apiserver',+ 'paddleocr_algorithm',+ 'paddleocr_api_url',+ 'provider_order',+] as const;++export const SavedProviderConfigFieldSet = new Set<string>(+ SavedProviderConfigFields,+);++export function pickSavedProviderConfigOverrides(+ value: unknown,+): Record<string, unknown> {+ let config = value;+ if (typeof config === 'string') {+ try {+ config = JSON.parse(config);+ } catch {+ return {};+ }+ }+ if (!config || typeof config !== 'object' || Array.isArray(config)) return {};++ return Object.fromEntries(+ Object.entries(config as Record<string, unknown>).filter(+ ([key, fieldValue]) =>+ SavedProviderConfigFieldSet.has(key) &&+ fieldValue !== undefined &&+ fieldValue !== SAVED_CREDENTIAL_MASK,+ ),+ );+}++export function hasUnsavedProviderCredential(value: unknown): boolean {+ if (typeof value === 'string') {+ const trimmed = value.trim();+ if (!trimmed) return false;+ try {+ const parsed = JSON.parse(trimmed);+ if (parsed && typeof parsed === 'object') {+ return hasUnsavedProviderCredential(parsed);+ }+ } catch {+ return true;+ }+ return true;+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;++ return Object.entries(value as Record<string, unknown>).some(+ ([field, fieldValue]) =>+ !SavedProviderConfigFieldSet.has(field) &&+ hasProviderCredentialInput({ [field]: fieldValue }),+ );+}diff --git a/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.test.ts b/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.test.tsindex d5b77624ee..0c6b33c2cd 100644--- a/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.test.ts+++ b/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.test.ts@@ -51,3 +51,40 @@ describe('Azure OpenAI provider configuration', () => {});});});++describe('provider instance submit transforms', () => {+ it.each([+ [+ LLMFactory.GoogleCloud,+ {+ google_project_id: 'project-1',+ google_region: 'us-central1',+ google_service_account_key: '{"type":"service_account"}',+ },+ ],+ [+ LLMFactory.TencentCloud,+ {+ TencentCloud_sid: 'sid-1',+ TencentCloud_sk: 'secret-1',+ },+ ],+ [+ LLMFactory.FishAudio,+ {+ fish_audio_ak: 'key-1',+ fish_audio_refid: 'voice-1',+ },+ ],+ ])('%s places provider settings in api_key', (provider, settings) => {+ const payload = ProviderConfigMap[provider].submitTransform?.({+ instance_name: 'test-instance',+ ...settings,+ });++ expect(payload?.api_key).toEqual(settings);+ for (const field of Object.keys(settings)) {+ expect(payload).not.toHaveProperty(field);+ }+ });+});diff --git a/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.ts b/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.tsindex 06619efb73..4eb9413dea 100644--- a/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.ts+++ b/web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.ts@@ -192,9 +192,11 @@ export const ProviderConfigMap: Record<string, ProviderConfig> = {submitTransform: (values) => ({instance_name: values.instance_name,llm_factory: LLMFactory.GoogleCloud,- google_project_id: values.google_project_id,- google_region: values.google_region,- google_service_account_key: values.google_service_account_key,+ api_key: {+ google_project_id: values.google_project_id,+ google_region: values.google_region,+ google_service_account_key: values.google_service_account_key,+ },model_info: [],}),echoTransform: (instance) => ({@@ -249,8 +251,10 @@ export const ProviderConfigMap: Record<string, ProviderConfig> = {submitTransform: (values) => ({instance_name: values.instance_name,llm_factory: LLMFactory.TencentCloud,- TencentCloud_sid: values.TencentCloud_sid,- TencentCloud_sk: values.TencentCloud_sk,+ api_key: {+ TencentCloud_sid: values.TencentCloud_sid,+ TencentCloud_sk: values.TencentCloud_sk,+ },model_info: [],}),echoTransform: (instance) => ({@@ -422,8 +426,10 @@ export const ProviderConfigMap: Record<string, ProviderConfig> = {submitTransform: (values) => ({instance_name: values.instance_name,llm_factory: LLMFactory.FishAudio,- fish_audio_ak: values.fish_audio_ak,- fish_audio_refid: values.fish_audio_refid,+ api_key: {+ fish_audio_ak: values.fish_audio_ak,+ fish_audio_refid: values.fish_audio_refid,+ },model_info: [],}),echoTransform: (instance) => ({@@ -493,7 +499,7 @@ export const ProviderConfigMap: Record<string, ProviderConfig> = {};},echoTransform: (instance) => {- const obj = parseApiKeyAsObject(instance.api_key) ?? {};+ const obj = parseApiKeyAsObject(instance.api_key_config) ?? {};return {opendataloader_apiserver: obj.opendataloader_apiserver ?? '',opendataloader_api_key: obj.opendataloader_api_key ?? '',@@ -581,7 +587,7 @@ export const ProviderConfigMap: Record<string, ProviderConfig> = {};},echoTransform: (instance) => {- const obj = parseApiKeyAsObject(instance.api_key) ?? {};+ const obj = parseApiKeyAsObject(instance.api_key_config) ?? {};return {paddleocr_api_url: obj.paddleocr_api_url ?? '',paddleocr_access_token: obj.paddleocr_access_token ?? '',@@ -637,7 +643,7 @@ export const ProviderConfigMap: Record<string, ProviderConfig> = {}),echoTransform: (instance) => ({paddleocr_api_url: instance.base_url ?? '',- paddleocr_access_token: instance.api_key ?? '',+ paddleocr_access_token: '',}),},@@ -728,7 +734,7 @@ export const ProviderConfigMap: Record<string, ProviderConfig> = {model_info: [],}),echoTransform: (instance) => {- const obj = parseApiKeyAsObject(instance.api_key) ?? {};+ const obj = parseApiKeyAsObject(instance.api_key_config) ?? {};const rawDelete = obj.mineru_delete_output;return {mineru_apiserver:diff --git a/web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts b/web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsindex 6f6bb63430..da155e4909 100644--- a/web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts+++ b/web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts@@ -42,12 +42,9 @@ export function applyChatToVision(}/**- * Parse a backend `api_key` value (which may be a JSON string, an- * already-parsed object, or a bare string) into the underlying object.- * Used by `echoTransform` implementations to lift provider-specific- * credential fields that the backend persists nested inside `api_key`- * (e.g. XunFei Spark's `spark_api_password`, PaddleOCR's nested config,- * MinerU's full config bundle).+ * Parse the backend's safe provider config object. `echoTransform`+ * implementations use it to restore non-secret provider settings; secret+ * fields are filtered by the backend before this data reaches the browser.** Returns `undefined` for bare strings or unparseable input so callers* can fall back to empty values via `??`.@@ -68,6 +65,44 @@ export function parseApiKeyAsObject(return obj && typeof obj === 'object' ? obj : undefined;}+const credentialFieldPattern =+ /(api[_-]?key|secret|token|password|credential|private|access[_-]?key|role[_-]?arn|_(ak|sk|sid|key)$)/i;++function hasCredentialValue(value: unknown): boolean {+ if (typeof value === 'string') return value.trim() !== '';+ if (Array.isArray(value)) return value.some(hasCredentialValue);+ if (value && typeof value === 'object') {+ return Object.values(value as Record<string, unknown>).some(+ hasCredentialValue,+ );+ }+ return Boolean(value);+}++/** Whether a provider credential payload contains a non-empty credential. */+export function hasProviderCredentialInput(value: unknown): boolean {+ if (typeof value === 'string') {+ const trimmed = value.trim();+ if (!trimmed) return false;+ try {+ const parsed = JSON.parse(trimmed);+ if (parsed && typeof parsed === 'object') {+ return hasProviderCredentialInput(parsed);+ }+ } catch {+ // A non-JSON string is a plain API key.+ }+ return true;+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ return false;+ }+ return Object.entries(value as Record<string, unknown>).some(+ ([key, fieldValue]) =>+ credentialFieldPattern.test(key) && hasCredentialValue(fieldValue),+ );+}+/*** Build the IModelInfo[] payload for verify/submit from the form values.*