| 2589 | } |
| 2590 | |
| 2591 | func TestRegexProgramSizeLimit(t *testing.T) { |
| 2592 | env, err := NewEnv( |
| 2593 | Variable("pattern", StringType), |
| 2594 | RegexProgramSizeLimit(5), |
| 2595 | ) |
| 2596 | if err != nil { |
| 2597 | t.Fatalf("NewEnv failed: %v", err) |
| 2598 | } |
| 2599 | |
| 2600 | tests := []struct { |
| 2601 | name string |
| 2602 | expr string |
| 2603 | progOpts []ProgramOption |
| 2604 | vars any |
| 2605 | want ref.Val |
| 2606 | compileErr string |
| 2607 | progErr string |
| 2608 | evalErr string |
| 2609 | }{ |
| 2610 | { |
| 2611 | name: "constant_regex_exceeds_limit_ast_validation", |
| 2612 | expr: `"123 abc 456".matches('(a|b)*[0-9]+')`, |
| 2613 | compileErr: "regex program size 8 exceeds limit of 5", |
| 2614 | }, |
| 2615 | { |
| 2616 | name: "dynamic_regex_exceeds_limit_runtime", |
| 2617 | expr: `"123 abc 456".matches(pattern)`, |
| 2618 | vars: map[string]any{"pattern": "(a|b)*[0-9]+"}, |
| 2619 | evalErr: "regex program size 8 exceeds limit of 5", |
| 2620 | }, |
| 2621 | { |
| 2622 | name: "dynamic_regex_within_limit", |
| 2623 | expr: `"123 abc 456".matches(pattern)`, |
| 2624 | vars: map[string]any{"pattern": "[0-9]+"}, |
| 2625 | want: types.True, |
| 2626 | }, |
| 2627 | } |
| 2628 | |
| 2629 | for _, tc := range tests { |
| 2630 | t.Run(tc.name, func(tt *testing.T) { |
| 2631 | ast, iss := env.Compile(tc.expr) |
| 2632 | if tc.compileErr != "" { |
| 2633 | if iss.Err() == nil { |
| 2634 | tt.Fatalf("env.Compile(%s) succeeded, wanted error %s", tc.expr, tc.compileErr) |
| 2635 | } |
| 2636 | if !strings.Contains(iss.Err().Error(), tc.compileErr) { |
| 2637 | tt.Errorf("got compile error %v, wanted error containing %s", iss.Err(), tc.compileErr) |
| 2638 | } |
| 2639 | return |
| 2640 | } |
| 2641 | if iss.Err() != nil { |
| 2642 | tt.Fatalf("env.Compile(%s) failed: %v", tc.expr, iss.Err()) |
| 2643 | } |
| 2644 | prg, err := env.Program(ast, tc.progOpts...) |
| 2645 | if tc.progErr != "" { |
| 2646 | if err == nil { |
| 2647 | tt.Fatalf("env.Program(%s) succeeded, wanted error %s", tc.expr, tc.progErr) |
| 2648 | } |