File: compile_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 (254 lines) | stat: -rw-r--r-- 7,074 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
/*
Copyright 2023 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 cel

import (
	"reflect"
	"strings"
	"testing"

	authenticationv1 "k8s.io/api/authentication/v1"
	apiservercel "k8s.io/apiserver/pkg/cel"
)

func TestCompileClaimsExpression(t *testing.T) {
	testCases := []struct {
		name                string
		expressionAccessors []ExpressionAccessor
	}{
		{
			name: "valid ClaimMappingCondition",
			expressionAccessors: []ExpressionAccessor{
				&ClaimMappingExpression{
					Expression: "claims.foo",
				},
			},
		},
		{
			name: "valid ClaimValidationCondition",
			expressionAccessors: []ExpressionAccessor{
				&ClaimValidationCondition{
					Expression: "claims.foo == 'bar'",
				},
			},
		},
		{
			name: "valid ExtraMapppingCondition",
			expressionAccessors: []ExpressionAccessor{
				&ExtraMappingExpression{
					Expression: "claims.foo",
				},
			},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			for _, expressionAccessor := range tc.expressionAccessors {
				_, err := NewDefaultCompiler().CompileClaimsExpression(expressionAccessor)
				if err != nil {
					t.Errorf("unexpected error: %v", err)
				}
			}
		})
	}
}

func TestCompileUserExpression(t *testing.T) {
	testCases := []struct {
		name                string
		expressionAccessors []ExpressionAccessor
	}{
		{
			name: "valid UserValidationCondition",
			expressionAccessors: []ExpressionAccessor{
				&ExtraMappingExpression{
					Expression: "user.username == 'bar'",
				},
			},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			for _, expressionAccessor := range tc.expressionAccessors {
				_, err := NewDefaultCompiler().CompileUserExpression(expressionAccessor)
				if err != nil {
					t.Errorf("unexpected error: %v", err)
				}
			}
		})
	}
}

func TestCompileClaimsExpressionError(t *testing.T) {
	testCases := []struct {
		name                string
		expressionAccessors []ExpressionAccessor
		wantErr             string
	}{
		{
			name: "invalid ClaimValidationCondition",
			expressionAccessors: []ExpressionAccessor{
				&ClaimValidationCondition{
					Expression: "claims.foo",
				},
			},
			wantErr: "must evaluate to bool",
		},
		{
			name: "UserValidationCondition with wrong env",
			expressionAccessors: []ExpressionAccessor{
				&UserValidationCondition{
					Expression: "user.username == 'foo'",
				},
			},
			wantErr: `compilation failed: ERROR: <input>:1:1: undeclared reference to 'user' (in container '')`,
		},
		{
			name: "invalid ClaimMappingCondition",
			expressionAccessors: []ExpressionAccessor{
				&ClaimMappingExpression{
					Expression: "claims + 1",
				},
			},
			wantErr: `compilation failed: ERROR: <input>:1:8: found no matching overload for '_+_' applied to '(map(string, any), int)'`,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			for _, expressionAccessor := range tc.expressionAccessors {
				_, err := NewDefaultCompiler().CompileClaimsExpression(expressionAccessor)
				if err == nil {
					t.Errorf("expected error but got nil")
				}
				if !strings.Contains(err.Error(), tc.wantErr) {
					t.Errorf("expected error to contain %q but got %q", tc.wantErr, err.Error())
				}
			}
		})
	}
}

func TestCompileUserExpressionError(t *testing.T) {
	testCases := []struct {
		name                string
		expressionAccessors []ExpressionAccessor
		wantErr             string
	}{
		{
			name: "invalid UserValidationCondition",
			expressionAccessors: []ExpressionAccessor{
				&UserValidationCondition{
					Expression: "user.username",
				},
			},
			wantErr: "must evaluate to bool",
		},
		{
			name: "ClamMappingCondition with wrong env",
			expressionAccessors: []ExpressionAccessor{
				&ClaimMappingExpression{
					Expression: "claims.foo",
				},
			},
			wantErr: `compilation failed: ERROR: <input>:1:1: undeclared reference to 'claims' (in container '')`,
		},
		{
			name: "ExtraMappingCondition with wrong env",
			expressionAccessors: []ExpressionAccessor{
				&ExtraMappingExpression{
					Expression: "claims.foo",
				},
			},
			wantErr: `compilation failed: ERROR: <input>:1:1: undeclared reference to 'claims' (in container '')`,
		},
		{
			name: "ClaimValidationCondition with wrong env",
			expressionAccessors: []ExpressionAccessor{
				&ClaimValidationCondition{
					Expression: "claims.foo == 'bar'",
				},
			},
			wantErr: `compilation failed: ERROR: <input>:1:1: undeclared reference to 'claims' (in container '')`,
		},
		{
			name: "UserValidationCondition expression with unknown field",
			expressionAccessors: []ExpressionAccessor{
				&UserValidationCondition{
					Expression: "user.unknown == 'foo'",
				},
			},
			wantErr: `compilation failed: ERROR: <input>:1:5: undefined field 'unknown'`,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			for _, expressionAccessor := range tc.expressionAccessors {
				_, err := NewDefaultCompiler().CompileUserExpression(expressionAccessor)
				if err == nil {
					t.Errorf("expected error but got nil")
				}
				if !strings.Contains(err.Error(), tc.wantErr) {
					t.Errorf("expected error to contain %q but got %q", tc.wantErr, err.Error())
				}
			}
		})
	}
}

func TestBuildUserType(t *testing.T) {
	userDeclType := buildUserType()
	userType := reflect.TypeOf(authenticationv1.UserInfo{})

	if len(userDeclType.Fields) != userType.NumField() {
		t.Errorf("expected %d fields, got %d", userType.NumField(), len(userDeclType.Fields))
	}

	for i := 0; i < userType.NumField(); i++ {
		field := userType.Field(i)
		jsonTagParts := strings.Split(field.Tag.Get("json"), ",")
		if len(jsonTagParts) < 1 {
			t.Fatal("expected json tag to be present")
		}
		fieldName := jsonTagParts[0]

		declField, ok := userDeclType.Fields[fieldName]
		if !ok {
			t.Errorf("expected field %q to be present", field.Name)
		}
		if nativeTypeToCELType(t, field.Type).CelType().Equal(declField.Type.CelType()).Value() != true {
			t.Errorf("expected field %q to have type %v, got %v", field.Name, field.Type, declField.Type)
		}
	}
}

func nativeTypeToCELType(t *testing.T, nativeType reflect.Type) *apiservercel.DeclType {
	switch nativeType {
	case reflect.TypeOf(""):
		return apiservercel.StringType
	case reflect.TypeOf([]string{}):
		return apiservercel.NewListType(apiservercel.StringType, -1)
	case reflect.TypeOf(map[string]authenticationv1.ExtraValue{}):
		return apiservercel.NewMapType(apiservercel.StringType, apiservercel.AnyType, -1)
	default:
		t.Fatalf("unsupported type %v", nativeType)
	}
	return nil
}