| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package configurablehttpprovider |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"crypto/rand" |
| 9 |
"crypto/rsa" |
| 10 |
"crypto/tls" |
| 11 |
"crypto/x509" |
| 12 |
"crypto/x509/pkix" |
| 13 |
"encoding/pem" |
| 14 |
"fmt" |
| 15 |
"math/big" |
| 16 |
"net/http" |
| 17 |
"net/http/httptest" |
| 18 |
"net/url" |
| 19 |
"os" |
| 20 |
"testing" |
| 21 |
"time" |
| 22 |
|
| 23 |
"github.com/stretchr/testify/assert" |
| 24 |
"github.com/stretchr/testify/require" |
| 25 |
|
| 26 |
"go.opentelemetry.io/collector/confmap" |
| 27 |
"go.opentelemetry.io/collector/confmap/confmaptest" |
| 28 |
"go.opentelemetry.io/collector/internal/testutil" |
| 29 |
) |
| 30 |
|
| 31 |
func newConfigurableHTTPProvider(scheme SchemeType, set confmap.ProviderSettings) *provider { |
| 32 |
return New(scheme, set).(*provider) |
| 33 |
} |
| 34 |
|
| 35 |
func answerGet(w http.ResponseWriter, _ *http.Request) { |
| 36 |
f, err := os.ReadFile("./testdata/otel-config.yaml") |
| 37 |
if err != nil { |
| 38 |
w.WriteHeader(http.StatusNotFound) |
| 39 |
_, innerErr := w.Write([]byte("Cannot find the config file")) |
| 40 |
if innerErr != nil { |
| 41 |
fmt.Println("Write failed: ", innerErr) |
| 42 |
} |
| 43 |
return |
| 44 |
} |
| 45 |
w.WriteHeader(http.StatusOK) |
| 46 |
_, err = w.Write(f) |
| 47 |
if err != nil { |
| 48 |
fmt.Println("Write failed: ", err) |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
// Generate a self signed certificate specific for the tests. Based on |
| 53 |
// https://go.dev/src/crypto/tls/generate_cert.go |
| 54 |
func generateCertificate(t *testing.T, hostname string) (cert, key string, err error) { |
| 55 |
testutil.SkipIfFIPSOnly(t, "x509.CreateCertificate uses SHA-1") |
| 56 |
priv, err := rsa.GenerateKey(rand.Reader, 2048) |
| 57 |
if err != nil { |
| 58 |
return "", "", fmt.Errorf("Failed to generate private key: %w", err) |
| 59 |
} |
| 60 |
|
| 61 |
keyUsage := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign |
| 62 |
notBefore := time.Now() |
| 63 |
notAfter := notBefore.Add(time.Hour * 12) |
| 64 |
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) |
| 65 |
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) |
| 66 |
if err != nil { |
| 67 |
return "", "", fmt.Errorf("Failed to generate serial number: %w", err) |
| 68 |
} |
| 69 |
|
| 70 |
template := x509.Certificate{ |
| 71 |
SerialNumber: serialNumber, |
| 72 |
Subject: pkix.Name{ |
| 73 |
Organization: []string{"Httpprovider Co"}, |
| 74 |
}, |
| 75 |
NotBefore: notBefore, |
| 76 |
NotAfter: notAfter, |
| 77 |
KeyUsage: keyUsage, |
| 78 |
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 79 |
BasicConstraintsValid: true, |
| 80 |
IsCA: true, |
| 81 |
DNSNames: []string{hostname}, |
| 82 |
} |
| 83 |
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) |
| 84 |
if err != nil { |
| 85 |
return "", "", fmt.Errorf("Failed to create certificate: %w", err) |
| 86 |
} |
| 87 |
|
| 88 |
tempDir := t.TempDir() |
| 89 |
certOut, err := os.CreateTemp(tempDir, "cert*.pem") |
| 90 |
if err != nil { |
| 91 |
return "", "", fmt.Errorf("Failed to open cert.pem for writing: %w", err) |
| 92 |
} |
| 93 |
|
| 94 |
defer certOut.Close() |
| 95 |
|
| 96 |
if err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { |
| 97 |
return "", "", fmt.Errorf("Failed to write data to cert.pem: %w", err) |
| 98 |
} |
| 99 |
|
| 100 |
keyOut, err := os.CreateTemp(tempDir, "key*.pem") |
| 101 |
if err != nil { |
| 102 |
return "", "", fmt.Errorf("Failed to open key.pem for writing: %w", err) |
| 103 |
} |
| 104 |
defer keyOut.Close() |
| 105 |
|
| 106 |
privBytes, err := x509.MarshalPKCS8PrivateKey(priv) |
| 107 |
if err != nil { |
| 108 |
return "", "", fmt.Errorf("Unable to marshal private key: %w", err) |
| 109 |
} |
| 110 |
|
| 111 |
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { |
| 112 |
return "", "", fmt.Errorf("Failed to write data to key.pem: %w", err) |
| 113 |
} |
| 114 |
|
| 115 |
return certOut.Name(), keyOut.Name(), nil |
| 116 |
} |
| 117 |
|
| 118 |
func TestFunctionalityDownloadFileHTTP(t *testing.T) { |
| 119 |
fp := newConfigurableHTTPProvider(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 120 |
ts := httptest.NewServer(http.HandlerFunc(answerGet)) |
| 121 |
defer ts.Close() |
| 122 |
_, err := fp.Retrieve(context.Background(), ts.URL, nil) |
| 123 |
assert.NoError(t, err) |
| 124 |
assert.NoError(t, fp.Shutdown(context.Background())) |
| 125 |
} |
| 126 |
|
| 127 |
func TestFunctionalityDownloadFileHTTPS(t *testing.T) { |
| 128 |
certPath, keyPath, err := generateCertificate(t, "localhost") |
| 129 |
require.NoError(t, err) |
| 130 |
|
| 131 |
invalidCert, err := os.CreateTemp(t.TempDir(), "cert*.crt") |
| 132 |
defer func() { require.NoError(t, invalidCert.Close()) }() |
| 133 |
require.NoError(t, err) |
| 134 |
_, err = invalidCert.Write([]byte{0, 1, 2}) |
| 135 |
require.NoError(t, err) |
| 136 |
|
| 137 |
cert, err := tls.LoadX509KeyPair(certPath, keyPath) |
| 138 |
require.NoError(t, err) |
| 139 |
ts := httptest.NewUnstartedServer(http.HandlerFunc(answerGet)) |
| 140 |
ts.TLS = &tls.Config{Certificates: []tls.Certificate{cert}} |
| 141 |
ts.StartTLS() |
| 142 |
|
| 143 |
defer ts.Close() |
| 144 |
|
| 145 |
tests := []struct { |
| 146 |
name string |
| 147 |
certPath string |
| 148 |
hostName string |
| 149 |
useCertificate bool |
| 150 |
skipHostnameValidation bool |
| 151 |
shouldError bool |
| 152 |
}{ |
| 153 |
{ |
| 154 |
name: "Test valid certificate and name", |
| 155 |
certPath: certPath, |
| 156 |
hostName: "localhost", |
| 157 |
useCertificate: true, |
| 158 |
skipHostnameValidation: false, |
| 159 |
shouldError: false, |
| 160 |
}, |
| 161 |
{ |
| 162 |
name: "Test valid certificate with invalid name", |
| 163 |
certPath: certPath, |
| 164 |
hostName: "127.0.0.1", |
| 165 |
useCertificate: true, |
| 166 |
skipHostnameValidation: false, |
| 167 |
shouldError: true, |
| 168 |
}, |
| 169 |
{ |
| 170 |
name: "Test valid certificate with invalid name, skip validation", |
| 171 |
certPath: certPath, |
| 172 |
hostName: "127.0.0.1", |
| 173 |
useCertificate: true, |
| 174 |
skipHostnameValidation: true, |
| 175 |
shouldError: false, |
| 176 |
}, |
| 177 |
{ |
| 178 |
name: "Test no certificate should fail", |
| 179 |
certPath: certPath, |
| 180 |
hostName: "localhost", |
| 181 |
useCertificate: false, |
| 182 |
skipHostnameValidation: false, |
| 183 |
shouldError: true, |
| 184 |
}, |
| 185 |
{ |
| 186 |
name: "Test invalid cert", |
| 187 |
certPath: invalidCert.Name(), |
| 188 |
hostName: "localhost", |
| 189 |
useCertificate: true, |
| 190 |
skipHostnameValidation: false, |
| 191 |
shouldError: true, |
| 192 |
}, |
| 193 |
{ |
| 194 |
name: "Test no cert", |
| 195 |
certPath: "no_certificate", |
| 196 |
hostName: "localhost", |
| 197 |
useCertificate: true, |
| 198 |
skipHostnameValidation: false, |
| 199 |
shouldError: true, |
| 200 |
}, |
| 201 |
} |
| 202 |
|
| 203 |
for _, tt := range tests { |
| 204 |
t.Run(tt.name, func(t *testing.T) { |
| 205 |
fp := newConfigurableHTTPProvider(HTTPSScheme, confmaptest.NewNopProviderSettings()) |
| 206 |
// Parse url of the test server to get the port number. |
| 207 |
tsURL, err := url.Parse(ts.URL) |
| 208 |
require.NoError(t, err) |
| 209 |
if tt.useCertificate { |
| 210 |
fp.caCertPath = tt.certPath |
| 211 |
} |
| 212 |
fp.insecureSkipVerify = tt.skipHostnameValidation |
| 213 |
_, err = fp.Retrieve(context.Background(), fmt.Sprintf("https://%s:%s", tt.hostName, tsURL.Port()), nil) |
| 214 |
if tt.shouldError { |
| 215 |
assert.Error(t, err) |
| 216 |
} else { |
| 217 |
assert.NoError(t, err) |
| 218 |
} |
| 219 |
}) |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
func TestUnsupportedScheme(t *testing.T) { |
| 224 |
fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 225 |
_, err := fp.Retrieve(context.Background(), "https://...", nil) |
| 226 |
require.Error(t, err) |
| 227 |
require.NoError(t, fp.Shutdown(context.Background())) |
| 228 |
|
| 229 |
fp = New(HTTPSScheme, confmaptest.NewNopProviderSettings()) |
| 230 |
_, err = fp.Retrieve(context.Background(), "http://...", nil) |
| 231 |
require.Error(t, err) |
| 232 |
assert.NoError(t, fp.Shutdown(context.Background())) |
| 233 |
} |
| 234 |
|
| 235 |
func TestEmptyURI(t *testing.T) { |
| 236 |
fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 237 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 238 |
w.WriteHeader(http.StatusBadRequest) |
| 239 |
})) |
| 240 |
defer ts.Close() |
| 241 |
_, err := fp.Retrieve(context.Background(), ts.URL, nil) |
| 242 |
require.Error(t, err) |
| 243 |
require.NoError(t, fp.Shutdown(context.Background())) |
| 244 |
} |
| 245 |
|
| 246 |
func TestRetrieveFromShutdownServer(t *testing.T) { |
| 247 |
fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 248 |
ts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) |
| 249 |
ts.Close() |
| 250 |
_, err := fp.Retrieve(context.Background(), ts.URL, nil) |
| 251 |
require.Error(t, err) |
| 252 |
require.NoError(t, fp.Shutdown(context.Background())) |
| 253 |
} |
| 254 |
|
| 255 |
func TestNonExistent(t *testing.T) { |
| 256 |
fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 257 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 258 |
w.WriteHeader(http.StatusNotFound) |
| 259 |
})) |
| 260 |
defer ts.Close() |
| 261 |
_, err := fp.Retrieve(context.Background(), ts.URL, nil) |
| 262 |
require.Error(t, err) |
| 263 |
require.NoError(t, fp.Shutdown(context.Background())) |
| 264 |
} |
| 265 |
|
| 266 |
func TestInvalidYAML(t *testing.T) { |
| 267 |
fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 268 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 269 |
w.WriteHeader(http.StatusOK) |
| 270 |
_, err := w.Write([]byte("wrong : [")) |
| 271 |
if err != nil { |
| 272 |
fmt.Println("Write failed: ", err) |
| 273 |
} |
| 274 |
})) |
| 275 |
defer ts.Close() |
| 276 |
ret, err := fp.Retrieve(context.Background(), ts.URL, nil) |
| 277 |
require.NoError(t, err) |
| 278 |
raw, err := ret.AsRaw() |
| 279 |
require.NoError(t, err) |
| 280 |
assert.Equal(t, "wrong : [", raw) |
| 281 |
require.NoError(t, fp.Shutdown(context.Background())) |
| 282 |
} |
| 283 |
|
| 284 |
func TestScheme(t *testing.T) { |
| 285 |
fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 286 |
assert.Equal(t, "http", fp.Scheme()) |
| 287 |
require.NoError(t, fp.Shutdown(context.Background())) |
| 288 |
} |
| 289 |
|
| 290 |
func TestValidateProviderScheme(t *testing.T) { |
| 291 |
assert.NoError(t, confmaptest.ValidateProviderScheme(New(HTTPScheme, confmaptest.NewNopProviderSettings()))) |
| 292 |
} |
| 293 |
|
| 294 |
func TestInvalidURI(t *testing.T) { |
| 295 |
fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) |
| 296 |
|
| 297 |
tests := []struct { |
| 298 |
uri string |
| 299 |
err string |
| 300 |
}{ |
| 301 |
{ |
| 302 |
uri: "foo://..", |
| 303 |
err: "uri is not supported by \"http\" provider", |
| 304 |
}, |
| 305 |
{ |
| 306 |
uri: "http://", |
| 307 |
err: "no Host in request URL", |
| 308 |
}, |
| 309 |
{ |
| 310 |
uri: "http://{}", |
| 311 |
err: "invalid character \"{\" in host name", |
| 312 |
}, |
| 313 |
} |
| 314 |
|
| 315 |
for _, tt := range tests { |
| 316 |
t.Run(tt.uri, func(t *testing.T) { |
| 317 |
_, err := fp.Retrieve(context.Background(), tt.uri, nil) |
| 318 |
assert.ErrorContains(t, err, tt.err) |
| 319 |
}) |
| 320 |
} |
| 321 |
} |