@@ -7,20 +7,13 @@ package stubstatus
7
7
8
8
import (
9
9
"context"
10
- "crypto/rand"
11
- "crypto/rsa"
12
10
"crypto/tls"
13
11
"crypto/x509"
14
- "crypto/x509/pkix"
15
- "encoding/pem"
16
- "math/big"
17
12
"net"
18
13
"net/http"
19
14
"net/http/httptest"
20
15
"os"
21
- "path/filepath"
22
16
"testing"
23
- "time"
24
17
25
18
"github.com/stretchr/testify/assert"
26
19
"github.com/stretchr/testify/require"
@@ -29,71 +22,39 @@ import (
29
22
"go.opentelemetry.io/collector/receiver/receivertest"
30
23
31
24
"github.com/nginx/agent/v3/internal/collector/nginxossreceiver/internal/config"
25
+ "github.com/nginx/agent/v3/test/helpers"
32
26
)
33
27
34
28
func TestStubStatusScraperTLS (t * testing.T ) {
35
- // Create a test CA certificate and key
36
- ca := & x509.Certificate {
37
- SerialNumber : big .NewInt (1 ),
38
- Subject : pkix.Name {
39
- Organization : []string {"NGINX Agent Test CA" },
40
- },
41
- NotBefore : time .Now (),
42
- NotAfter : time .Now ().AddDate (10 , 0 , 0 ),
43
- KeyUsage : x509 .KeyUsageCertSign | x509 .KeyUsageDigitalSignature ,
44
- ExtKeyUsage : []x509.ExtKeyUsage {x509 .ExtKeyUsageClientAuth , x509 .ExtKeyUsageServerAuth },
45
- BasicConstraintsValid : true ,
46
- IsCA : true ,
47
- }
48
-
49
- caPrivKey , caPrivKeyErr := rsa .GenerateKey (rand .Reader , 2048 )
50
- require .NoError (t , caPrivKeyErr )
51
-
52
- caBytes , caBytesErr := x509 .CreateCertificate (rand .Reader , ca , ca , & caPrivKey .PublicKey , caPrivKey )
53
- require .NoError (t , caBytesErr )
54
-
55
- // Create a test server certificate signed by the CA
56
- cert := & x509.Certificate {
57
- SerialNumber : big .NewInt (2 ),
58
- Subject : pkix.Name {
59
- Organization : []string {"NGINX Agent Test" },
60
- },
61
- NotBefore : time .Now (),
62
- NotAfter : time .Now ().AddDate (10 , 0 , 0 ),
63
- SubjectKeyId : []byte {1 , 2 , 3 , 4 , 6 },
64
- ExtKeyUsage : []x509.ExtKeyUsage {x509 .ExtKeyUsageClientAuth , x509 .ExtKeyUsageServerAuth },
65
- KeyUsage : x509 .KeyUsageDigitalSignature ,
66
- IPAddresses : []net.IP {net .IPv4 (127 , 0 , 0 , 1 )},
67
- DNSNames : []string {"localhost" },
68
- }
69
-
70
- certPrivKey , certPrivKeyErr := rsa .GenerateKey (rand .Reader , 2048 )
71
- require .NoError (t , certPrivKeyErr )
72
-
73
- certBytes , certBytesErr := x509 .CreateCertificate (rand .Reader , cert , ca , & certPrivKey .PublicKey , caPrivKey )
74
- require .NoError (t , certBytesErr )
29
+ // Generate self-signed certificate using helper
30
+ keyBytes , certBytes := helpers .GenerateSelfSignedCert (t )
75
31
76
32
// Create a temporary directory for test files
77
33
tempDir := t .TempDir ()
78
34
79
- // Save CA certificate to a file
80
- caFile := filepath .Join (tempDir , "ca.crt" )
81
- caPEM := pem .EncodeToMemory (& pem.Block {Type : "CERTIFICATE" , Bytes : caBytes })
82
- writeErr := os .WriteFile (caFile , caPEM , 0o600 )
83
- require .NoError (t , writeErr )
35
+ // Save certificate to a file
36
+ certFile := helpers .WriteCertFiles (t , tempDir , helpers.Cert {
37
+ Name : "server.crt" ,
38
+ Type : "CERTIFICATE" ,
39
+ Contents : certBytes ,
40
+ })
41
+
42
+ // Parse the private key
43
+ key , err := x509 .ParsePKCS1PrivateKey (keyBytes )
44
+ require .NoError (t , err )
45
+
46
+ // Create a TLS config with our self-signed certificate
47
+ tlsCert := tls.Certificate {
48
+ Certificate : [][]byte {certBytes },
49
+ PrivateKey : key ,
50
+ }
84
51
85
- // Create a TLS config for the server
86
52
serverTLSConfig := & tls.Config {
87
- MinVersion : tls .VersionTLS13 ,
88
- Certificates : []tls.Certificate {
89
- {
90
- Certificate : [][]byte {certBytes },
91
- PrivateKey : certPrivKey ,
92
- },
93
- },
53
+ MinVersion : tls .VersionTLS13 ,
54
+ Certificates : []tls.Certificate {tlsCert },
94
55
}
95
56
96
- // Create a test server with TLS
57
+ // Create a test server with our custom TLS config
97
58
server := httptest .NewUnstartedServer (http .HandlerFunc (func (rw http.ResponseWriter , req * http.Request ) {
98
59
if req .URL .Path == "/status" {
99
60
rw .WriteHeader (http .StatusOK )
@@ -112,56 +73,65 @@ Reading: 6 Writing: 179 Waiting: 106
112
73
server .StartTLS ()
113
74
defer server .Close ()
114
75
115
- // Test with TLS configuration
116
- t .Run ("with TLS CA " , func (t * testing.T ) {
76
+ // Test with TLS configuration using our self-signed certificate
77
+ t .Run ("with self-signed TLS " , func (t * testing.T ) {
117
78
cfg , ok := config .CreateDefaultConfig ().(* config.Config )
118
79
require .True (t , ok )
119
80
120
81
cfg .APIDetails .URL = server .URL + "/status"
121
- cfg .APIDetails .Ca = caFile
82
+ // Use the self-signed certificate for verification
83
+ cfg .APIDetails .Ca = certFile
122
84
123
85
scraper := NewScraper (receivertest .NewNopSettings (component.Type {}), cfg )
124
86
125
- err := scraper .Start (context .Background (), componenttest .NewNopHost ())
126
- require .NoError (t , err )
87
+ startErr := scraper .Start (context .Background (), componenttest .NewNopHost ())
88
+ require .NoError (t , startErr )
127
89
128
90
_ , err = scraper .Scrape (context .Background ())
129
- assert .NoError (t , err )
91
+ assert .NoError (t , err , "Scraping with self-signed certificate should succeed" )
130
92
})
131
93
}
132
94
133
95
func TestStubStatusScraperUnixSocket (t * testing.T ) {
134
- // Use a shorter path for the socket to avoid path length issues
135
- socketPath := filepath .Join (os .TempDir (), "test-nginx.sock" )
136
- // Clean up the socket file after the test
137
- t .Cleanup (func () { os .Remove (socketPath ) })
138
-
139
- // Create a Unix domain socket listener
140
- listener , listenErr := net .Listen ("unix" , socketPath )
141
- require .NoError (t , listenErr )
142
- defer listener .Close ()
143
-
144
- // Start a simple HTTP server on the Unix socket
145
- server := & http.Server {
146
- Handler : http .HandlerFunc (func (rw http.ResponseWriter , req * http.Request ) {
147
- if req .URL .Path == "/status" {
148
- rw .WriteHeader (http .StatusOK )
149
- _ , _ = rw .Write ([]byte (`Active connections: 291
96
+ // Create a test server with a Unix domain socket
97
+ handler := http .HandlerFunc (func (rw http.ResponseWriter , req * http.Request ) {
98
+ if req .URL .Path == "/status" {
99
+ rw .WriteHeader (http .StatusOK )
100
+ _ , _ = rw .Write ([]byte (`Active connections: 291
150
101
server accepts handled requests
151
102
16630948 16630946 31070465
152
103
Reading: 6 Writing: 179 Waiting: 106
153
104
` ))
154
105
155
- return
156
- }
157
- rw .WriteHeader (http .StatusNotFound )
158
- }),
106
+ return
107
+ }
108
+ rw .WriteHeader (http .StatusNotFound )
109
+ })
110
+
111
+ // Create a socket file in a temporary directory with a shorter path
112
+ socketPath := "/tmp/nginx-test.sock"
113
+
114
+ // Clean up any existing socket file
115
+ os .Remove (socketPath )
116
+
117
+ // Create a listener for the Unix socket
118
+ listener , err := net .Listen ("unix" , socketPath )
119
+ require .NoError (t , err , "Failed to create Unix socket listener" )
120
+
121
+ // Create a test server with our custom listener
122
+ server := & httptest.Server {
123
+ Listener : listener ,
124
+ Config : & http.Server {Handler : handler },
159
125
}
160
126
161
- go func () {
162
- _ = server .Serve (listener )
163
- }()
164
- defer server .Close ()
127
+ // Start the server
128
+ server .Start ()
129
+
130
+ // Ensure cleanup of the socket file
131
+ t .Cleanup (func () {
132
+ server .Close ()
133
+ os .Remove (socketPath )
134
+ })
165
135
166
136
// Test with Unix socket
167
137
t .Run ("with Unix socket" , func (t * testing.T ) {
@@ -173,8 +143,8 @@ Reading: 6 Writing: 179 Waiting: 106
173
143
174
144
scraper := NewScraper (receivertest .NewNopSettings (component.Type {}), cfg )
175
145
176
- err := scraper .Start (context .Background (), componenttest .NewNopHost ())
177
- require .NoError (t , err )
146
+ startErr := scraper .Start (context .Background (), componenttest .NewNopHost ())
147
+ require .NoError (t , startErr )
178
148
179
149
_ , err = scraper .Scrape (context .Background ())
180
150
assert .NoError (t , err )
0 commit comments