| 1 |
/* |
| 2 |
Copyright 2016 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package webhook |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"crypto/tls" |
| 22 |
"crypto/x509" |
| 23 |
"encoding/json" |
| 24 |
"fmt" |
| 25 |
"io/ioutil" |
| 26 |
"net/http" |
| 27 |
"net/http/httptest" |
| 28 |
"net/url" |
| 29 |
"os" |
| 30 |
"path/filepath" |
| 31 |
"reflect" |
| 32 |
"strings" |
| 33 |
"testing" |
| 34 |
"text/template" |
| 35 |
"time" |
| 36 |
|
| 37 |
"github.com/google/go-cmp/cmp" |
| 38 |
|
| 39 |
authorizationv1 "k8s.io/api/authorization/v1" |
| 40 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 41 |
"k8s.io/apimachinery/pkg/fields" |
| 42 |
"k8s.io/apimachinery/pkg/labels" |
| 43 |
"k8s.io/apimachinery/pkg/selection" |
| 44 |
"k8s.io/apimachinery/pkg/util/wait" |
| 45 |
"k8s.io/apiserver/pkg/apis/apiserver" |
| 46 |
"k8s.io/apiserver/pkg/authentication/user" |
| 47 |
"k8s.io/apiserver/pkg/authorization/authorizer" |
| 48 |
authorizationcel "k8s.io/apiserver/pkg/authorization/cel" |
| 49 |
"k8s.io/apiserver/pkg/features" |
| 50 |
utilfeature "k8s.io/apiserver/pkg/util/feature" |
| 51 |
webhookutil "k8s.io/apiserver/pkg/util/webhook" |
| 52 |
"k8s.io/apiserver/plugin/pkg/authorizer/webhook/metrics" |
| 53 |
v1 "k8s.io/client-go/tools/clientcmd/api/v1" |
| 54 |
utiltesting "k8s.io/client-go/util/testing" |
| 55 |
featuregatetesting "k8s.io/component-base/featuregate/testing" |
| 56 |
"k8s.io/component-base/metrics/legacyregistry" |
| 57 |
"k8s.io/component-base/metrics/testutil" |
| 58 |
) |
| 59 |
|
| 60 |
var testRetryBackoff = wait.Backoff{ |
| 61 |
Duration: 5 * time.Millisecond, |
| 62 |
Factor: 1.5, |
| 63 |
Jitter: 0.2, |
| 64 |
Steps: 5, |
| 65 |
} |
| 66 |
|
| 67 |
func TestV1NewFromConfig(t *testing.T) { |
| 68 |
dir, err := ioutil.TempDir("", "") |
| 69 |
if err != nil { |
| 70 |
t.Fatal(err) |
| 71 |
} |
| 72 |
defer os.RemoveAll(dir) |
| 73 |
|
| 74 |
data := struct { |
| 75 |
CA string |
| 76 |
Cert string |
| 77 |
Key string |
| 78 |
}{ |
| 79 |
CA: filepath.Join(dir, "ca.pem"), |
| 80 |
Cert: filepath.Join(dir, "clientcert.pem"), |
| 81 |
Key: filepath.Join(dir, "clientkey.pem"), |
| 82 |
} |
| 83 |
|
| 84 |
files := []struct { |
| 85 |
name string |
| 86 |
data []byte |
| 87 |
}{ |
| 88 |
{data.CA, caCert}, |
| 89 |
{data.Cert, clientCert}, |
| 90 |
{data.Key, clientKey}, |
| 91 |
} |
| 92 |
for _, file := range files { |
| 93 |
if err := ioutil.WriteFile(file.name, file.data, 0400); err != nil { |
| 94 |
t.Fatal(err) |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
tests := []struct { |
| 99 |
msg string |
| 100 |
configTmpl string |
| 101 |
wantErr bool |
| 102 |
}{ |
| 103 |
{ |
| 104 |
msg: "a single cluster and single user", |
| 105 |
configTmpl: ` |
| 106 |
clusters: |
| 107 |
- cluster: |
| 108 |
certificate-authority: {{ .CA }} |
| 109 |
server: https://authz.example.com |
| 110 |
name: foobar |
| 111 |
users: |
| 112 |
- name: a cluster |
| 113 |
user: |
| 114 |
client-certificate: {{ .Cert }} |
| 115 |
client-key: {{ .Key }} |
| 116 |
`, |
| 117 |
wantErr: true, |
| 118 |
}, |
| 119 |
{ |
| 120 |
msg: "multiple clusters with no context", |
| 121 |
configTmpl: ` |
| 122 |
clusters: |
| 123 |
- cluster: |
| 124 |
certificate-authority: {{ .CA }} |
| 125 |
server: https://authz.example.com |
| 126 |
name: foobar |
| 127 |
- cluster: |
| 128 |
certificate-authority: a bad certificate path |
| 129 |
server: https://authz.example.com |
| 130 |
name: barfoo |
| 131 |
users: |
| 132 |
- name: a name |
| 133 |
user: |
| 134 |
client-certificate: {{ .Cert }} |
| 135 |
client-key: {{ .Key }} |
| 136 |
`, |
| 137 |
wantErr: true, |
| 138 |
}, |
| 139 |
{ |
| 140 |
msg: "multiple clusters with a context", |
| 141 |
configTmpl: ` |
| 142 |
clusters: |
| 143 |
- cluster: |
| 144 |
certificate-authority: a bad certificate path |
| 145 |
server: https://authz.example.com |
| 146 |
name: foobar |
| 147 |
- cluster: |
| 148 |
certificate-authority: {{ .CA }} |
| 149 |
server: https://authz.example.com |
| 150 |
name: barfoo |
| 151 |
users: |
| 152 |
- name: a name |
| 153 |
user: |
| 154 |
client-certificate: {{ .Cert }} |
| 155 |
client-key: {{ .Key }} |
| 156 |
contexts: |
| 157 |
- name: default |
| 158 |
context: |
| 159 |
cluster: barfoo |
| 160 |
user: a name |
| 161 |
current-context: default |
| 162 |
`, |
| 163 |
wantErr: false, |
| 164 |
}, |
| 165 |
{ |
| 166 |
msg: "cluster with bad certificate path specified", |
| 167 |
configTmpl: ` |
| 168 |
clusters: |
| 169 |
- cluster: |
| 170 |
certificate-authority: a bad certificate path |
| 171 |
server: https://authz.example.com |
| 172 |
name: foobar |
| 173 |
- cluster: |
| 174 |
certificate-authority: {{ .CA }} |
| 175 |
server: https://authz.example.com |
| 176 |
name: barfoo |
| 177 |
users: |
| 178 |
- name: a name |
| 179 |
user: |
| 180 |
client-certificate: {{ .Cert }} |
| 181 |
client-key: {{ .Key }} |
| 182 |
contexts: |
| 183 |
- name: default |
| 184 |
context: |
| 185 |
cluster: foobar |
| 186 |
user: a name |
| 187 |
current-context: default |
| 188 |
`, |
| 189 |
wantErr: true, |
| 190 |
}, |
| 191 |
} |
| 192 |
|
| 193 |
for _, tt := range tests { |
| 194 |
// Use a closure so defer statements trigger between loop iterations. |
| 195 |
err := func() error { |
| 196 |
tempfile, err := ioutil.TempFile("", "") |
| 197 |
if err != nil { |
| 198 |
return err |
| 199 |
} |
| 200 |
p := tempfile.Name() |
| 201 |
defer utiltesting.CloseAndRemove(t, tempfile) |
| 202 |
|
| 203 |
tmpl, err := template.New("test").Parse(tt.configTmpl) |
| 204 |
if err != nil { |
| 205 |
return fmt.Errorf("failed to parse test template: %v", err) |
| 206 |
} |
| 207 |
if err := tmpl.Execute(tempfile, data); err != nil { |
| 208 |
return fmt.Errorf("failed to execute test template: %v", err) |
| 209 |
} |
| 210 |
// Create a new authorizer |
| 211 |
clientConfig, err := webhookutil.LoadKubeconfig(p, nil) |
| 212 |
if err != nil { |
| 213 |
return err |
| 214 |
} |
| 215 |
sarClient, err := subjectAccessReviewInterfaceFromConfig(clientConfig, "v1", testRetryBackoff) |
| 216 |
if err != nil { |
| 217 |
return fmt.Errorf("error building sar client: %v", err) |
| 218 |
} |
| 219 |
_, err = newWithBackoff(sarClient, 0, 0, testRetryBackoff, authorizer.DecisionNoOpinion, []apiserver.WebhookMatchCondition{}, noopAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), "") |
| 220 |
return err |
| 221 |
}() |
| 222 |
if err != nil && !tt.wantErr { |
| 223 |
t.Errorf("failed to load plugin from config %q: %v", tt.msg, err) |
| 224 |
} |
| 225 |
if err == nil && tt.wantErr { |
| 226 |
t.Errorf("wanted an error when loading config, did not get one: %q", tt.msg) |
| 227 |
} |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
// V1Service mocks a remote service. |
| 232 |
type V1Service interface { |
| 233 |
Review(*authorizationv1.SubjectAccessReview) |
| 234 |
HTTPStatusCode() int |
| 235 |
} |
| 236 |
|
| 237 |
// NewV1TestServer wraps a V1Service as an httptest.Server. |
| 238 |
func NewV1TestServer(s V1Service, cert, key, caCert []byte) (*httptest.Server, error) { |
| 239 |
const webhookPath = "/testserver" |
| 240 |
var tlsConfig *tls.Config |
| 241 |
if cert != nil { |
| 242 |
cert, err := tls.X509KeyPair(cert, key) |
| 243 |
if err != nil { |
| 244 |
return nil, err |
| 245 |
} |
| 246 |
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}} |
| 247 |
} |
| 248 |
|
| 249 |
if caCert != nil { |
| 250 |
rootCAs := x509.NewCertPool() |
| 251 |
rootCAs.AppendCertsFromPEM(caCert) |
| 252 |
if tlsConfig == nil { |
| 253 |
tlsConfig = &tls.Config{} |
| 254 |
} |
| 255 |
tlsConfig.ClientCAs = rootCAs |
| 256 |
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert |
| 257 |
} |
| 258 |
|
| 259 |
serveHTTP := func(w http.ResponseWriter, r *http.Request) { |
| 260 |
if r.Method != "POST" { |
| 261 |
http.Error(w, fmt.Sprintf("unexpected method: %v", r.Method), http.StatusMethodNotAllowed) |
| 262 |
return |
| 263 |
} |
| 264 |
if r.URL.Path != webhookPath { |
| 265 |
http.Error(w, fmt.Sprintf("unexpected path: %v", r.URL.Path), http.StatusNotFound) |
| 266 |
return |
| 267 |
} |
| 268 |
|
| 269 |
var review authorizationv1.SubjectAccessReview |
| 270 |
bodyData, _ := ioutil.ReadAll(r.Body) |
| 271 |
if err := json.Unmarshal(bodyData, &review); err != nil { |
| 272 |
http.Error(w, fmt.Sprintf("failed to decode body: %v", err), http.StatusBadRequest) |
| 273 |
return |
| 274 |
} |
| 275 |
|
| 276 |
// ensure we received the serialized review as expected |
| 277 |
if review.APIVersion != "authorization.k8s.io/v1" { |
| 278 |
http.Error(w, fmt.Sprintf("wrong api version: %s", string(bodyData)), http.StatusBadRequest) |
| 279 |
return |
| 280 |
} |
| 281 |
// once we have a successful request, always call the review to record that we were called |
| 282 |
s.Review(&review) |
| 283 |
if s.HTTPStatusCode() < 200 || s.HTTPStatusCode() >= 300 { |
| 284 |
http.Error(w, "HTTP Error", s.HTTPStatusCode()) |
| 285 |
return |
| 286 |
} |
| 287 |
type status struct { |
| 288 |
Allowed bool `json:"allowed"` |
| 289 |
Reason string `json:"reason"` |
| 290 |
EvaluationError string `json:"evaluationError"` |
| 291 |
} |
| 292 |
resp := struct { |
| 293 |
APIVersion string `json:"apiVersion"` |
| 294 |
Status status `json:"status"` |
| 295 |
}{ |
| 296 |
APIVersion: authorizationv1.SchemeGroupVersion.String(), |
| 297 |
Status: status{review.Status.Allowed, review.Status.Reason, review.Status.EvaluationError}, |
| 298 |
} |
| 299 |
w.Header().Set("Content-Type", "application/json") |
| 300 |
json.NewEncoder(w).Encode(resp) |
| 301 |
} |
| 302 |
|
| 303 |
server := httptest.NewUnstartedServer(http.HandlerFunc(serveHTTP)) |
| 304 |
server.TLS = tlsConfig |
| 305 |
server.StartTLS() |
| 306 |
|
| 307 |
// Adjust the path to point to our custom path |
| 308 |
serverURL, _ := url.Parse(server.URL) |
| 309 |
serverURL.Path = webhookPath |
| 310 |
server.URL = serverURL.String() |
| 311 |
|
| 312 |
return server, nil |
| 313 |
} |
| 314 |
|
| 315 |
// A service that can be set to allow all or deny all authorization requests. |
| 316 |
type mockV1Service struct { |
| 317 |
allow bool |
| 318 |
statusCode int |
| 319 |
called int |
| 320 |
|
| 321 |
// reviewHook is called just before returning from the Review() method |
| 322 |
reviewHook func(*authorizationv1.SubjectAccessReview) |
| 323 |
} |
| 324 |
|
| 325 |
func (m *mockV1Service) Review(r *authorizationv1.SubjectAccessReview) { |
| 326 |
m.called++ |
| 327 |
r.Status.Allowed = m.allow |
| 328 |
|
| 329 |
if m.reviewHook != nil { |
| 330 |
m.reviewHook(r) |
| 331 |
} |
| 332 |
} |
| 333 |
func (m *mockV1Service) Allow() { m.allow = true } |
| 334 |
func (m *mockV1Service) Deny() { m.allow = false } |
| 335 |
func (m *mockV1Service) HTTPStatusCode() int { return m.statusCode } |
| 336 |
|
| 337 |
// newV1Authorizer creates a temporary kubeconfig file from the provided arguments and attempts to load |
| 338 |
// a new WebhookAuthorizer from it. |
| 339 |
func newV1Authorizer(callbackURL string, clientCert, clientKey, ca []byte, cacheTime time.Duration, metrics metrics.AuthorizerMetrics, compiler authorizationcel.Compiler, expressions []apiserver.WebhookMatchCondition, authzName string) (*WebhookAuthorizer, error) { |
| 340 |
tempfile, err := ioutil.TempFile("", "") |
| 341 |
if err != nil { |
| 342 |
return nil, err |
| 343 |
} |
| 344 |
p := tempfile.Name() |
| 345 |
defer os.Remove(p) |
| 346 |
config := v1.Config{ |
| 347 |
Clusters: []v1.NamedCluster{ |
| 348 |
{ |
| 349 |
Cluster: v1.Cluster{Server: callbackURL, CertificateAuthorityData: ca}, |
| 350 |
}, |
| 351 |
}, |
| 352 |
AuthInfos: []v1.NamedAuthInfo{ |
| 353 |
{ |
| 354 |
AuthInfo: v1.AuthInfo{ClientCertificateData: clientCert, ClientKeyData: clientKey}, |
| 355 |
}, |
| 356 |
}, |
| 357 |
} |
| 358 |
if err := json.NewEncoder(tempfile).Encode(config); err != nil { |
| 359 |
return nil, err |
| 360 |
} |
| 361 |
clientConfig, err := webhookutil.LoadKubeconfig(p, nil) |
| 362 |
if err != nil { |
| 363 |
return nil, err |
| 364 |
} |
| 365 |
sarClient, err := subjectAccessReviewInterfaceFromConfig(clientConfig, "v1", testRetryBackoff) |
| 366 |
if err != nil { |
| 367 |
return nil, fmt.Errorf("error building sar client: %v", err) |
| 368 |
} |
| 369 |
return newWithBackoff(sarClient, cacheTime, cacheTime, testRetryBackoff, authorizer.DecisionNoOpinion, expressions, metrics, compiler, authzName) |
| 370 |
} |
| 371 |
|
| 372 |
func TestV1TLSConfig(t *testing.T) { |
| 373 |
tests := []struct { |
| 374 |
test string |
| 375 |
clientCert, clientKey, clientCA []byte |
| 376 |
serverCert, serverKey, serverCA []byte |
| 377 |
wantAuth, wantErr bool |
| 378 |
}{ |
| 379 |
{ |
| 380 |
test: "TLS setup between client and server", |
| 381 |
clientCert: clientCert, clientKey: clientKey, clientCA: caCert, |
| 382 |
serverCert: serverCert, serverKey: serverKey, serverCA: caCert, |
| 383 |
wantAuth: true, |
| 384 |
}, |
| 385 |
{ |
| 386 |
test: "Server does not require client auth", |
| 387 |
clientCA: caCert, |
| 388 |
serverCert: serverCert, serverKey: serverKey, |
| 389 |
wantAuth: true, |
| 390 |
}, |
| 391 |
{ |
| 392 |
test: "Server does not require client auth, client provides it", |
| 393 |
clientCert: clientCert, clientKey: clientKey, clientCA: caCert, |
| 394 |
serverCert: serverCert, serverKey: serverKey, |
| 395 |
wantAuth: true, |
| 396 |
}, |
| 397 |
{ |
| 398 |
test: "Client does not trust server", |
| 399 |
clientCert: clientCert, clientKey: clientKey, |
| 400 |
serverCert: serverCert, serverKey: serverKey, |
| 401 |
wantErr: true, |
| 402 |
}, |
| 403 |
{ |
| 404 |
test: "Server does not trust client", |
| 405 |
clientCert: clientCert, clientKey: clientKey, clientCA: caCert, |
| 406 |
serverCert: serverCert, serverKey: serverKey, serverCA: badCACert, |
| 407 |
wantErr: true, |
| 408 |
}, |
| 409 |
{ |
| 410 |
// Plugin does not support insecure configurations. |
| 411 |
test: "Server is using insecure connection", |
| 412 |
wantErr: true, |
| 413 |
}, |
| 414 |
} |
| 415 |
for _, tt := range tests { |
| 416 |
// Use a closure so defer statements trigger between loop iterations. |
| 417 |
func() { |
| 418 |
service := new(mockV1Service) |
| 419 |
service.statusCode = 200 |
| 420 |
|
| 421 |
server, err := NewV1TestServer(service, tt.serverCert, tt.serverKey, tt.serverCA) |
| 422 |
if err != nil { |
| 423 |
t.Errorf("%s: failed to create server: %v", tt.test, err) |
| 424 |
return |
| 425 |
} |
| 426 |
defer server.Close() |
| 427 |
|
| 428 |
wh, err := newV1Authorizer(server.URL, tt.clientCert, tt.clientKey, tt.clientCA, 0, noopAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), []apiserver.WebhookMatchCondition{}, "") |
| 429 |
if err != nil { |
| 430 |
t.Errorf("%s: failed to create client: %v", tt.test, err) |
| 431 |
return |
| 432 |
} |
| 433 |
|
| 434 |
attr := authorizer.AttributesRecord{User: &user.DefaultInfo{}} |
| 435 |
|
| 436 |
// Allow all and see if we get an error. |
| 437 |
service.Allow() |
| 438 |
decision, _, err := wh.Authorize(context.Background(), attr) |
| 439 |
if tt.wantAuth { |
| 440 |
if decision != authorizer.DecisionAllow { |
| 441 |
t.Errorf("expected successful authorization") |
| 442 |
} |
| 443 |
} else { |
| 444 |
if decision == authorizer.DecisionAllow { |
| 445 |
t.Errorf("expected failed authorization") |
| 446 |
} |
| 447 |
} |
| 448 |
if tt.wantErr { |
| 449 |
if err == nil { |
| 450 |
t.Errorf("expected error making authorization request: %v", err) |
| 451 |
} |
| 452 |
return |
| 453 |
} |
| 454 |
if err != nil { |
| 455 |
t.Errorf("%s: failed to authorize with AllowAll policy: %v", tt.test, err) |
| 456 |
return |
| 457 |
} |
| 458 |
|
| 459 |
service.Deny() |
| 460 |
if decision, _, _ := wh.Authorize(context.Background(), attr); decision == authorizer.DecisionAllow { |
| 461 |
t.Errorf("%s: incorrectly authorized with DenyAll policy", tt.test) |
| 462 |
} |
| 463 |
}() |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
// recorderV1Service records all access review requests. |
| 468 |
type recorderV1Service struct { |
| 469 |
last authorizationv1.SubjectAccessReview |
| 470 |
err error |
| 471 |
} |
| 472 |
|
| 473 |
func (rec *recorderV1Service) Review(r *authorizationv1.SubjectAccessReview) { |
| 474 |
rec.last = authorizationv1.SubjectAccessReview{} |
| 475 |
rec.last = *r |
| 476 |
r.Status.Allowed = true |
| 477 |
} |
| 478 |
|
| 479 |
func (rec *recorderV1Service) Last() (authorizationv1.SubjectAccessReview, error) { |
| 480 |
return rec.last, rec.err |
| 481 |
} |
| 482 |
|
| 483 |
func (rec *recorderV1Service) HTTPStatusCode() int { return 200 } |
| 484 |
|
| 485 |
func TestV1Webhook(t *testing.T) { |
| 486 |
serv := new(recorderV1Service) |
| 487 |
s, err := NewV1TestServer(serv, serverCert, serverKey, caCert) |
| 488 |
if err != nil { |
| 489 |
t.Fatal(err) |
| 490 |
} |
| 491 |
defer s.Close() |
| 492 |
|
| 493 |
wh, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 0, noopAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), []apiserver.WebhookMatchCondition{}, "") |
| 494 |
if err != nil { |
| 495 |
t.Fatal(err) |
| 496 |
} |
| 497 |
|
| 498 |
expTypeMeta := metav1.TypeMeta{ |
| 499 |
APIVersion: "authorization.k8s.io/v1", |
| 500 |
Kind: "SubjectAccessReview", |
| 501 |
} |
| 502 |
|
| 503 |
tests := []struct { |
| 504 |
attr authorizer.Attributes |
| 505 |
want authorizationv1.SubjectAccessReview |
| 506 |
}{ |
| 507 |
{ |
| 508 |
attr: authorizer.AttributesRecord{User: &user.DefaultInfo{}}, |
| 509 |
want: authorizationv1.SubjectAccessReview{ |
| 510 |
TypeMeta: expTypeMeta, |
| 511 |
Spec: authorizationv1.SubjectAccessReviewSpec{ |
| 512 |
NonResourceAttributes: &authorizationv1.NonResourceAttributes{}, |
| 513 |
}, |
| 514 |
}, |
| 515 |
}, |
| 516 |
{ |
| 517 |
attr: authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "jane"}}, |
| 518 |
want: authorizationv1.SubjectAccessReview{ |
| 519 |
TypeMeta: expTypeMeta, |
| 520 |
Spec: authorizationv1.SubjectAccessReviewSpec{ |
| 521 |
User: "jane", |
| 522 |
NonResourceAttributes: &authorizationv1.NonResourceAttributes{}, |
| 523 |
}, |
| 524 |
}, |
| 525 |
}, |
| 526 |
{ |
| 527 |
attr: authorizer.AttributesRecord{ |
| 528 |
User: &user.DefaultInfo{ |
| 529 |
Name: "jane", |
| 530 |
UID: "1", |
| 531 |
Groups: []string{"group1", "group2"}, |
| 532 |
}, |
| 533 |
Verb: "GET", |
| 534 |
Namespace: "kittensandponies", |
| 535 |
APIGroup: "group3", |
| 536 |
APIVersion: "v7beta3", |
| 537 |
Resource: "pods", |
| 538 |
Subresource: "proxy", |
| 539 |
Name: "my-pod", |
| 540 |
ResourceRequest: true, |
| 541 |
Path: "/foo", |
| 542 |
}, |
| 543 |
want: authorizationv1.SubjectAccessReview{ |
| 544 |
TypeMeta: expTypeMeta, |
| 545 |
Spec: authorizationv1.SubjectAccessReviewSpec{ |
| 546 |
User: "jane", |
| 547 |
UID: "1", |
| 548 |
Groups: []string{"group1", "group2"}, |
| 549 |
ResourceAttributes: &authorizationv1.ResourceAttributes{ |
| 550 |
Verb: "GET", |
| 551 |
Namespace: "kittensandponies", |
| 552 |
Group: "group3", |
| 553 |
Version: "v7beta3", |
| 554 |
Resource: "pods", |
| 555 |
Subresource: "proxy", |
| 556 |
Name: "my-pod", |
| 557 |
}, |
| 558 |
}, |
| 559 |
}, |
| 560 |
}, |
| 561 |
} |
| 562 |
|
| 563 |
for i, tt := range tests { |
| 564 |
decision, _, err := wh.Authorize(context.Background(), tt.attr) |
| 565 |
if err != nil { |
| 566 |
t.Fatal(err) |
| 567 |
} |
| 568 |
if decision != authorizer.DecisionAllow { |
| 569 |
t.Errorf("case %d: authorization failed", i) |
| 570 |
continue |
| 571 |
} |
| 572 |
|
| 573 |
gotAttr, err := serv.Last() |
| 574 |
if err != nil { |
| 575 |
t.Errorf("case %d: failed to deserialize webhook request: %v", i, err) |
| 576 |
continue |
| 577 |
} |
| 578 |
if !reflect.DeepEqual(gotAttr, tt.want) { |
| 579 |
t.Errorf("case %d: got != want:\n%s", i, cmp.Diff(gotAttr, tt.want)) |
| 580 |
} |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
// TestWebhookCache verifies that error responses from the server are not |
| 585 |
// cached, but successful responses are. |
| 586 |
func TestV1WebhookCache(t *testing.T) { |
| 587 |
serv := new(mockV1Service) |
| 588 |
s, err := NewV1TestServer(serv, serverCert, serverKey, caCert) |
| 589 |
if err != nil { |
| 590 |
t.Fatal(err) |
| 591 |
} |
| 592 |
defer s.Close() |
| 593 |
expressions := []apiserver.WebhookMatchCondition{ |
| 594 |
{ |
| 595 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 596 |
}, |
| 597 |
} |
| 598 |
// Create an authorizer that caches successful responses "forever" (100 days). |
| 599 |
wh, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 2400*time.Hour, noopAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), expressions, "") |
| 600 |
if err != nil { |
| 601 |
t.Fatal(err) |
| 602 |
} |
| 603 |
|
| 604 |
aliceAttr := authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "alice"}, ResourceRequest: true, Namespace: "kittensandponies"} |
| 605 |
bobAttr := authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "bob"}, ResourceRequest: true, Namespace: "kittensandponies"} |
| 606 |
aliceRidiculousAttr := authorizer.AttributesRecord{ |
| 607 |
User: &user.DefaultInfo{Name: "alice"}, |
| 608 |
ResourceRequest: true, |
| 609 |
Verb: strings.Repeat("v", 2000), |
| 610 |
APIGroup: strings.Repeat("g", 2000), |
| 611 |
APIVersion: strings.Repeat("a", 2000), |
| 612 |
Resource: strings.Repeat("r", 2000), |
| 613 |
Name: strings.Repeat("n", 2000), |
| 614 |
Namespace: "kittensandponies", |
| 615 |
} |
| 616 |
bobRidiculousAttr := authorizer.AttributesRecord{ |
| 617 |
User: &user.DefaultInfo{Name: "bob"}, |
| 618 |
ResourceRequest: true, |
| 619 |
Verb: strings.Repeat("v", 2000), |
| 620 |
APIGroup: strings.Repeat("g", 2000), |
| 621 |
APIVersion: strings.Repeat("a", 2000), |
| 622 |
Resource: strings.Repeat("r", 2000), |
| 623 |
Name: strings.Repeat("n", 2000), |
| 624 |
Namespace: "kittensandponies", |
| 625 |
} |
| 626 |
|
| 627 |
type webhookCacheTestCase struct { |
| 628 |
name string |
| 629 |
|
| 630 |
attr authorizer.AttributesRecord |
| 631 |
|
| 632 |
allow bool |
| 633 |
statusCode int |
| 634 |
|
| 635 |
expectedErr bool |
| 636 |
expectedAuthorized bool |
| 637 |
expectedCalls int |
| 638 |
} |
| 639 |
|
| 640 |
tests := []webhookCacheTestCase{ |
| 641 |
// server error and 429's retry |
| 642 |
{name: "server errors retry", attr: aliceAttr, allow: false, statusCode: 500, expectedErr: true, expectedAuthorized: false, expectedCalls: 5}, |
| 643 |
{name: "429s retry", attr: aliceAttr, allow: false, statusCode: 429, expectedErr: true, expectedAuthorized: false, expectedCalls: 5}, |
| 644 |
// regular errors return errors but do not retry |
| 645 |
{name: "404 doesnt retry", attr: aliceAttr, allow: false, statusCode: 404, expectedErr: true, expectedAuthorized: false, expectedCalls: 1}, |
| 646 |
{name: "403 doesnt retry", attr: aliceAttr, allow: false, statusCode: 403, expectedErr: true, expectedAuthorized: false, expectedCalls: 1}, |
| 647 |
{name: "401 doesnt retry", attr: aliceAttr, allow: false, statusCode: 401, expectedErr: true, expectedAuthorized: false, expectedCalls: 1}, |
| 648 |
// successful responses are cached |
| 649 |
{name: "alice successful request", attr: aliceAttr, allow: true, statusCode: 200, expectedErr: false, expectedAuthorized: true, expectedCalls: 1}, |
| 650 |
// later requests within the cache window don't hit the backend |
| 651 |
{name: "alice cached request", attr: aliceAttr, allow: false, statusCode: 500, expectedErr: false, expectedAuthorized: true, expectedCalls: 0}, |
| 652 |
|
| 653 |
// a request with different attributes doesn't hit the cache |
| 654 |
{name: "bob failed request", attr: bobAttr, allow: false, statusCode: 500, expectedErr: true, expectedAuthorized: false, expectedCalls: 5}, |
| 655 |
// successful response for other attributes is cached |
| 656 |
{name: "bob unauthorized request", attr: bobAttr, allow: false, statusCode: 200, expectedErr: false, expectedAuthorized: false, expectedCalls: 1}, |
| 657 |
// later requests within the cache window don't hit the backend |
| 658 |
{name: "bob unauthorized cached request", attr: bobAttr, allow: false, statusCode: 500, expectedErr: false, expectedAuthorized: false, expectedCalls: 0}, |
| 659 |
// ridiculous unauthorized requests are not cached. |
| 660 |
{name: "ridiculous unauthorized request", attr: bobRidiculousAttr, allow: false, statusCode: 200, expectedErr: false, expectedAuthorized: false, expectedCalls: 1}, |
| 661 |
// later ridiculous requests within the cache window still hit the backend |
| 662 |
{name: "ridiculous unauthorized request again", attr: bobRidiculousAttr, allow: false, statusCode: 200, expectedErr: false, expectedAuthorized: false, expectedCalls: 1}, |
| 663 |
// ridiculous authorized requests are not cached. |
| 664 |
{name: "ridiculous authorized request", attr: aliceRidiculousAttr, allow: true, statusCode: 200, expectedErr: false, expectedAuthorized: true, expectedCalls: 1}, |
| 665 |
// later ridiculous requests within the cache window still hit the backend |
| 666 |
{name: "ridiculous authorized request again", attr: aliceRidiculousAttr, allow: true, statusCode: 200, expectedErr: false, expectedAuthorized: true, expectedCalls: 1}, |
| 667 |
} |
| 668 |
|
| 669 |
for i, test := range tests { |
| 670 |
t.Run(test.name, func(t *testing.T) { |
| 671 |
serv.called = 0 |
| 672 |
serv.allow = test.allow |
| 673 |
serv.statusCode = test.statusCode |
| 674 |
authorized, _, err := wh.Authorize(context.Background(), test.attr) |
| 675 |
if test.expectedErr && err == nil { |
| 676 |
t.Fatalf("%d: Expected error", i) |
| 677 |
} else if !test.expectedErr && err != nil { |
| 678 |
t.Fatalf("%d: unexpected error: %v", i, err) |
| 679 |
} |
| 680 |
|
| 681 |
if test.expectedAuthorized != (authorized == authorizer.DecisionAllow) { |
| 682 |
t.Errorf("%d: expected authorized=%v, got %v", i, test.expectedAuthorized, authorized) |
| 683 |
} |
| 684 |
|
| 685 |
if test.expectedCalls != serv.called { |
| 686 |
t.Errorf("%d: expected %d calls, got %d", i, test.expectedCalls, serv.called) |
| 687 |
} |
| 688 |
}) |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
// TestStructuredAuthzConfigFeatureEnablement verifies cel expressions can only be used when feature is enabled |
| 693 |
func TestStructuredAuthzConfigFeatureEnablement(t *testing.T) { |
| 694 |
service := new(mockV1Service) |
| 695 |
service.statusCode = 200 |
| 696 |
service.Allow() |
| 697 |
s, err := NewV1TestServer(service, serverCert, serverKey, caCert) |
| 698 |
if err != nil { |
| 699 |
t.Fatal(err) |
| 700 |
} |
| 701 |
defer s.Close() |
| 702 |
|
| 703 |
labelRequirement, _ := labels.NewRequirement("baz", selection.Equals, []string{"qux"}) |
| 704 |
|
| 705 |
type webhookMatchConditionsTestCase struct { |
| 706 |
name string |
| 707 |
attr authorizer.AttributesRecord |
| 708 |
allow bool |
| 709 |
expectedCompileErr bool |
| 710 |
expectedEvalErr bool |
| 711 |
expectedDecision authorizer.Decision |
| 712 |
expressions []apiserver.WebhookMatchCondition |
| 713 |
selectorEnabled bool |
| 714 |
} |
| 715 |
aliceAttr := authorizer.AttributesRecord{ |
| 716 |
User: &user.DefaultInfo{ |
| 717 |
Name: "alice", |
| 718 |
UID: "1", |
| 719 |
Groups: []string{"group1", "group2"}, |
| 720 |
Extra: map[string][]string{"key1": {"a", "b", "c"}}, |
| 721 |
}, |
| 722 |
ResourceRequest: true, |
| 723 |
Namespace: "kittensandponies", |
| 724 |
Verb: "get", |
| 725 |
} |
| 726 |
aliceWithSelectorsAttr := authorizer.AttributesRecord{ |
| 727 |
User: &user.DefaultInfo{ |
| 728 |
Name: "alice", |
| 729 |
UID: "1", |
| 730 |
Groups: []string{"group1", "group2"}, |
| 731 |
Extra: map[string][]string{"key1": {"a", "b", "c"}}, |
| 732 |
}, |
| 733 |
ResourceRequest: true, |
| 734 |
Namespace: "kittensandponies", |
| 735 |
Verb: "get", |
| 736 |
FieldSelectorRequirements: fields.Requirements{fields.Requirement{Field: "foo", Operator: selection.Equals, Value: "bar"}}, |
| 737 |
LabelSelectorRequirements: labels.Requirements{*labelRequirement}, |
| 738 |
} |
| 739 |
tests := []webhookMatchConditionsTestCase{ |
| 740 |
{ |
| 741 |
name: "no match condition does not require feature enablement", |
| 742 |
attr: aliceAttr, |
| 743 |
allow: true, |
| 744 |
expectedCompileErr: false, |
| 745 |
expectedDecision: authorizer.DecisionAllow, |
| 746 |
expressions: []apiserver.WebhookMatchCondition{}, |
| 747 |
}, |
| 748 |
{ |
| 749 |
name: "feature enabled, match all against all expressions", |
| 750 |
attr: aliceWithSelectorsAttr, |
| 751 |
allow: true, |
| 752 |
expectedCompileErr: false, |
| 753 |
expectedDecision: authorizer.DecisionAllow, |
| 754 |
expressions: []apiserver.WebhookMatchCondition{ |
| 755 |
{ |
| 756 |
Expression: "request.user == 'alice'", |
| 757 |
}, |
| 758 |
{ |
| 759 |
Expression: "request.uid == '1'", |
| 760 |
}, |
| 761 |
{ |
| 762 |
Expression: "('group1' in request.groups)", |
| 763 |
}, |
| 764 |
{ |
| 765 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 766 |
}, |
| 767 |
{ |
| 768 |
Expression: "request.?resourceAttributes.fieldSelector.requirements.orValue([]).exists(r, r.key=='foo' && r.operator=='In' && ('bar' in r.values))", |
| 769 |
}, |
| 770 |
{ |
| 771 |
Expression: "request.?resourceAttributes.labelSelector.requirements.orValue([]).exists(r, r.key=='baz' && r.operator=='In' && ('qux' in r.values))", |
| 772 |
}, |
| 773 |
{ |
| 774 |
Expression: "request.resourceAttributes.?labelSelector.requirements.orValue([]).exists(r, r.key=='baz' && r.operator=='In' && ('qux' in r.values))", |
| 775 |
}, |
| 776 |
{ |
| 777 |
Expression: "request.resourceAttributes.labelSelector.?requirements.orValue([]).exists(r, r.key=='baz' && r.operator=='In' && ('qux' in r.values))", |
| 778 |
}, |
| 779 |
}, |
| 780 |
selectorEnabled: true, |
| 781 |
}, |
| 782 |
} |
| 783 |
|
| 784 |
for i, test := range tests { |
| 785 |
t.Run(test.name, func(t *testing.T) { |
| 786 |
featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.AuthorizeWithSelectors, test.selectorEnabled) |
| 787 |
|
| 788 |
// create new compiler because it depends on the feature gate |
| 789 |
compiler := authorizationcel.NewDefaultCompiler() |
| 790 |
|
| 791 |
wh, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 0, noopAuthorizerMetrics(), compiler, test.expressions, "") |
| 792 |
if test.expectedCompileErr && err == nil { |
| 793 |
t.Fatalf("%d: Expected compile error", i) |
| 794 |
} else if !test.expectedCompileErr && err != nil { |
| 795 |
t.Fatalf("%d: unexpected error when creating a new WebhookAuthorizer: %v", i, err) |
| 796 |
} |
| 797 |
if err == nil { |
| 798 |
authorized, _, err := wh.Authorize(context.Background(), test.attr) |
| 799 |
if test.expectedEvalErr && err == nil { |
| 800 |
t.Fatalf("%d: Expected eval error", i) |
| 801 |
} else if !test.expectedEvalErr && err != nil { |
| 802 |
t.Fatalf("%d: unexpected error when authorizing: %v", i, err) |
| 803 |
} |
| 804 |
|
| 805 |
if test.expectedDecision != authorized { |
| 806 |
t.Errorf("%d: expected authorized=%v, got %v", i, test.expectedDecision, authorized) |
| 807 |
} |
| 808 |
} |
| 809 |
}) |
| 810 |
} |
| 811 |
} |
| 812 |
|
| 813 |
func TestWebhookMetrics(t *testing.T) { |
| 814 |
service := new(mockV1Service) |
| 815 |
service.statusCode = 200 |
| 816 |
service.Allow() |
| 817 |
s, err := NewV1TestServer(service, serverCert, serverKey, caCert) |
| 818 |
if err != nil { |
| 819 |
t.Fatal(err) |
| 820 |
} |
| 821 |
defer s.Close() |
| 822 |
|
| 823 |
aliceAttr := authorizer.AttributesRecord{ |
| 824 |
User: &user.DefaultInfo{ |
| 825 |
Name: "alice", |
| 826 |
UID: "1", |
| 827 |
}, |
| 828 |
} |
| 829 |
|
| 830 |
testCases := []struct { |
| 831 |
name string |
| 832 |
attr authorizer.AttributesRecord |
| 833 |
expressions1 []apiserver.WebhookMatchCondition |
| 834 |
expressions2 []apiserver.WebhookMatchCondition |
| 835 |
metrics []string |
| 836 |
want string |
| 837 |
}{ |
| 838 |
{ |
| 839 |
name: "should have one evaluation error from multiple failed match conditions", |
| 840 |
attr: aliceAttr, |
| 841 |
expressions1: []apiserver.WebhookMatchCondition{ |
| 842 |
{ |
| 843 |
Expression: "request.user == 'alice'", |
| 844 |
}, |
| 845 |
{ |
| 846 |
Expression: "request.resourceAttributes.verb == 'get'", |
| 847 |
}, |
| 848 |
{ |
| 849 |
Expression: "request.resourceAttributes.namespace == 'kittensandponies'", |
| 850 |
}, |
| 851 |
}, |
| 852 |
expressions2: []apiserver.WebhookMatchCondition{ |
| 853 |
{ |
| 854 |
Expression: "request.user == 'alice'", |
| 855 |
}, |
| 856 |
}, |
| 857 |
metrics: []string{ |
| 858 |
"apiserver_authorization_match_condition_evaluation_errors_total", |
| 859 |
}, |
| 860 |
want: fmt.Sprintf(` |
| 861 |
# HELP apiserver_authorization_match_condition_evaluation_errors_total [ALPHA] Total number of errors when an authorization webhook encounters a match condition error split by authorizer type and name. |
| 862 |
# TYPE apiserver_authorization_match_condition_evaluation_errors_total counter |
| 863 |
apiserver_authorization_match_condition_evaluation_errors_total{name="%s",type="%s"} 1 |
| 864 |
`, "wh1.example.com", "Webhook"), |
| 865 |
}, |
| 866 |
{ |
| 867 |
name: "should have two webhook exclusions due to match condition", |
| 868 |
attr: aliceAttr, |
| 869 |
expressions1: []apiserver.WebhookMatchCondition{ |
| 870 |
{ |
| 871 |
Expression: "request.user == 'alice2'", |
| 872 |
}, |
| 873 |
{ |
| 874 |
Expression: "request.uid == '1'", |
| 875 |
}, |
| 876 |
}, |
| 877 |
expressions2: []apiserver.WebhookMatchCondition{ |
| 878 |
{ |
| 879 |
Expression: "request.user == 'alice1'", |
| 880 |
}, |
| 881 |
}, |
| 882 |
metrics: []string{ |
| 883 |
"apiserver_authorization_match_condition_exclusions_total", |
| 884 |
}, |
| 885 |
want: fmt.Sprintf(` |
| 886 |
# HELP apiserver_authorization_match_condition_exclusions_total [ALPHA] Total number of exclusions when an authorization webhook is skipped because match conditions exclude it. |
| 887 |
# TYPE apiserver_authorization_match_condition_exclusions_total counter |
| 888 |
apiserver_authorization_match_condition_exclusions_total{name="%s",type="%s"} 1 |
| 889 |
apiserver_authorization_match_condition_exclusions_total{name="%s",type="%s"} 1 |
| 890 |
`, "wh1.example.com", "Webhook", "wh2.example.com", "Webhook"), |
| 891 |
}, |
| 892 |
} |
| 893 |
|
| 894 |
for _, tt := range testCases { |
| 895 |
t.Run(tt.name, func(t *testing.T) { |
| 896 |
authorizationcel.ResetMetricsForTest() |
| 897 |
defer authorizationcel.ResetMetricsForTest() |
| 898 |
wh1, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 0, celAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), tt.expressions1, "wh1.example.com") |
| 899 |
if err != nil { |
| 900 |
t.Fatal(err) |
| 901 |
} |
| 902 |
wh2, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 0, celAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), tt.expressions2, "wh2.example.com") |
| 903 |
if err != nil { |
| 904 |
t.Fatal(err) |
| 905 |
} |
| 906 |
if err == nil { |
| 907 |
_, _, _ = wh1.Authorize(context.Background(), tt.attr) |
| 908 |
_, _, _ = wh2.Authorize(context.Background(), tt.attr) |
| 909 |
} |
| 910 |
|
| 911 |
if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tt.want), tt.metrics...); err != nil { |
| 912 |
t.Fatal(err) |
| 913 |
} |
| 914 |
}) |
| 915 |
} |
| 916 |
} |
| 917 |
|
| 918 |
func BenchmarkNoCELExpressionFeatureOn(b *testing.B) { |
| 919 |
expressions := []apiserver.WebhookMatchCondition{} |
| 920 |
b.Run("compile", func(b *testing.B) { |
| 921 |
benchmarkNewWebhookAuthorizer(b, expressions) |
| 922 |
}) |
| 923 |
b.Run("authorize", func(b *testing.B) { |
| 924 |
benchmarkWebhookAuthorize(b, expressions) |
| 925 |
}) |
| 926 |
} |
| 927 |
func BenchmarkWithOneCELExpressions(b *testing.B) { |
| 928 |
expressions := []apiserver.WebhookMatchCondition{ |
| 929 |
{ |
| 930 |
Expression: "request.user == 'alice'", |
| 931 |
}, |
| 932 |
} |
| 933 |
b.Run("compile", func(b *testing.B) { |
| 934 |
benchmarkNewWebhookAuthorizer(b, expressions) |
| 935 |
}) |
| 936 |
b.Run("authorize", func(b *testing.B) { |
| 937 |
benchmarkWebhookAuthorize(b, expressions) |
| 938 |
}) |
| 939 |
} |
| 940 |
func BenchmarkWithOneCELExpressionsFalse(b *testing.B) { |
| 941 |
expressions := []apiserver.WebhookMatchCondition{ |
| 942 |
{ |
| 943 |
Expression: "request.user == 'alice2'", |
| 944 |
}, |
| 945 |
} |
| 946 |
b.Run("compile", func(b *testing.B) { |
| 947 |
benchmarkNewWebhookAuthorizer(b, expressions) |
| 948 |
}) |
| 949 |
b.Run("authorize", func(b *testing.B) { |
| 950 |
benchmarkWebhookAuthorize(b, expressions) |
| 951 |
}) |
| 952 |
} |
| 953 |
func BenchmarkWithTwoCELExpressions(b *testing.B) { |
| 954 |
expressions := []apiserver.WebhookMatchCondition{ |
| 955 |
{ |
| 956 |
Expression: "request.user == 'alice'", |
| 957 |
}, |
| 958 |
{ |
| 959 |
Expression: "request.uid == '1'", |
| 960 |
}, |
| 961 |
} |
| 962 |
b.Run("compile", func(b *testing.B) { |
| 963 |
benchmarkNewWebhookAuthorizer(b, expressions) |
| 964 |
}) |
| 965 |
b.Run("authorize", func(b *testing.B) { |
| 966 |
benchmarkWebhookAuthorize(b, expressions) |
| 967 |
}) |
| 968 |
} |
| 969 |
func BenchmarkWithTwoCELExpressionsFalse(b *testing.B) { |
| 970 |
expressions := []apiserver.WebhookMatchCondition{ |
| 971 |
{ |
| 972 |
Expression: "request.user == 'alice'", |
| 973 |
}, |
| 974 |
{ |
| 975 |
Expression: "request.uid == '2'", |
| 976 |
}, |
| 977 |
} |
| 978 |
b.Run("compile", func(b *testing.B) { |
| 979 |
benchmarkNewWebhookAuthorizer(b, expressions) |
| 980 |
}) |
| 981 |
b.Run("authorize", func(b *testing.B) { |
| 982 |
benchmarkWebhookAuthorize(b, expressions) |
| 983 |
}) |
| 984 |
} |
| 985 |
func BenchmarkWithManyCELExpressions(b *testing.B) { |
| 986 |
expressions := []apiserver.WebhookMatchCondition{ |
| 987 |
{ |
| 988 |
Expression: "request.user == 'alice'", |
| 989 |
}, |
| 990 |
{ |
| 991 |
Expression: "request.uid == '1'", |
| 992 |
}, |
| 993 |
{ |
| 994 |
Expression: "('group1' in request.groups)", |
| 995 |
}, |
| 996 |
{ |
| 997 |
Expression: "('key1' in request.extra)", |
| 998 |
}, |
| 999 |
{ |
| 1000 |
Expression: "!('key2' in request.extra)", |
| 1001 |
}, |
| 1002 |
{ |
| 1003 |
Expression: "('a' in request.extra['key1'])", |
| 1004 |
}, |
| 1005 |
{ |
| 1006 |
Expression: "!('z' in request.extra['key1'])", |
| 1007 |
}, |
| 1008 |
{ |
| 1009 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 1010 |
}, |
| 1011 |
} |
| 1012 |
b.Run("compile", func(b *testing.B) { |
| 1013 |
benchmarkNewWebhookAuthorizer(b, expressions) |
| 1014 |
}) |
| 1015 |
b.Run("authorize", func(b *testing.B) { |
| 1016 |
benchmarkWebhookAuthorize(b, expressions) |
| 1017 |
}) |
| 1018 |
} |
| 1019 |
func BenchmarkWithManyCELExpressionsFalse(b *testing.B) { |
| 1020 |
expressions := []apiserver.WebhookMatchCondition{ |
| 1021 |
{ |
| 1022 |
Expression: "request.user == 'alice'", |
| 1023 |
}, |
| 1024 |
{ |
| 1025 |
Expression: "request.uid == '1'", |
| 1026 |
}, |
| 1027 |
{ |
| 1028 |
Expression: "('group1' in request.groups)", |
| 1029 |
}, |
| 1030 |
{ |
| 1031 |
Expression: "('key1' in request.extra)", |
| 1032 |
}, |
| 1033 |
{ |
| 1034 |
Expression: "!('key2' in request.extra)", |
| 1035 |
}, |
| 1036 |
{ |
| 1037 |
Expression: "('a' in request.extra['key1'])", |
| 1038 |
}, |
| 1039 |
{ |
| 1040 |
Expression: "!('z' in request.extra['key1'])", |
| 1041 |
}, |
| 1042 |
{ |
| 1043 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies1'", |
| 1044 |
}, |
| 1045 |
} |
| 1046 |
b.Run("compile", func(b *testing.B) { |
| 1047 |
benchmarkNewWebhookAuthorizer(b, expressions) |
| 1048 |
}) |
| 1049 |
b.Run("authorize", func(b *testing.B) { |
| 1050 |
benchmarkWebhookAuthorize(b, expressions) |
| 1051 |
}) |
| 1052 |
} |
| 1053 |
|
| 1054 |
func benchmarkNewWebhookAuthorizer(b *testing.B, expressions []apiserver.WebhookMatchCondition) { |
| 1055 |
service := new(mockV1Service) |
| 1056 |
service.statusCode = 200 |
| 1057 |
service.Allow() |
| 1058 |
s, err := NewV1TestServer(service, serverCert, serverKey, caCert) |
| 1059 |
if err != nil { |
| 1060 |
b.Fatal(err) |
| 1061 |
} |
| 1062 |
defer s.Close() |
| 1063 |
|
| 1064 |
b.ResetTimer() |
| 1065 |
for i := 0; i < b.N; i++ { |
| 1066 |
// Create an authorizer with or without expressions to compile |
| 1067 |
_, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 0, noopAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), expressions, "") |
| 1068 |
if err != nil { |
| 1069 |
b.Fatal(err) |
| 1070 |
} |
| 1071 |
} |
| 1072 |
b.StopTimer() |
| 1073 |
} |
| 1074 |
|
| 1075 |
func benchmarkWebhookAuthorize(b *testing.B, expressions []apiserver.WebhookMatchCondition) { |
| 1076 |
attr := authorizer.AttributesRecord{ |
| 1077 |
User: &user.DefaultInfo{ |
| 1078 |
Name: "alice", |
| 1079 |
UID: "1", |
| 1080 |
Groups: []string{"group1", "group2"}, |
| 1081 |
Extra: map[string][]string{"key1": {"a", "b", "c"}}, |
| 1082 |
}, |
| 1083 |
ResourceRequest: true, |
| 1084 |
Namespace: "kittensandponies", |
| 1085 |
Verb: "get", |
| 1086 |
} |
| 1087 |
service := new(mockV1Service) |
| 1088 |
service.statusCode = 200 |
| 1089 |
service.Allow() |
| 1090 |
s, err := NewV1TestServer(service, serverCert, serverKey, caCert) |
| 1091 |
if err != nil { |
| 1092 |
b.Fatal(err) |
| 1093 |
} |
| 1094 |
defer s.Close() |
| 1095 |
// Create an authorizer with or without expressions to compile |
| 1096 |
wh, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 0, noopAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), expressions, "") |
| 1097 |
if err != nil { |
| 1098 |
b.Fatal(err) |
| 1099 |
} |
| 1100 |
|
| 1101 |
b.ResetTimer() |
| 1102 |
for i := 0; i < b.N; i++ { |
| 1103 |
// Call authorize may or may not require cel evaluations |
| 1104 |
_, _, err = wh.Authorize(context.Background(), attr) |
| 1105 |
if err != nil { |
| 1106 |
b.Fatal(err) |
| 1107 |
} |
| 1108 |
} |
| 1109 |
b.StopTimer() |
| 1110 |
} |
| 1111 |
|
| 1112 |
// TestV1WebhookMatchConditions verifies cel expressions are compiled and evaluated correctly |
| 1113 |
func TestV1WebhookMatchConditions(t *testing.T) { |
| 1114 |
service := new(mockV1Service) |
| 1115 |
service.statusCode = 200 |
| 1116 |
service.Allow() |
| 1117 |
s, err := NewV1TestServer(service, serverCert, serverKey, caCert) |
| 1118 |
if err != nil { |
| 1119 |
t.Fatal(err) |
| 1120 |
} |
| 1121 |
defer s.Close() |
| 1122 |
|
| 1123 |
aliceAttr := authorizer.AttributesRecord{ |
| 1124 |
User: &user.DefaultInfo{ |
| 1125 |
Name: "alice", |
| 1126 |
UID: "1", |
| 1127 |
Groups: []string{"group1", "group2"}, |
| 1128 |
Extra: map[string][]string{"key1": {"a", "b", "c"}}, |
| 1129 |
}, |
| 1130 |
ResourceRequest: true, |
| 1131 |
Namespace: "kittensandponies", |
| 1132 |
Verb: "get", |
| 1133 |
} |
| 1134 |
bobAttr := authorizer.AttributesRecord{ |
| 1135 |
User: &user.DefaultInfo{ |
| 1136 |
Name: "bob", |
| 1137 |
}, |
| 1138 |
ResourceRequest: false, |
| 1139 |
Namespace: "kittensandponies", |
| 1140 |
Verb: "get", |
| 1141 |
} |
| 1142 |
alice2Attr := authorizer.AttributesRecord{ |
| 1143 |
User: &user.DefaultInfo{ |
| 1144 |
Name: "alice2", |
| 1145 |
}, |
| 1146 |
} |
| 1147 |
type webhookMatchConditionsTestCase struct { |
| 1148 |
name string |
| 1149 |
attr authorizer.AttributesRecord |
| 1150 |
expectedCompileErr string |
| 1151 |
expectedEvalErr string |
| 1152 |
expectedDecision authorizer.Decision |
| 1153 |
expressions []apiserver.WebhookMatchCondition |
| 1154 |
} |
| 1155 |
|
| 1156 |
tests := []webhookMatchConditionsTestCase{ |
| 1157 |
{ |
| 1158 |
name: "match all with no expressions", |
| 1159 |
attr: aliceAttr, |
| 1160 |
expectedCompileErr: "", |
| 1161 |
expectedDecision: authorizer.DecisionAllow, |
| 1162 |
expressions: []apiserver.WebhookMatchCondition{}, |
| 1163 |
}, |
| 1164 |
{ |
| 1165 |
name: "match all against all expressions", |
| 1166 |
attr: aliceAttr, |
| 1167 |
expectedCompileErr: "", |
| 1168 |
expectedDecision: authorizer.DecisionAllow, |
| 1169 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1170 |
{ |
| 1171 |
Expression: "request.user == 'alice'", |
| 1172 |
}, |
| 1173 |
{ |
| 1174 |
Expression: "request.uid == '1'", |
| 1175 |
}, |
| 1176 |
{ |
| 1177 |
Expression: "('group1' in request.groups)", |
| 1178 |
}, |
| 1179 |
{ |
| 1180 |
Expression: "('key1' in request.extra)", |
| 1181 |
}, |
| 1182 |
{ |
| 1183 |
Expression: "!('key2' in request.extra)", |
| 1184 |
}, |
| 1185 |
{ |
| 1186 |
Expression: "('a' in request.extra['key1'])", |
| 1187 |
}, |
| 1188 |
{ |
| 1189 |
Expression: "!('z' in request.extra['key1'])", |
| 1190 |
}, |
| 1191 |
{ |
| 1192 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 1193 |
}, |
| 1194 |
}, |
| 1195 |
}, |
| 1196 |
{ |
| 1197 |
name: "match all except group, eval to one successful false, no error", |
| 1198 |
attr: aliceAttr, |
| 1199 |
expectedCompileErr: "", |
| 1200 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1201 |
expectedEvalErr: "", |
| 1202 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1203 |
{ |
| 1204 |
Expression: "request.user == 'alice'", |
| 1205 |
}, |
| 1206 |
{ |
| 1207 |
Expression: "request.uid == '1'", |
| 1208 |
}, |
| 1209 |
{ |
| 1210 |
Expression: "('group3' in request.groups)", |
| 1211 |
}, |
| 1212 |
{ |
| 1213 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 1214 |
}, |
| 1215 |
}, |
| 1216 |
}, |
| 1217 |
{ |
| 1218 |
name: "match condition with one compilation error", |
| 1219 |
attr: aliceAttr, |
| 1220 |
expectedCompileErr: "matchConditions[2].expression: Invalid value: \"('group3' in request.group)\": compilation failed: ERROR: <input>:1:21: undefined field 'group'\n | ('group3' in request.group)\n | ....................^", |
| 1221 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1222 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1223 |
{ |
| 1224 |
Expression: "request.user == 'alice'", |
| 1225 |
}, |
| 1226 |
{ |
| 1227 |
Expression: "request.uid == '1'", |
| 1228 |
}, |
| 1229 |
{ |
| 1230 |
Expression: "('group3' in request.group)", |
| 1231 |
}, |
| 1232 |
{ |
| 1233 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 1234 |
}, |
| 1235 |
}, |
| 1236 |
}, |
| 1237 |
{ |
| 1238 |
name: "match all except uid", |
| 1239 |
attr: aliceAttr, |
| 1240 |
expectedCompileErr: "", |
| 1241 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1242 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1243 |
{ |
| 1244 |
Expression: "request.user == 'alice'", |
| 1245 |
}, |
| 1246 |
{ |
| 1247 |
Expression: "request.uid == '2'", |
| 1248 |
}, |
| 1249 |
{ |
| 1250 |
Expression: "('group1' in request.groups)", |
| 1251 |
}, |
| 1252 |
{ |
| 1253 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 1254 |
}, |
| 1255 |
}, |
| 1256 |
}, |
| 1257 |
{ |
| 1258 |
name: "match on user name but not namespace", |
| 1259 |
attr: aliceAttr, |
| 1260 |
expectedCompileErr: "", |
| 1261 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1262 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1263 |
{ |
| 1264 |
Expression: "request.user == 'alice'", |
| 1265 |
}, |
| 1266 |
{ |
| 1267 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kube-system'", |
| 1268 |
}, |
| 1269 |
}, |
| 1270 |
}, |
| 1271 |
{ |
| 1272 |
name: "mismatch on user name", |
| 1273 |
attr: bobAttr, |
| 1274 |
expectedCompileErr: "", |
| 1275 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1276 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1277 |
{ |
| 1278 |
Expression: "request.user == 'alice'", |
| 1279 |
}, |
| 1280 |
}, |
| 1281 |
}, |
| 1282 |
{ |
| 1283 |
name: "match on user name but not resourceAttributes", |
| 1284 |
attr: bobAttr, |
| 1285 |
expectedCompileErr: "", |
| 1286 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1287 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1288 |
{ |
| 1289 |
Expression: "request.user == 'bob'", |
| 1290 |
}, |
| 1291 |
{ |
| 1292 |
Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kittensandponies'", |
| 1293 |
}, |
| 1294 |
}, |
| 1295 |
}, |
| 1296 |
{ |
| 1297 |
name: "expression failed to compile due to wrong return type", |
| 1298 |
attr: bobAttr, |
| 1299 |
expectedCompileErr: `matchConditions[0].expression: Invalid value: "request.user": must evaluate to bool but got string`, |
| 1300 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1301 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1302 |
{ |
| 1303 |
Expression: "request.user", |
| 1304 |
}, |
| 1305 |
}, |
| 1306 |
}, |
| 1307 |
{ |
| 1308 |
name: "eval failed due to errors, no successful fail", |
| 1309 |
attr: alice2Attr, |
| 1310 |
expectedCompileErr: "", |
| 1311 |
expectedEvalErr: "cel evaluation error: expression 'request.resourceAttributes.namespace == 'kittensandponies'' resulted in error: no such key: resourceAttributes", |
| 1312 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1313 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1314 |
{ |
| 1315 |
Expression: "request.user == 'alice2'", |
| 1316 |
}, |
| 1317 |
{ |
| 1318 |
Expression: "request.resourceAttributes.namespace == 'kittensandponies'", |
| 1319 |
}, |
| 1320 |
}, |
| 1321 |
}, |
| 1322 |
{ |
| 1323 |
name: "at least one matchCondition successfully evaluates to FALSE, error ignored", |
| 1324 |
attr: alice2Attr, |
| 1325 |
expectedCompileErr: "", |
| 1326 |
expectedEvalErr: "", |
| 1327 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1328 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1329 |
{ |
| 1330 |
Expression: "request.user != 'alice2'", |
| 1331 |
}, |
| 1332 |
{ |
| 1333 |
Expression: "request.resourceAttributes.namespace == 'kittensandponies'", |
| 1334 |
}, |
| 1335 |
}, |
| 1336 |
}, |
| 1337 |
{ |
| 1338 |
name: "match on user name but failed to compile due to type check in nonResourceAttributes", |
| 1339 |
attr: bobAttr, |
| 1340 |
expectedCompileErr: "matchConditions[1].expression: Invalid value: \"request.nonResourceAttributes.verb == 2\": compilation failed: ERROR: <input>:1:36: found no matching overload for '_==_' applied to '(string, int)'\n | request.nonResourceAttributes.verb == 2\n | ...................................^", |
| 1341 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1342 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1343 |
{ |
| 1344 |
Expression: "request.user == 'bob'", |
| 1345 |
}, |
| 1346 |
{ |
| 1347 |
Expression: "request.nonResourceAttributes.verb == 2", |
| 1348 |
}, |
| 1349 |
}, |
| 1350 |
}, |
| 1351 |
{ |
| 1352 |
name: "match on user name and nonresourceAttributes", |
| 1353 |
attr: bobAttr, |
| 1354 |
expectedCompileErr: "", |
| 1355 |
expectedDecision: authorizer.DecisionAllow, |
| 1356 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1357 |
{ |
| 1358 |
Expression: "request.user == 'bob'", |
| 1359 |
}, |
| 1360 |
{ |
| 1361 |
Expression: "has(request.nonResourceAttributes) && request.nonResourceAttributes.verb == 'get'", |
| 1362 |
}, |
| 1363 |
}, |
| 1364 |
}, |
| 1365 |
{ |
| 1366 |
name: "match eval failed with bad SubjectAccessReviewSpec", |
| 1367 |
attr: authorizer.AttributesRecord{}, |
| 1368 |
expectedCompileErr: "", |
| 1369 |
// default decisionOnError in newWithBackoff to skip |
| 1370 |
expectedDecision: authorizer.DecisionNoOpinion, |
| 1371 |
expectedEvalErr: "cel evaluation error: expression 'request.resourceAttributes.verb == 'get'' resulted in error: no such key: resourceAttributes", |
| 1372 |
expressions: []apiserver.WebhookMatchCondition{ |
| 1373 |
{ |
| 1374 |
Expression: "request.resourceAttributes.verb == 'get'", |
| 1375 |
}, |
| 1376 |
}, |
| 1377 |
}, |
| 1378 |
} |
| 1379 |
|
| 1380 |
for i, test := range tests { |
| 1381 |
t.Run(test.name, func(t *testing.T) { |
| 1382 |
wh, err := newV1Authorizer(s.URL, clientCert, clientKey, caCert, 0, noopAuthorizerMetrics(), authorizationcel.NewDefaultCompiler(), test.expressions, "") |
| 1383 |
if len(test.expectedCompileErr) > 0 && err == nil { |
| 1384 |
t.Fatalf("%d: Expected compile error", i) |
| 1385 |
} else if len(test.expectedCompileErr) == 0 && err != nil { |
| 1386 |
t.Fatalf("%d: unexpected error when creating a new WebhookAuthorizer: %v", i, err) |
| 1387 |
} |
| 1388 |
if err != nil { |
| 1389 |
if d := cmp.Diff(test.expectedCompileErr, err.Error()); d != "" { |
| 1390 |
t.Fatalf("newV1Authorizer mismatch (-want +got):\n%s", d) |
| 1391 |
} |
| 1392 |
} |
| 1393 |
if err == nil { |
| 1394 |
authorized, _, err := wh.Authorize(context.Background(), test.attr) |
| 1395 |
if len(test.expectedEvalErr) > 0 && err == nil { |
| 1396 |
t.Fatalf("%d: Expected eval error", i) |
| 1397 |
} else if len(test.expectedEvalErr) == 0 && err != nil { |
| 1398 |
t.Fatalf("%d: unexpected error when authorizing: %v", i, err) |
| 1399 |
} |
| 1400 |
|
| 1401 |
if err != nil { |
| 1402 |
if d := cmp.Diff(test.expectedEvalErr, err.Error()); d != "" { |
| 1403 |
t.Fatalf("Authorize mismatch (-want +got):\n%s", d) |
| 1404 |
} |
| 1405 |
} |
| 1406 |
|
| 1407 |
if test.expectedDecision != authorized { |
| 1408 |
t.Errorf("%d: expected authorized=%v, got %v", i, test.expectedDecision, authorized) |
| 1409 |
} |
| 1410 |
} |
| 1411 |
}) |
| 1412 |
} |
| 1413 |
} |
| 1414 |
|
| 1415 |
func noopAuthorizerMetrics() metrics.AuthorizerMetrics { |
| 1416 |
return metrics.NoopAuthorizerMetrics{} |
| 1417 |
} |
| 1418 |
|
| 1419 |
func celAuthorizerMetrics() metrics.AuthorizerMetrics { |
| 1420 |
return celAuthorizerMetricsType{ |
| 1421 |
MatcherMetrics: authorizationcel.NewMatcherMetrics(), |
| 1422 |
} |
| 1423 |
} |
| 1424 |
|
| 1425 |
type celAuthorizerMetricsType struct { |
| 1426 |
metrics.NoopRequestMetrics |
| 1427 |
metrics.NoopWebhookMetrics |
| 1428 |
authorizationcel.MatcherMetrics |
| 1429 |
} |