TestBackslashHandlingConsistency tests that backslashes in string literals within matcher expressions are handled consistently with CSV-parsed values. This addresses the issue where govaluate interprets escape sequences in string literals, but CSV parsing treats backslashes as literal characters.
(t *testing.T)
| 26 | // This addresses the issue where govaluate interprets escape sequences in |
| 27 | // string literals, but CSV parsing treats backslashes as literal characters. |
| 28 | func TestBackslashHandlingConsistency(t *testing.T) { |
| 29 | // Test case 1: Literal string in matcher should match CSV-parsed request |
| 30 | t.Run("LiteralInMatcher", func(t *testing.T) { |
| 31 | m := model.NewModel() |
| 32 | m.AddDef("r", "r", "sub, obj, act") |
| 33 | m.AddDef("p", "p", "sub, obj, act") |
| 34 | m.AddDef("e", "e", "some(where (p.eft == allow))") |
| 35 | // User writes '\1\2' in matcher - should be treated as literal backslashes |
| 36 | m.AddDef("m", "m", "regexMatch('\\1\\2', p.obj)") |
| 37 | |
| 38 | e, err := NewEnforcer(m, fileadapter.NewAdapter("examples/basic_policy.csv")) |
| 39 | if err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | |
| 43 | // Add a policy with a regex pattern containing backslashes |
| 44 | // CSV format: "\\[0-9]+\\" means literal string with 4 backslashes |
| 45 | _, err = e.AddPolicy("filename", "\\\\[0-9]+\\\\", "read") |
| 46 | if err != nil { |
| 47 | t.Fatal(err) |
| 48 | } |
| 49 | |
| 50 | // This should match because '\1\2' after escaping becomes \1\2, |
| 51 | // and the pattern \\[0-9]+\\ matches strings like \1\ (which is a substring of \1\2) |
| 52 | result, err := e.Enforce("filename", "dummy", "read") |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | |
| 57 | if !result { |
| 58 | t.Errorf("Expected true, got false - literal '\\1\\2' should match after escape processing") |
| 59 | } |
| 60 | }) |
| 61 | |
| 62 | // Test case 2: Request parameter should match policy with same backslash content |
| 63 | t.Run("RequestParameterVsPolicy", func(t *testing.T) { |
| 64 | m := model.NewModel() |
| 65 | m.AddDef("r", "r", "sub, obj, act") |
| 66 | m.AddDef("p", "p", "sub, obj, act") |
| 67 | m.AddDef("e", "e", "some(where (p.eft == allow))") |
| 68 | m.AddDef("m", "m", "regexMatch(r.obj, p.obj)") |
| 69 | |
| 70 | e, err := NewEnforcer(m, fileadapter.NewAdapter("examples/basic_policy.csv")) |
| 71 | if err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | |
| 75 | // Add policy with regex pattern |
| 76 | _, err = e.AddPolicy("filename", "\\\\[0-9]+\\\\", "read") |
| 77 | if err != nil { |
| 78 | t.Fatal(err) |
| 79 | } |
| 80 | |
| 81 | // Request with backslashes - simulating CSV input "\1\2" which becomes \1\2 |
| 82 | result, err := e.Enforce("filename", "\\1\\2", "read") |
| 83 | if err != nil { |
| 84 | t.Fatal(err) |
| 85 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…