| 1 | package exporter |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io" |
| 6 | "math/rand" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/url" |
| 11 | "os" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | |
| 16 | log "github.com/sirupsen/logrus" |
| 17 | ) |
| 18 | |
| 19 | func TestHTTPScrapeMetricsEndpoints(t *testing.T) { |
| 20 | if os.Getenv("TEST_REDIS_URI") == "" || os.Getenv("TEST_PWD_REDIS_URI") == "" { |
| 21 | t.Skipf("Skipping TestHTTPScrapeMetricsEndpoints, missing env vars") |
| 22 | } |
| 23 | |
| 24 | setupTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 25 | defer deleteTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 26 | setupTestKeys(t, os.Getenv("TEST_PWD_REDIS_URI")) |
| 27 | defer deleteTestKeys(t, os.Getenv("TEST_PWD_REDIS_URI")) |
| 28 | |
| 29 | csk := dbNumStrFull + "=" + url.QueryEscape(testKeys[0]) // check-single-keys |
| 30 | css := dbNumStrFull + "=" + TestKeyNameStream // check-single-streams |
| 31 | cntk := dbNumStrFull + "=" + testKeys[0] + "*" // count-keys |
| 32 | |
| 33 | u, err := url.Parse(os.Getenv("TEST_REDIS_URI")) |
| 34 | if err != nil { |
| 35 | t.Fatalf("url.Parse() err: %s", err) |
| 36 | } |
| 37 | |
| 38 | testRedisIPAddress := "" |
| 39 | testRedisHostname := u.Hostname() |
| 40 | |
| 41 | if testRedisHostname == "localhost" { |
| 42 | testRedisIPAddress = "127.0.0.1" |
| 43 | } else { |
| 44 | ips, err := net.LookupIP(testRedisHostname) |
| 45 | if err != nil { |
| 46 | t.Fatalf("Could not get IP address: %s", err) |
| 47 | } |
| 48 | if len(ips) == 0 { |
| 49 | t.Fatal("No IP addresses found") |
| 50 | } |
| 51 | testRedisIPAddress = ips[0].String() |
| 52 | } |
| 53 | |
| 54 | testRedisIPAddress = fmt.Sprintf("%s:%s", testRedisIPAddress, u.Port()) |
| 55 | testRedisHostname = fmt.Sprintf("%s:%s", testRedisHostname, u.Port()) |
| 56 | |
| 57 | t.Logf("testRedisIPAddress: %s", testRedisIPAddress) |
| 58 | t.Logf("testRedisHostname: %s", testRedisHostname) |
| 59 | |
| 60 | for _, tst := range []struct { |
| 61 | name string |
| 62 | addr string |
| 63 | ck string |
| 64 | csk string |
| 65 | cs string |
| 66 | scrapeCs string |
| 67 | css string |
| 68 | cntk string |
| 69 | pwd string |
| 70 | scrape bool |
| 71 | target string |
| 72 | |
| 73 | wantStatusCode int |
| 74 | }{ |
| 75 | {name: "ip-addr", addr: testRedisIPAddress, csk: csk, css: css, cntk: cntk}, |
| 76 | {name: "hostname", addr: testRedisHostname, csk: csk, css: css, cntk: cntk}, |
| 77 | |
| 78 | {name: "check-keys", addr: os.Getenv("TEST_REDIS_URI"), ck: csk, cs: css, cntk: cntk}, |
| 79 | {name: "check-single-keys", addr: os.Getenv("TEST_REDIS_URI"), csk: csk, css: css, cntk: cntk}, |
| 80 | |
| 81 | {name: "addr-no-prefix", addr: strings.TrimPrefix(os.Getenv("TEST_REDIS_URI"), "redis://"), csk: csk, css: css, cntk: cntk}, |
| 82 | |
| 83 | {name: "scrape-target-no-prefix", pwd: "", scrape: true, target: strings.TrimPrefix(os.Getenv("TEST_REDIS_URI"), "redis://"), ck: csk, cs: css, cntk: cntk}, |
| 84 | {name: "scrape-broken-target", wantStatusCode: http.StatusBadRequest, scrape: true, target: "://nope"}, |
| 85 | {name: "scrape-broken-target2", wantStatusCode: http.StatusBadRequest, scrape: true, target: os.Getenv("TEST_REDIS_URI") + "-", csk: csk, css: css, cntk: cntk}, |
| 86 | {name: "scrape-broken-cs", wantStatusCode: http.StatusBadRequest, scrape: true, target: os.Getenv("TEST_REDIS_URI"), scrapeCs: "1=2=3=4"}, |
| 87 | |
| 88 | {name: "scrape-ck", pwd: "", scrape: true, target: os.Getenv("TEST_REDIS_URI"), ck: csk, scrapeCs: css, cntk: cntk}, |
| 89 | {name: "scrape-csk", pwd: "", scrape: true, target: os.Getenv("TEST_REDIS_URI"), csk: csk, css: css, cntk: cntk}, |
| 90 | |
| 91 | {name: "scrape-pwd-ck", pwd: "redis-password", scrape: true, target: os.Getenv("TEST_PWD_REDIS_URI"), ck: csk, scrapeCs: css, cntk: cntk}, |
| 92 | {name: "scrape-pwd-csk", pwd: "redis-password", scrape: true, target: os.Getenv("TEST_PWD_REDIS_URI"), csk: csk, scrapeCs: css, cntk: cntk}, |
| 93 | |
| 94 | {name: "error-scrape-no-target", wantStatusCode: http.StatusBadRequest, scrape: true, target: ""}, |
| 95 | } { |
| 96 | t.Run(tst.name, func(t *testing.T) { |
| 97 | options := Options{ |
| 98 | Namespace: "test", |
| 99 | Password: tst.pwd, |
| 100 | LuaScript: map[string][]byte{ |
| 101 | "test.lua": []byte(`return {"a", "11", "b", "12", "c", "13"}`), |
| 102 | }, |
| 103 | } |
| 104 | |
| 105 | options.CheckSingleKeys = tst.csk |
| 106 | options.CheckKeys = tst.ck |
| 107 | options.CheckSingleStreams = tst.css |
| 108 | options.CheckStreams = tst.cs |
| 109 | options.CountKeys = tst.cntk |
| 110 | options.CheckKeysBatchSize = 1000 |
| 111 | |
| 112 | e, _ := NewRedisExporter(tst.addr, options) |
| 113 | ts := httptest.NewServer(e) |
| 114 | |
| 115 | u := ts.URL |
| 116 | if tst.scrape { |
| 117 | u += "/scrape" |
| 118 | v := url.Values{} |
| 119 | v.Add("target", tst.target) |
| 120 | v.Add("check-single-keys", tst.csk) |
| 121 | v.Add("check-keys", tst.ck) |
| 122 | v.Add("check-streams", tst.scrapeCs) |
| 123 | v.Add("check-single-streams", tst.css) |
| 124 | v.Add("count-keys", tst.cntk) |
| 125 | |
| 126 | up, _ := url.Parse(u) |
| 127 | up.RawQuery = v.Encode() |
| 128 | u = up.String() |
| 129 | } else { |
| 130 | u += "/metrics" |
| 131 | } |
| 132 | |
| 133 | wantStatusCode := http.StatusOK |
| 134 | if tst.wantStatusCode != 0 { |
| 135 | wantStatusCode = tst.wantStatusCode |
| 136 | } |
| 137 | |
| 138 | gotStatusCode, body := downloadURLWithStatusCode(t, u) |
| 139 | |
| 140 | if gotStatusCode != wantStatusCode { |
| 141 | t.Fatalf("got status code: %d wanted: %d", gotStatusCode, wantStatusCode) |
| 142 | return |
| 143 | } |
| 144 | |
| 145 | // we can stop here if we expected a non-200 response |
| 146 | if wantStatusCode != http.StatusOK { |
| 147 | return |
| 148 | } |
| 149 | |
| 150 | wants := []string{ |
| 151 | // metrics |
| 152 | `test_connected_clients`, |
| 153 | `test_commands_processed_total`, |
| 154 | `test_instance_info`, |
| 155 | |
| 156 | "db_keys", |
| 157 | "db_avg_ttl_seconds", |
| 158 | "cpu_sys_seconds_total", |
| 159 | "loading_dump_file", // testing renames |
| 160 | "config_maxmemory", // testing config extraction |
| 161 | "config_maxclients", // testing config extraction |
| 162 | "slowlog_length", |
| 163 | "slowlog_last_id", |
| 164 | "start_time_seconds", |
| 165 | "uptime_in_seconds", |
| 166 | |
| 167 | // labels and label values |
| 168 | `redis_mode`, |
| 169 | `cmd="config`, |
| 170 | "maxmemory_policy", |
| 171 | |
| 172 | `test_script_value`, // lua script |
| 173 | |
| 174 | `test_key_size{db="db11",key="` + testKeys[0] + `"} 7`, |
| 175 | `test_key_value{db="db11",key="` + testKeys[0] + `"} 1234.56`, |
| 176 | |
| 177 | `test_keys_count{db="db11",key="` + testKeys[0] + `*"} 1`, |
| 178 | |
| 179 | `test_db_keys{db="db11"} `, |
| 180 | `test_db_keys_expiring{db="db11"} `, |
| 181 | // streams |
| 182 | `stream_length`, |
| 183 | `stream_groups`, |
| 184 | `stream_radix_tree_keys`, |
| 185 | `stream_radix_tree_nodes`, |
| 186 | `stream_group_consumers`, |
| 187 | `stream_group_messages_pending`, |
| 188 | `stream_group_consumer_messages_pending`, |
| 189 | `stream_group_consumer_idle_seconds`, |
| 190 | `test_up 1`, |
| 191 | } |
| 192 | |
| 193 | for _, want := range wants { |
| 194 | if !strings.Contains(body, want) { |
| 195 | t.Errorf("url: %s want metrics to include %q, have:\n%s", u, want, body) |
| 196 | break |
| 197 | } |
| 198 | } |
| 199 | ts.Close() |
| 200 | }) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func TestSimultaneousMetricsHttpRequests(t *testing.T) { |
| 205 | if os.Getenv("TEST_REDIS_URI") == "" || |
| 206 | os.Getenv("TEST_KEYDB01_URI") == "" || |
| 207 | os.Getenv("TEST_KEYDB02_URI") == "" || |
| 208 | os.Getenv("TEST_REDIS5_URI") == "" || |
| 209 | os.Getenv("TEST_REDIS6_URI") == "" || |
| 210 | os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI") == "" || |
| 211 | os.Getenv("TEST_REDIS_CLUSTER_SLAVE_URI") == "" || |
| 212 | os.Getenv("TEST_TILE38_URI") == "" || |
| 213 | os.Getenv("TEST_VALKEY8_BUNDLE_URI") == "" { |
| 214 | t.Skipf("Skipping TestSimultaneousMetricsHttpRequests, missing env vars") |
| 215 | } |
| 216 | |
| 217 | setupTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 218 | defer deleteTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 219 | |
| 220 | e, _ := NewRedisExporter("", Options{Namespace: "test", InclSystemMetrics: false}) |
| 221 | ts := httptest.NewServer(e) |
| 222 | defer ts.Close() |
| 223 | |
| 224 | uris := []string{ |
| 225 | os.Getenv("TEST_REDIS_URI"), |
| 226 | |
| 227 | os.Getenv("TEST_REDIS7_URI"), |
| 228 | |
| 229 | os.Getenv("TEST_VALKEY7_URI"), |
| 230 | os.Getenv("TEST_VALKEY8_URI"), |
| 231 | |
| 232 | os.Getenv("TEST_KEYDB01_URI"), |
| 233 | os.Getenv("TEST_KEYDB02_URI"), |
| 234 | |
| 235 | os.Getenv("TEST_REDIS5_URI"), |
| 236 | os.Getenv("TEST_REDIS6_URI"), |
| 237 | os.Getenv("TEST_VALKEY8_BUNDLE_URI"), |
| 238 | |
| 239 | // tile38 & Cluster need to be last in this list, so we can identify them when selected, down in line 229 |
| 240 | os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI"), |
| 241 | os.Getenv("TEST_REDIS_CLUSTER_SLAVE_URI"), |
| 242 | os.Getenv("TEST_TILE38_URI"), |
| 243 | } |
| 244 | |
| 245 | t.Logf("uris: %#v", uris) |
| 246 | |
| 247 | goroutines := 20 |
| 248 | var wg sync.WaitGroup |
| 249 | wg.Add(goroutines) |
| 250 | for ; goroutines > 0; goroutines-- { |
| 251 | go func() { |
| 252 | requests := 100 |
| 253 | for ; requests > 0; requests-- { |
| 254 | v := url.Values{} |
| 255 | |
| 256 | uriIdx := rand.Intn(len(uris)) |
| 257 | target := uris[uriIdx] |
| 258 | v.Add("target", target) |
| 259 | |
| 260 | // not appending this param for Tile38 and cluster (the last two in the list) |
| 261 | // Tile38 & cluster don't support the SELECT command, so this test will fail and spam the logs |
| 262 | if uriIdx < len(uris)-3 { |
| 263 | v.Add("check-single-keys", dbNumStrFull+"="+url.QueryEscape(testKeys[0])) |
| 264 | } |
| 265 | up, _ := url.Parse(ts.URL + "/scrape") |
| 266 | up.RawQuery = v.Encode() |
| 267 | fullURL := up.String() |
| 268 | |
| 269 | body := downloadURL(t, fullURL) |
| 270 | wants := []string{ |
| 271 | `test_connected_clients`, |
| 272 | `test_commands_processed_total`, |
| 273 | `test_instance_info`, |
| 274 | `test_up 1`, |
| 275 | } |
| 276 | for _, want := range wants { |
| 277 | if !strings.Contains(body, want) { |
| 278 | t.Errorf("fullURL: %s - want metrics to include %q, have:\n%s", fullURL, want, body) |
| 279 | break |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | wg.Done() |
| 284 | }() |
| 285 | } |
| 286 | wg.Wait() |
| 287 | } |
| 288 | |
| 289 | func TestHttpHandlers(t *testing.T) { |
| 290 | if os.Getenv("TEST_PWD_REDIS_URI") == "" { |
| 291 | t.Skipf("TEST_PWD_REDIS_URI not set - skipping") |
| 292 | } |
| 293 | |
| 294 | e, _ := NewRedisExporter(os.Getenv("TEST_PWD_REDIS_URI"), Options{Namespace: "test"}) |
| 295 | ts := httptest.NewServer(e) |
| 296 | defer ts.Close() |
| 297 | |
| 298 | for _, tst := range []struct { |
| 299 | path string |
| 300 | want string |
| 301 | }{ |
| 302 | { |
| 303 | path: "/", |
| 304 | want: `<head><title>Redis Exporter `, |
| 305 | }, |
| 306 | { |
| 307 | path: "/health", |
| 308 | want: `ok`, |
| 309 | }, |
| 310 | } { |
| 311 | t.Run(fmt.Sprintf("path: %s", tst.path), func(t *testing.T) { |
| 312 | body := downloadURL(t, ts.URL+tst.path) |
| 313 | if !strings.Contains(body, tst.want) { |
| 314 | t.Fatalf(`error, expected string "%s" in body, got body: \n\n%s`, tst.want, body) |
| 315 | } |
| 316 | }) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | func TestHttpDiscoverClusterNodesHandlers(t *testing.T) { |
| 321 | clusterAddr := os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI") |
| 322 | nonClusterAddr := os.Getenv("TEST_REDIS_URI") |
| 323 | if clusterAddr == "" || nonClusterAddr == "" { |
| 324 | t.Skipf("TEST_REDIS_CLUSTER_MASTER_URI or TEST_REDIS_URI not set - skipping") |
| 325 | } |
| 326 | |
| 327 | tests := []struct { |
| 328 | addr string |
| 329 | want string |
| 330 | isCluster bool |
| 331 | }{ |
| 332 | { |
| 333 | addr: clusterAddr, |
| 334 | want: "redis://127.0.0.1:7000", |
| 335 | isCluster: true, |
| 336 | }, |
| 337 | { |
| 338 | addr: clusterAddr, |
| 339 | want: "redis://127.0.0.1:7001", |
| 340 | isCluster: true, |
| 341 | }, |
| 342 | { |
| 343 | addr: clusterAddr, |
| 344 | want: "redis://127.0.0.1:7002", |
| 345 | isCluster: true, |
| 346 | }, |
| 347 | { |
| 348 | addr: clusterAddr, |
| 349 | want: "The discovery endpoint is only available on a redis cluster", |
| 350 | isCluster: false, |
| 351 | }, |
| 352 | { |
| 353 | addr: nonClusterAddr, |
| 354 | want: "The discovery endpoint is only available on a redis cluster", |
| 355 | isCluster: false, |
| 356 | }, |
| 357 | { |
| 358 | addr: nonClusterAddr, |
| 359 | want: "ouldn't connect to redis cluster: cluster refresh failed", |
| 360 | isCluster: true, |
| 361 | }, |
| 362 | { |
| 363 | addr: "doesnt-exist:9876", |
| 364 | want: "The discovery endpoint is only available on a redis cluster", |
| 365 | isCluster: false, |
| 366 | }, |
| 367 | { |
| 368 | addr: "doesnt-exist:9876", |
| 369 | want: "Couldn't connect to redis cluster: cluster refresh failed: redisc: all nodes failed", |
| 370 | isCluster: true, |
| 371 | }, |
| 372 | } |
| 373 | |
| 374 | for _, tst := range tests { |
| 375 | t.Run(fmt.Sprintf("addr: %s, isCluster: %v", tst.addr, tst.isCluster), func(t *testing.T) { |
| 376 | e, _ := NewRedisExporter(tst.addr, Options{ |
| 377 | Namespace: "test", |
| 378 | IsCluster: tst.isCluster, |
| 379 | }) |
| 380 | ts := httptest.NewServer(e) |
| 381 | defer ts.Close() |
| 382 | |
| 383 | body := downloadURL(t, ts.URL+"/discover-cluster-nodes") |
| 384 | if !strings.Contains(body, tst.want) { |
| 385 | t.Fatalf(`error, expected string "%s" in body, got body: \n\n%s`, tst.want, body) |
| 386 | } |
| 387 | }) |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | func TestReloadHandlers(t *testing.T) { |
| 392 | if os.Getenv("TEST_PWD_REDIS_URI") == "" { |
| 393 | t.Skipf("TEST_PWD_REDIS_URI not set - skipping") |
| 394 | } |
| 395 | |
| 396 | eWithPwdfile, _ := NewRedisExporter(os.Getenv("TEST_PWD_REDIS_URI"), Options{Namespace: "test", RedisPwdFile: "../contrib/sample-pwd-file.json"}) |
| 397 | ts := httptest.NewServer(eWithPwdfile) |
| 398 | defer ts.Close() |
| 399 | |
| 400 | for _, tst := range []struct { |
| 401 | e *Exporter |
| 402 | path string |
| 403 | want string |
| 404 | }{ |
| 405 | { |
| 406 | path: "/-/reload", |
| 407 | want: `ok`, |
| 408 | }, |
| 409 | } { |
| 410 | t.Run(fmt.Sprintf("path: %s", tst.path), func(t *testing.T) { |
| 411 | body := downloadURL(t, ts.URL+tst.path) |
| 412 | if !strings.Contains(body, tst.want) { |
| 413 | t.Fatalf(`error, expected string "%s" in body, got body: \n\n%s`, tst.want, body) |
| 414 | } |
| 415 | }) |
| 416 | } |
| 417 | |
| 418 | eWithnoPwdfile, _ := NewRedisExporter(os.Getenv("TEST_PWD_REDIS_URI"), Options{Namespace: "test"}) |
| 419 | ts2 := httptest.NewServer(eWithnoPwdfile) |
| 420 | defer ts2.Close() |
| 421 | |
| 422 | for _, tst := range []struct { |
| 423 | e *Exporter |
| 424 | path string |
| 425 | want string |
| 426 | }{ |
| 427 | { |
| 428 | path: "/-/reload", |
| 429 | want: `There is no pwd file specified`, |
| 430 | }, |
| 431 | } { |
| 432 | t.Run(fmt.Sprintf("path: %s", tst.path), func(t *testing.T) { |
| 433 | body := downloadURL(t, ts2.URL+tst.path) |
| 434 | if !strings.Contains(body, tst.want) { |
| 435 | t.Fatalf(`error, expected string "%s" in body, got body: \n\n%s`, tst.want, body) |
| 436 | } |
| 437 | }) |
| 438 | } |
| 439 | |
| 440 | eWithMalformedPwdfile, _ := NewRedisExporter(os.Getenv("TEST_PWD_REDIS_URI"), Options{Namespace: "test", RedisPwdFile: "../contrib/sample-pwd-file.json-malformed"}) |
| 441 | ts3 := httptest.NewServer(eWithMalformedPwdfile) |
| 442 | defer ts3.Close() |
| 443 | |
| 444 | for _, tst := range []struct { |
| 445 | e *Exporter |
| 446 | path string |
| 447 | want string |
| 448 | }{ |
| 449 | { |
| 450 | path: "/-/reload", |
| 451 | want: `failed to reload passwords file: unexpected end of JSON input`, |
| 452 | }, |
| 453 | } { |
| 454 | t.Run(fmt.Sprintf("path: %s", tst.path), func(t *testing.T) { |
| 455 | body := downloadURL(t, ts3.URL+tst.path) |
| 456 | if !strings.Contains(body, tst.want) { |
| 457 | t.Fatalf(`error, expected string "%s" in body, got body: \n\n%s`, tst.want, body) |
| 458 | } |
| 459 | }) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | func TestIsBasicAuthConfigured(t *testing.T) { |
| 464 | tests := []struct { |
| 465 | name string |
| 466 | username string |
| 467 | password string |
| 468 | want bool |
| 469 | }{ |
| 470 | { |
| 471 | name: "no credentials configured", |
| 472 | username: "", |
| 473 | password: "", |
| 474 | want: false, |
| 475 | }, |
| 476 | { |
| 477 | name: "only username configured", |
| 478 | username: "user", |
| 479 | password: "", |
| 480 | want: false, |
| 481 | }, |
| 482 | { |
| 483 | name: "only password configured", |
| 484 | username: "", |
| 485 | password: "pass", |
| 486 | want: false, |
| 487 | }, |
| 488 | { |
| 489 | name: "both credentials configured", |
| 490 | username: "user", |
| 491 | password: "pass", |
| 492 | want: true, |
| 493 | }, |
| 494 | } |
| 495 | |
| 496 | for _, tt := range tests { |
| 497 | t.Run(tt.name, func(t *testing.T) { |
| 498 | e, _ := NewRedisExporter("", Options{ |
| 499 | BasicAuthUsername: tt.username, |
| 500 | BasicAuthPassword: tt.password, |
| 501 | }) |
| 502 | |
| 503 | if got := e.isBasicAuthConfigured(); got != tt.want { |
| 504 | t.Errorf("isBasicAuthConfigured() = %v, want %v", got, tt.want) |
| 505 | } |
| 506 | }) |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | func TestVerifyBasicAuth(t *testing.T) { |
| 511 | tests := []struct { |
| 512 | name string |
| 513 | configUser string |
| 514 | configPass string |
| 515 | configHashPass string |
| 516 | providedUser string |
| 517 | providedPass string |
| 518 | authHeaderSet bool |
| 519 | wantErr bool |
| 520 | wantErrString string |
| 521 | }{ |
| 522 | { |
| 523 | name: "no auth configured - no credentials provided", |
| 524 | configUser: "", |
| 525 | configPass: "", |
| 526 | providedUser: "", |
| 527 | providedPass: "", |
| 528 | authHeaderSet: false, |
| 529 | wantErr: false, |
| 530 | }, |
| 531 | { |
| 532 | name: "auth configured - no auth header", |
| 533 | configUser: "user", |
| 534 | configPass: "pass", |
| 535 | providedUser: "", |
| 536 | providedPass: "", |
| 537 | authHeaderSet: false, |
| 538 | wantErr: true, |
| 539 | wantErrString: "Unauthorized", |
| 540 | }, |
| 541 | { |
| 542 | name: "auth configured - correct credentials", |
| 543 | configUser: "user", |
| 544 | configPass: "pass", |
| 545 | providedUser: "user", |
| 546 | providedPass: "pass", |
| 547 | authHeaderSet: true, |
| 548 | wantErr: false, |
| 549 | }, |
| 550 | { |
| 551 | name: "auth configured - wrong username", |
| 552 | configUser: "user", |
| 553 | configPass: "pass", |
| 554 | providedUser: "wronguser", |
| 555 | providedPass: "pass", |
| 556 | authHeaderSet: true, |
| 557 | wantErr: true, |
| 558 | wantErrString: "Unauthorized", |
| 559 | }, |
| 560 | { |
| 561 | name: "auth configured - wrong password", |
| 562 | configUser: "user", |
| 563 | configPass: "pass", |
| 564 | providedUser: "user", |
| 565 | providedPass: "wrongpass", |
| 566 | authHeaderSet: true, |
| 567 | wantErr: true, |
| 568 | wantErrString: "Unauthorized", |
| 569 | }, |
| 570 | { |
| 571 | name: "auth configured with hash password - correct credentials", |
| 572 | configUser: "user", |
| 573 | configHashPass: "$2b$12$slCbgjdTTCEZKRvp7fEd3exTXLqvq43kr3bZ6cGUfVLGJTC18SNJO", |
| 574 | providedUser: "user", |
| 575 | providedPass: "pass", |
| 576 | authHeaderSet: true, |
| 577 | wantErr: false, |
| 578 | }, |
| 579 | { |
| 580 | name: "auth configured with hash password - wrong username", |
| 581 | configUser: "user", |
| 582 | configHashPass: "$2b$12$slCbgjdTTCEZKRvp7fEd3exTXLqvq43kr3bZ6cGUfVLGJTC18SNJO", |
| 583 | providedUser: "wronguser", |
| 584 | providedPass: "pass", |
| 585 | authHeaderSet: true, |
| 586 | wantErr: true, |
| 587 | wantErrString: "Unauthorized", |
| 588 | }, |
| 589 | { |
| 590 | name: "auth configured with hash password - wrong password", |
| 591 | configUser: "user", |
| 592 | configHashPass: "$2b$12$slCbgjdTTCEZKRvp7fEd3exTXLqvq43kr3bZ6cGUfVLGJTC18SNJO", |
| 593 | providedUser: "user", |
| 594 | providedPass: "wrongpass", |
| 595 | authHeaderSet: true, |
| 596 | wantErr: true, |
| 597 | wantErrString: "Unauthorized", |
| 598 | }, |
| 599 | } |
| 600 | |
| 601 | for _, tt := range tests { |
| 602 | t.Run(tt.name, func(t *testing.T) { |
| 603 | e, _ := NewRedisExporter("", Options{ |
| 604 | BasicAuthUsername: tt.configUser, |
| 605 | BasicAuthPassword: tt.configPass, |
| 606 | BasicAuthHashPassword: tt.configHashPass, |
| 607 | }) |
| 608 | |
| 609 | err := e.verifyBasicAuth(tt.providedUser, tt.providedPass, tt.authHeaderSet) |
| 610 | |
| 611 | if (err != nil) != tt.wantErr { |
| 612 | t.Errorf("verifyBasicAuth() error = %v, wantErr %v", err, tt.wantErr) |
| 613 | return |
| 614 | } |
| 615 | |
| 616 | if err != nil && err.Error() != tt.wantErrString { |
| 617 | t.Errorf("verifyBasicAuth() error = %v, wantErrString %v", err, tt.wantErrString) |
| 618 | } |
| 619 | }) |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | func TestBasicAuth(t *testing.T) { |
| 624 | if os.Getenv("TEST_REDIS_URI") == "" { |
| 625 | t.Skipf("TEST_REDIS_URI not set - skipping") |
| 626 | } |
| 627 | |
| 628 | tests := []struct { |
| 629 | name string |
| 630 | username string |
| 631 | password string |
| 632 | configUsername string |
| 633 | configPassword string |
| 634 | configHashPassword string |
| 635 | wantStatusCode int |
| 636 | }{ |
| 637 | { |
| 638 | name: "No auth configured - no credentials provided", |
| 639 | username: "", |
| 640 | password: "", |
| 641 | configUsername: "", |
| 642 | configPassword: "", |
| 643 | wantStatusCode: http.StatusOK, |
| 644 | }, |
| 645 | { |
| 646 | name: "Auth configured - correct credentials", |
| 647 | username: "testuser", |
| 648 | password: "testpass", |
| 649 | configUsername: "testuser", |
| 650 | configPassword: "testpass", |
| 651 | wantStatusCode: http.StatusOK, |
| 652 | }, |
| 653 | { |
| 654 | name: "Auth configured - wrong username", |
| 655 | username: "wronguser", |
| 656 | password: "testpass", |
| 657 | configUsername: "testuser", |
| 658 | configPassword: "testpass", |
| 659 | wantStatusCode: http.StatusUnauthorized, |
| 660 | }, |
| 661 | { |
| 662 | name: "Auth configured - wrong password", |
| 663 | username: "testuser", |
| 664 | password: "wrongpass", |
| 665 | configUsername: "testuser", |
| 666 | configPassword: "testpass", |
| 667 | wantStatusCode: http.StatusUnauthorized, |
| 668 | }, |
| 669 | { |
| 670 | name: "Auth configured - no credentials provided", |
| 671 | username: "", |
| 672 | password: "", |
| 673 | configUsername: "testuser", |
| 674 | configPassword: "testpass", |
| 675 | wantStatusCode: http.StatusUnauthorized, |
| 676 | }, |
| 677 | { |
| 678 | name: "Auth configured with hash password - correct credentials", |
| 679 | username: "testuser", |
| 680 | password: "testpass", |
| 681 | configUsername: "testuser", |
| 682 | configHashPassword: "$2b$12$6LXQAFSyKb4lP67Zrk7rtOTyXhpomZZAQbRmvj90mCJ0Lgs3jTmhi", |
| 683 | wantStatusCode: http.StatusOK, |
| 684 | }, |
| 685 | { |
| 686 | name: "Auth configured with hash password - wrong password", |
| 687 | username: "testuser", |
| 688 | password: "wrongpass", |
| 689 | configUsername: "testuser", |
| 690 | configHashPassword: "$2b$12$6LXQAFSyKb4lP67Zrk7rtOTyXhpomZZAQbRmvj90mCJ0Lgs3jTmhi", |
| 691 | wantStatusCode: http.StatusUnauthorized, |
| 692 | }, |
| 693 | { |
| 694 | name: "Auth configured with hash password - wrong username", |
| 695 | username: "wronguser", |
| 696 | password: "testpass", |
| 697 | configUsername: "testuser", |
| 698 | configHashPassword: "$2b$12$6LXQAFSyKb4lP67Zrk7rtOTyXhpomZZAQbRmvj90mCJ0Lgs3jTmhi", |
| 699 | wantStatusCode: http.StatusUnauthorized, |
| 700 | }, |
| 701 | { |
| 702 | name: "Auth configured with hash password - no credentials provided", |
| 703 | username: "", |
| 704 | password: "", |
| 705 | configUsername: "testuser", |
| 706 | configHashPassword: "$2b$12$6LXQAFSyKb4lP67Zrk7rtOTyXhpomZZAQbRmvj90mCJ0Lgs3jTmhi", |
| 707 | wantStatusCode: http.StatusUnauthorized, |
| 708 | }, |
| 709 | } |
| 710 | |
| 711 | for _, tt := range tests { |
| 712 | t.Run(tt.name, func(t *testing.T) { |
| 713 | e, _ := NewRedisExporter(os.Getenv("TEST_REDIS_URI"), Options{ |
| 714 | Namespace: "test", |
| 715 | BasicAuthUsername: tt.configUsername, |
| 716 | BasicAuthPassword: tt.configPassword, |
| 717 | BasicAuthHashPassword: tt.configHashPassword, |
| 718 | }) |
| 719 | ts := httptest.NewServer(e) |
| 720 | defer ts.Close() |
| 721 | |
| 722 | client := &http.Client{} |
| 723 | req, err := http.NewRequest("GET", ts.URL+"/metrics", nil) |
| 724 | if err != nil { |
| 725 | t.Fatalf("Failed to create request: %v", err) |
| 726 | } |
| 727 | |
| 728 | if tt.username != "" || tt.password != "" { |
| 729 | req.SetBasicAuth(tt.username, tt.password) |
| 730 | } |
| 731 | |
| 732 | resp, err := client.Do(req) |
| 733 | if err != nil { |
| 734 | t.Fatalf("Failed to send request: %v", err) |
| 735 | } |
| 736 | defer resp.Body.Close() |
| 737 | |
| 738 | if resp.StatusCode != tt.wantStatusCode { |
| 739 | t.Errorf("Expected status code %d, got %d", tt.wantStatusCode, resp.StatusCode) |
| 740 | } |
| 741 | |
| 742 | body, err := io.ReadAll(resp.Body) |
| 743 | if err != nil { |
| 744 | t.Fatalf("Failed to read response body: %v", err) |
| 745 | } |
| 746 | |
| 747 | if tt.wantStatusCode == http.StatusOK { |
| 748 | if !strings.Contains(string(body), "test_up") { |
| 749 | t.Errorf("Expected body to contain 'test_up', got: %s", string(body)) |
| 750 | } |
| 751 | } else { |
| 752 | if !strings.Contains(resp.Header.Get("WWW-Authenticate"), "Basic realm=\"redis-exporter") { |
| 753 | t.Errorf("Expected WWW-Authenticate header, got: %s", resp.Header.Get("WWW-Authenticate")) |
| 754 | } |
| 755 | } |
| 756 | }) |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | func downloadURL(t *testing.T, u string) string { |
| 761 | _, res := downloadURLWithStatusCode(t, u) |
| 762 | return res |
| 763 | } |
| 764 | |
| 765 | func downloadURLWithStatusCode(t *testing.T, u string) (int, string) { |
| 766 | log.Debugf("downloadURL() %s", u) |
| 767 | |
| 768 | resp, err := http.Get(u) |
| 769 | if err != nil { |
| 770 | t.Fatal(err) |
| 771 | } |
| 772 | defer resp.Body.Close() |
| 773 | body, err := io.ReadAll(resp.Body) |
| 774 | if err != nil { |
| 775 | t.Fatal(err) |
| 776 | } |
| 777 | |
| 778 | return resp.StatusCode, string(body) |
| 779 | } |
| 780 | |
| 781 | func TestScrapeEndpointDisabled(t *testing.T) { |
| 782 | e, _ := NewRedisExporter("", Options{ |
| 783 | Namespace: "test", |
| 784 | DisableScrapeEndpoint: true, |
| 785 | }) |
| 786 | ts := httptest.NewServer(e) |
| 787 | defer ts.Close() |
| 788 | |
| 789 | resp, err := http.Get(ts.URL + "/scrape") |
| 790 | if err != nil { |
| 791 | t.Fatalf("Failed to send request: %v", err) |
| 792 | } |
| 793 | defer resp.Body.Close() |
| 794 | |
| 795 | if resp.StatusCode != http.StatusNotFound { |
| 796 | t.Errorf("Expected status code %d for disabled /scrape endpoint, got %d", http.StatusNotFound, resp.StatusCode) |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | func TestUnknownPathReturns404(t *testing.T) { |
| 801 | e, _ := NewRedisExporter("", Options{ |
| 802 | Namespace: "test", |
| 803 | }) |
| 804 | ts := httptest.NewServer(e) |
| 805 | defer ts.Close() |
| 806 | |
| 807 | paths := []string{ |
| 808 | "/nonexistent", |
| 809 | "/foo/bar", |
| 810 | "/metrics2", |
| 811 | "/scrape2", |
| 812 | "/admin", |
| 813 | } |
| 814 | |
| 815 | for _, path := range paths { |
| 816 | t.Run(path, func(t *testing.T) { |
| 817 | resp, err := http.Get(ts.URL + path) |
| 818 | if err != nil { |
| 819 | t.Fatalf("Failed to send request to %s: %v", path, err) |
| 820 | } |
| 821 | defer resp.Body.Close() |
| 822 | |
| 823 | if resp.StatusCode != http.StatusNotFound { |
| 824 | t.Errorf("Expected 404 for path %s, got %d", path, resp.StatusCode) |
| 825 | } |
| 826 | }) |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | func TestValidateBasicAuthPassword(t *testing.T) { |
| 831 | tests := []struct { |
| 832 | name string |
| 833 | configHashPassword string |
| 834 | configPassword string |
| 835 | inputPassword string |
| 836 | expectStatus bool |
| 837 | }{ |
| 838 | { |
| 839 | name: "Valid password", |
| 840 | configPassword: "password", |
| 841 | inputPassword: "password", |
| 842 | expectStatus: true, |
| 843 | }, { |
| 844 | name: "Invalid password", |
| 845 | configPassword: "password", |
| 846 | inputPassword: "wrongpassword", |
| 847 | expectStatus: false, |
| 848 | }, |
| 849 | { |
| 850 | name: "Valid hash password", |
| 851 | configHashPassword: "$2b$12$ODSJd0tmxY7H/adgD7R5SO43d8nmhUsa8OM6Weo7VFs3MbrsEY7tu", |
| 852 | inputPassword: "password", |
| 853 | expectStatus: true, |
| 854 | }, |
| 855 | { |
| 856 | name: "Invalid bcrypt hash", |
| 857 | configHashPassword: "$2b$12$ODSJd0tmxY7H/adgD7R5SO43d8nmhUsa8OM6Weo7VFs3MbrsEY7tu", |
| 858 | inputPassword: "wrongpassword", |
| 859 | expectStatus: false, |
| 860 | }, |
| 861 | } |
| 862 | |
| 863 | for _, tt := range tests { |
| 864 | t.Run(tt.name, func(t *testing.T) { |
| 865 | e := &Exporter{ |
| 866 | options: Options{ |
| 867 | BasicAuthHashPassword: tt.configHashPassword, |
| 868 | BasicAuthPassword: tt.configPassword, |
| 869 | }, |
| 870 | } |
| 871 | st := e.validateBasicAuthPassword(tt.inputPassword) |
| 872 | if st != tt.expectStatus { |
| 873 | t.Errorf("Expected error: %v, got: %v", tt.expectStatus, st) |
| 874 | } |
| 875 | }) |
| 876 | } |
| 877 | } |