1// Copyright 2020 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package httputil
16
17import (
18	"net/http"
19	"net/http/httptest"
20	"testing"
21)
22
23func TestWrapHandlerInBasicAuth(t *testing.T) {
24	type args struct {
25		h http.Handler
26		b BasicAuth
27	}
28
29	dummyHandler := http.HandlerFunc(func(h http.ResponseWriter, r *http.Request) {
30		h.WriteHeader(http.StatusOK)
31	})
32
33	tests := []struct {
34		name    string
35		args    args
36		want    int
37		reqAuth bool
38	}{
39		{
40			name:    "no user or password setup",
41			args:    args{h: dummyHandler},
42			want:    http.StatusOK,
43			reqAuth: false,
44		},
45		{
46			name: "only user set",
47			args: args{
48				h: dummyHandler,
49				b: BasicAuth{Username: "test"}, // no basic auth
50			},
51			want:    http.StatusOK,
52			reqAuth: false,
53		},
54		{
55			name: "only pass set",
56			args: args{
57				h: dummyHandler,
58				b: BasicAuth{Password: "test"}, // no basic auth
59			},
60			want:    http.StatusOK,
61			reqAuth: false,
62		},
63		{
64			name: "credentials correct",
65			args: args{
66				h: dummyHandler,
67				b: BasicAuth{Username: "test", Password: "test"}, // basic auth enabled
68			},
69			want:    http.StatusOK,
70			reqAuth: true,
71		},
72		{
73			name: "credentials wrong",
74			args: args{
75				h: dummyHandler,
76				b: BasicAuth{Username: "test1", Password: "test"}, // basic auth enabled
77			},
78			want:    http.StatusForbidden,
79			reqAuth: true,
80		},
81		{
82			name: "no basic auth in request",
83			args: args{
84				h: dummyHandler,
85				b: BasicAuth{Username: "test", Password: "test"}, // basic auth enabled
86			},
87			want:    http.StatusForbidden,
88			reqAuth: false,
89		},
90	}
91	for _, tt := range tests {
92		t.Run(tt.name, func(t *testing.T) {
93			baHandler := WrapHandlerInBasicAuth(tt.args.h, tt.args.b)
94
95			req := httptest.NewRequest("GET", "http://localhost/metrics", nil)
96			if tt.reqAuth {
97				req.SetBasicAuth("test", "test")
98			}
99
100			w := httptest.NewRecorder()
101			baHandler(w, req)
102			resp := w.Result()
103
104			if resp.StatusCode != tt.want {
105				t.Errorf("Expected status code %d, got %d", resp.StatusCode, tt.want)
106			}
107		})
108	}
109}
110