fix(security): redact integration secrets from viewer-accessible endpoints

Prevent low-privileged tenant members from reading raw API keys and
infrastructure credentials via tenant profile, KV config, model/MCP/web
search listings, and KB initialization config responses.
This commit is contained in:
wizardchen
2026-07-02 12:31:57 +08:00
committed by lyingbug
parent 8325dac738
commit 0b73080bb8
18 changed files with 649 additions and 61 deletions
+14 -4
View File
@@ -10,6 +10,7 @@
package dto
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
@@ -68,10 +69,11 @@ type CredentialFieldMetadata struct {
// Headers, EnvVars, StdioConfig) stripped — these reveal how the tenant
// configured an upstream provider and must not be visible to other tenants
// that see the same builtin row via the cross-tenant list.
func NewMCPServiceResponse(svc *types.MCPService) *MCPServiceResponse {
func NewMCPServiceResponse(ctx context.Context, svc *types.MCPService) *MCPServiceResponse {
if svc == nil {
return nil
}
includeDetail := CanViewIntegrationSecrets(ctx)
resp := &MCPServiceResponse{
ID: svc.ID,
TenantID: svc.TenantID,
@@ -88,14 +90,22 @@ func NewMCPServiceResponse(svc *types.MCPService) *MCPServiceResponse {
CreatedAt: svc.CreatedAt,
UpdatedAt: svc.UpdatedAt,
}
if !includeDetail {
resp.Headers = nil
resp.EnvVars = nil
}
if svc.AuthConfig != nil {
resp.AuthConfig = &MCPAuthConfigResponse{
auth := &MCPAuthConfigResponse{
AuthType: svc.AuthConfig.AuthType,
APIKeyHeader: svc.AuthConfig.APIKeyHeader,
CustomHeaders: svc.AuthConfig.CustomHeaders,
Scopes: svc.AuthConfig.Scopes,
AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,
}
if !includeDetail {
auth.CustomHeaders = nil
}
resp.AuthConfig = auth
}
if svc.IsBuiltin {
// Builtin services are shared across tenants — strip everything that
@@ -115,10 +125,10 @@ func NewMCPServiceResponse(svc *types.MCPService) *MCPServiceResponse {
}
// NewMCPServiceResponses is the slice convenience wrapper used by ListMCPServices.
func NewMCPServiceResponses(svcs []*types.MCPService) []*MCPServiceResponse {
func NewMCPServiceResponses(ctx context.Context, svcs []*types.MCPService) []*MCPServiceResponse {
out := make([]*MCPServiceResponse, 0, len(svcs))
for _, s := range svcs {
out = append(out, NewMCPServiceResponse(s))
out = append(out, NewMCPServiceResponse(ctx, s))
}
return out
}
+21 -5
View File
@@ -25,7 +25,7 @@ func TestMCPServiceResponse_OmitsSecrets(t *testing.T) {
CustomHeaders: map[string]string{"X-Trace": "abc"},
},
}
body, err := json.Marshal(NewMCPServiceResponse(svc))
body, err := json.Marshal(NewMCPServiceResponse(adminContext(), svc))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "sk-real-api-key-do-not-leak",
@@ -63,7 +63,7 @@ func TestMCPServiceResponse_BuiltinStripsTenantConfig(t *testing.T) {
APIKey: "should-not-leak-via-builtin",
},
}
resp := NewMCPServiceResponse(svc)
resp := NewMCPServiceResponse(adminContext(), svc)
assert.Nil(t, resp.URL, "builtin must not leak per-tenant URL")
assert.Nil(t, resp.Headers, "builtin must not leak per-tenant headers")
assert.Nil(t, resp.AuthConfig, "builtin must not leak auth config")
@@ -73,7 +73,23 @@ func TestMCPServiceResponse_BuiltinStripsTenantConfig(t *testing.T) {
assert.False(t, strings.Contains(string(body), "X-Tenant-Secret"))
}
func TestMCPServiceResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewMCPServiceResponse(nil))
assert.Equal(t, []*MCPServiceResponse{}, NewMCPServiceResponses(nil))
func TestMCPServiceResponse_ViewerStripsIntegrationDetail(t *testing.T) {
svc := &types.MCPService{
ID: "svc-2",
Headers: types.MCPHeaders{"Authorization": "Bearer secret"},
EnvVars: types.MCPEnvVars{"TOKEN": "secret"},
AuthConfig: &types.MCPAuthConfig{
CustomHeaders: map[string]string{"X-Auth": "secret"},
},
}
resp := NewMCPServiceResponse(viewerContext(), svc)
assert.Nil(t, resp.Headers)
assert.Nil(t, resp.EnvVars)
assert.NotNil(t, resp.AuthConfig)
assert.Nil(t, resp.AuthConfig.CustomHeaders)
}
func TestMCPServiceResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewMCPServiceResponse(adminContext(), nil))
assert.Equal(t, []*MCPServiceResponse{}, NewMCPServiceResponses(adminContext(), nil))
}
+8 -3
View File
@@ -1,6 +1,7 @@
package dto
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
@@ -53,7 +54,7 @@ type ModelParametersDTO struct {
//
// Builtin models are shared across tenants — strip BaseURL (which can leak
// the tenant's private endpoint) and any non-shared parameters.
func NewModelResponse(m *types.Model) *ModelResponse {
func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
if m == nil {
return nil
}
@@ -68,6 +69,10 @@ func NewModelResponse(m *types.Model) *ModelResponse {
SupportsVision: m.Parameters.SupportsVision,
AppID: m.Parameters.AppID,
}
if !CanViewIntegrationSecrets(ctx) {
params.ExtraConfig = nil
params.CustomHeaders = nil
}
if m.IsBuiltin {
// Builtin: strip everything that could reveal per-tenant config.
// EmbeddingParameters and ParameterSize / Provider / InterfaceType /
@@ -104,10 +109,10 @@ func NewModelResponse(m *types.Model) *ModelResponse {
}
// NewModelResponses is the slice convenience wrapper.
func NewModelResponses(models []*types.Model) []*ModelResponse {
func NewModelResponses(ctx context.Context, models []*types.Model) []*ModelResponse {
out := make([]*ModelResponse, 0, len(models))
for _, m := range models {
out = append(out, NewModelResponse(m))
out = append(out, NewModelResponse(ctx, m))
}
return out
}
+18 -5
View File
@@ -22,7 +22,7 @@ func TestModelResponse_OmitsSecrets(t *testing.T) {
Provider: "openai",
},
}
body, err := json.Marshal(NewModelResponse(m))
body, err := json.Marshal(NewModelResponse(adminContext(), m))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "sk-real-api-key-do-not-leak")
@@ -55,7 +55,7 @@ func TestModelResponse_BuiltinStripsTenantConfig(t *testing.T) {
ExtraConfig: map[string]string{"region": "cn-hangzhou"},
},
}
resp := NewModelResponse(m)
resp := NewModelResponse(adminContext(), m)
assert.Empty(t, resp.Parameters.BaseURL,
"builtin must not leak per-tenant base URL")
assert.Empty(t, resp.Parameters.AppID,
@@ -70,7 +70,20 @@ func TestModelResponse_BuiltinStripsTenantConfig(t *testing.T) {
assert.False(t, strings.Contains(string(body), "tenant-private.example.com"))
}
func TestModelResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewModelResponse(nil))
assert.Equal(t, []*ModelResponse{}, NewModelResponses(nil))
func TestModelResponse_ViewerStripsIntegrationDetail(t *testing.T) {
m := &types.Model{
ID: "m-2",
Parameters: types.ModelParameters{
CustomHeaders: map[string]string{"Authorization": "Bearer secret"},
ExtraConfig: map[string]string{"region": "cn-hangzhou"},
},
}
resp := NewModelResponse(viewerContext(), m)
assert.Nil(t, resp.Parameters.CustomHeaders)
assert.Nil(t, resp.Parameters.ExtraConfig)
}
func TestModelResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewModelResponse(adminContext(), nil))
assert.Equal(t, []*ModelResponse{}, NewModelResponses(adminContext(), nil))
}
+22
View File
@@ -0,0 +1,22 @@
package dto
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// RoleFromContext returns the caller's tenant role from ctx.
func RoleFromContext(ctx context.Context) types.TenantRole {
return types.TenantRoleFromContext(ctx)
}
// CanViewIntegrationSecrets is true for Admin+ (includes Owner).
func CanViewIntegrationSecrets(ctx context.Context) bool {
return RoleFromContext(ctx).HasPermission(types.TenantRoleAdmin)
}
// CanViewTenantAPIKey is true for Owner+ only.
func CanViewTenantAPIKey(ctx context.Context) bool {
return RoleFromContext(ctx).HasPermission(types.TenantRoleOwner)
}
+79
View File
@@ -0,0 +1,79 @@
package dto
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
"gorm.io/gorm"
)
// TenantResponse is the viewer-safe tenant profile shape. Secret-bearing
// columns are omitted or redacted unless the caller has Admin+ (Owner for
// api_key).
type TenantResponse struct {
ID uint64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
APIKey string `json:"api_key,omitempty"`
Status string `json:"status"`
RetrieverEngines types.RetrieverEngines `json:"retriever_engines"`
Business string `json:"business"`
StorageQuota int64 `json:"storage_quota"`
StorageUsed int64 `json:"storage_used"`
ContextConfig *types.ContextConfig `json:"context_config,omitempty"`
WebSearchConfig *types.WebSearchConfig `json:"web_search_config,omitempty"`
ParserEngineConfig *types.ParserEngineConfig `json:"parser_engine_config,omitempty"`
Credentials *types.CredentialsConfig `json:"credentials,omitempty"`
StorageEngineConfig *types.StorageEngineConfig `json:"storage_engine_config,omitempty"`
ChatHistoryConfig *types.ChatHistoryConfig `json:"chat_history_config,omitempty"`
RetrievalConfig *types.RetrievalConfig `json:"retrieval_config,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at"`
}
// NewTenantResponse converts a stored tenant into its HTTP response shape.
func NewTenantResponse(ctx context.Context, tenant *types.Tenant) *TenantResponse {
if tenant == nil {
return nil
}
includeSecrets := CanViewIntegrationSecrets(ctx)
includeAPIKey := CanViewTenantAPIKey(ctx)
resp := &TenantResponse{
ID: tenant.ID,
Name: tenant.Name,
Description: tenant.Description,
Status: tenant.Status,
RetrieverEngines: tenant.RetrieverEngines,
Business: tenant.Business,
StorageQuota: tenant.StorageQuota,
StorageUsed: tenant.StorageUsed,
ContextConfig: tenant.ContextConfig,
ChatHistoryConfig: tenant.ChatHistoryConfig,
RetrievalConfig: tenant.RetrievalConfig,
CreatedAt: tenant.CreatedAt,
UpdatedAt: tenant.UpdatedAt,
DeletedAt: tenant.DeletedAt,
}
if includeAPIKey {
resp.APIKey = tenant.APIKey
}
if includeSecrets {
resp.WebSearchConfig = types.WebSearchConfigForResponse(tenant.WebSearchConfig, true)
resp.ParserEngineConfig = types.ParserEngineConfigForResponse(tenant.ParserEngineConfig, true)
resp.Credentials = types.CredentialsConfigForResponse(tenant.Credentials, true)
resp.StorageEngineConfig = types.StorageEngineConfigForResponse(tenant.StorageEngineConfig, true)
}
return resp
}
// NewTenantResponses is the slice convenience wrapper.
func NewTenantResponses(ctx context.Context, tenants []*types.Tenant) []*TenantResponse {
out := make([]*TenantResponse, 0, len(tenants))
for _, t := range tenants {
out = append(out, NewTenantResponse(ctx, t))
}
return out
}
+77
View File
@@ -0,0 +1,77 @@
package dto
import (
"encoding/json"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTenantResponse_ViewerOmitsSecrets(t *testing.T) {
tenant := sampleSecretTenant()
body, err := json.Marshal(NewTenantResponse(viewerContext(), tenant))
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "tenant-api-key-123")
assert.NotContains(t, s, "legacy-search-secret-999")
assert.NotContains(t, s, "wk-app-secret-def")
assert.NotContains(t, s, "parser-secret-123")
assert.NotContains(t, s, "minio-secret-789")
assert.NotContains(t, s, "web_search_config")
assert.NotContains(t, s, "parser_engine_config")
assert.NotContains(t, s, "storage_engine_config")
assert.NotContains(t, s, "credentials")
}
func TestTenantResponse_OwnerGetsAPIKeyOnly(t *testing.T) {
tenant := sampleSecretTenant()
body, err := json.Marshal(NewTenantResponse(ownerContext(), tenant))
require.NoError(t, err)
s := string(body)
assert.Contains(t, s, "tenant-api-key-123")
assert.NotContains(t, s, "legacy-search-secret-999")
assert.NotContains(t, s, "parser-secret-123")
}
func TestTenantResponse_AdminGetsRedactedIntegrationConfigs(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewTenantResponse(adminContext(), tenant)
require.NotNil(t, resp.WebSearchConfig)
assert.Equal(t, types.RedactedSecretPlaceholder, resp.WebSearchConfig.ProxyURL)
assert.Empty(t, resp.WebSearchConfig.APIKey)
require.NotNil(t, resp.ParserEngineConfig)
assert.Equal(t, types.RedactedSecretPlaceholder, resp.ParserEngineConfig.MinerUAPIKey)
require.NotNil(t, resp.StorageEngineConfig.MinIO)
assert.Equal(t, types.RedactedSecretPlaceholder, resp.StorageEngineConfig.MinIO.SecretAccessKey)
}
func sampleSecretTenant() *types.Tenant {
return &types.Tenant{
ID: 42,
Name: "tenant",
APIKey: "tenant-api-key-123",
WebSearchConfig: &types.WebSearchConfig{
APIKey: "legacy-search-secret-999",
ProxyURL: "http://proxy.internal:8080",
},
Credentials: &types.CredentialsConfig{
WeKnoraCloud: &types.WeKnoraCloudCredentials{
AppID: "wk-app-id-abc",
AppSecret: "wk-app-secret-def",
},
},
ParserEngineConfig: &types.ParserEngineConfig{
MinerUAPIKey: "parser-secret-123",
PaddleOCRVLCloudToken: "paddle-secret-456",
},
StorageEngineConfig: &types.StorageEngineConfig{
DefaultProvider: "minio",
MinIO: &types.MinIOEngineConfig{
AccessKeyID: "minio-access-id",
SecretAccessKey: "minio-secret-789",
},
},
}
}
+22
View File
@@ -0,0 +1,22 @@
package dto
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
func adminContext() context.Context {
ctx := context.Background()
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
}
func viewerContext() context.Context {
ctx := context.Background()
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
}
func ownerContext() context.Context {
ctx := context.Background()
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleOwner)
}
+18 -12
View File
@@ -1,6 +1,7 @@
package dto
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
@@ -34,35 +35,40 @@ type WebSearchProviderParametersDTO struct {
}
// NewWebSearchProviderResponse converts a stored entity into its response shape.
func NewWebSearchProviderResponse(e *types.WebSearchProviderEntity) *WebSearchProviderResponse {
func NewWebSearchProviderResponse(ctx context.Context, e *types.WebSearchProviderEntity) *WebSearchProviderResponse {
if e == nil {
return nil
}
params := WebSearchProviderParametersDTO{
EngineID: e.Parameters.EngineID,
BaseURL: e.Parameters.BaseURL,
ProxyURL: e.Parameters.ProxyURL,
ExtraConfig: e.Parameters.ExtraConfig,
}
if !CanViewIntegrationSecrets(ctx) {
params.ProxyURL = ""
params.ExtraConfig = nil
}
return &WebSearchProviderResponse{
ID: e.ID,
TenantID: e.TenantID,
Name: e.Name,
Provider: e.Provider,
Description: e.Description,
Parameters: WebSearchProviderParametersDTO{
EngineID: e.Parameters.EngineID,
BaseURL: e.Parameters.BaseURL,
ProxyURL: e.Parameters.ProxyURL,
ExtraConfig: e.Parameters.ExtraConfig,
},
IsDefault: e.IsDefault,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
Parameters: params,
IsDefault: e.IsDefault,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
Credentials: map[string]CredentialFieldMetadata{
"api_key": {Configured: e.Parameters.APIKey != ""},
},
}
}
func NewWebSearchProviderResponses(es []*types.WebSearchProviderEntity) []*WebSearchProviderResponse {
func NewWebSearchProviderResponses(ctx context.Context, es []*types.WebSearchProviderEntity) []*WebSearchProviderResponse {
out := make([]*WebSearchProviderResponse, 0, len(es))
for _, e := range es {
out = append(out, NewWebSearchProviderResponse(e))
out = append(out, NewWebSearchProviderResponse(ctx, e))
}
return out
}
@@ -19,7 +19,7 @@ func TestWebSearchProviderResponse_OmitsSecrets(t *testing.T) {
BaseURL: "https://example.com",
},
}
body, err := json.Marshal(NewWebSearchProviderResponse(e))
body, err := json.Marshal(NewWebSearchProviderResponse(adminContext(), e))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "bing-secret-do-not-leak")
@@ -35,7 +35,20 @@ func TestWebSearchProviderResponse_OmitsSecrets(t *testing.T) {
assert.Contains(t, s, "example.com")
}
func TestWebSearchProviderResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewWebSearchProviderResponse(nil))
assert.Equal(t, []*WebSearchProviderResponse{}, NewWebSearchProviderResponses(nil))
func TestWebSearchProviderResponse_ViewerStripsIntegrationDetail(t *testing.T) {
e := &types.WebSearchProviderEntity{
ID: "wsp-2",
Parameters: types.WebSearchProviderParameters{
ProxyURL: "http://proxy:8080",
ExtraConfig: map[string]string{"token": "secret"},
},
}
resp := NewWebSearchProviderResponse(viewerContext(), e)
assert.Empty(t, resp.Parameters.ProxyURL)
assert.Nil(t, resp.Parameters.ExtraConfig)
}
func TestWebSearchProviderResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewWebSearchProviderResponse(adminContext(), nil))
assert.Equal(t, []*WebSearchProviderResponse{}, NewWebSearchProviderResponses(adminContext(), nil))
}