| 1 | // Copyright 2020 Google LLC |
| 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 | |
| 15 | package ext |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "strings" |
| 20 | "testing" |
| 21 | "time" |
| 22 | "unicode/utf8" |
| 23 | |
| 24 | "github.com/google/cel-go/cel" |
| 25 | "github.com/google/cel-go/checker" |
| 26 | "github.com/google/cel-go/common/types" |
| 27 | "github.com/google/cel-go/common/types/ref" |
| 28 | ) |
| 29 | |
| 30 | // TODO: move these tests to a conformance test. |
| 31 | var stringTests = []struct { |
| 32 | expr string |
| 33 | err string |
| 34 | parseOnly bool |
| 35 | }{ |
| 36 | // CharAt test. |
| 37 | {expr: `'tacocat'.charAt(3) == 'o'`}, |
| 38 | {expr: `'tacocat'.charAt(7) == ''`}, |
| 39 | {expr: `'©αT'.charAt(0) == '©' && '©αT'.charAt(1) == 'α' && '©αT'.charAt(2) == 'T'`}, |
| 40 | // Index of search string tests. |
| 41 | {expr: `'tacocat'.indexOf('') == 0`}, |
| 42 | {expr: `'tacocat'.indexOf('ac') == 1`}, |
| 43 | {expr: `'tacocat'.indexOf('none') == -1`}, |
| 44 | {expr: `'tacocat'.indexOf('', 3) == 3`}, |
| 45 | {expr: `'tacocat'.indexOf('a', 3) == 5`}, |
| 46 | {expr: `'tacocat'.indexOf('at', 3) == 5`}, |
| 47 | {expr: `'ta©o©αT'.indexOf('©') == 2`}, |
| 48 | {expr: `'ta©o©αT'.indexOf('©', 3) == 4`}, |
| 49 | {expr: `'ta©o©αT'.indexOf('©αT', 3) == 4`}, |
| 50 | {expr: `'ta©o©αT'.indexOf('©α', 5) == -1`}, |
| 51 | {expr: `'ijk'.indexOf('k') == 2`}, |
| 52 | {expr: `'hello wello'.indexOf('hello wello') == 0`}, |
| 53 | {expr: `'hello wello'.indexOf('ello', 6) == 7`}, |
| 54 | {expr: `'hello wello'.indexOf('elbo room!!') == -1`}, |
| 55 | {expr: `'hello wello'.indexOf('elbo room!!!') == -1`}, |
| 56 | {expr: `''.lastIndexOf('@@') == -1`}, |
| 57 | {expr: `'tacocat'.lastIndexOf('') == 7`}, |
| 58 | {expr: `'tacocat'.lastIndexOf('at') == 5`}, |
| 59 | {expr: `'tacocat'.lastIndexOf('none') == -1`}, |
| 60 | {expr: `'tacocat'.lastIndexOf('', 3) == 3`}, |
| 61 | {expr: `'tacocat'.lastIndexOf('a', 3) == 1`}, |
| 62 | {expr: `'ta©o©αT'.lastIndexOf('©') == 4`}, |
| 63 | {expr: `'ta©o©αT'.lastIndexOf('©', 3) == 2`}, |
| 64 | {expr: `'ta©o©αT'.lastIndexOf('©α', 4) == 4`}, |
| 65 | {expr: `'hello wello'.lastIndexOf('ello', 6) == 1`}, |
| 66 | {expr: `'hello wello'.lastIndexOf('low') == -1`}, |
| 67 | {expr: `'hello wello'.lastIndexOf('elbo room!!') == -1`}, |
| 68 | {expr: `'hello wello'.lastIndexOf('elbo room!!!') == -1`}, |
| 69 | {expr: `'hello wello'.lastIndexOf('hello wello') == 0`}, |
| 70 | {expr: `'bananananana'.lastIndexOf('nana', 7) == 6`}, |
| 71 | // Lower ASCII tests. |
| 72 | {expr: `'TacoCat'.lowerAscii() == 'tacocat'`}, |
| 73 | {expr: `'TacoCÆt'.lowerAscii() == 'tacocÆt'`}, |
| 74 | {expr: `'TacoCÆt Xii'.lowerAscii() == 'tacocÆt xii'`}, |
| 75 | // Replace tests |
| 76 | {expr: `"12 days 12 hours".replace("{0}", "2") == "12 days 12 hours"`}, |
| 77 | {expr: `"{0} days {0} hours".replace("{0}", "2") == "2 days 2 hours"`}, |
| 78 | {expr: `"{0} days {0} hours".replace("{0}", "2", 1).replace("{0}", "23") == "2 days 23 hours"`}, |
| 79 | {expr: `"1 ©αT taco".replace("αT", "o©α") == "1 ©o©α taco"`}, |
| 80 | {expr: `"hello hello".replace("", "_") == "_h_e_l_l_o_ _h_e_l_l_o_"`}, |
| 81 | {expr: `"hello hello".replace("h", "") == "ello ello"`}, |
| 82 | // Split tests. |
| 83 | {expr: `"hello world".split(" ") == ["hello", "world"]`}, |
| 84 | {expr: `"hello world events!".split(" ", 0) == []`}, |
| 85 | {expr: `"hello world events!".split(" ", 1) == ["hello world events!"]`}, |
| 86 | {expr: `"o©o©o©o".split("©", -1) == ["o", "o", "o", "o"]`}, |
| 87 | // Substring tests. |
| 88 | {expr: `"tacocat".substring(4) == "cat"`}, |
| 89 | {expr: `"tacocat".substring(7) == ""`}, |
| 90 | {expr: `"tacocat".substring(0, 4) == "taco"`}, |
| 91 | {expr: `"tacocat".substring(4, 4) == ""`}, |
| 92 | {expr: `'ta©o©αT'.substring(2, 6) == "©o©α"`}, |
| 93 | {expr: `'ta©o©αT'.substring(7, 7) == ""`}, |
| 94 | // Trim tests using the unicode standard for whitespace. |
| 95 | {expr: `" \f\n\r\t\vtext ".trim() == "text"`}, |
| 96 | {expr: `"\u0085\u00a0\u1680text".trim() == "text"`}, |
| 97 | {expr: `"text\u2000\u2001\u2002\u2003\u2004\u2004\u2006\u2007\u2008\u2009".trim() == "text"`}, |
| 98 | {expr: `"\u200atext\u2028\u2029\u202F\u205F\u3000".trim() == "text"`}, |
| 99 | // Trim test with whitespace-like characters not included. |
| 100 | {expr: `"\u180etext\u200b\u200c\u200d\u2060\ufeff".trim() |
| 101 | == "\u180etext\u200b\u200c\u200d\u2060\ufeff"`}, |
| 102 | // Upper ASCII tests. |
| 103 | {expr: `'tacoCat'.upperAscii() == 'TACOCAT'`}, |
| 104 | {expr: `'tacoCαt'.upperAscii() == 'TACOCαT'`}, |
| 105 | // Reverse tests. |
| 106 | {expr: `'gums'.reverse() == 'smug'`}, |
| 107 | {expr: `'palindromes'.reverse() == 'semordnilap'`}, |
| 108 | {expr: `'John Smith'.reverse() == 'htimS nhoJ'`}, |
| 109 | {expr: `'u180etext'.reverse() == 'txete081u'`}, |
| 110 | {expr: `'2600+U'.reverse() == 'U+0062'`}, |
| 111 | {expr: `'\u180e\u200b\u200c\u200d\u2060\ufeff'.reverse() == '\ufeff\u2060\u200d\u200c\u200b\u180e'`}, |
| 112 | // Join tests. |
| 113 | {expr: `['x', 'y'].join() == 'xy'`}, |
| 114 | {expr: `['x', 'y'].join('-') == 'x-y'`}, |
| 115 | {expr: `[].join() == ''`}, |
| 116 | {expr: `[].join('-') == ''`}, |
| 117 | // Escaping tests. |
| 118 | {expr: `strings.quote("first\nsecond") == "\"first\\nsecond\""`}, |
| 119 | {expr: `strings.quote("bell\a") == "\"bell\\a\""`}, |
| 120 | {expr: `strings.quote("\bbackspace") == "\"\\bbackspace\""`}, |
| 121 | {expr: `strings.quote("\fform feed") == "\"\\fform feed\""`}, |
| 122 | {expr: `strings.quote("carriage \r return") == "\"carriage \\r return\""`}, |
| 123 | {expr: `strings.quote("horizontal tab\t") == "\"horizontal tab\\t\""`}, |
| 124 | {expr: `strings.quote("vertical \v tab") == "\"vertical \\v tab\""`}, |
| 125 | {expr: `strings.quote("double \\\\ slash") == "\"double \\\\\\\\ slash\""`}, |
| 126 | {expr: `strings.quote("two escape sequences \a\n") == "\"two escape sequences \\a\\n\""`}, |
| 127 | {expr: `strings.quote("verbatim") == "\"verbatim\""`}, |
| 128 | {expr: `strings.quote("ends with \\") == "\"ends with \\\\\""`}, |
| 129 | {expr: `strings.quote("\\ starts with") == "\"\\\\ starts with\""`}, |
| 130 | {expr: `strings.quote("printable unicode😀") == "\"printable unicode😀\""`}, |
| 131 | {expr: `strings.quote("mid string \" quote") == "\"mid string \\\" quote\""`}, |
| 132 | {expr: `strings.quote('single-quote with "double quote"') == "\"single-quote with \\\"double quote\\\"\""`}, |
| 133 | {expr: `strings.quote("size('ÿ')") == "\"size('ÿ')\""`}, |
| 134 | {expr: `strings.quote("size('πέντε')") == "\"size('πέντε')\""`}, |
| 135 | {expr: `strings.quote("завтра") == "\"завтра\""`}, |
| 136 | {expr: `strings.quote("\U0001F431\U0001F600\U0001F61B") == "\"\U0001F431\U0001F600\U0001F61B\""`}, |
| 137 | {expr: `strings.quote("ta©o©αT") == "\"ta©o©αT\""`}, |
| 138 | {expr: `strings.quote("") == "\"\""`}, |
| 139 | // Format tests with a non-literal as the format string |
| 140 | { |
| 141 | expr: `strings.quote('%s %s').format(['hello', 'world']) == "\"hello world\""`, |
| 142 | }, |
| 143 | // Error test cases based on checked expression usage. |
| 144 | { |
| 145 | expr: `'tacocat'.charAt(30) == ''`, |
| 146 | err: "index out of range: 30", |
| 147 | }, |
| 148 | {expr: `'tacocat'.indexOf('a', 30) == -1`}, |
| 149 | { |
| 150 | expr: `'tacocat'.lastIndexOf('a', -1) == -1`, |
| 151 | err: "index out of range: -1", |
| 152 | }, |
| 153 | {expr: `'tacocat'.lastIndexOf('a', 30) == -1`}, |
| 154 | { |
| 155 | expr: `"tacocat".substring(40) == "cat"`, |
| 156 | err: "index out of range: 40", |
| 157 | }, |
| 158 | { |
| 159 | expr: `"tacocat".substring(-1) == "cat"`, |
| 160 | err: "index out of range: -1", |
| 161 | }, |
| 162 | { |
| 163 | expr: `"tacocat".substring(1, 50) == "cat"`, |
| 164 | err: "index out of range: 50", |
| 165 | }, |
| 166 | { |
| 167 | expr: `"tacocat".substring(49, 50) == "cat"`, |
| 168 | err: "index out of range: 49", |
| 169 | }, |
| 170 | { |
| 171 | expr: `"tacocat".substring(4, 3) == ""`, |
| 172 | err: "invalid substring range. start: 4, end: 3", |
| 173 | }, |
| 174 | // Valid parse-only expressions which should generate runtime errors. |
| 175 | { |
| 176 | expr: `42.charAt(2) == ""`, |
| 177 | err: "no such overload", |
| 178 | parseOnly: true, |
| 179 | }, |
| 180 | { |
| 181 | expr: `'hello'.charAt(true) == ""`, |
| 182 | err: "no such overload", |
| 183 | parseOnly: true, |
| 184 | }, |
| 185 | { |
| 186 | expr: `24.indexOf('2') == 0`, |
| 187 | err: "no such overload", |
| 188 | parseOnly: true, |
| 189 | }, |
| 190 | { |
| 191 | expr: `'hello'.indexOf(true) == 1`, |
| 192 | err: "no such overload", |
| 193 | parseOnly: true, |
| 194 | }, |
| 195 | { |
| 196 | expr: `42.indexOf('4', 0) == 0`, |
| 197 | err: "no such overload", |
| 198 | parseOnly: true, |
| 199 | }, |
| 200 | { |
| 201 | expr: `'42'.indexOf(4, 0) == 0`, |
| 202 | err: "no such overload", |
| 203 | parseOnly: true, |
| 204 | }, |
| 205 | { |
| 206 | expr: `'42'.indexOf('4', '0') == 0`, |
| 207 | err: "no such overload", |
| 208 | parseOnly: true, |
| 209 | }, |
| 210 | { |
| 211 | expr: `'42'.indexOf('4', 0, 1) == 0`, |
| 212 | err: "no such overload", |
| 213 | parseOnly: true, |
| 214 | }, |
| 215 | { |
| 216 | expr: `42.split("2") == ["4"]`, |
| 217 | err: "no such overload", |
| 218 | parseOnly: true, |
| 219 | }, |
| 220 | { |
| 221 | expr: `42.replace(2, 1) == "41"`, |
| 222 | err: "no such overload", |
| 223 | parseOnly: true, |
| 224 | }, |
| 225 | { |
| 226 | expr: `"42".replace(2, 1) == "41"`, |
| 227 | err: "no such overload", |
| 228 | parseOnly: true, |
| 229 | }, |
| 230 | { |
| 231 | expr: `"42".replace("2", 1) == "41"`, |
| 232 | err: "no such overload", |
| 233 | parseOnly: true, |
| 234 | }, |
| 235 | { |
| 236 | expr: `42.replace("2", "1", 1) == "41"`, |
| 237 | err: "no such overload", |
| 238 | parseOnly: true, |
| 239 | }, |
| 240 | { |
| 241 | expr: `"42".replace(2, "1", 1) == "41"`, |
| 242 | err: "no such overload", |
| 243 | parseOnly: true, |
| 244 | }, |
| 245 | { |
| 246 | expr: `"42".replace("2", 1, 1) == "41"`, |
| 247 | err: "no such overload", |
| 248 | parseOnly: true, |
| 249 | }, |
| 250 | { |
| 251 | expr: `"42".replace("2", "1", "1") == "41"`, |
| 252 | err: "no such overload", |
| 253 | parseOnly: true, |
| 254 | }, |
| 255 | { |
| 256 | expr: `"42".replace("2", "1", 1, false) == "41"`, |
| 257 | err: "no such overload", |
| 258 | parseOnly: true, |
| 259 | }, |
| 260 | { |
| 261 | expr: `42.split("") == ["4", "2"]`, |
| 262 | err: "no such overload", |
| 263 | parseOnly: true, |
| 264 | }, |
| 265 | { |
| 266 | expr: `"42".split(2) == ["4"]`, |
| 267 | err: "no such overload", |
| 268 | parseOnly: true, |
| 269 | }, |
| 270 | { |
| 271 | expr: `42.split("2", "1") == ["4"]`, |
| 272 | err: "no such overload", |
| 273 | parseOnly: true, |
| 274 | }, |
| 275 | { |
| 276 | expr: `"42".split(2, 1) == ["4"]`, |
| 277 | err: "no such overload", |
| 278 | parseOnly: true, |
| 279 | }, |
| 280 | { |
| 281 | expr: `"42".split("2", "1") == ["4"]`, |
| 282 | err: "no such overload", |
| 283 | parseOnly: true, |
| 284 | }, |
| 285 | { |
| 286 | expr: `"42".split("2", 1, 1) == ["4"]`, |
| 287 | err: "no such overload", |
| 288 | parseOnly: true, |
| 289 | }, |
| 290 | { |
| 291 | expr: `'hello'.substring(1, 2, 3) == ""`, |
| 292 | err: "no such overload", |
| 293 | parseOnly: true, |
| 294 | }, |
| 295 | { |
| 296 | expr: `30.substring(true, 3) == ""`, |
| 297 | err: "no such overload", |
| 298 | parseOnly: true, |
| 299 | }, |
| 300 | { |
| 301 | expr: `"tacocat".substring(true, 3) == ""`, |
| 302 | err: "no such overload", |
| 303 | parseOnly: true, |
| 304 | }, |
| 305 | { |
| 306 | expr: `"tacocat".substring(0, false) == ""`, |
| 307 | err: "no such overload", |
| 308 | parseOnly: true, |
| 309 | }, |
| 310 | } |
| 311 | |
| 312 | func TestStrings(t *testing.T) { |
| 313 | env, err := cel.NewEnv(Strings()) |
| 314 | if err != nil { |
| 315 | t.Fatalf("cel.NewEnv(Strings()) failed: %v", err) |
| 316 | } |
| 317 | for i, tst := range stringTests { |
| 318 | tc := tst |
| 319 | t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) { |
| 320 | var asts []*cel.Ast |
| 321 | pAst, iss := env.Parse(tc.expr) |
| 322 | if iss.Err() != nil { |
| 323 | t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err()) |
| 324 | } |
| 325 | asts = append(asts, pAst) |
| 326 | if !tc.parseOnly { |
| 327 | cAst, iss := env.Check(pAst) |
| 328 | if iss.Err() != nil { |
| 329 | t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err()) |
| 330 | } |
| 331 | asts = append(asts, cAst) |
| 332 | } |
| 333 | for _, ast := range asts { |
| 334 | prg, err := env.Program(ast) |
| 335 | if err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | out, _, err := prg.Eval(cel.NoVars()) |
| 339 | if tc.err != "" { |
| 340 | if err == nil { |
| 341 | t.Fatalf("got value %v, wanted error %s for expr: %s", |
| 342 | out.Value(), tc.err, tc.expr) |
| 343 | } |
| 344 | if !strings.Contains(err.Error(), tc.err) { |
| 345 | t.Errorf("got %q, expected error to contain %q for expr: %s", err, tc.err, tc.expr) |
| 346 | } |
| 347 | } else if err != nil { |
| 348 | t.Fatal(err) |
| 349 | } else if out.Value() != true { |
| 350 | t.Errorf("got %v, wanted true for expr: %s", out.Value(), tc.expr) |
| 351 | } |
| 352 | } |
| 353 | }) |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | func TestStringsVersions(t *testing.T) { |
| 358 | versionCases := []struct { |
| 359 | version uint32 |
| 360 | supportedFunctions map[string]string |
| 361 | }{ |
| 362 | { |
| 363 | version: 0, |
| 364 | supportedFunctions: map[string]string{ |
| 365 | "chatAt": "''.charAt(0) == ''", |
| 366 | "indexOf": "'a'.indexOf('a') == 0", |
| 367 | "lastIndexOf": "'a'.lastIndexOf('a') == 0", |
| 368 | "join": "['a', 'b'].join() == 'ab'", |
| 369 | "joinSep": "['a', 'b'].join('-') == 'a-b'", |
| 370 | "lowerAscii": "'a'.lowerAscii() == 'a'", |
| 371 | "replace": "'hello hello'.replace('he', 'we') == 'wello wello'", |
| 372 | "split": "'hello hello hello'.split(' ') == ['hello', 'hello', 'hello']", |
| 373 | "substring": "'tacocat'.substring(4) == 'cat'", |
| 374 | "trim": "' \\ttrim\\n '.trim() == 'trim'", |
| 375 | "upperAscii": "'TacoCat'.upperAscii() == 'TACOCAT'", |
| 376 | }, |
| 377 | }, |
| 378 | { |
| 379 | version: 1, |
| 380 | supportedFunctions: map[string]string{ |
| 381 | "format": "'a %d'.format([1]) == 'a 1'", |
| 382 | "quote": `strings.quote('\a \b "double quotes"') == '"\\a \\b \\"double quotes\\""'`, |
| 383 | }, |
| 384 | }, |
| 385 | { |
| 386 | version: 3, |
| 387 | supportedFunctions: map[string]string{ |
| 388 | "reverse": "'taco'.reverse() == 'ocat'", |
| 389 | }, |
| 390 | }, |
| 391 | } |
| 392 | for _, lib := range versionCases { |
| 393 | env, err := cel.NewEnv(Strings(StringsVersion(lib.version))) |
| 394 | if err != nil { |
| 395 | t.Fatalf("cel.NewEnv(Strings(StringsVersion(%d))) failed: %v", lib.version, err) |
| 396 | } |
| 397 | t.Run(fmt.Sprintf("version=%d", lib.version), func(t *testing.T) { |
| 398 | for _, tc := range versionCases { |
| 399 | for name, expr := range tc.supportedFunctions { |
| 400 | supported := lib.version >= tc.version |
| 401 | t.Run(fmt.Sprintf("%s-supported=%t", name, supported), func(t *testing.T) { |
| 402 | ast, iss := env.Compile(expr) |
| 403 | if supported { |
| 404 | if iss.Err() != nil { |
| 405 | t.Errorf("unexpected error: %v", iss.Err()) |
| 406 | } |
| 407 | } else { |
| 408 | if iss.Err() == nil || !strings.Contains(iss.Err().Error(), "undeclared reference") { |
| 409 | t.Errorf("got error %v, wanted error %s for expr: %s, version: %d", iss.Err(), "undeclared reference", expr, tc.version) |
| 410 | } |
| 411 | return |
| 412 | } |
| 413 | prg, err := env.Program(ast) |
| 414 | if err != nil { |
| 415 | t.Fatalf("env.Program() failed: %v", err) |
| 416 | } |
| 417 | out, _, err := prg.Eval(cel.NoVars()) |
| 418 | if err != nil { |
| 419 | t.Fatalf("prg.Eval() failed: %v", err) |
| 420 | } |
| 421 | if out != types.True { |
| 422 | t.Errorf("prg.Eval() got %v, wanted true", out) |
| 423 | } |
| 424 | }) |
| 425 | } |
| 426 | } |
| 427 | }) |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | func TestStringsWithExtension(t *testing.T) { |
| 432 | env, err := cel.NewEnv(Strings()) |
| 433 | if err != nil { |
| 434 | t.Fatalf("cel.NewEnv(Strings()) failed: %v", err) |
| 435 | } |
| 436 | _, err = env.Extend(Strings()) |
| 437 | if err != nil { |
| 438 | t.Fatalf("env.Extend(Strings()) failed: %v", err) |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | func mustParseDuration(s string) time.Duration { |
| 443 | d, err := time.ParseDuration(s) |
| 444 | if err != nil { |
| 445 | panic(err) |
| 446 | } |
| 447 | return d |
| 448 | } |
| 449 | |
| 450 | func unquote(s string) (string, error) { |
| 451 | r := []rune(sanitize(s)) |
| 452 | if r[0] != '"' || r[len(r)-1] != '"' { |
| 453 | return "", fmt.Errorf("expected given string to be enclosed in double quotes: %q", r) |
| 454 | } |
| 455 | var unquotedStrBuilder strings.Builder |
| 456 | noQuotes := r[1 : len(r)-1] |
| 457 | for i := 0; i < len(noQuotes); { |
| 458 | c := noQuotes[i] |
| 459 | hasNext := i+1 < len(noQuotes) |
| 460 | if c == '\\' { |
| 461 | if hasNext { |
| 462 | nextChar := noQuotes[i+1] |
| 463 | switch nextChar { |
| 464 | case 'a': |
| 465 | unquotedStrBuilder.WriteRune('\a') |
| 466 | case 'b': |
| 467 | unquotedStrBuilder.WriteRune('\b') |
| 468 | case 'f': |
| 469 | unquotedStrBuilder.WriteRune('\f') |
| 470 | case 'n': |
| 471 | unquotedStrBuilder.WriteRune('\n') |
| 472 | case 'r': |
| 473 | unquotedStrBuilder.WriteRune('\r') |
| 474 | case 't': |
| 475 | unquotedStrBuilder.WriteRune('\t') |
| 476 | case 'v': |
| 477 | unquotedStrBuilder.WriteRune('\v') |
| 478 | case '\\': |
| 479 | unquotedStrBuilder.WriteRune('\\') |
| 480 | case '"': |
| 481 | unquotedStrBuilder.WriteRune('"') |
| 482 | default: |
| 483 | unquotedStrBuilder.WriteRune(c) |
| 484 | unquotedStrBuilder.WriteRune(nextChar) |
| 485 | } |
| 486 | i += 2 |
| 487 | continue |
| 488 | } |
| 489 | } |
| 490 | unquotedStrBuilder.WriteRune(c) |
| 491 | i++ |
| 492 | } |
| 493 | return unquotedStrBuilder.String(), nil |
| 494 | } |
| 495 | |
| 496 | func TestQuoteUnquote(t *testing.T) { |
| 497 | tests := []struct { |
| 498 | name string |
| 499 | testStr string |
| 500 | expectedErr string |
| 501 | expectedOutput string |
| 502 | expectedRuntimeCost uint64 |
| 503 | expectedEstimatedCost checker.CostEstimate |
| 504 | disableQuote bool |
| 505 | disableCELEval bool |
| 506 | }{ |
| 507 | { |
| 508 | name: "remove quotes only", |
| 509 | testStr: "this is a test", |
| 510 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 511 | expectedRuntimeCost: 2, |
| 512 | }, |
| 513 | { |
| 514 | name: "mid-string newline", |
| 515 | testStr: "first\nsecond", |
| 516 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 517 | expectedRuntimeCost: 2, |
| 518 | }, |
| 519 | { |
| 520 | name: "bell", |
| 521 | testStr: "bell\a", |
| 522 | expectedEstimatedCost: checker.FixedCostEstimate(1), |
| 523 | expectedRuntimeCost: 1, |
| 524 | }, |
| 525 | { |
| 526 | name: "backspace", |
| 527 | testStr: "\bbackspace", |
| 528 | expectedEstimatedCost: checker.FixedCostEstimate(1), |
| 529 | expectedRuntimeCost: 1, |
| 530 | }, |
| 531 | { |
| 532 | name: "form feed", |
| 533 | testStr: "\fform feed", |
| 534 | expectedEstimatedCost: checker.FixedCostEstimate(1), |
| 535 | expectedRuntimeCost: 1, |
| 536 | }, |
| 537 | { |
| 538 | name: "carriage return", |
| 539 | testStr: "carriage \r return", |
| 540 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 541 | expectedRuntimeCost: 2, |
| 542 | }, |
| 543 | { |
| 544 | name: "horizontal tab", |
| 545 | testStr: "horizontal \ttab", |
| 546 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 547 | expectedRuntimeCost: 2, |
| 548 | }, |
| 549 | { |
| 550 | name: "vertical tab", |
| 551 | testStr: "vertical \v tab", |
| 552 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 553 | expectedRuntimeCost: 2, |
| 554 | }, |
| 555 | { |
| 556 | name: "double slash", |
| 557 | testStr: "double \\\\ slash", |
| 558 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 559 | expectedRuntimeCost: 2, |
| 560 | }, |
| 561 | { |
| 562 | name: "two escape sequences", |
| 563 | testStr: "two escape sequences \a\n", |
| 564 | expectedEstimatedCost: checker.FixedCostEstimate(3), |
| 565 | expectedRuntimeCost: 3, |
| 566 | }, |
| 567 | { |
| 568 | name: "ends with slash", |
| 569 | testStr: "ends with \\", |
| 570 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 571 | expectedRuntimeCost: 2, |
| 572 | }, |
| 573 | { |
| 574 | name: "starts with slash", |
| 575 | testStr: "\\ starts with", |
| 576 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 577 | expectedRuntimeCost: 2, |
| 578 | }, |
| 579 | { |
| 580 | name: "printable unicode", |
| 581 | testStr: "printable unicode😀", |
| 582 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 583 | expectedRuntimeCost: 2, |
| 584 | }, |
| 585 | { |
| 586 | name: "mid-string quote", |
| 587 | testStr: "mid-string \" quote", |
| 588 | expectedEstimatedCost: checker.FixedCostEstimate(2), |
| 589 | expectedRuntimeCost: 2, |
| 590 | }, |
| 591 | { |
| 592 | name: "single-quote with double quote", |
| 593 | testStr: `single-quote with "double quote"`, |
| 594 | expectedEstimatedCost: checker.FixedCostEstimate(4), |
| 595 | expectedRuntimeCost: 4, |
| 596 | }, |
| 597 | { |
| 598 | name: "CEL-only escape sequences", |
| 599 | testStr: "\\? and \\`", |
| 600 | expectedEstimatedCost: checker.FixedCostEstimate(1), |
| 601 | expectedRuntimeCost: 1, |
| 602 | }, |
| 603 | { |
| 604 | name: "test cost", |
| 605 | testStr: "this is a very very very long string used to ensure that cost tracking works", |
| 606 | expectedEstimatedCost: checker.FixedCostEstimate(8), |
| 607 | expectedRuntimeCost: 8, |
| 608 | }, |
| 609 | { |
| 610 | name: "missing opening quote", |
| 611 | testStr: `only one quote"`, |
| 612 | expectedErr: "expected given string to be enclosed in double quotes", |
| 613 | disableQuote: true, |
| 614 | }, |
| 615 | { |
| 616 | name: "missing closing quote", |
| 617 | testStr: `"only one quote`, |
| 618 | expectedErr: "expected given string to be enclosed in double quotes", |
| 619 | disableQuote: true, |
| 620 | }, |
| 621 | { |
| 622 | name: "invalid utf8", |
| 623 | testStr: "filler \x9f", |
| 624 | expectedOutput: "filler " + string(utf8.RuneError), |
| 625 | // disable CEL eval in order to simulate a string variable with invalid UTF-8 |
| 626 | disableCELEval: true, |
| 627 | }, |
| 628 | { |
| 629 | name: "trailing single slash", |
| 630 | testStr: "\"trailing slash \\\"", |
| 631 | expectedOutput: "trailing slash \\", |
| 632 | disableQuote: true, |
| 633 | }, |
| 634 | } |
| 635 | for _, tt := range tests { |
| 636 | t.Run(tt.name, func(t *testing.T) { |
| 637 | var s string |
| 638 | if tt.disableQuote { |
| 639 | s = tt.testStr |
| 640 | } else { |
| 641 | if tt.disableCELEval { |
| 642 | s, _ = quote(tt.testStr) |
| 643 | } else { |
| 644 | s = evalWithCEL(tt.testStr, tt.expectedRuntimeCost, tt.expectedEstimatedCost, t) |
| 645 | } |
| 646 | } |
| 647 | output, err := unquote(s) |
| 648 | if err != nil { |
| 649 | if tt.expectedErr != "" { |
| 650 | if !strings.Contains(err.Error(), tt.expectedErr) { |
| 651 | t.Fatalf("expected error message %q to contain %q", err, tt.expectedErr) |
| 652 | } |
| 653 | } else { |
| 654 | t.Fatalf("unexpected error: %s", err) |
| 655 | } |
| 656 | } else { |
| 657 | if tt.expectedErr != "" { |
| 658 | t.Fatalf("expected error message with substring %q but no error was seen", tt.expectedErr) |
| 659 | } |
| 660 | if tt.expectedOutput != "" { |
| 661 | if output != tt.expectedOutput { |
| 662 | t.Fatalf("expected output: %q, got: %q", tt.expectedOutput, output) |
| 663 | } |
| 664 | } else if output != tt.testStr { |
| 665 | t.Fatalf("input-output mismatch: original: %q, quote/unquote: %q", tt.testStr, output) |
| 666 | } |
| 667 | } |
| 668 | }) |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | type noopCostEstimator struct{} |
| 673 | |
| 674 | func (e *noopCostEstimator) CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64 { |
| 675 | return nil |
| 676 | } |
| 677 | |
| 678 | func (e *noopCostEstimator) EstimateCallCost(function, overloadID string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 679 | return nil |
| 680 | } |
| 681 | |
| 682 | func (e *noopCostEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate { |
| 683 | return nil |
| 684 | } |
| 685 | |
| 686 | func evalWithCEL(input string, expectedRuntimeCost uint64, expectedEstimatedCost checker.CostEstimate, t *testing.T) string { |
| 687 | env, err := cel.NewEnv(Strings()) |
| 688 | if err != nil { |
| 689 | t.Fatalf("cel.NewEnv() failed: %v", err) |
| 690 | } |
| 691 | expr := fmt.Sprintf(`strings.quote(%q)`, input) |
| 692 | parsedAst, issues := env.Parse(expr) |
| 693 | if issues.Err() != nil { |
| 694 | t.Fatalf("env.Parse() failed: %v", issues.Err()) |
| 695 | } |
| 696 | checkedAst, issues := env.Check(parsedAst) |
| 697 | if issues.Err() != nil { |
| 698 | t.Fatalf("env.Check() failed: %v", issues.Err()) |
| 699 | } |
| 700 | |
| 701 | costTracker := &noopCostEstimator{} |
| 702 | actualEstimatedCost, err := env.EstimateCost(checkedAst, costTracker) |
| 703 | if err != nil { |
| 704 | t.Fatal(err) |
| 705 | } |
| 706 | if expectedEstimatedCost.Min != 0 && expectedEstimatedCost.Max != 0 { |
| 707 | if actualEstimatedCost.Min != expectedEstimatedCost.Min && actualEstimatedCost.Max != expectedEstimatedCost.Max { |
| 708 | t.Fatalf("expected estimated cost range to be %v, was %v", expectedEstimatedCost, actualEstimatedCost) |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | program, err := env.Program(checkedAst, cel.CostTracking(costTracker)) |
| 713 | if err != nil { |
| 714 | t.Fatal(err) |
| 715 | } |
| 716 | out, evalDetails, err := program.Eval(cel.NoVars()) |
| 717 | if err != nil { |
| 718 | t.Fatal(err) |
| 719 | } |
| 720 | if evalDetails == nil { |
| 721 | t.Fatal("evalDetails could not be calculated") |
| 722 | } else if evalDetails.ActualCost() == nil { |
| 723 | t.Fatal("could not calculate runtime cost") |
| 724 | } |
| 725 | if expectedRuntimeCost != 0 { |
| 726 | if *evalDetails.ActualCost() != expectedRuntimeCost { |
| 727 | t.Fatalf("expected runtime cost of %d, got %d", expectedRuntimeCost, *evalDetails.ActualCost()) |
| 728 | } |
| 729 | if expectedEstimatedCost.Min != 0 && expectedEstimatedCost.Max != 0 { |
| 730 | if *evalDetails.ActualCost() < expectedEstimatedCost.Min || *evalDetails.ActualCost() > expectedEstimatedCost.Max { |
| 731 | t.Fatalf("runtime cost %d outside of expected estimated cost range %v", *evalDetails.ActualCost(), expectedEstimatedCost) |
| 732 | } |
| 733 | } |
| 734 | } |
| 735 | if out.Type() != types.StringType { |
| 736 | t.Fatalf("expected expr output to be a string, got %s", out.Type().TypeName()) |
| 737 | } |
| 738 | return out.Value().(string) |
| 739 | } |
| 740 | |
| 741 | func TestFunctionsForVersions(t *testing.T) { |
| 742 | tests := []struct { |
| 743 | version uint32 |
| 744 | introducedFunctions []string |
| 745 | }{ |
| 746 | { |
| 747 | version: 0, |
| 748 | introducedFunctions: []string{"lastIndexOf", "lowerAscii", "split", "trim", "join", "charAt", "indexOf", "replace", "substring", "upperAscii"}, |
| 749 | }, |
| 750 | { |
| 751 | version: 1, |
| 752 | introducedFunctions: []string{"strings.quote", "format"}, |
| 753 | }, |
| 754 | { |
| 755 | version: 2, |
| 756 | introducedFunctions: []string{}, // join changed, no functions added |
| 757 | }, |
| 758 | { |
| 759 | version: 3, |
| 760 | introducedFunctions: []string{"reverse"}, |
| 761 | }, |
| 762 | } |
| 763 | var functions []string |
| 764 | for _, tt := range tests { |
| 765 | functions = append(functions, tt.introducedFunctions...) |
| 766 | t.Run(fmt.Sprintf("version %d", tt.version), func(t *testing.T) { |
| 767 | e, err := cel.NewCustomEnv(Strings(StringsVersion(tt.version))) |
| 768 | if err != nil { |
| 769 | t.Fatalf("NewEnv() failed: %v", err) |
| 770 | } |
| 771 | if len(functions) != len(e.Functions()) { |
| 772 | var functionNames []string |
| 773 | for name := range e.Functions() { |
| 774 | functionNames = append(functionNames, name) |
| 775 | } |
| 776 | t.Fatalf("Expected functions: %#v, got %#v", functions, functionNames) |
| 777 | } |
| 778 | for _, expected := range functions { |
| 779 | if !e.HasFunction(expected) { |
| 780 | t.Errorf("Expected HasFunction() to return true for '%s'", expected) |
| 781 | } |
| 782 | |
| 783 | if _, ok := e.Functions()[expected]; !ok { |
| 784 | t.Errorf("Expected Functions() to include '%s'", expected) |
| 785 | } |
| 786 | } |
| 787 | }) |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | func FuzzQuote(f *testing.F) { |
| 792 | tests := []string{ |
| 793 | "this is a test", |
| 794 | `only one quote"`, |
| 795 | `"only one quote`, |
| 796 | "first\nsecond", |
| 797 | "bell\a", |
| 798 | "\bbackspace", |
| 799 | "\fform feed", |
| 800 | "carriage \r return", |
| 801 | "horizontal \ttab", |
| 802 | "vertical \v tab", |
| 803 | "double \\\\ slash", |
| 804 | "two escape sequences \a\n", |
| 805 | "ends with \\", |
| 806 | "\\ starts with", |
| 807 | "printable unicode😀", |
| 808 | "mid-string \" quote", |
| 809 | "\\? and \\`", |
| 810 | "filler \x9f", |
| 811 | "size('ÿ')", |
| 812 | "size('πέντε')", |
| 813 | "завтра", |
| 814 | "\U0001F431\U0001F600\U0001F61B", |
| 815 | "ta©o©αT", |
| 816 | } |
| 817 | for _, tc := range tests { |
| 818 | f.Add(tc) |
| 819 | } |
| 820 | f.Fuzz(func(t *testing.T, s string) { |
| 821 | quoted, err := quote(s) |
| 822 | if err != nil { |
| 823 | if utf8.ValidString(s) { |
| 824 | t.Errorf("unexpected error: %s", err) |
| 825 | } |
| 826 | } else { |
| 827 | unquoted, err := unquote(quoted) |
| 828 | if err != nil { |
| 829 | t.Errorf("unexpected error: %s", err) |
| 830 | } else if s != sanitize(s) { |
| 831 | if unquoted != sanitize(s) { |
| 832 | t.Errorf("input-output mismatch on test case containing invalid UTF-8: sanitized original: %q, quoted: %q, quote/unquote: %q", sanitize(s), quoted, unquoted) |
| 833 | } |
| 834 | } else if unquoted != s { |
| 835 | t.Errorf("input-output mismatch: original: %q, quoted: %q, quote/unquote: %q", s, quoted, unquoted) |
| 836 | } |
| 837 | } |
| 838 | }) |
| 839 | } |