|
| 1 | +// Copyright 2021 The Prometheus Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package web |
| 15 | + |
| 16 | +import ( |
| 17 | + "context" |
| 18 | + "net/http" |
| 19 | + "sync" |
| 20 | + "testing" |
| 21 | +) |
| 22 | + |
| 23 | +// TestBasicAuthCache validates that the cache is working by calling a password |
| 24 | +// protected endpoint multiple times. |
| 25 | +func TestBasicAuthCache(t *testing.T) { |
| 26 | + server := &http.Server{ |
| 27 | + Addr: port, |
| 28 | + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 29 | + w.Write([]byte("Hello World!")) |
| 30 | + }), |
| 31 | + } |
| 32 | + |
| 33 | + done := make(chan struct{}) |
| 34 | + t.Cleanup(func() { |
| 35 | + if err := server.Shutdown(context.Background()); err != nil { |
| 36 | + t.Fatal(err) |
| 37 | + } |
| 38 | + <-done |
| 39 | + }) |
| 40 | + |
| 41 | + go func() { |
| 42 | + ListenAndServe(server, "testdata/tls_config_users_noTLS.good.yml", testlogger) |
| 43 | + close(done) |
| 44 | + }() |
| 45 | + |
| 46 | + login := func(username, password string, code int) { |
| 47 | + client := &http.Client{} |
| 48 | + req, err := http.NewRequest("GET", "http://localhost"+port, nil) |
| 49 | + if err != nil { |
| 50 | + t.Fatal(err) |
| 51 | + } |
| 52 | + req.SetBasicAuth(username, password) |
| 53 | + r, err := client.Do(req) |
| 54 | + if err != nil { |
| 55 | + t.Fatal(err) |
| 56 | + } |
| 57 | + if r.StatusCode != code { |
| 58 | + t.Fatalf("bad return code, expected %d, got %d", code, r.StatusCode) |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Initial logins, checking that it just works. |
| 63 | + login("alice", "alice123", 200) |
| 64 | + login("alice", "alice1234", 401) |
| 65 | + |
| 66 | + var ( |
| 67 | + start = make(chan struct{}) |
| 68 | + wg sync.WaitGroup |
| 69 | + ) |
| 70 | + wg.Add(300) |
| 71 | + for i := 0; i < 150; i++ { |
| 72 | + go func() { |
| 73 | + <-start |
| 74 | + login("alice", "alice123", 200) |
| 75 | + wg.Done() |
| 76 | + }() |
| 77 | + go func() { |
| 78 | + <-start |
| 79 | + login("alice", "alice1234", 401) |
| 80 | + wg.Done() |
| 81 | + }() |
| 82 | + } |
| 83 | + close(start) |
| 84 | + wg.Wait() |
| 85 | +} |
0 commit comments