chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
package dto
import "academy/internal/types"
// AuthLoginResponse is the HTTP-safe login / switch-tenant response shape.
type AuthLoginResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *types.User `json:"user,omitempty"`
ActiveTenant *TenantResponse `json:"active_tenant,omitempty"`
Memberships []types.Membership `json:"memberships"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
}
// AuthOIDCCallbackResponse is the HTTP-safe OIDC callback payload shape.
type AuthOIDCCallbackResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *types.User `json:"user,omitempty"`
Tenant *TenantResponse `json:"tenant,omitempty"`
Memberships []types.Membership `json:"memberships"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
IsNewUser bool `json:"is_new_user,omitempty"`
}
// NewAuthLoginResponse converts a service-layer login response for HTTP output.
func NewAuthLoginResponse(resp *types.LoginResponse) *AuthLoginResponse {
if resp == nil {
return nil
}
var role types.TenantRole
if resp.ActiveTenant != nil {
role = membershipRoleForTenant(resp.Memberships, resp.ActiveTenant.ID)
}
return &AuthLoginResponse{
Success: resp.Success,
Message: resp.Message,
User: resp.User,
ActiveTenant: NewTenantResponseWithRole(resp.ActiveTenant, role),
Memberships: resp.Memberships,
Token: resp.Token,
RefreshToken: resp.RefreshToken,
}
}
// NewAuthOIDCCallbackResponse converts an OIDC callback response for HTTP output.
func NewAuthOIDCCallbackResponse(resp *types.OIDCCallbackResponse) *AuthOIDCCallbackResponse {
if resp == nil {
return nil
}
var role types.TenantRole
if resp.Tenant != nil {
role = membershipRoleForTenant(resp.Memberships, resp.Tenant.ID)
}
return &AuthOIDCCallbackResponse{
Success: resp.Success,
Message: resp.Message,
User: resp.User,
Tenant: NewTenantResponseWithRole(resp.Tenant, role),
Memberships: resp.Memberships,
Token: resp.Token,
RefreshToken: resp.RefreshToken,
IsNewUser: resp.IsNewUser,
}
}
func membershipRoleForTenant(memberships []types.Membership, tenantID uint64) types.TenantRole {
for _, m := range memberships {
if m.TenantID == tenantID && m.Role.IsValid() {
return m.Role
}
}
return ""
}
+60
View File
@@ -0,0 +1,60 @@
package dto
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAuthLoginResponse_ViewerOmitsActiveTenantSecrets(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewAuthLoginResponse(&types.LoginResponse{
Success: true,
ActiveTenant: tenant,
Memberships: []types.Membership{{
TenantID: tenant.ID,
Role: types.TenantRoleViewer,
}},
})
body, err := json.Marshal(resp)
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "tenant-api-key-123")
assert.NotContains(t, s, "parser-secret-123")
}
func TestAuthLoginResponse_OwnerOmitsLegacyTenantAPIKey(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewAuthLoginResponse(&types.LoginResponse{
Success: true,
ActiveTenant: tenant,
Memberships: []types.Membership{{
TenantID: tenant.ID,
Role: types.TenantRoleOwner,
}},
})
body, err := json.Marshal(resp)
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, `"api_key"`)
assert.NotContains(t, s, "legacy-search-secret-999")
assert.Contains(t, s, "web_search_config")
}
func TestAuthOIDCCallbackResponse_ViewerOmitsTenantSecrets(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewAuthOIDCCallbackResponse(&types.OIDCCallbackResponse{
Success: true,
Tenant: tenant,
Memberships: []types.Membership{{
TenantID: tenant.ID,
Role: types.TenantRoleViewer,
}},
})
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "tenant-api-key-123")
}
+140
View File
@@ -0,0 +1,140 @@
package dto
import (
"encoding/json"
"strings"
"time"
"academy/internal/types"
)
// DataSourceResponse mirrors types.DataSource for response bodies, with the
// connector Credentials map stripped from the Config jsonb. Credential
// presence is exposed via the dedicated /credentials subresource.
//
// Unlike MCP / Model / WebSearch (which have a flat set of named credential
// fields), DataSource credentials are a per-connector atomic map — an OAuth
// token pair, a Confluence email+token bundle, etc. Splitting them at the
// field level would leave half-configured states that can't actually
// authenticate. The subresource therefore exposes only one logical field,
// "credentials", with PUT replacing the whole map and DELETE wiping it.
type DataSourceResponse struct {
ID string `json:"id" extensions:"x-agent=data_source_id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id" extensions:"x-agent"`
Name string `json:"name" extensions:"x-agent"`
Type string `json:"type" extensions:"x-agent"`
Config *DataSourceConfigDTO `json:"config,omitempty" extensions:"x-agent"`
SyncSchedule string `json:"sync_schedule" extensions:"x-agent"`
SyncMode string `json:"sync_mode" extensions:"x-agent"`
Status string `json:"status" extensions:"x-agent"`
ConflictStrategy string `json:"conflict_strategy" extensions:"x-agent"`
SyncDeletions bool `json:"sync_deletions" extensions:"x-agent"`
LastSyncAt *time.Time `json:"last_sync_at" extensions:"x-agent"`
LastSyncCursor json.RawMessage `json:"last_sync_cursor,omitempty"`
LastSyncResult json.RawMessage `json:"last_sync_result,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
SyncLogRetentionDays int `json:"sync_log_retention_days"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
TotalItemsSynced int64 `json:"total_items_synced" extensions:"x-agent"`
LatestSyncLog *types.SyncLog `json:"latest_sync_log,omitempty"`
// Single logical credential field — DataSource credentials are a
// per-connector atomic map, so "configured?" applies to the whole set.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
}
// DataSourceConfigDTO is types.DataSourceConfig with the Credentials map
// removed by construction. Type, ResourceIDs and Settings remain visible.
type DataSourceConfigDTO struct {
Type string `json:"type"`
ResourceIDs []string `json:"resource_ids,omitempty" extensions:"x-agent"`
Settings map[string]interface{} `json:"settings,omitempty"`
}
// NewDataSourceResponse converts a stored entity into its response shape.
// Returns nil for nil input.
func NewDataSourceResponse(ds *types.DataSource) *DataSourceResponse {
if ds == nil {
return nil
}
var cfgDTO *DataSourceConfigDTO
configured := false
if parsed, err := ds.ParseConfig(); err == nil && parsed != nil {
cfgDTO = &DataSourceConfigDTO{
Type: parsed.Type,
ResourceIDs: parsed.ResourceIDs,
Settings: parsed.Settings,
}
enrichRSSFeedURLsInSettings(ds.Type, parsed, cfgDTO)
configured = parsed.HasConfiguredCredentials(ds.Type)
}
return &DataSourceResponse{
ID: ds.ID,
TenantID: ds.TenantID,
KnowledgeBaseID: ds.KnowledgeBaseID,
Name: ds.Name,
Type: ds.Type,
Config: cfgDTO,
SyncSchedule: ds.SyncSchedule,
SyncMode: ds.SyncMode,
Status: ds.Status,
ConflictStrategy: ds.ConflictStrategy,
SyncDeletions: ds.SyncDeletions,
LastSyncAt: ds.LastSyncAt,
LastSyncCursor: json.RawMessage(ds.LastSyncCursor),
LastSyncResult: json.RawMessage(ds.LastSyncResult),
ErrorMessage: ds.ErrorMessage,
SyncLogRetentionDays: ds.SyncLogRetentionDays,
CreatedAt: ds.CreatedAt,
UpdatedAt: ds.UpdatedAt,
TotalItemsSynced: ds.TotalItemsSynced,
LatestSyncLog: ds.LatestSyncLog,
Credentials: map[string]CredentialFieldMetadata{
"credentials": {Configured: configured},
},
}
}
// enrichRSSFeedURLsInSettings copies feed_urls from credentials into settings
// for API responses. Feed URLs are not secrets but may still live in the
// encrypted credentials blob on rows created before they moved to settings.
func enrichRSSFeedURLsInSettings(dsType string, parsed *types.DataSourceConfig, cfgDTO *DataSourceConfigDTO) {
if dsType != types.ConnectorTypeRSS || parsed == nil || cfgDTO == nil {
return
}
if cfgDTO.Settings != nil {
if v, ok := cfgDTO.Settings["feed_urls"].(string); ok && strings.TrimSpace(v) != "" {
return
}
}
raw, ok := parsed.Credentials["feed_urls"]
if !ok {
return
}
feedURLs, ok := raw.(string)
if !ok || strings.TrimSpace(feedURLs) == "" {
return
}
if cfgDTO.Settings == nil {
cfgDTO.Settings = make(map[string]interface{})
}
cfgDTO.Settings["feed_urls"] = feedURLs
}
// NewDataSourceResponses converts a list of entities for the list endpoint.
// The sync cursor is stripped from every element: the settings page polls
// the list every few seconds during a sync, cursors can grow to megabytes,
// and no list consumer reads them. Detail, create and update responses
// still carry the cursor through NewDataSourceResponse.
func NewDataSourceResponses(dss []*types.DataSource) []*DataSourceResponse {
out := make([]*DataSourceResponse, 0, len(dss))
for _, d := range dss {
resp := NewDataSourceResponse(d)
if resp != nil {
resp.LastSyncCursor = nil
}
out = append(out, resp)
}
return out
}
+139
View File
@@ -0,0 +1,139 @@
package dto
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
)
func TestDataSourceResponse_OmitsCredentials(t *testing.T) {
cfg := types.DataSourceConfig{
Type: "github",
Credentials: map[string]interface{}{
"token": "ghp-secret-do-not-leak",
},
ResourceIDs: []string{"repo-1"},
Settings: map[string]interface{}{"branch": "main"},
}
blob, _ := cfg.ToJSON()
ds := &types.DataSource{
ID: "ds-1",
Name: "github-prod",
Type: "github",
Config: blob,
}
body, err := json.Marshal(NewDataSourceResponse(ds))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "ghp-secret-do-not-leak")
// The inner config object must not carry the credentials map (the
// DataSourceConfigDTO type omits it structurally).
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
if cfgRaw, ok := raw["config"]; ok {
var inner map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(cfgRaw, &inner))
_, hasCredsInConfig := inner["credentials"]
assert.False(t, hasCredsInConfig,
"credentials map must not appear inside the config DTO")
}
// Top-level credentials map is just the "configured?" indicator,
// replaces the removed GET /credentials endpoint.
assert.Contains(t, s, `"credentials":{"credentials":{"configured":true}}`)
// Non-secret config fields pass through.
assert.Contains(t, s, "repo-1")
assert.Contains(t, s, "branch")
assert.Contains(t, s, "main")
}
func TestDataSourceResponses_OmitsLastSyncCursor(t *testing.T) {
ds := &types.DataSource{
ID: "ds-1",
Name: "github-prod",
Type: "github",
LastSyncCursor: types.JSON(`{"page":42}`),
LastSyncResult: types.JSON(`{"total":10}`),
}
list := NewDataSourceResponses([]*types.DataSource{ds})
assert.Len(t, list, 1)
got := list[0]
assert.Empty(t, got.LastSyncCursor)
body, err := json.Marshal(got)
assert.NoError(t, err)
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
assert.NotContains(t, raw, "last_sync_cursor")
// Every other field must match the single-entity conversion.
want := NewDataSourceResponse(ds)
assert.Equal(t, json.RawMessage(`{"page":42}`), want.LastSyncCursor)
want.LastSyncCursor = nil
assert.Equal(t, want, got)
}
func TestDataSourceResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewDataSourceResponse(nil))
assert.Equal(t, []*DataSourceResponse{}, NewDataSourceResponses(nil))
}
func TestDataSourceResponse_RSSFeedURLsFromCredentials(t *testing.T) {
cfg := types.DataSourceConfig{
Type: types.ConnectorTypeRSS,
Credentials: map[string]interface{}{
"feed_urls": "https://example.com/a.xml\nhttps://example.com/b.xml",
},
ResourceIDs: []string{"https://example.com/a.xml"},
}
blob, _ := cfg.ToJSON()
ds := &types.DataSource{
ID: "ds-rss",
Name: "my-rss",
Type: types.ConnectorTypeRSS,
Config: blob,
}
resp := NewDataSourceResponse(ds)
assert.NotNil(t, resp.Config)
assert.Equal(t, "https://example.com/a.xml\nhttps://example.com/b.xml", resp.Config.Settings["feed_urls"])
assert.False(t, resp.Credentials["credentials"].Configured)
body, err := json.Marshal(resp)
assert.NoError(t, err)
s := string(body)
assert.Contains(t, s, "https://example.com/a.xml")
assert.NotContains(t, s, "Bearer secret")
}
func TestDataSourceResponse_RSSAuthHeadersConfigured(t *testing.T) {
cfg := types.DataSourceConfig{
Type: types.ConnectorTypeRSS,
Credentials: map[string]interface{}{
"auth_headers": "Authorization: Bearer secret",
},
Settings: map[string]interface{}{
"feed_urls": "https://example.com/feed.xml",
},
}
blob, _ := cfg.ToJSON()
ds := &types.DataSource{
ID: "ds-rss-auth",
Name: "my-rss",
Type: types.ConnectorTypeRSS,
Config: blob,
}
resp := NewDataSourceResponse(ds)
assert.True(t, resp.Credentials["credentials"].Configured)
body, err := json.Marshal(resp)
assert.NoError(t, err)
assert.NotContains(t, string(body), "Bearer secret")
}
func TestDataSourceResponse_NoConfig(t *testing.T) {
ds := &types.DataSource{ID: "x", Name: "x"}
body, err := json.Marshal(NewDataSourceResponse(ds))
assert.NoError(t, err)
// No config jsonb stored → no config object in the response.
assert.NotContains(t, string(body), `"config":`)
}
+216
View File
@@ -0,0 +1,216 @@
// Package dto holds response shapes for handler responses that need to differ
// from the persisted GORM model — most notably, response types that must NOT
// carry secret fields.
//
// Why a separate package: response DTOs are deliberately distinct from the
// internal model so the "no secret in responses" guarantee is a compile-time
// invariant rather than a runtime redaction step. If a future contributor
// wants to expose a credential in a response, they must add it to the DTO
// explicitly, which makes the leak surface review-able in a single diff.
package dto
import (
"context"
"time"
"academy/internal/types"
)
// MCPServiceResponse mirrors types.MCPService for response bodies, omitting
// every secret field (api_key, token). Credential presence/absence is exposed
// separately via the /credentials subresource endpoint; this shape carries
// only a boolean per credential field so the frontend can render a
// "configured / not configured" badge without an additional round-trip.
type MCPServiceResponse struct {
UsageInstructions string `json:"usage_instructions"`
ID string `json:"id" extensions:"x-agent=mcp_service_id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Enabled bool `json:"enabled" extensions:"x-agent"`
TransportType types.MCPTransportType `json:"transport_type" extensions:"x-agent"`
URL *string `json:"url,omitempty"`
Headers types.MCPHeaders `json:"headers,omitempty"`
AuthConfig *MCPAuthConfigResponse `json:"auth_config,omitempty" extensions:"x-agent"`
AdvancedConfig *types.MCPAdvancedConfig `json:"advanced_config,omitempty"`
StdioConfig *types.MCPStdioConfig `json:"stdio_config,omitempty"`
EnvVars types.MCPEnvVars `json:"env_vars,omitempty"`
IsBuiltin bool `json:"is_builtin" extensions:"x-agent"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Credentials is the per-field "configured?" map. Embedded on the main
// response so the credential UI doesn't need a follow-up GET. The
// frontend never sees the actual secret value — only whether one is
// stored. Omitted entirely for builtin services (they can't have
// per-tenant credentials).
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
// Catalog is the persisted tool-directory summary for list cards.
// Omitted when this principal has never synchronized the service.
Catalog *MCPCatalogSummary `json:"catalog,omitempty"`
}
// MCPCatalogSummary is the list-card view of a saved MCP directory.
type MCPCatalogSummary struct {
ToolCount int `json:"tool_count"`
Stale bool `json:"stale"`
SyncedAt time.Time `json:"synced_at"`
}
// MCPAuthConfigResponse intentionally has no APIKey, Token or ClientSecret
// fields. Their presence is signalled via MCPServiceResponse.Credentials.
// AuthType, Scopes, AuthServerMetadataURL and ClientID are non-secret OAuth
// configuration and are safe to echo back so the UI can render the current
// strategy.
type MCPAuthConfigResponse struct {
AuthType types.MCPAuthType `json:"auth_type,omitempty" extensions:"x-agent"`
APIKeyHeader string `json:"api_key_header,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
Scopes []string `json:"scopes,omitempty"`
AuthServerMetadataURL string `json:"auth_server_metadata_url,omitempty"`
ClientID string `json:"client_id,omitempty"`
}
// CredentialFieldMetadata reports whether a credential field has a value
// stored server-side, without exposing the value itself.
type CredentialFieldMetadata struct {
Configured bool `json:"configured"`
}
// NewMCPServiceResponse converts a stored MCPService into its response shape.
//
// Builtin MCP services have their tenant-specific transport details (URL,
// 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(ctx context.Context, svc *types.MCPService) *MCPServiceResponse {
if svc == nil {
return nil
}
includeDetail := CanViewIntegrationSecrets(ctx)
resp := &MCPServiceResponse{
ID: svc.ID,
TenantID: svc.TenantID,
Name: svc.Name,
Description: svc.Description,
UsageInstructions: svc.UsageInstructions,
Enabled: svc.Enabled,
TransportType: svc.TransportType,
URL: svc.URL,
Headers: svc.Headers,
AdvancedConfig: svc.AdvancedConfig,
StdioConfig: svc.StdioConfig,
EnvVars: svc.EnvVars,
IsBuiltin: svc.IsBuiltin,
CreatedAt: svc.CreatedAt,
UpdatedAt: svc.UpdatedAt,
}
if !includeDetail {
resp.Headers = nil
resp.EnvVars = nil
resp.URL = nil
resp.StdioConfig = nil
resp.AdvancedConfig = nil
}
if svc.AuthConfig != nil {
auth := &MCPAuthConfigResponse{
AuthType: svc.AuthConfig.AuthType,
APIKeyHeader: svc.AuthConfig.APIKeyHeader,
CustomHeaders: svc.AuthConfig.CustomHeaders,
Scopes: svc.AuthConfig.Scopes,
AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,
ClientID: svc.AuthConfig.ClientID,
}
if !includeDetail {
auth.CustomHeaders = nil
}
resp.AuthConfig = auth
}
if svc.IsBuiltin {
// Builtin services are shared across tenants — strip everything that
// could leak how this tenant configured the underlying provider.
resp.URL = nil
resp.Headers = nil
resp.EnvVars = nil
resp.StdioConfig = nil
resp.AuthConfig = nil
} else {
resp.Credentials = map[string]CredentialFieldMetadata{
"api_key": {Configured: svc.AuthConfig != nil && svc.AuthConfig.APIKey != ""},
"token": {Configured: svc.AuthConfig != nil && svc.AuthConfig.Token != ""},
"client_secret": {Configured: svc.AuthConfig != nil && svc.AuthConfig.ClientSecret != ""},
}
}
return resp
}
// NewMCPServiceResponses is the slice convenience wrapper used by ListMCPServices.
func NewMCPServiceResponses(ctx context.Context, svcs []*types.MCPService) []*MCPServiceResponse {
out := make([]*MCPServiceResponse, 0, len(svcs))
for _, s := range svcs {
out = append(out, NewMCPServiceResponse(ctx, s))
}
return out
}
// NewSharedAgentMCPServiceResponses is the cross-workspace list shape: the
// @MCP picker of a borrowed agent needs a service's identity and how many
// tools it offers, and nothing else.
//
// It fills the fields explicitly instead of reusing NewMCPServiceResponse and
// blanking the rest, so a field added to MCPServiceResponse later is absent
// here until someone decides it may cross a workspace boundary. Endpoint URLs,
// headers, env vars, stdio commands, auth config and credential metadata all
// describe how the OWNER wired the service up; the borrower never configures
// it and must not see it.
func NewSharedAgentMCPServiceResponses(svcs []*types.MCPService) []*MCPServiceResponse {
out := make([]*MCPServiceResponse, 0, len(svcs))
for _, s := range svcs {
if s == nil {
continue
}
out = append(out, &MCPServiceResponse{
ID: s.ID,
TenantID: s.TenantID,
Name: s.Name,
Description: s.Description,
UsageInstructions: s.UsageInstructions,
Enabled: s.Enabled,
TransportType: s.TransportType,
IsBuiltin: s.IsBuiltin,
})
}
return out
}
// AttachMCPCatalogs copies persisted directory counts onto list/detail responses.
func AttachMCPCatalogs(
resp []*MCPServiceResponse,
services []*types.MCPService,
summaries map[string]*types.MCPMetadataSummary,
) {
if len(resp) != len(services) || summaries == nil {
return
}
for i, service := range services {
if resp[i] == nil || service == nil {
continue
}
summary := summaries[service.ID]
if summary == nil {
continue
}
resp[i].Catalog = &MCPCatalogSummary{
ToolCount: summary.ToolCount,
Stale: summary.ConfigFingerprint != types.MCPConfigFingerprint(service),
SyncedAt: summary.SyncedAt,
}
}
}
// CredentialsResponse is the shared shape returned by PUT
// /{resource}/{id}/credentials. Keyed by field name (e.g. "api_key",
// "token"). The frontend uses this to update its in-memory metadata after a
// successful save without needing to re-fetch the whole resource.
type CredentialsResponse struct {
Fields map[string]CredentialFieldMetadata `json:"fields"`
}
+139
View File
@@ -0,0 +1,139 @@
package dto
import (
"encoding/json"
"strings"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
)
// The most important guarantee of the DTO layer is structural: the serialized
// response body must NEVER contain api_key or token under any condition,
// regardless of the underlying entity's state. We assert this via the
// serialized JSON (not just struct shape) because reflection-based
// custom-marshalers anywhere downstream could otherwise reintroduce a leak.
func TestMCPServiceResponse_OmitsSecrets(t *testing.T) {
svc := &types.MCPService{
ID: "svc-1",
Name: "svc",
AuthConfig: &types.MCPAuthConfig{
APIKey: "sk-real-api-key-do-not-leak",
Token: "tok-real-bearer-token-do-not-leak",
CustomHeaders: map[string]string{"X-Trace": "abc"},
},
}
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",
"raw api_key must never appear in MCPServiceResponse")
assert.NotContains(t, s, "tok-real-bearer-token-do-not-leak",
"raw token must never appear in MCPServiceResponse")
// auth_config no longer has api_key/token fields (only custom_headers
// survived). Verify the auth_config sub-object contains no secret keys.
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
if ac, ok := raw["auth_config"]; ok {
acStr := string(ac)
assert.NotContains(t, acStr, `"api_key"`)
assert.NotContains(t, acStr, `"token"`)
}
// The new credentials map exposes "configured?" booleans by design
// (replaces the standalone GET /credentials endpoint). Verify the
// values are booleans, not strings.
assert.Contains(t, s, `"credentials"`)
assert.Contains(t, s, `"api_key":{"configured":true}`)
assert.Contains(t, s, `"token":{"configured":true}`)
// CustomHeaders is structural metadata and SHOULD pass through.
assert.Contains(t, s, `"custom_headers"`)
assert.Contains(t, s, `"X-Trace"`)
}
func TestMCPServiceResponse_BuiltinStripsTenantConfig(t *testing.T) {
url := "https://tenant-private.example.com"
svc := &types.MCPService{
ID: "builtin-1",
IsBuiltin: true,
URL: &url,
Headers: types.MCPHeaders{"X-Tenant-Secret": "shhh"},
AuthConfig: &types.MCPAuthConfig{
APIKey: "should-not-leak-via-builtin",
},
}
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")
body, _ := json.Marshal(resp)
assert.False(t, strings.Contains(string(body), "should-not-leak-via-builtin"))
assert.False(t, strings.Contains(string(body), "X-Tenant-Secret"))
}
func TestMCPServiceResponse_ViewerStripsIntegrationDetail(t *testing.T) {
url := "https://tenant-private.example.com"
svc := &types.MCPService{
ID: "svc-2",
URL: &url,
Headers: types.MCPHeaders{"Authorization": "Bearer secret"},
EnvVars: types.MCPEnvVars{"TOKEN": "secret"},
StdioConfig: &types.MCPStdioConfig{
Command: "npx",
Args: []string{"-y", "mcp-server"},
},
AdvancedConfig: &types.MCPAdvancedConfig{},
AuthConfig: &types.MCPAuthConfig{
CustomHeaders: map[string]string{"X-Auth": "secret"},
},
}
resp := NewMCPServiceResponse(viewerContext(), svc)
assert.Nil(t, resp.URL)
assert.Nil(t, resp.Headers)
assert.Nil(t, resp.EnvVars)
assert.Nil(t, resp.StdioConfig)
assert.Nil(t, resp.AdvancedConfig)
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))
}
func TestAttachMCPCatalogs_MarksStaleWithoutCopyingTools(t *testing.T) {
svc := &types.MCPService{ID: "svc-1", TransportType: types.MCPTransportSSE}
resp := NewMCPServiceResponses(adminContext(), []*types.MCPService{svc})
AttachMCPCatalogs(resp, []*types.MCPService{svc}, map[string]*types.MCPMetadataSummary{
"svc-1": {ServiceID: "svc-1", ToolCount: 3, ConfigFingerprint: "old"},
})
require := assert.New(t)
require.NotNil(resp[0].Catalog)
require.Equal(3, resp[0].Catalog.ToolCount)
require.True(resp[0].Catalog.Stale)
body, err := json.Marshal(resp[0])
require.NoError(err)
require.NotContains(string(body), `"tools"`)
require.Contains(string(body), `"tool_count":3`)
}
func TestMCPServiceResponse_EchoesClientIDButNotItsSecret(t *testing.T) {
svc := &types.MCPService{
ID: "svc-1",
Name: "svc",
AuthConfig: &types.MCPAuthConfig{
AuthType: types.MCPAuthOAuth,
ClientID: "pre-registered",
ClientSecret: "client-secret-do-not-leak",
},
}
body, err := json.Marshal(NewMCPServiceResponse(adminContext(), svc))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "client-secret-do-not-leak")
assert.Contains(t, s, `"client_id":"pre-registered"`)
assert.Contains(t, s, `"client_secret":{"configured":true}`)
}
+350
View File
@@ -0,0 +1,350 @@
package dto
import (
"context"
"strings"
"time"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
)
// VendorRef identifies the vendor a set of model parameters belongs to.
// BaseURL covers legacy rows saved before provider was stored; the vendor is
// then detected from the endpoint.
type VendorRef struct {
Provider string
BaseURL string
}
// vendorID resolves the ref to a comparable vendor id. An id that matches no
// registered vendor is returned as typed, so two rows pinned to the same
// hand-written provider still compare equal.
func (r VendorRef) vendorID() string {
id := strings.ToLower(strings.TrimSpace(r.Provider))
if id == "" {
id = modelruntime.DetectByURL(r.BaseURL)
}
return id
}
// names reports whether the ref identifies a vendor at all. A PUT body that
// carries neither provider nor base URL names none, and must not be read as
// "the user moved this row to another vendor".
func (r VendorRef) names() bool {
return strings.TrimSpace(r.Provider) != "" || strings.TrimSpace(r.BaseURL) != ""
}
func secretKeysOf(v *modelruntime.Provider, into map[string]bool) map[string]bool {
for _, f := range v.ExtraFields {
if !f.Secret && f.Type != "password" {
continue
}
if into == nil {
into = map[string]bool{}
}
into[f.Key] = true
}
return into
}
// SecretExtraConfigKeys returns the extra_config keys the vendor declares as
// secret (providers.ExtraField.Secret, or a password input). These are real
// credentials — LKEAP and Volcengine rerank keep an IAM/CAM secret key there
// — so they get the same treatment as api_key / app_secret: never echoed,
// only reported as present.
//
// The field's ModelTypes restriction is deliberately ignored: a key that is
// secret for any model type of the vendor is redacted for every row of that
// vendor.
func SecretExtraConfigKeys(provider, baseURL string) map[string]bool {
v, ok := modelruntime.Get(VendorRef{Provider: provider, BaseURL: baseURL}.vendorID())
if !ok {
return nil
}
return secretKeysOf(v, nil)
}
// AllSecretExtraConfigKeys returns every extra_config key any registered
// vendor declares secret.
//
// Redaction must not depend on the row's own provider being the one that
// declared the key: a row whose provider was switched, hand-edited or never
// stored would otherwise echo a credential in plaintext simply because its
// current vendor declares no secret field. Treating a name that is secret
// somewhere as secret everywhere is the safe direction — the worst case is
// withholding a value that happened to reuse the name.
func AllSecretExtraConfigKeys() map[string]bool {
var keys map[string]bool
for _, v := range modelruntime.List() {
keys = secretKeysOf(v, keys)
}
return keys
}
// redactedSecretPlaceholder reports whether an incoming extra_config value
// carries no new secret: empty, or a mask the UI shows for a value it never
// received (GET omits the key entirely, but forms happily render bullets).
func redactedSecretPlaceholder(v string) bool {
t := strings.TrimSpace(v)
return t == "" || strings.Trim(t, "*•·●") == ""
}
// PreserveStoredSecretExtras merges the stored secret extra_config values
// into an incoming map.
//
// PUT /models/{id} replaces extra_config wholesale and the frontend always
// sends the map for remote rows, but GET redacts the vendor's secret fields,
// so a plain edit-and-save round-trip carries no value for them. Without this
// merge the first save after any unrelated edit would erase the stored secret
// key and break rerank for that row. An incoming value that is absent, empty
// or a mask means "unchanged"; anything else replaces the stored secret.
//
// storedVendor identifies the vendor the stored values belong to; edited is
// the vendor the incoming values are for. They differ when the user moves the
// row to another vendor, and then the stored credential must be dropped
// rather than carried over: it belongs to the previous integration's account,
// the editor no longer renders a field for it, and the new vendor may not
// declare it secret at all — which is how it ended up echoed in plaintext.
//
// incoming is filled in place and returned.
func PreserveStoredSecretExtras(
stored, incoming map[string]string, storedVendor, edited VendorRef,
) map[string]string {
keys := SecretExtraConfigKeys(storedVendor.Provider, storedVendor.BaseURL)
// A request that names no vendor at all changed none: keep the old
// contract, which rerank rows rely on for their redacted secret.
switched := edited.names() && edited.vendorID() != storedVendor.vendorID()
if incoming == nil {
if !switched || len(keys) == 0 || len(stored) == 0 {
return stored
}
// extra_config omitted entirely still keeps the rest of the stored
// map, but not the previous vendor's credential.
out := make(map[string]string, len(stored))
for k, v := range stored {
if !keys[k] {
out[k] = v
}
}
return out
}
if len(keys) == 0 {
return incoming
}
if switched {
// Only a value the user actually typed survives a vendor switch; an
// absent or masked one would otherwise resurrect the old secret when
// the new vendor happens to reuse the key name.
for key := range keys {
if redactedSecretPlaceholder(incoming[key]) {
delete(incoming, key)
}
}
return incoming
}
for key := range keys {
storedValue := stored[key]
if storedValue == "" {
continue
}
if redactedSecretPlaceholder(incoming[key]) {
incoming[key] = storedValue
}
}
return incoming
}
// HasAllSecretExtras reports whether extra already carries a usable value for
// every secret extra field the vendor declares. Callers that would otherwise
// skip a lookup of the stored row use it to notice that the request is
// missing a redacted secret.
func HasAllSecretExtras(provider, baseURL string, extra map[string]string) bool {
for key := range SecretExtraConfigKeys(provider, baseURL) {
if redactedSecretPlaceholder(extra[key]) {
return false
}
}
return true
}
// ModelResponse mirrors types.Model for response bodies, with all secret
// fields (APIKey, AppSecret) removed by construction. Credential presence
// metadata lives behind the /credentials subresource, not inlined here.
//
// BaseURL is preserved for tenant-owned models (the frontend needs it to
// render which endpoint a custom model points at). For builtin models it is
// stripped along with every other field that could leak how a particular
// tenant configured the upstream provider.
type ModelResponse struct {
ID string `json:"id" extensions:"x-agent=model_id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name" extensions:"x-agent"`
DisplayName string `json:"display_name" extensions:"x-agent"`
Type types.ModelType `json:"type" extensions:"x-agent"`
Source types.ModelSource `json:"source" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Parameters ModelParametersDTO `json:"parameters" extensions:"x-agent"`
IsDefault bool `json:"is_default" extensions:"x-agent"`
IsBuiltin bool `json:"is_builtin" extensions:"x-agent"`
Status types.ModelStatus `json:"status" extensions:"x-agent"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Per-field "configured?" map. Omitted for builtin models unless the
// caller is a system administrator. See MCPServiceResponse.Credentials.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
// Capabilities is the catalog view of the model. Chat models get the
// protocol, thinking levels and context window; embedding and rerank
// models get input modalities, including support for image input.
Capabilities *modelruntime.Capabilities `json:"capabilities,omitempty" extensions:"x-agent,x-agent-detail"`
}
// ModelParametersDTO carries every parameter field EXCEPT the two secret
// ones (APIKey, AppSecret). AppID is non-secret and stays — it's an account
// identifier the Academy Cloud frontend renders. CustomHeaders is also kept
// (structural metadata, not a credential).
type ModelParametersDTO struct {
// BaseURL is empty for callers who may not view integration detail, and
// for builtin models; see NewModelResponse.
BaseURL string `json:"base_url" extensions:"x-agent"`
InterfaceType string `json:"interface_type"`
EmbeddingParameters types.EmbeddingParameters `json:"embedding_parameters"`
ParameterSize string `json:"parameter_size"`
Provider string `json:"provider" extensions:"x-agent"`
ExtraConfig map[string]string `json:"extra_config,omitempty" extensions:"x-agent,x-agent-detail,x-agent-keys=remote_model_name"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
SupportsVision bool `json:"supports_vision"`
ContextWindow int `json:"context_window,omitempty"`
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
MaxConcurrency int `json:"max_concurrency,omitempty"`
AppID string `json:"app_id,omitempty"`
Spec *types.ModelSpecOverride `json:"spec,omitempty"`
}
// NewModelResponse converts a stored Model into its response shape.
//
// Builtin models are shared across tenants — strip BaseURL (which can leak
// the tenant's private endpoint) and any non-shared parameters.
func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
if m == nil {
return nil
}
params := ModelParametersDTO{
BaseURL: m.Parameters.BaseURL,
InterfaceType: m.Parameters.InterfaceType,
EmbeddingParameters: m.Parameters.EmbeddingParameters,
ParameterSize: m.Parameters.ParameterSize,
Provider: m.Parameters.Provider,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
SupportsVision: m.Parameters.SupportsVision,
ContextWindow: m.Parameters.ContextWindow,
MaxOutputTokens: m.Parameters.MaxOutputTokens,
MaxConcurrency: m.Parameters.MaxConcurrency,
AppID: m.Parameters.AppID,
Spec: m.Parameters.Spec,
}
canManageBuiltin := m.IsBuiltin && types.IsSystemAdminFromContext(ctx)
if !CanViewIntegrationSecrets(ctx) && !canManageBuiltin {
params.ExtraConfig = nil
params.CustomHeaders = nil
params.BaseURL = ""
// Spec is deployment configuration of the same kind: it pins the
// protocol and carries the compat overlay, whose extra_body is
// merged verbatim into every request. It belongs with ExtraConfig,
// not with the capability fields kept below.
params.Spec = nil
}
if m.IsBuiltin && !canManageBuiltin {
// Builtin: strip everything that could reveal per-tenant config.
// EmbeddingParameters and ParameterSize / Provider / InterfaceType /
// SupportsVision / ContextWindow / MaxOutputTokens are intentionally
// preserved (they describe the capability surface, not the configured
// endpoint).
params.BaseURL = ""
params.ExtraConfig = nil
params.CustomHeaders = nil
params.AppID = ""
params.Spec = nil
}
// Vendor-declared secret extra fields are credentials that happen to be
// stored in extra_config. Drop them from the echoed map — even for
// callers allowed to see integration detail, exactly as api_key is
// withheld from an admin — and report presence instead. The stored map is
// never mutated: params.ExtraConfig still aliases it here.
//
// Redaction spans every registered vendor, not just this row's: a row
// whose provider was switched or hand-edited must not leak a leftover
// credential just because its current vendor declares no secret field.
secretKeys := SecretExtraConfigKeys(m.Parameters.Provider, m.Parameters.BaseURL)
redactKeys := AllSecretExtraConfigKeys()
if len(redactKeys) > 0 && len(params.ExtraConfig) > 0 {
sanitized := make(map[string]string, len(params.ExtraConfig))
for k, v := range params.ExtraConfig {
if !redactKeys[k] {
sanitized[k] = v
}
}
params.ExtraConfig = sanitized
}
var creds map[string]CredentialFieldMetadata
if !m.IsBuiltin || canManageBuiltin {
creds = map[string]CredentialFieldMetadata{
"api_key": {Configured: m.Parameters.APIKey != ""},
"app_secret": {Configured: m.Parameters.AppSecret != ""},
}
for key := range secretKeys {
creds[key] = CredentialFieldMetadata{
Configured: strings.TrimSpace(m.Parameters.ExtraConfig[key]) != "",
}
}
// A key this row's vendor does not declare was still withheld above,
// so say it is there — otherwise the value silently vanishes from the
// editor with nothing to explain why.
for key := range redactKeys {
if _, reported := creds[key]; reported {
continue
}
if strings.TrimSpace(m.Parameters.ExtraConfig[key]) != "" {
creds[key] = CredentialFieldMetadata{Configured: true}
}
}
}
var caps *modelruntime.Capabilities
switch m.Type {
case types.ModelTypeKnowledgeQA, types.ModelTypeVLLM, types.ModelTypeEmbedding, types.ModelTypeRerank:
if resolved, err := modelruntime.Resolve(modelruntime.Ref{
Provider: m.Parameters.Provider, Model: m.Name, BaseURL: m.Parameters.BaseURL,
ModelType: m.Type, Extra: m.Parameters.ExtraConfig, Override: m.Parameters.Spec,
}); err == nil && m.Source == types.ModelSourceRemote {
c := resolved.Capabilities()
caps = &c
}
}
return &ModelResponse{
ID: m.ID,
TenantID: m.TenantID,
Name: m.Name,
DisplayName: m.DisplayName,
Type: m.Type,
Source: m.Source,
Description: m.Description,
Parameters: params,
IsDefault: m.IsDefault,
IsBuiltin: m.IsBuiltin,
Status: m.Status,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
Credentials: creds,
Capabilities: caps,
}
}
// NewModelResponses is the slice convenience wrapper.
func NewModelResponses(ctx context.Context, models []*types.Model) []*ModelResponse {
out := make([]*ModelResponse, 0, len(models))
for _, m := range models {
out = append(out, NewModelResponse(ctx, m))
}
return out
}
+377
View File
@@ -0,0 +1,377 @@
package dto
import (
"context"
"encoding/json"
"slices"
"strings"
"testing"
"academy/internal/models/providers"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestModelResponse_OmitsSecrets(t *testing.T) {
m := &types.Model{
ID: "m-1",
Name: "gpt-x",
DisplayName: "Support QA",
Parameters: types.ModelParameters{
APIKey: "sk-real-api-key-do-not-leak",
AppSecret: "app-real-secret-do-not-leak",
AppID: "appid-public-ok-to-show",
BaseURL: "https://api.example.com",
Provider: "openai",
},
}
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")
assert.NotContains(t, s, "app-real-secret-do-not-leak")
// Parameters sub-object must contain no secret keys.
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
params := string(raw["parameters"])
assert.NotContains(t, params, `"api_key"`)
assert.NotContains(t, params, `"app_secret"`)
// Credential metadata map exposes booleans only.
assert.Contains(t, s, `"credentials"`)
assert.Contains(t, s, `"api_key":{"configured":true}`)
assert.Contains(t, s, `"app_secret":{"configured":true}`)
// Non-secret fields pass through.
assert.Contains(t, s, "appid-public-ok-to-show")
assert.Contains(t, s, "api.example.com")
assert.Contains(t, s, `"display_name":"Support QA"`)
}
func TestModelResponse_BuiltinStripsTenantConfig(t *testing.T) {
m := &types.Model{
ID: "builtin-1",
IsBuiltin: true,
Parameters: types.ModelParameters{
BaseURL: "https://tenant-private.example.com",
APIKey: "should-not-leak",
AppID: "tenant-app-id",
SupportsVision: true,
ExtraConfig: map[string]string{"region": "cn-hangzhou"},
},
}
resp := NewModelResponse(adminContext(), m)
assert.Empty(t, resp.Parameters.BaseURL,
"builtin must not leak per-tenant base URL")
assert.Empty(t, resp.Parameters.AppID,
"builtin must not leak per-tenant app_id")
assert.Nil(t, resp.Parameters.ExtraConfig,
"builtin must not leak per-tenant extra_config")
assert.True(t, resp.Parameters.SupportsVision,
"capability metadata must survive (not per-tenant)")
body, _ := json.Marshal(resp)
assert.False(t, strings.Contains(string(body), "should-not-leak"))
assert.False(t, strings.Contains(string(body), "tenant-private.example.com"))
}
func TestModelResponse_SystemAdminCanManageBuiltinConfig(t *testing.T) {
ctx := context.WithValue(viewerContext(), types.SystemAdminContextKey, true)
m := &types.Model{
ID: "builtin-1",
IsBuiltin: true,
Parameters: types.ModelParameters{
BaseURL: "https://global-provider.example.com",
APIKey: "should-never-be-returned",
AppSecret: "also-never-returned",
AppID: "global-app-id",
ExtraConfig: map[string]string{"region": "ap-guangzhou"},
CustomHeaders: map[string]string{"X-Route": "global"},
},
}
resp := NewModelResponse(ctx, m)
assert.Equal(t, "https://global-provider.example.com", resp.Parameters.BaseURL)
assert.Equal(t, "global-app-id", resp.Parameters.AppID)
assert.Equal(t, map[string]string{"region": "ap-guangzhou"}, resp.Parameters.ExtraConfig)
assert.Equal(t, map[string]string{"X-Route": "global"}, resp.Parameters.CustomHeaders)
assert.True(t, resp.Credentials["api_key"].Configured)
assert.True(t, resp.Credentials["app_secret"].Configured)
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "should-never-be-returned")
assert.NotContains(t, string(body), "also-never-returned")
}
func TestModelResponse_ViewerStripsIntegrationDetail(t *testing.T) {
m := &types.Model{
ID: "m-2",
Parameters: types.ModelParameters{
BaseURL: "https://tenant-private.example.com",
CustomHeaders: map[string]string{"Authorization": "Bearer secret"},
ExtraConfig: map[string]string{"region": "cn-hangzhou"},
},
}
resp := NewModelResponse(viewerContext(), m)
assert.Empty(t, resp.Parameters.BaseURL)
assert.Nil(t, resp.Parameters.CustomHeaders)
assert.Nil(t, resp.Parameters.ExtraConfig)
}
// registerSecretExtraVendor adds a vendor whose extra_config carries a real
// credential, the way LKEAP / Volcengine rerank declare secret_key.
func registerSecretExtraVendor(t *testing.T) string {
t.Helper()
id := "dto-secret-extra-vendor"
modelruntime.Register(&providers.Definition{
ID: id,
Name: "Secret Extra Vendor",
ModelTypes: []types.ModelType{types.ModelTypeRerank},
URLPatterns: []string{"secret-extra-vendor.example.com"},
ExtraFields: []providers.ExtraField{
{Key: "secret_key", Label: "Secret Key", Type: "password", Secret: true},
{Key: "region", Label: "Region", Type: "string"},
},
})
return id
}
// A vendor-declared secret extra field is a credential that happens to live
// in extra_config: GET must report its presence, never its value — even to a
// caller allowed to see integration detail, exactly like api_key.
func TestModelResponse_RedactsVendorSecretExtraConfig(t *testing.T) {
provider := registerSecretExtraVendor(t)
m := &types.Model{
ID: "m-rerank",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{
Provider: provider,
BaseURL: "https://secret-extra-vendor.example.com",
APIKey: "AKID-public-id",
ExtraConfig: map[string]string{
"secret_key": "cam-secret-do-not-leak",
"region": "ap-guangzhou",
},
},
}
resp := NewModelResponse(adminContext(), m)
assert.NotContains(t, resp.Parameters.ExtraConfig, "secret_key")
assert.Equal(t, "ap-guangzhou", resp.Parameters.ExtraConfig["region"],
"non-secret extra fields still round-trip")
assert.True(t, resp.Credentials["secret_key"].Configured,
"presence is reported in the same shape as api_key")
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "cam-secret-do-not-leak")
assert.Equal(t, "cam-secret-do-not-leak", m.Parameters.ExtraConfig["secret_key"],
"the stored model must not be mutated by rendering a response")
}
func TestModelResponse_SecretExtraConfigReportsAbsence(t *testing.T) {
provider := registerSecretExtraVendor(t)
m := &types.Model{
ID: "m-rerank",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{Provider: provider, ExtraConfig: map[string]string{"region": "ap-beijing"}},
}
resp := NewModelResponse(adminContext(), m)
assert.False(t, resp.Credentials["secret_key"].Configured)
assert.Equal(t, "ap-beijing", resp.Parameters.ExtraConfig["region"])
}
// Legacy rows saved before provider was stored are matched by endpoint.
func TestModelResponse_RedactsSecretExtraConfigForLegacyRowWithoutProvider(t *testing.T) {
registerSecretExtraVendor(t)
m := &types.Model{
ID: "m-legacy",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{
BaseURL: "https://secret-extra-vendor.example.com/v1",
ExtraConfig: map[string]string{"secret_key": "cam-secret-do-not-leak"},
},
}
resp := NewModelResponse(adminContext(), m)
assert.NotContains(t, resp.Parameters.ExtraConfig, "secret_key")
assert.True(t, resp.Credentials["secret_key"].Configured)
}
// PUT replaces extra_config wholesale and GET redacts the secret, so the
// save that follows an unrelated edit must not erase the stored key.
func TestPreserveStoredSecretExtras(t *testing.T) {
provider := registerSecretExtraVendor(t)
stored := map[string]string{"secret_key": "cam-secret-stored", "region": "ap-guangzhou"}
sameVendor := VendorRef{Provider: provider}
t.Run("incoming omits the key", func(t *testing.T) {
got := PreserveStoredSecretExtras(
stored, map[string]string{"region": "ap-beijing"}, sameVendor, sameVendor)
assert.Equal(t, "cam-secret-stored", got["secret_key"])
assert.Equal(t, "ap-beijing", got["region"], "non-secret edits still apply")
})
t.Run("incoming carries an empty or masked value", func(t *testing.T) {
for _, masked := range []string{"", " ", "******", "••••"} {
got := PreserveStoredSecretExtras(
stored, map[string]string{"secret_key": masked}, sameVendor, sameVendor)
assert.Equal(t, "cam-secret-stored", got["secret_key"], "masked value %q means unchanged", masked)
}
})
t.Run("incoming carries a new value", func(t *testing.T) {
got := PreserveStoredSecretExtras(
stored, map[string]string{"secret_key": "cam-secret-rotated"}, sameVendor, sameVendor)
assert.Equal(t, "cam-secret-rotated", got["secret_key"])
})
t.Run("nil incoming keeps the whole stored map", func(t *testing.T) {
assert.Equal(t, stored, PreserveStoredSecretExtras(stored, nil, sameVendor, sameVendor))
})
t.Run("unknown stored provider passes the map through", func(t *testing.T) {
in := map[string]string{"secret_key": ""}
assert.Equal(t, in,
PreserveStoredSecretExtras(stored, in, VendorRef{Provider: "no-such-vendor"}, sameVendor))
})
t.Run("a request naming no vendor is not a vendor change", func(t *testing.T) {
got := PreserveStoredSecretExtras(stored, map[string]string{}, sameVendor, VendorRef{})
assert.Equal(t, "cam-secret-stored", got["secret_key"])
})
// Switching the row to another vendor leaves the credential behind: it
// authenticates the account of the integration being replaced.
t.Run("vendor change drops the stored secret", func(t *testing.T) {
other := VendorRef{Provider: "openai"}
got := PreserveStoredSecretExtras(stored, map[string]string{"api": "openai_completions"}, sameVendor, other)
assert.NotContains(t, got, "secret_key")
assert.Equal(t, "openai_completions", got["api"])
})
t.Run("vendor change drops a masked secret instead of refilling it", func(t *testing.T) {
other := VendorRef{Provider: "openai"}
got := PreserveStoredSecretExtras(stored, map[string]string{"secret_key": "****"}, sameVendor, other)
assert.NotContains(t, got, "secret_key")
})
t.Run("vendor change keeps a value the user typed", func(t *testing.T) {
other := VendorRef{Provider: "openai"}
got := PreserveStoredSecretExtras(stored, map[string]string{"secret_key": "typed-now"}, sameVendor, other)
assert.Equal(t, "typed-now", got["secret_key"])
})
t.Run("vendor change with no extra_config at all", func(t *testing.T) {
got := PreserveStoredSecretExtras(stored, nil, sameVendor, VendorRef{Provider: "openai"})
assert.NotContains(t, got, "secret_key")
assert.Equal(t, "ap-guangzhou", got["region"], "non-secret settings are not credentials")
assert.Equal(t, "cam-secret-stored", stored["secret_key"], "the stored map is not mutated")
})
t.Run("a legacy row is matched by endpoint, not treated as a switch", func(t *testing.T) {
legacy := VendorRef{BaseURL: "https://secret-extra-vendor.example.com/v1"}
got := PreserveStoredSecretExtras(stored, map[string]string{}, legacy, legacy)
assert.Equal(t, "cam-secret-stored", got["secret_key"])
})
}
// Redaction may not depend on the row's provider being the one that declared
// the key: a hand-edited or emptied provider would otherwise echo a stored
// credential in plaintext.
func TestModelResponse_RedactsSecretExtraDeclaredByAnotherVendor(t *testing.T) {
registerSecretExtraVendor(t)
for _, provider := range []string{"openai", ""} {
m := &types.Model{
ID: "m-switched",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{
Provider: provider,
ExtraConfig: map[string]string{"secret_key": "cam-secret-do-not-leak", "region": "ap-beijing"},
},
}
resp := NewModelResponse(adminContext(), m)
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "cam-secret-do-not-leak", "provider %q", provider)
assert.Equal(t, "ap-beijing", resp.Parameters.ExtraConfig["region"])
assert.True(t, resp.Credentials["secret_key"].Configured,
"a withheld value is still reported as present")
}
}
func TestHasAllSecretExtras(t *testing.T) {
provider := registerSecretExtraVendor(t)
assert.True(t, HasAllSecretExtras(provider, "", map[string]string{"secret_key": "cam-secret"}))
assert.False(t, HasAllSecretExtras(provider, "", map[string]string{"region": "ap-guangzhou"}))
assert.False(t, HasAllSecretExtras(provider, "", map[string]string{"secret_key": "****"}))
assert.True(t, HasAllSecretExtras("no-such-vendor", "", nil), "a vendor with no secret extras is complete")
}
func TestModelResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewModelResponse(adminContext(), nil))
assert.Equal(t, []*ModelResponse{}, NewModelResponses(adminContext(), nil))
}
func TestNewModelResponseStripsSpecFromNonAdmins(t *testing.T) {
// Spec pins the protocol and carries the compat overlay, whose
// extra_body is merged verbatim into every request. It is deployment
// configuration, like base_url and extra_config beside it, not part of
// the capability surface a viewer is shown.
spec := &types.ModelSpecOverride{
API: "anthropic-messages",
Compat: map[string]any{"extra_body": map[string]any{"internal_route": "eu-gateway"}},
}
model := &types.Model{
ID: "m1", Name: "claude-sonnet-4-5", Type: types.ModelTypeKnowledgeQA,
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
Provider: "anthropic", BaseURL: "https://gateway.internal/v1", Spec: spec,
},
}
admin := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
if got := NewModelResponse(admin, model).Parameters.Spec; got == nil {
t.Fatalf("an admin configures this; it must still be returned")
}
viewer := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
params := NewModelResponse(viewer, model).Parameters
if params.Spec != nil {
t.Errorf("viewer should not see the protocol override, got %+v", params.Spec)
}
if params.BaseURL != "" || params.ExtraConfig != nil {
t.Errorf("the neighbouring fields should still be stripped")
}
// The stored model is shared; stripping must not mutate it.
if model.Parameters.Spec == nil {
t.Errorf("NewModelResponse must not clear the stored spec")
}
}
func TestNewModelResponseReportsEmbeddingInputModalities(t *testing.T) {
// Whether an embedding model maps images into the same space as text is
// what decides if a knowledge base can store image vectors. The catalog
// knows it for listed models; a row can declare it through spec.input.
declare := func(input ...string) *types.ModelSpecOverride { return &types.ModelSpecOverride{Input: input} }
embedding := func(provider, name string, spec *types.ModelSpecOverride) *types.Model {
return &types.Model{
ID: "e1", Name: name, Type: types.ModelTypeEmbedding, Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{Provider: provider, Spec: spec},
}
}
viewer := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
cases := []struct {
name string
model *types.Model
image bool
}{
{"catalog multimodal", embedding("volcengine", "doubao-embedding-vision-251215", nil), true},
{"catalog pattern", embedding("aliyun", "qwen3-vl-embedding", nil), true},
{"catalog text only", embedding("openai", "text-embedding-3-small", nil), false},
{"row declares image", embedding("openai", "my-clip", declare("text", "image")), true},
{"row narrows catalog", embedding("jina", "jina-embeddings-v4", declare("text")), false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// A viewer never sees spec, but the capability it implies is
// not configuration and stays visible.
caps := NewModelResponse(viewer, tc.model).Capabilities
require.NotNil(t, caps)
assert.Equal(t, tc.image, slices.Contains(caps.Input, "image"), "input=%v", caps.Input)
assert.Empty(t, caps.ThinkingLevels, "an embedding model does not think")
})
}
}
+42
View File
@@ -0,0 +1,42 @@
package dto
import (
"context"
"academy/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+ tenant members and for API keys
// with full tenant access or the manage_tenant_settings capability.
func CanViewIntegrationSecrets(ctx context.Context) bool {
if RoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
return true
}
return apiKeyCanManageIntegrationSecrets(ctx)
}
func apiKeyCanManageIntegrationSecrets(ctx context.Context) bool {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok {
return false
}
if scope.FullAccess {
return true
}
return scope.HasCapability(types.APIKeyCapabilityManageTenantSettings)
}
// RoleCanViewTenantAPIKey is true for Owner+ only.
func RoleCanViewTenantAPIKey(role types.TenantRole) bool {
return role.HasPermission(types.TenantRoleOwner)
}
// CanViewTenantAPIKey is true for Owner+ only.
func CanViewTenantAPIKey(ctx context.Context) bool {
return RoleCanViewTenantAPIKey(RoleFromContext(ctx))
}
+42
View File
@@ -0,0 +1,42 @@
package dto
import (
"context"
"testing"
"academy/internal/types"
)
func TestCanViewIntegrationSecretsAdminRole(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
if !CanViewIntegrationSecrets(ctx) {
t.Fatal("admin should view integration secrets")
}
}
func TestCanViewIntegrationSecretsViewerDenied(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
if CanViewIntegrationSecrets(ctx) {
t.Fatal("viewer should not view integration secrets")
}
}
func TestCanViewIntegrationSecretsScopedAPIKeyWithManageTenantSettings(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Capabilities: types.StringArray{string(types.APIKeyCapabilityManageTenantSettings)},
})
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
if !CanViewIntegrationSecrets(ctx) {
t.Fatal("manage_tenant_settings API key should view integration secrets")
}
}
func TestCanViewIntegrationSecretsScopedAPIKeyWithoutCapabilityDenied(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Capabilities: types.StringArray{string(types.APIKeyCapabilityChat)},
})
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
if CanViewIntegrationSecrets(ctx) {
t.Fatal("chat-only API key should not view integration secrets")
}
}
+93
View File
@@ -0,0 +1,93 @@
package dto
import (
"context"
"time"
"academy/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+.
type TenantResponse struct {
ID uint64 `json:"id" extensions:"x-agent=workspace_id"`
Name string `json:"name" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Status string `json:"status" extensions:"x-agent"`
RetrieverEngines types.RetrieverEngines `json:"retriever_engines"`
Business string `json:"business"`
StorageQuota int64 `json:"storage_quota" extensions:"x-agent"`
StorageUsed int64 `json:"storage_used" extensions:"x-agent"`
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"`
MemoryConfig *types.MemoryConfig `json:"memory_config,omitempty"`
AssistantConfig *types.AssistantConfig `json:"assistant_config,omitempty"`
CreatedAt time.Time `json:"created_at" extensions:"x-agent"`
UpdatedAt time.Time `json:"updated_at" extensions:"x-agent"`
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 {
return NewTenantResponseWithRole(tenant, RoleFromContext(ctx))
}
// NewTenantResponseWithRole converts a stored tenant using an explicit role
// (for auth flows where tenant role is not yet in request context).
func NewTenantResponseWithRole(tenant *types.Tenant, role types.TenantRole) *TenantResponse {
if tenant == nil {
return nil
}
includeSecrets := role.HasPermission(types.TenantRoleAdmin)
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,
MemoryConfig: tenant.MemoryConfig,
AssistantConfig: tenant.AssistantConfig,
CreatedAt: tenant.CreatedAt,
UpdatedAt: tenant.UpdatedAt,
DeletedAt: tenant.DeletedAt,
}
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
}
// NewTenantResponsesCrossTenant redacts every tenant as Viewer regardless of
// the caller's active-tenant role. Used by cross-tenant list/search endpoints
// where the caller's home-tenant role must not unlock other tenants' secrets.
func NewTenantResponsesCrossTenant(tenants []*types.Tenant) []*TenantResponse {
out := make([]*TenantResponse, 0, len(tenants))
for _, t := range tenants {
out = append(out, NewTenantResponseWithRole(t, types.TenantRoleViewer))
}
return out
}
+86
View File
@@ -0,0 +1,86 @@
package dto
import (
"encoding/json"
"testing"
"academy/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_OwnerOmitsLegacyTenantAPIKey(t *testing.T) {
tenant := sampleSecretTenant()
body, err := json.Marshal(NewTenantResponse(ownerContext(), tenant))
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, `"api_key"`)
assert.NotContains(t, s, "legacy-search-secret-999")
assert.NotContains(t, s, "parser-secret-123")
assert.Contains(t, s, "web_search_config")
}
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 TestTenantResponsesCrossTenant_RedactsEvenForOwnerContext(t *testing.T) {
tenant := sampleSecretTenant()
body, err := json.Marshal(NewTenantResponsesCrossTenant([]*types.Tenant{tenant}))
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "tenant-api-key-123")
assert.NotContains(t, s, "parser-secret-123")
}
func sampleSecretTenant() *types.Tenant {
return &types.Tenant{
ID: 42,
Name: "tenant",
WebSearchConfig: &types.WebSearchConfig{
APIKey: "legacy-search-secret-999",
ProxyURL: "http://proxy.internal:8080",
},
Credentials: &types.CredentialsConfig{
AcademyCloud: &types.AcademyCloudCredentials{
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"
"academy/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)
}
@@ -0,0 +1,74 @@
package dto
import (
"context"
"time"
"academy/internal/types"
)
// WebSearchProviderResponse mirrors types.WebSearchProviderEntity for
// response bodies, with the APIKey field removed by construction. Credential
// presence is exposed via the /credentials subresource.
type WebSearchProviderResponse struct {
ID string `json:"id" extensions:"x-agent=web_search_provider_id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name" extensions:"x-agent"`
Provider types.WebSearchProviderType `json:"provider" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Parameters WebSearchProviderParametersDTO `json:"parameters"`
IsDefault bool `json:"is_default" extensions:"x-agent"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Per-field "configured?" map. See MCPServiceResponse.Credentials.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
}
// WebSearchProviderParametersDTO holds every parameter field except APIKey.
// EngineID, BaseURL, ProxyURL and ExtraConfig are not secrets (they describe
// where to send the request, not how to authenticate) and remain visible.
type WebSearchProviderParametersDTO struct {
EngineID string `json:"engine_id,omitempty"`
BaseURL string `json:"base_url,omitempty"`
ProxyURL string `json:"proxy_url,omitempty"`
ExtraConfig map[string]string `json:"extra_config,omitempty"`
}
// NewWebSearchProviderResponse converts a stored entity into its response shape.
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: params,
IsDefault: e.IsDefault,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
Credentials: map[string]CredentialFieldMetadata{
"api_key": {Configured: e.Parameters.APIKey != ""},
},
}
}
func NewWebSearchProviderResponses(ctx context.Context, es []*types.WebSearchProviderEntity) []*WebSearchProviderResponse {
out := make([]*WebSearchProviderResponse, 0, len(es))
for _, e := range es {
out = append(out, NewWebSearchProviderResponse(ctx, e))
}
return out
}
@@ -0,0 +1,54 @@
package dto
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
)
func TestWebSearchProviderResponse_OmitsSecrets(t *testing.T) {
e := &types.WebSearchProviderEntity{
ID: "wsp-1",
Name: "bing prod",
Provider: types.WebSearchProviderTypeBing,
Parameters: types.WebSearchProviderParameters{
APIKey: "bing-secret-do-not-leak",
EngineID: "engine-public-id",
BaseURL: "https://example.com",
},
}
body, err := json.Marshal(NewWebSearchProviderResponse(adminContext(), e))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "bing-secret-do-not-leak")
// Parameters sub-object must contain no secret keys.
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
assert.NotContains(t, string(raw["parameters"]), `"api_key"`)
// Credential metadata map exposes booleans only.
assert.Contains(t, s, `"credentials"`)
assert.Contains(t, s, `"api_key":{"configured":true}`)
// Non-secret fields pass through.
assert.Contains(t, s, "engine-public-id")
assert.Contains(t, s, "example.com")
}
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))
}