forked from operator-framework/operator-lifecycle-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_test.go
More file actions
564 lines (474 loc) · 16.6 KB
/
server_test.go
File metadata and controls
564 lines (474 loc) · 16.6 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
package server
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/client-go/rest"
)
// TestGetListenAndServeFunc_WithAuthenticatedMetrics tests that the server
// correctly creates an HTTP client with TLS configuration when kubeConfig is provided
func TestGetListenAndServeFunc_WithAuthenticatedMetrics(t *testing.T) {
// Generate test certificates dynamically
caCert, caKey, err := generateCA()
require.NoError(t, err)
serverCert, serverKey, err := generateServerCert(caCert, caKey, "localhost")
require.NoError(t, err)
// Create temporary directory for test certificates
tmpDir, err := os.MkdirTemp("", "server-test-*")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
// Write dynamically generated certificates to files
tlsCertPath := filepath.Join(tmpDir, "tls.crt")
tlsKeyPath := filepath.Join(tmpDir, "tls.key")
clientCAPath := filepath.Join(tmpDir, "ca.crt")
err = os.WriteFile(tlsCertPath, serverCert, 0644)
require.NoError(t, err)
err = os.WriteFile(tlsKeyPath, serverKey, 0600) // Private key should have restricted permissions
require.NoError(t, err)
err = os.WriteFile(clientCAPath, caCert, 0644)
require.NoError(t, err)
// Create a test kubeConfig with CA data
kubeConfig := &rest.Config{
Host: "https://test-api-server:6443",
TLSClientConfig: rest.TLSClientConfig{
CAData: caCert,
},
}
logger := logrus.New()
logger.SetOutput(io.Discard) // Suppress logs during test
// Test with authenticated metrics (kubeConfig + TLS enabled)
_, err = GetListenAndServeFunc(
WithLogger(logger),
WithTLS(&tlsCertPath, &tlsKeyPath, &clientCAPath),
WithKubeConfig(kubeConfig),
WithDebug(false),
)
// The function should succeed - if httpClient is properly configured,
// it won't fail during filter creation
assert.NoError(t, err, "GetListenAndServeFunc should succeed with proper TLS configuration")
}
// TestGetListenAndServeFunc_WithoutKubeConfig tests that metrics endpoint
// falls back to unprotected mode when kubeConfig is not provided
func TestGetListenAndServeFunc_WithoutKubeConfig(t *testing.T) {
// Generate test certificates dynamically
caCert, caKey, err := generateCA()
require.NoError(t, err)
serverCert, serverKey, err := generateServerCert(caCert, caKey, "localhost")
require.NoError(t, err)
tmpDir, err := os.MkdirTemp("", "server-test-*")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
tlsCertPath := filepath.Join(tmpDir, "tls.crt")
tlsKeyPath := filepath.Join(tmpDir, "tls.key")
clientCAPath := filepath.Join(tmpDir, "ca.crt")
err = os.WriteFile(tlsCertPath, serverCert, 0644)
require.NoError(t, err)
err = os.WriteFile(tlsKeyPath, serverKey, 0600)
require.NoError(t, err)
err = os.WriteFile(clientCAPath, caCert, 0644)
require.NoError(t, err)
logger := logrus.New()
logger.SetOutput(io.Discard)
// Test without kubeConfig - should use unprotected metrics
_, err = GetListenAndServeFunc(
WithLogger(logger),
WithTLS(&tlsCertPath, &tlsKeyPath, &clientCAPath),
WithDebug(false),
)
assert.NoError(t, err, "GetListenAndServeFunc should succeed without kubeConfig")
}
// TestGetListenAndServeFunc_WithEmptyClientCA tests that the server
// starts successfully when TLS is enabled but client-ca is empty
func TestGetListenAndServeFunc_WithEmptyClientCA(t *testing.T) {
// Generate test certificates dynamically
caCert, caKey, err := generateCA()
require.NoError(t, err)
serverCert, serverKey, err := generateServerCert(caCert, caKey, "localhost")
require.NoError(t, err)
tmpDir, err := os.MkdirTemp("", "server-test-*")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
tlsCertPath := filepath.Join(tmpDir, "tls.crt")
tlsKeyPath := filepath.Join(tmpDir, "tls.key")
emptyClientCAPath := "" // Empty client CA path
err = os.WriteFile(tlsCertPath, serverCert, 0644)
require.NoError(t, err)
err = os.WriteFile(tlsKeyPath, serverKey, 0600)
require.NoError(t, err)
logger := logrus.New()
logger.SetOutput(io.Discard)
// Test with TLS enabled but empty client CA - should succeed
_, err = GetListenAndServeFunc(
WithLogger(logger),
WithTLS(&tlsCertPath, &tlsKeyPath, &emptyClientCAPath),
WithDebug(false),
)
assert.NoError(t, err, "GetListenAndServeFunc should succeed with empty client-ca")
}
// TestGetListenAndServeFunc_WithNilClientCA tests that the server
// starts successfully when TLS is enabled but client-ca pointer is nil
func TestGetListenAndServeFunc_WithNilClientCA(t *testing.T) {
// Generate test certificates dynamically
caCert, caKey, err := generateCA()
require.NoError(t, err)
serverCert, serverKey, err := generateServerCert(caCert, caKey, "localhost")
require.NoError(t, err)
tmpDir, err := os.MkdirTemp("", "server-test-*")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
tlsCertPath := filepath.Join(tmpDir, "tls.crt")
tlsKeyPath := filepath.Join(tmpDir, "tls.key")
err = os.WriteFile(tlsCertPath, serverCert, 0644)
require.NoError(t, err)
err = os.WriteFile(tlsKeyPath, serverKey, 0600)
require.NoError(t, err)
logger := logrus.New()
logger.SetOutput(io.Discard)
// Test with TLS enabled but nil client CA pointer - should succeed
_, err = GetListenAndServeFunc(
WithLogger(logger),
WithTLS(&tlsCertPath, &tlsKeyPath, nil),
WithDebug(false),
)
assert.NoError(t, err, "GetListenAndServeFunc should succeed with nil client-ca pointer")
}
// TestClientCAEnabled tests the clientCAEnabled helper function
func TestClientCAEnabled(t *testing.T) {
tests := []struct {
name string
clientCAPath *string
expected bool
}{
{
name: "nil pointer",
clientCAPath: nil,
expected: false,
},
{
name: "empty string",
clientCAPath: strPtr(""),
expected: false,
},
{
name: "valid path",
clientCAPath: strPtr("/path/to/ca.crt"),
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sc := &serverConfig{
clientCAPath: tt.clientCAPath,
}
assert.Equal(t, tt.expected, sc.clientCAEnabled(), "clientCAEnabled result should match expected")
})
}
}
func strPtr(s string) *string {
return &s
}
// TestHTTPClientHasTLSConfig verifies that rest.HTTPClientFor creates a client
// with proper TLS configuration including CA certificates
func TestHTTPClientHasTLSConfig(t *testing.T) {
// Generate test CA dynamically
caCert, _, err := generateCA()
require.NoError(t, err)
kubeConfig := &rest.Config{
Host: "https://test-api-server:6443",
TLSClientConfig: rest.TLSClientConfig{
CAData: caCert,
},
Timeout: 30 * time.Second,
}
// Create HTTP client using rest.HTTPClientFor
httpClient, err := rest.HTTPClientFor(kubeConfig)
require.NoError(t, err, "HTTPClientFor should succeed")
require.NotNil(t, httpClient, "HTTP client should not be nil")
// Verify that the client has a transport configured
require.NotNil(t, httpClient.Transport, "HTTP client transport should be configured")
// Check if it's an http.Transport with TLS config
transport, ok := httpClient.Transport.(*http.Transport)
require.True(t, ok, "Transport should be *http.Transport")
require.NotNil(t, transport.TLSClientConfig, "TLS config should be set")
// Verify that RootCAs is configured (this proves CA cert is loaded)
assert.NotNil(t, transport.TLSClientConfig.RootCAs, "RootCAs should be configured from kubeConfig")
// Verify timeout is set
assert.Equal(t, 30*time.Second, httpClient.Timeout, "Timeout should match kubeConfig")
}
// TestEmptyHTTPClientMissingTLSConfig demonstrates the bug:
// Creating an empty http.Client doesn't have TLS configuration
func TestEmptyHTTPClientMissingTLSConfig(t *testing.T) {
// This is the buggy code pattern from the original implementation
buggyClient := &http.Client{
Timeout: 30 * time.Second,
}
// The buggy client doesn't have a transport or TLS config
assert.Nil(t, buggyClient.Transport, "Empty http.Client has no transport (uses default)")
// When used with NewForConfigAndClient, it would fail to verify API server certs
// because it doesn't have the CA certificates from the kubeConfig
}
// TestMetricsEndpointAccessible tests that the metrics endpoint is accessible
// and properly configured (integration-style test)
func TestMetricsEndpointAccessible(t *testing.T) {
logger := logrus.New()
logger.SetOutput(io.Discard)
// Test unprotected metrics endpoint (no kubeConfig, no TLS)
emptyStr := ""
listenAndServe, err := GetListenAndServeFunc(
WithLogger(logger),
WithTLS(&emptyStr, &emptyStr, &emptyStr),
WithDebug(false),
)
require.NoError(t, err)
// Start a test server
mux := http.NewServeMux()
mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "# HELP test_metric Test metric")
})
server := httptest.NewServer(mux)
defer server.Close()
// Test that metrics endpoint responds
resp, err := http.Get(server.URL + "/metrics")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode, "Metrics endpoint should return 200")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Contains(t, string(body), "test_metric", "Response should contain metrics")
// Verify listenAndServe function is not nil
assert.NotNil(t, listenAndServe, "listenAndServe function should be returned")
}
// generateCA generates a test CA certificate and private key.
// Returns CA certificate PEM, CA private key, and error.
// This function generates certificates dynamically at test runtime to avoid
// hardcoding private keys in source code.
func generateCA() ([]byte, *rsa.PrivateKey, error) {
// Generate RSA private key for CA
caKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate CA key: %w", err)
}
// Create CA certificate template
caTemplate := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: "Test CA",
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour), // Valid for 1 day
IsCA: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}
// Create self-signed CA certificate
caCertBytes, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to create CA certificate: %w", err)
}
// Encode CA certificate to PEM
caCertPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: caCertBytes,
})
return caCertPEM, caKey, nil
}
// generateServerCert generates a server certificate signed by the given CA.
// Returns server certificate PEM, server private key PEM, and error.
func generateServerCert(caCertPEM []byte, caKey *rsa.PrivateKey, commonName string) ([]byte, []byte, error) {
// Parse CA certificate
block, _ := pem.Decode(caCertPEM)
if block == nil {
return nil, nil, fmt.Errorf("failed to parse CA certificate PEM")
}
caCert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse CA certificate: %w", err)
}
// Generate RSA private key for server
serverKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate server key: %w", err)
}
// Create server certificate template
serverTemplate := &x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{
CommonName: commonName,
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour), // Valid for 1 day
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
// Create server certificate signed by CA
serverCertBytes, err := x509.CreateCertificate(rand.Reader, serverTemplate, caCert, &serverKey.PublicKey, caKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to create server certificate: %w", err)
}
// Encode server certificate to PEM
serverCertPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: serverCertBytes,
})
// Encode server private key to PEM
serverKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(serverKey),
})
return serverCertPEM, serverKeyPEM, nil
}
// TestServerConfig_TLSEnabled tests the TLS detection logic
func TestServerConfig_TLSEnabled(t *testing.T) {
tests := []struct {
name string
certPath string
keyPath string
expectTLS bool
expectError bool
}{
{
name: "both cert and key provided",
certPath: "/path/to/cert",
keyPath: "/path/to/key",
expectTLS: true,
expectError: false,
},
{
name: "neither cert nor key provided",
certPath: "",
keyPath: "",
expectTLS: false,
expectError: false,
},
{
name: "only cert provided",
certPath: "/path/to/cert",
keyPath: "",
expectTLS: false,
expectError: true,
},
{
name: "only key provided",
certPath: "",
keyPath: "/path/to/key",
expectTLS: false,
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sc := &serverConfig{
tlsCertPath: &tt.certPath,
tlsKeyPath: &tt.keyPath,
}
enabled, err := sc.tlsEnabled()
if tt.expectError {
assert.Error(t, err, "Expected error for mismatched cert/key")
} else {
assert.NoError(t, err, "Should not error")
assert.Equal(t, tt.expectTLS, enabled, "TLS enabled state should match")
}
})
}
}
// TestServerConfig_GetAddress tests address selection based on TLS
func TestServerConfig_GetAddress(t *testing.T) {
sc := &serverConfig{}
httpsAddr := sc.getAddress(true)
assert.Equal(t, ":8443", httpsAddr, "HTTPS should use port 8443")
httpAddr := sc.getAddress(false)
assert.Equal(t, ":8080", httpAddr, "HTTP should use port 8080")
}
// TestWithOptions tests that configuration options are properly applied
func TestWithOptions(t *testing.T) {
logger := logrus.New()
tlsCert := "/path/to/cert"
tlsKey := "/path/to/key"
clientCA := "/path/to/ca"
kubeConfig := &rest.Config{Host: "https://test:6443"}
sc := defaultServerConfig()
sc.apply([]Option{
WithLogger(logger),
WithTLS(&tlsCert, &tlsKey, &clientCA),
WithKubeConfig(kubeConfig),
WithDebug(true),
})
assert.Equal(t, logger, sc.logger, "Logger should be set")
assert.Equal(t, &tlsCert, sc.tlsCertPath, "TLS cert path should be set")
assert.Equal(t, &tlsKey, sc.tlsKeyPath, "TLS key path should be set")
assert.Equal(t, &clientCA, sc.clientCAPath, "Client CA path should be set")
assert.Equal(t, kubeConfig, sc.kubeConfig, "KubeConfig should be set")
assert.True(t, sc.debug, "Debug should be enabled")
}
// TestRootCAsConfiguration verifies that CA certificates are properly loaded
func TestRootCAsConfiguration(t *testing.T) {
// Generate test CA dynamically
caCertPEM, _, err := generateCA()
require.NoError(t, err)
caCert := caCertPEM
// Test that CA data can be parsed
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM(caCert)
assert.True(t, ok, "CA certificate should be parseable")
// Create rest.Config with CA data
config := &rest.Config{
Host: "https://test-api:6443",
TLSClientConfig: rest.TLSClientConfig{
CAData: caCert,
},
}
// Create HTTP client
client, err := rest.HTTPClientFor(config)
require.NoError(t, err)
// Verify transport has TLS config
transport, ok := client.Transport.(*http.Transport)
require.True(t, ok)
require.NotNil(t, transport.TLSClientConfig)
// The RootCAs should be configured
if transport.TLSClientConfig.RootCAs != nil {
// Success - RootCAs are configured
assert.NotNil(t, transport.TLSClientConfig.RootCAs)
} else {
// On some systems, if CAData is invalid, RootCAs might be nil
// but the important thing is no error was returned
t.Log("RootCAs is nil - this might be due to invalid test certificate")
}
}
// TestHTTPClientTimeout verifies timeout configuration
func TestHTTPClientTimeout(t *testing.T) {
config := &rest.Config{
Host: "https://test-api:6443",
Timeout: 45 * time.Second,
}
client, err := rest.HTTPClientFor(config)
require.NoError(t, err)
assert.Equal(t, 45*time.Second, client.Timeout, "Client timeout should match config")
}
// BenchmarkHTTPClientCreation benchmarks the performance of creating HTTP clients
func BenchmarkHTTPClientCreation(b *testing.B) {
config := &rest.Config{
Host: "https://test-api:6443",
TLSClientConfig: rest.TLSClientConfig{
CAData: []byte("test-ca-data"),
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = rest.HTTPClientFor(config)
}
}