File: metrics_test.go

package info (click to toggle)
golang-k8s-apiserver 0.33.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,660 kB
  • sloc: sh: 236; makefile: 5
file content (271 lines) | stat: -rw-r--r-- 8,950 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package filters

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	auditinternal "k8s.io/apiserver/pkg/apis/audit"
	"k8s.io/apiserver/pkg/authentication/authenticator"
	"k8s.io/apiserver/pkg/authentication/user"
	"k8s.io/apiserver/pkg/authorization/authorizer"
	"k8s.io/component-base/metrics/legacyregistry"
	"k8s.io/component-base/metrics/testutil"
)

func TestMetrics(t *testing.T) {
	// Excluding authentication_duration_seconds since it is difficult to predict its values.
	metrics := []string{
		"authenticated_user_requests",
		"authentication_attempts",
	}

	testCases := []struct {
		desc        string
		response    *authenticator.Response
		status      bool
		err         error
		apiAudience authenticator.Audiences
		want        string
	}{
		{
			desc: "auth ok",
			response: &authenticator.Response{
				User: &user.DefaultInfo{Name: "admin"},
			},
			status: true,
			want: `
				# HELP authenticated_user_requests [ALPHA] Counter of authenticated requests broken out by username.
				# TYPE authenticated_user_requests counter
				authenticated_user_requests{username="admin"} 1
        # HELP authentication_attempts [ALPHA] Counter of authenticated attempts.
        # TYPE authentication_attempts counter
        authentication_attempts{result="success"} 1
				`,
		},
		{
			desc: "auth failed with error",
			err:  errors.New("some error"),
			want: `
        # HELP authentication_attempts [ALPHA] Counter of authenticated attempts.
        # TYPE authentication_attempts counter
        authentication_attempts{result="error"} 1
				`,
		},
		{
			desc: "auth failed with status false",
			want: `
        # HELP authentication_attempts [ALPHA] Counter of authenticated attempts.
        # TYPE authentication_attempts counter
        authentication_attempts{result="failure"} 1
				`,
		},
		{
			desc: "auth failed due to audiences not intersecting",
			response: &authenticator.Response{
				User:      &user.DefaultInfo{Name: "admin"},
				Audiences: authenticator.Audiences{"audience-x"},
			},
			status:      true,
			apiAudience: authenticator.Audiences{"audience-y"},
			want: `
        # HELP authentication_attempts [ALPHA] Counter of authenticated attempts.
        # TYPE authentication_attempts counter
        authentication_attempts{result="error"} 1
				`,
		},
		{
			desc: "audiences not supplied in the response",
			response: &authenticator.Response{
				User: &user.DefaultInfo{Name: "admin"},
			},
			status:      true,
			apiAudience: authenticator.Audiences{"audience-y"},
			want: `
        # HELP authenticated_user_requests [ALPHA] Counter of authenticated requests broken out by username.
				# TYPE authenticated_user_requests counter
				authenticated_user_requests{username="admin"} 1
        # HELP authentication_attempts [ALPHA] Counter of authenticated attempts.
        # TYPE authentication_attempts counter
        authentication_attempts{result="success"} 1
				`,
		},
		{
			desc: "audiences not supplied to the handler",
			response: &authenticator.Response{
				User:      &user.DefaultInfo{Name: "admin"},
				Audiences: authenticator.Audiences{"audience-x"},
			},
			status: true,
			want: `
        # HELP authenticated_user_requests [ALPHA] Counter of authenticated requests broken out by username.
				# TYPE authenticated_user_requests counter
				authenticated_user_requests{username="admin"} 1
        # HELP authentication_attempts [ALPHA] Counter of authenticated attempts.
        # TYPE authentication_attempts counter
        authentication_attempts{result="success"} 1
				`,
		},
	}

	// Since prometheus' gatherer is global, other tests may have updated metrics already, so
	// we need to reset them prior running this test.
	// This also implies that we can't run this test in parallel with other auth tests.
	authenticatedUserCounter.Reset()
	authenticatedAttemptsCounter.Reset()

	for _, tt := range testCases {
		t.Run(tt.desc, func(t *testing.T) {
			defer authenticatedUserCounter.Reset()
			defer authenticatedAttemptsCounter.Reset()
			done := make(chan struct{})
			auth := WithAuthentication(
				http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
					close(done)
				}),
				authenticator.RequestFunc(func(_ *http.Request) (*authenticator.Response, bool, error) {
					return tt.response, tt.status, tt.err
				}),
				http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
					close(done)
				}),
				tt.apiAudience,
				nil,
			)

			auth.ServeHTTP(httptest.NewRecorder(), &http.Request{})
			<-done

			if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tt.want), metrics...); err != nil {
				t.Fatal(err)
			}
		})
	}
}

func TestRecordAuthorizationMetricsMetrics(t *testing.T) {
	// Excluding authorization_duration_seconds since it is difficult to predict its values.
	metrics := []string{
		"authorization_attempts_total",
		"authorization_decision_annotations_total",
	}

	testCases := []struct {
		desc       string
		authorizer fakeAuthorizer
		want       string
	}{
		{
			desc: "auth ok",
			authorizer: fakeAuthorizer{
				authorizer.DecisionAllow,
				"RBAC: allowed to patch pod",
				nil,
			},
			want: `
			# HELP authorization_attempts_total [ALPHA] Counter of authorization attempts broken down by result. It can be either 'allowed', 'denied', 'no-opinion' or 'error'.
			# TYPE authorization_attempts_total counter
			authorization_attempts_total{result="allowed"} 1
				`,
		},
		{
			desc: "decision forbid",
			authorizer: fakeAuthorizer{
				authorizer.DecisionDeny,
				"RBAC: not allowed to patch pod",
				nil,
			},
			want: `
			# HELP authorization_attempts_total [ALPHA] Counter of authorization attempts broken down by result. It can be either 'allowed', 'denied', 'no-opinion' or 'error'.
			# TYPE authorization_attempts_total counter
			authorization_attempts_total{result="denied"} 1
				`,
		},
		{
			desc: "authorizer failed with error",
			authorizer: fakeAuthorizer{
				authorizer.DecisionNoOpinion,
				"",
				errors.New("can't parse user info"),
			},
			want: `
			# HELP authorization_attempts_total [ALPHA] Counter of authorization attempts broken down by result. It can be either 'allowed', 'denied', 'no-opinion' or 'error'.
			# TYPE authorization_attempts_total counter
			authorization_attempts_total{result="error"} 1
				`,
		},
		{
			desc: "authorizer decided allow with error",
			authorizer: fakeAuthorizer{
				authorizer.DecisionAllow,
				"",
				errors.New("can't parse user info"),
			},
			want: `
			# HELP authorization_attempts_total [ALPHA] Counter of authorization attempts broken down by result. It can be either 'allowed', 'denied', 'no-opinion' or 'error'.
			# TYPE authorization_attempts_total counter
			authorization_attempts_total{result="allowed"} 1
				`,
		},
		{
			desc: "authorizer failed with error",
			authorizer: fakeAuthorizer{
				authorizer.DecisionNoOpinion,
				"",
				nil,
			},
			want: `
			# HELP authorization_attempts_total [ALPHA] Counter of authorization attempts broken down by result. It can be either 'allowed', 'denied', 'no-opinion' or 'error'.
			# TYPE authorization_attempts_total counter
			authorization_attempts_total{result="no-opinion"} 1
				`,
		},
	}

	// Since prometheus' gatherer is global, other tests may have updated metrics already, so
	// we need to reset them prior running this test.
	// This also implies that we can't run this test in parallel with other auth tests.
	authorizationAttemptsCounter.Reset()

	scheme := runtime.NewScheme()
	negotiatedSerializer := serializer.NewCodecFactory(scheme).WithoutConversion()

	for _, tt := range testCases {
		t.Run(tt.desc, func(t *testing.T) {
			defer authorizationAttemptsCounter.Reset()

			audit := &auditinternal.Event{Level: auditinternal.LevelMetadata}
			handler := WithAuthorization(&fakeHTTPHandler{}, tt.authorizer, negotiatedSerializer)
			// TODO: fake audit injector

			req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil)
			req = withTestContext(req, nil, audit)
			req.RemoteAddr = "127.0.0.1"
			handler.ServeHTTP(httptest.NewRecorder(), req)

			if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tt.want), metrics...); err != nil {
				t.Fatal(err)
			}
		})
	}
}