@@ -7,20 +7,13 @@ package stubstatus
77
88import (
99 "context"
10- "crypto/rand"
11- "crypto/rsa"
1210 "crypto/tls"
1311 "crypto/x509"
14- "crypto/x509/pkix"
15- "encoding/pem"
16- "math/big"
1712 "net"
1813 "net/http"
1914 "net/http/httptest"
2015 "os"
21- "path/filepath"
2216 "testing"
23- "time"
2417
2518 "github.com/stretchr/testify/assert"
2619 "github.com/stretchr/testify/require"
@@ -29,71 +22,39 @@ import (
2922 "go.opentelemetry.io/collector/receiver/receivertest"
3023
3124 "github.com/nginx/agent/v3/internal/collector/nginxossreceiver/internal/config"
25+ "github.com/nginx/agent/v3/test/helpers"
3226)
3327
3428func 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 )
7531
7632 // Create a temporary directory for test files
7733 tempDir := t .TempDir ()
7834
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+ }
8451
85- // Create a TLS config for the server
8652 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 },
9455 }
9556
96- // Create a test server with TLS
57+ // Create a test server with our custom TLS config
9758 server := httptest .NewUnstartedServer (http .HandlerFunc (func (rw http.ResponseWriter , req * http.Request ) {
9859 if req .URL .Path == "/status" {
9960 rw .WriteHeader (http .StatusOK )
@@ -112,56 +73,65 @@ Reading: 6 Writing: 179 Waiting: 106
11273 server .StartTLS ()
11374 defer server .Close ()
11475
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 ) {
11778 cfg , ok := config .CreateDefaultConfig ().(* config.Config )
11879 require .True (t , ok )
11980
12081 cfg .APIDetails .URL = server .URL + "/status"
121- cfg .APIDetails .Ca = caFile
82+ // Use the self-signed certificate for verification
83+ cfg .APIDetails .Ca = certFile
12284
12385 scraper := NewScraper (receivertest .NewNopSettings (component.Type {}), cfg )
12486
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 )
12789
12890 _ , err = scraper .Scrape (context .Background ())
129- assert .NoError (t , err )
91+ assert .NoError (t , err , "Scraping with self-signed certificate should succeed" )
13092 })
13193}
13294
13395func 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
150101server accepts handled requests
151102 16630948 16630946 31070465
152103Reading: 6 Writing: 179 Waiting: 106
153104` ))
154105
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 },
159125 }
160126
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+ })
165135
166136 // Test with Unix socket
167137 t .Run ("with Unix socket" , func (t * testing.T ) {
@@ -173,8 +143,8 @@ Reading: 6 Writing: 179 Waiting: 106
173143
174144 scraper := NewScraper (receivertest .NewNopSettings (component.Type {}), cfg )
175145
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 )
178148
179149 _ , err = scraper .Scrape (context .Background ())
180150 assert .NoError (t , err )
0 commit comments