github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/tools/querytee/proxy_backend_test.go (about)

     1  package querytee
     2  
     3  import (
     4  	"fmt"
     5  	"net/http/httptest"
     6  	"net/url"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func Test_ProxyBackend_createBackendRequest_HTTPBasicAuthentication(t *testing.T) {
    15  	tests := map[string]struct {
    16  		clientUser   string
    17  		clientPass   string
    18  		backendUser  string
    19  		backendPass  string
    20  		expectedUser string
    21  		expectedPass string
    22  	}{
    23  		"no auth": {
    24  			expectedUser: "",
    25  			expectedPass: "",
    26  		},
    27  		"if the request is authenticated and the backend has no auth it should forward the request auth": {
    28  			clientUser:   "marco",
    29  			clientPass:   "marco-secret",
    30  			expectedUser: "marco",
    31  			expectedPass: "marco-secret",
    32  		},
    33  		"if the request is authenticated and the backend has an username set it should forward the request password only": {
    34  			clientUser:   "marco",
    35  			clientPass:   "marco-secret",
    36  			backendUser:  "backend",
    37  			expectedUser: "backend",
    38  			expectedPass: "marco-secret",
    39  		},
    40  		"if the request is authenticated and the backend is authenticated it should use the backend auth": {
    41  			clientUser:   "marco",
    42  			clientPass:   "marco-secret",
    43  			backendUser:  "backend",
    44  			backendPass:  "backend-secret",
    45  			expectedUser: "backend",
    46  			expectedPass: "backend-secret",
    47  		},
    48  		"if the request is NOT authenticated and the backend is authenticated it should use the backend auth": {
    49  			backendUser:  "backend",
    50  			backendPass:  "backend-secret",
    51  			expectedUser: "backend",
    52  			expectedPass: "backend-secret",
    53  		},
    54  	}
    55  
    56  	for testName, testData := range tests {
    57  		t.Run(testName, func(t *testing.T) {
    58  			u, err := url.Parse(fmt.Sprintf("http://%s:%s@test", testData.backendUser, testData.backendPass))
    59  			require.NoError(t, err)
    60  
    61  			orig := httptest.NewRequest("GET", "/test", nil)
    62  			orig.SetBasicAuth(testData.clientUser, testData.clientPass)
    63  
    64  			b := NewProxyBackend("test", u, time.Second, false)
    65  			r, err := b.createBackendRequest(orig)
    66  			require.NoError(t, err)
    67  
    68  			actualUser, actualPass, _ := r.BasicAuth()
    69  			assert.Equal(t, testData.expectedUser, actualUser)
    70  			assert.Equal(t, testData.expectedPass, actualPass)
    71  		})
    72  	}
    73  }