-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathserve_test.go
More file actions
347 lines (305 loc) · 10.2 KB
/
serve_test.go
File metadata and controls
347 lines (305 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0
package cli
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"gopkg.in/yaml.v3"
authserverconfig "github.com/stacklok/toolhive/pkg/authserver"
"github.com/stacklok/toolhive/pkg/groups"
"github.com/stacklok/toolhive/pkg/vmcp"
"github.com/stacklok/toolhive/pkg/vmcp/aggregator"
aggregatormocks "github.com/stacklok/toolhive/pkg/vmcp/aggregator/mocks"
clientmocks "github.com/stacklok/toolhive/pkg/vmcp/client/mocks"
"github.com/stacklok/toolhive/pkg/vmcp/config"
vmcpmocks "github.com/stacklok/toolhive/pkg/vmcp/mocks"
)
// TestLoadAndValidateConfig covers all config-loading paths.
func TestLoadAndValidateConfig(t *testing.T) {
t.Parallel()
tests := []struct {
name string
content string
wantErr bool
errContains string
}{
{
name: "valid config",
content: validConfigYAML,
wantErr: false,
},
{
name: "non-existent file",
content: "", // file will not be created
wantErr: true,
errContains: "configuration loading failed",
},
{
name: "malformed YAML",
content: ":::invalid yaml:::",
wantErr: true,
errContains: "configuration loading failed",
},
{
name: "fails semantic validation — missing groupRef",
content: `
name: test-vmcp
incomingAuth:
type: anonymous
outgoingAuth:
source: inline
aggregation:
conflictResolution: prefix
conflictResolutionConfig:
prefixFormat: "{workload}_"
`,
wantErr: true,
errContains: "group reference is required",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "vmcp.yaml")
if tc.content != "" {
require.NoError(t, os.WriteFile(path, []byte(tc.content), 0o600))
}
cfg, err := loadAndValidateConfig(path)
if tc.wantErr {
require.Error(t, err)
require.ErrorContains(t, err, tc.errContains)
require.Nil(t, cfg)
} else {
require.NoError(t, err)
require.NotNil(t, cfg)
assert.Equal(t, "test-group", cfg.Group)
}
})
}
}
// TestLoadAuthServerConfig covers all auth-server-config side-loading paths.
// (Additional cases live in auth_server_config_test.go, moved from cmd/vmcp/app.)
func TestLoadAuthServerConfig_NestedDir(t *testing.T) {
t.Parallel()
// Config lives in a subdirectory; sibling authserver-config.yaml must be found correctly.
dir := t.TempDir()
subdir := filepath.Join(dir, "sub", "dir")
require.NoError(t, os.MkdirAll(subdir, 0o750))
configPath := filepath.Join(subdir, "vmcp-config.yaml")
want := &authserverconfig.RunConfig{
Issuer: "https://nested.example.com",
SchemaVersion: "1",
}
data, err := yaml.Marshal(want)
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(subdir, "authserver-config.yaml"), data, 0o600))
rc, err := loadAuthServerConfig(configPath)
require.NoError(t, err)
require.NotNil(t, rc)
assert.Equal(t, "https://nested.example.com", rc.Issuer)
}
// TestDiscoverBackends_StaticMode exercises the static-backend path without
// needing a live Kubernetes API.
func TestDiscoverBackends_StaticMode(t *testing.T) {
t.Parallel()
// Build a minimal config with one static backend.
dir := t.TempDir()
path := filepath.Join(dir, "vmcp.yaml")
require.NoError(t, os.WriteFile(path, []byte(`
name: test-vmcp
groupRef: test-group
incomingAuth:
type: anonymous
outgoingAuth:
source: inline
default:
type: unauthenticated
aggregation:
conflictResolution: prefix
conflictResolutionConfig:
prefixFormat: "{workload}_"
backends:
- name: backend-one
url: http://127.0.0.1:9001/sse
transport: sse
`), 0o600))
cfg, err := loadAndValidateConfig(path)
require.NoError(t, err)
require.Len(t, cfg.Backends, 1)
backends, client, registry, err := discoverBackends(t.Context(), cfg)
require.NoError(t, err)
assert.NotNil(t, client)
assert.NotNil(t, registry)
// Static mode: one backend discovered.
assert.Len(t, backends, 1)
}
func newSessionFactoryMocks(t *testing.T) (*clientmocks.MockOutgoingAuthRegistry, *aggregatormocks.MockAggregator) {
t.Helper()
ctrl := gomock.NewController(t)
return clientmocks.NewMockOutgoingAuthRegistry(ctrl), aggregatormocks.NewMockAggregator(ctrl)
}
func TestCreateSessionFactory(t *testing.T) {
t.Parallel()
tests := []struct {
name string
useAgg bool
}{
{name: "with aggregator", useAgg: true},
{name: "without aggregator", useAgg: false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
registry, agg := newSessionFactoryMocks(t)
var aggArg aggregator.Aggregator
if tc.useAgg {
aggArg = agg
}
factory := createSessionFactory(registry, aggArg)
require.NotNil(t, factory)
})
}
}
// TestRunDiscovery_KubernetesGroupNotFound exercises the Kubernetes-specific branch
// in runDiscovery where ErrGroupNotFound is treated as a non-fatal condition.
// vMCP should start with zero backends and return nil error so it can begin
// serving before the MCPGroup CRD is created by the operator.
func TestRunDiscovery_KubernetesGroupNotFound(t *testing.T) {
// Cannot run in parallel: t.Setenv modifies the process environment.
t.Setenv("TOOLHIVE_RUNTIME", "kubernetes")
ctrl := gomock.NewController(t)
discoverer := aggregatormocks.NewMockBackendDiscoverer(ctrl)
backendClient := vmcpmocks.NewMockBackendClient(ctrl)
registry := clientmocks.NewMockOutgoingAuthRegistry(ctrl)
const groupRef = "test-group"
discoverer.EXPECT().
Discover(gomock.Any(), groupRef).
Return(nil, fmt.Errorf("wrapped: %w", groups.ErrGroupNotFound))
backends, gotClient, gotRegistry, err := runDiscovery(t.Context(), groupRef, discoverer, backendClient, registry)
require.NoError(t, err)
assert.NotNil(t, backends)
assert.Empty(t, backends)
assert.Same(t, backendClient, gotClient)
assert.Same(t, registry, gotRegistry)
}
// TestGenerateQuickModeConfig covers the generateQuickModeConfig helper.
func TestGenerateQuickModeConfig(t *testing.T) {
t.Parallel()
tests := []struct {
name string
groupRef string
wantErr bool
errContains string
}{
{
name: "valid group sets groupRef and inline source",
groupRef: "default",
},
{
name: "group name with hyphens",
groupRef: "my-group",
},
{
name: "empty groupRef returns error",
groupRef: "",
wantErr: true,
errContains: "--group must not be empty",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
cfg, err := generateQuickModeConfig(tc.groupRef)
if tc.wantErr {
require.Error(t, err)
require.ErrorContains(t, err, tc.errContains)
require.Nil(t, cfg)
return
}
require.NoError(t, err)
require.NotNil(t, cfg)
require.Equal(t, tc.groupRef, cfg.Group)
require.NotNil(t, cfg.OutgoingAuth)
require.Equal(t, "inline", cfg.OutgoingAuth.Source)
require.NotNil(t, cfg.IncomingAuth)
require.Equal(t, "anonymous", cfg.IncomingAuth.Type)
// Verify the generated config passes the real validator.
require.NoError(t, config.NewValidator().Validate(cfg))
})
}
}
// TestServe_NeitherConfigNorGroup verifies that Serve returns an error when
// both --config and --group are absent.
func TestServe_NeitherConfigNorGroup(t *testing.T) {
t.Parallel()
err := Serve(t.Context(), ServeConfig{})
require.Error(t, err)
require.ErrorContains(t, err, "--config or --group")
}
// TestValidateQuickModeHost exercises ServeConfig.validateQuickModeHost directly
// so the test never starts the HTTP server and cannot hang.
func TestValidateQuickModeHost(t *testing.T) {
t.Parallel()
tests := []struct {
name string
configPath string
groupRef string
host string
wantErr bool
errContains string
}{
// Quick mode (no --config): loopback-only
{name: "quick mode: loopback IPv4 allowed", groupRef: "my-group", host: "127.0.0.1"},
{name: "quick mode: loopback IPv6 allowed", groupRef: "my-group", host: "::1"},
{name: "quick mode: localhost allowed", groupRef: "my-group", host: "localhost"},
{name: "quick mode: empty host treated as loopback", groupRef: "my-group", host: ""},
{name: "quick mode: all-interfaces rejected", groupRef: "my-group", host: "0.0.0.0", wantErr: true, errContains: "quick mode"},
{name: "quick mode: LAN IP rejected", groupRef: "my-group", host: "192.168.1.10", wantErr: true, errContains: "quick mode"},
{name: "quick mode: non-IP hostname rejected", groupRef: "my-group", host: "not-an-ip", wantErr: true, errContains: "quick mode"},
// Config-file mode: host check does not apply
{name: "config mode: non-loopback allowed", configPath: "/some/config.yaml", host: "0.0.0.0"},
// Both flags set: ConfigPath takes precedence, host check skipped
{name: "both flags: non-loopback allowed", configPath: "/some/config.yaml", groupRef: "my-group", host: "0.0.0.0"},
// Neither flag: check is a no-op
{name: "neither flag: no-op", host: "0.0.0.0"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
err := ServeConfig{ConfigPath: tc.configPath, GroupRef: tc.groupRef, Host: tc.host}.validateQuickModeHost()
if tc.wantErr {
require.Error(t, err)
require.ErrorContains(t, err, tc.errContains)
} else {
require.NoError(t, err)
}
})
}
}
// TestRunDiscovery_ZeroBackends exercises the branch in runDiscovery where the
// discoverer succeeds but returns no backends. The function must return a
// non-error, an empty (non-nil) backend slice, and pass through the client and
// registry it received.
func TestRunDiscovery_ZeroBackends(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
discoverer := aggregatormocks.NewMockBackendDiscoverer(ctrl)
backendClient := vmcpmocks.NewMockBackendClient(ctrl)
registry := clientmocks.NewMockOutgoingAuthRegistry(ctrl)
const groupRef = "test-group"
discoverer.EXPECT().
Discover(gomock.Any(), groupRef).
Return([]vmcp.Backend{}, nil)
backends, gotClient, gotRegistry, err := runDiscovery(t.Context(), groupRef, discoverer, backendClient, registry)
require.NoError(t, err)
assert.NotNil(t, backends)
assert.Empty(t, backends)
assert.Same(t, backendClient, gotClient)
assert.Same(t, registry, gotRegistry)
}