GeezerVison is showing github.com — fix(cel): preserve original case across CEL syntax · majorcontext/keep@d7388fe
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: CHANGELOG.md +3Lines changed: 3 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 | 7 | 7 |
| 8 | 8 | ## [Unreleased] | 9 | 9 |
| | 10 | +## [0.7.0] - 2026-11-02 | | 11 | + | 10 | 12 | ### Added | 11 | 13 |
| 12 | 14 | - **`graphql()` CEL function** — parses a GraphQL-over-HTTP request body (`graphql(params.body)`) into `{valid, error, operations, queries, mutations, subscriptions}`. Each root field reports its real `name`, its `alias`, and `args` with variables and variable defaults substituted. Every operation in the document is reported regardless of `operationName`, root fragment spreads and inline fragments are expanded, and directives are ignored, so a rule sees every root field the document contains. The body is parsed in its original case even in case-insensitive scopes, since GraphQL names and node IDs are case-sensitive. Malformed input returns `valid: false` with empty lists rather than an error. | @@ -16,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 | 16 | 18 |
| 17 | 19 | - Fix `ValidateRuleBytes` rejecting rule files that use `defs` — previously it compiled each `when` expression without substituting defs, so a file that `LoadFromBytes` accepted failed validation with "undeclared reference". Validation now prepares expressions exactly as the engine does. | 18 | 20 | - Fix the original-case rewrite for `hasSecrets` — previously `hasSecrets(` inside a string literal or at the end of a longer identifier was rewritten too, corrupting the literal. | | 21 | +- Preserve original-case values for `graphql` and `hasSecrets` with whitespace before the call and bracket access to params. Expression rewriting and def/alias substitution now respect raw strings, triple-quoted strings, and comments. | 19 | 22 |
| 20 | 23 | ## [0.6.0] - 2026-06-22 | 21 | 24 |
| |
Collapse file Copy file name to clipboardExpand all lines: docs/content/reference/03-cel-functions.md +1Lines changed: 1 addition & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -283,6 +283,7 @@ Semantics: | 283 | 283 | - **Variables are substituted.** A variable takes its value from `variables` (an explicit `null` counts as a value), then from its default in the operation's variable definitions. A variable with neither is omitted from an object argument and becomes `null` inside a list. Variables nested in object and list literals are substituted too. | 284 | 284 | - **Literal values** become strings, ints, doubles, booleans, or `null`. Enum values become strings. String escapes are decoded. An integer outside the 64-bit range is kept as its literal text. | 285 | 285 | - **Original case.** GraphQL names and node IDs are case-sensitive, so `graphql(params.body)` parses the body as the client sent it, even when the scope lowercases params for matching (the default). Compare names and values with their exact case, or wrap them in `lower()`. | | 286 | +- **Computed bodies.** Pass a direct params path, such as `params.body` or `params['body']`, to preserve the original query and variable values. Reconstructed maps and other computed expressions use the argument as evaluated; in a case-insensitive scope, values read from `params` have already been lowercased, including variable values. Use `case_sensitive: true` when computing a body that must preserve case. | 286 | 287 | - **Limits.** Documents over 100,000 tokens, fragment nesting deeper than 32 levels, or more than 1,000 expanded root fields are invalid. | 287 | 288 | - **Never errors.** Invalid input returns `valid: false` with empty lists, so `.exists()` over `mutations` is always safe. Pair content rules with a `!graphql(params.body).valid` deny rule so an unparseable body fails closed. | 288 | 289 |
| |
Collapse file Copy file name to clipboardExpand all lines: internal/cel/alias.go +7-37Lines changed: 7 additions & 37 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -29,44 +29,14 @@ func ResolveAliases(expr string, aliases map[string]string) string { | 29 | 29 | for i < n { | 30 | 30 | c := expr[i] | 31 | 31 |
| 32 | | - // Handle single-quoted string literals. | 33 | | - if c == '\'' { | 34 | | - b.WriteByte(c) | 35 | | - i++ | 36 | | - for i < n { | 37 | | - ch := expr[i] | 38 | | - b.WriteByte(ch) | 39 | | - i++ | 40 | | - if ch == '\'' { | 41 | | - break | 42 | | - } | 43 | | - // simple escape: skip next char | 44 | | - if ch == '\\' && i < n { | 45 | | - b.WriteByte(expr[i]) | 46 | | - i++ | 47 | | - } | 48 | | - } | 49 | | - prevNonIdent = '\'' | 50 | | - continue | 51 | | - } | 52 | | - | 53 | | - // Handle double-quoted string literals. | 54 | | - if c == '"' { | 55 | | - b.WriteByte(c) | 56 | | - i++ | 57 | | - for i < n { | 58 | | - ch := expr[i] | 59 | | - b.WriteByte(ch) | 60 | | - i++ | 61 | | - if ch == '"' { | 62 | | - break | 63 | | - } | 64 | | - if ch == '\\' && i < n { | 65 | | - b.WriteByte(expr[i]) | 66 | | - i++ | 67 | | - } | | 32 | + // Keep literals and comments intact, including raw and triple-quoted | | 33 | + // strings. This uses the same scanner as the original-case rewrite. | | 34 | + if end := skipCELLiteralOrComment(expr, i); end > i { | | 35 | + b.WriteString(expr[i:end]) | | 36 | + if c != '/' { | | 37 | + prevNonIdent = expr[end-1] | 68 | 38 | } | 69 | | - prevNonIdent = '"' | | 39 | + i = end | 70 | 40 | continue | 71 | 41 | } | 72 | 42 |
| |
Collapse file Copy file name to clipboardExpand all lines: internal/cel/alias_test.go +11Lines changed: 11 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -4,6 +4,17 @@ import ( | 4 | 4 | "testing" | 5 | 5 | ) | 6 | 6 |
| | 7 | +func TestResolveAliases_LiteralsAndComments(t *testing.T) { | | 8 | + aliases := map[string]string{"id": "params.id", "r": "params.r", "b": "params.b"} | | 9 | + for _, literal := range []string{`r'\'`, `R"\"`, `br'\'`, `BR"\"`, `'''a'id'b'''`, `"""a"id"b"""`, `'escaped\'id'`} { | | 10 | + expr := literal + " == " + literal + " && id == 'x' // id\n" | | 11 | + want := literal + " == " + literal + " && params.id == 'x' // id\n" | | 12 | + if got := ResolveAliases(expr, aliases); got != want { | | 13 | + t.Errorf("ResolveAliases(%q) = %q, want %q", expr, got, want) | | 14 | + } | | 15 | + } | | 16 | +} | | 17 | + | 7 | 18 | func TestResolveAliases_Simple(t *testing.T) { | 8 | 19 | aliases := map[string]string{ | 9 | 20 | "priority": "params.priority", | |
Collapse file Copy file name to clipboardExpand all lines: internal/cel/graphql_test.go +74-1Lines changed: 74 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -215,7 +215,7 @@ func TestParseGraphQLRequest_Subscription(t *testing.T) { | 215 | 215 |
| 216 | 216 | func TestParseGraphQLRequest_StringEscapesDecoded(t *testing.T) { | 217 | 217 | // The server decodes escapes, so the policy must see the decoded value. | 218 | | - res := ParseGraphQLRequest(gqlBody(`mutation { createRef(input: {repositoryId: "R_ABC"}) }`, nil)) | | 218 | + res := ParseGraphQLRequest(gqlBody(`mutation { createRef(input: {repositoryId: "\u0052_ABC"}) }`, nil)) | 219 | 219 | mustValid(t, res) | 220 | 220 | input := fieldsOf(t, res, "mutations")[0]["args"].(map[string]any)["input"].(map[string]any) | 221 | 221 | if input["repositoryId"] != "R_ABC" { | @@ -388,6 +388,79 @@ func TestGraphQL_CEL_OriginalCase(t *testing.T) { | 388 | 388 | } | 389 | 389 | } | 390 | 390 |
| | 391 | +func TestGraphQL_CEL_RewriteSyntax(t *testing.T) { | | 392 | + env, err := NewEnv() | | 393 | + if err != nil { | | 394 | + t.Fatal(err) | | 395 | + } | | 396 | + original := gqlBody(`mutation($id: ID!) { createRef(input: {repositoryId: $id}) }`, map[string]any{"id": "R_AbCd"}) | | 397 | + lowered := gqlBody(strings.ToLower(original["query"].(string)), map[string]any{"id": "r_abcd"}) | | 398 | + for _, call := range []string{ | | 399 | + `graphql(params.body)`, | | 400 | + `graphql (params.body)`, | | 401 | + "graphql\n(params.body)", | | 402 | + "graphql // graphql(fake)\n(params.body)", | | 403 | + "graphql(params.body // body comment\n)", | | 404 | + `graphql(params['body'])`, | | 405 | + `graphql(params.body[r'\' == '' ? 'missing' : 'self'])`, | | 406 | + `graphql(params.body['''a'b'c''' == '' ? 'missing' : 'self'])`, | | 407 | + } { | | 408 | + t.Run(call, func(t *testing.T) { | | 409 | + // A self entry lets argument expressions exercise the string scanner. | | 410 | + params := map[string]any{"body": map[string]any{"self": lowered}} | | 411 | + originalParams := map[string]any{"body": map[string]any{"self": original}} | | 412 | + if !strings.Contains(call, "'self'") { | | 413 | + params["body"], originalParams["body"] = lowered, original | | 414 | + } | | 415 | + for _, prefix := range []string{"", `r'\' != '' && `, `BR'\' != b'' && `, "// graphql(fake)\n"} { | | 416 | + expr := prefix + call + `.mutations.exists(m, m.name == 'createRef' && m.args.input.repositoryId == 'R_AbCd')` | | 417 | + prog, err := env.Compile(InjectOriginalParams(expr)) | | 418 | + if err != nil { | | 419 | + t.Fatal(err) | | 420 | + } | | 421 | + got, err := prog.Eval(params, nil, originalParams) | | 422 | + if err != nil { | | 423 | + t.Fatal(err) | | 424 | + } | | 425 | + if !got { | | 426 | + t.Errorf("rewrite lost the original-case mutation name or variable: %s", expr) | | 427 | + } | | 428 | + got, err = prog.Eval(params, nil) | | 429 | + if err != nil { | | 430 | + t.Fatal(err) | | 431 | + } | | 432 | + if got { | | 433 | + t.Errorf("lowercased mutation and variable matched: %s", expr) | | 434 | + } | | 435 | + } | | 436 | + }) | | 437 | + } | | 438 | +} | | 439 | + | | 440 | +func TestGraphQL_CEL_ComputedBodyUsesNormalizedVariables(t *testing.T) { | | 441 | + env, err := NewEnv() | | 442 | + if err != nil { | | 443 | + t.Fatal(err) | | 444 | + } | | 445 | + // Reconstructed bodies have no corresponding original params path. Their | | 446 | + // variables retain the scope's normalization, as documented. | | 447 | + expr := `graphql({'query': 'mutation($id: ID!) { createRef(id: $id) }', 'variables': params.body.variables}).mutations[0].args.id == 'r_abcd'` | | 448 | + prog, err := env.Compile(InjectOriginalParams(expr)) | | 449 | + if err != nil { | | 450 | + t.Fatal(err) | | 451 | + } | | 452 | + got, err := prog.Eval( | | 453 | + map[string]any{"body": map[string]any{"variables": map[string]any{"id": "r_abcd"}}}, nil, | | 454 | + map[string]any{"body": map[string]any{"variables": map[string]any{"id": "R_AbCd"}}}, | | 455 | + ) | | 456 | + if err != nil { | | 457 | + t.Fatal(err) | | 458 | + } | | 459 | + if !got { | | 460 | + t.Error("expected the computed body's normalized variable value") | | 461 | + } | | 462 | +} | | 463 | + | 391 | 464 | func TestInjectOriginalParams_GraphQL(t *testing.T) { | 392 | 465 | tests := []struct { | 393 | 466 | in, want string | |
Collapse file Copy file name to clipboardExpand all lines: internal/cel/rewrite.go +80-46Lines changed: 80 additions & 46 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -31,42 +31,29 @@ func InjectOriginalParams(expr string) string { | 31 | 31 | } | 32 | 32 |
| 33 | 33 | func injectOriginalParamsForFunc(expr string, fnName string) string { | 34 | | - prefix := fnName + "(" | 35 | 34 | result := expr | 36 | 35 | offset := 0 | 37 | 36 |
| 38 | 37 | for { | 39 | | - idx := findCall(result, prefix, offset) | 40 | | - if idx < 0 { | | 38 | + start := findCallStart(result, fnName, offset) | | 39 | + if start < 0 { | 41 | 40 | break | 42 | 41 | } | 43 | | - start := idx + len(prefix) // position after opening paren | 44 | 42 |
| 45 | 43 | // Find the matching closing paren, respecting nesting and string literals. | 46 | 44 | depth := 1 | 47 | 45 | commaFound := false | 48 | 46 | i := start | 49 | 47 | for i < len(result) && depth > 0 { | | 48 | + if end := skipCELLiteralOrComment(result, i); end > i { | | 49 | + i = end | | 50 | + continue | | 51 | + } | 50 | 52 | c := result[i] | 51 | 53 | switch { | 52 | | - case c == '\'' || c == '"': | 53 | | - // Skip string literal. | 54 | | - i++ | 55 | | - for i < len(result) { | 56 | | - if result[i] == '\\' && i+1 < len(result) { | 57 | | - i += 2 | 58 | | - continue | 59 | | - } | 60 | | - if result[i] == c { | 61 | | - i++ | 62 | | - break | 63 | | - } | 64 | | - i++ | 65 | | - } | 66 | | - continue | 67 | | - case c == '(': | | 54 | + case c == '(' || c == '[' || c == '{': | 68 | 55 | depth++ | 69 | | - case c == ')': | | 56 | + case c == ')' || c == ']' || c == '}': | 70 | 57 | depth-- | 71 | 58 | case c == ',' && depth == 1: | 72 | 59 | commaFound = true | @@ -91,9 +78,11 @@ func injectOriginalParamsForFunc(expr string, fnName string) string { | 91 | 78 | // injecting the full _originalParams map. | 92 | 79 | arg := result[start:closePos] | 93 | 80 | var inject string | 94 | | - if strings.HasPrefix(strings.TrimSpace(arg), "params.") { | 95 | | - trimmed := strings.TrimSpace(arg) | 96 | | - origArg := "_originalParams." + trimmed[len("params."):] | | 81 | + // Keep trailing newlines so a final line comment cannot swallow | | 82 | + // the injected argument's closing parenthesis. | | 83 | + trimmed := strings.TrimLeft(arg, " \t\r\n\f") | | 84 | + if strings.HasPrefix(trimmed, "params.") || strings.HasPrefix(trimmed, "params[") { | | 85 | + origArg := "_originalParams" + trimmed[len("params"):] | 97 | 86 | inject = ", " + origArg | 98 | 87 | } else { | 99 | 88 | inject = ", _originalParams" | @@ -109,42 +98,87 @@ func injectOriginalParamsForFunc(expr string, fnName string) string { | 109 | 98 | return result | 110 | 99 | } | 111 | 100 |
| 112 | | -// findCall returns the index of the next call site of prefix (e.g. | 113 | | -// "graphql(") at or after from, or -1. Occurrences inside a string literal | | 101 | +// findCallStart returns the position after the opening paren of the next global | | 102 | +// function call at or after from, or -1. Whitespace before '(' is allowed. | | 103 | +// Occurrences inside a string literal | 114 | 104 | // (`'graphql(x)'`) or as the tail of a longer identifier or a method call | 115 | 105 | // (`mygraphql(`, `x.graphql(`) are not call sites of the global function and | 116 | 106 | // are skipped, so the rewrite never corrupts a literal or an unrelated call. | 117 | | -func findCall(expr, prefix string, from int) int { | 118 | | - var quote byte | | 107 | +func findCallStart(expr, fnName string, from int) int { | | 108 | + var previous byte | 119 | 109 | for i := 0; i < len(expr); i++ { | 120 | | - c := expr[i] | 121 | | - if quote != 0 { | 122 | | - switch c { | 123 | | - case '\\': | 124 | | - i++ // skip the escaped character | 125 | | - case quote: | 126 | | - quote = 0 | | 110 | + if end := skipCELLiteralOrComment(expr, i); end > i { | | 111 | + if expr[i] != '/' { | | 112 | + previous = expr[i] | 127 | 113 | } | | 114 | + i = end - 1 | 128 | 115 | continue | 129 | 116 | } | 130 | | - if c == '\'' || c == '"' { | 131 | | - quote = c | 132 | | - continue | 133 | | - } | 134 | | - if i < from || !strings.HasPrefix(expr[i:], prefix) { | | 117 | + c := expr[i] | | 118 | + if isCELSpace(c) { | 135 | 119 | continue | 136 | 120 | } | 137 | | - if i > 0 && isIdentOrDot(expr[i-1]) { | 138 | | - continue | | 121 | + if i >= from && previous != '.' && (i == 0 || !isIdentPart(expr[i-1])) && strings.HasPrefix(expr[i:], fnName) { | | 122 | + j := i + len(fnName) | | 123 | + for j < len(expr) { | | 124 | + if isCELSpace(expr[j]) { | | 125 | + j++ | | 126 | + } else if strings.HasPrefix(expr[j:], "//") { | | 127 | + j = skipCELLiteralOrComment(expr, j) | | 128 | + } else { | | 129 | + break | | 130 | + } | | 131 | + } | | 132 | + if j < len(expr) && expr[j] == '(' { | | 133 | + return j + 1 | | 134 | + } | 139 | 135 | } | 140 | | - return i | | 136 | + previous = c | 141 | 137 | } | 142 | 138 | return -1 | 143 | 139 | } | 144 | 140 |
| 145 | | -func isIdentOrDot(c byte) bool { | 146 | | - return c == '_' || c == '.' || | 147 | | - (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') | | 141 | +func isCELSpace(c byte) bool { | | 142 | + return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' | | 143 | +} | | 144 | + | | 145 | +// skipCELLiteralOrComment returns the position after a quoted string/bytes | | 146 | +// literal or line comment starting at i, or i otherwise. Raw literals don't | | 147 | +// process escapes; triple-quoted literals can contain individual quote marks. | | 148 | +func skipCELLiteralOrComment(expr string, i int) int { | | 149 | + if strings.HasPrefix(expr[i:], "//") { | | 150 | + if end := strings.IndexByte(expr[i:], '\n'); end >= 0 { | | 151 | + return i + end | | 152 | + } | | 153 | + return len(expr) | | 154 | + } | | 155 | + quote := i | | 156 | + if expr[quote] == 'b' || expr[quote] == 'B' { | | 157 | + quote++ | | 158 | + } | | 159 | + raw := quote < len(expr) && (expr[quote] == 'r' || expr[quote] == 'R') | | 160 | + if raw { | | 161 | + quote++ | | 162 | + } | | 163 | + if quote >= len(expr) || (expr[quote] != '\'' && expr[quote] != '"') { | | 164 | + return i | | 165 | + } | | 166 | + delimiter := expr[quote : quote+1] | | 167 | + if strings.HasPrefix(expr[quote:], strings.Repeat(delimiter, 3)) { | | 168 | + delimiter = strings.Repeat(delimiter, 3) | | 169 | + } | | 170 | + j := quote + len(delimiter) | | 171 | + for j < len(expr) { | | 172 | + if !raw && expr[j] == '\\' { | | 173 | + j += 2 | | 174 | + continue | | 175 | + } | | 176 | + if strings.HasPrefix(expr[j:], delimiter) { | | 177 | + return j + len(delimiter) | | 178 | + } | | 179 | + j++ | | 180 | + } | | 181 | + return len(expr) | 148 | 182 | } | 149 | 183 |
| 150 | 184 | // PrepareWhen turns a rule's `when` expression into the source that is | |
|