GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(cel): preserve original case across CEL syntax · majorcontext/keep@d7388fe

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • CHANGELOG.md
  • docs/content/reference
    • 03-cel-functions.md
  • internal/cel
    • alias.go
    • alias_test.go
    • graphql_test.go
    • rewrite.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎CHANGELOG.md‎

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 numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
## [0.7.0] - 2026-11-02
11+
1012
### Added
1113

1214
- **`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
1618

1719
- 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.
1820
- 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.
1922

2023
## [0.6.0] - 2026-06-22
2124

Collapse file

‎docs/content/reference/03-cel-functions.md‎

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 numberDiff line numberDiff line change
@@ -283,6 +283,7 @@ Semantics:
283283
- **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.
284284
- **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.
285285
- **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.
286287
- **Limits.** Documents over 100,000 tokens, fragment nesting deeper than 32 levels, or more than 1,000 expanded root fields are invalid.
287288
- **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.
288289

Collapse file

‎internal/cel/alias.go‎

Copy file name to clipboardExpand all lines: internal/cel/alias.go
+7-37Lines changed: 7 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -29,44 +29,14 @@ func ResolveAliases(expr string, aliases map[string]string) string {
2929
for i < n {
3030
c := expr[i]
3131

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]
6838
}
69-
prevNonIdent = '"'
39+
i = end
7040
continue
7141
}
7242

Collapse file

‎internal/cel/alias_test.go‎

Copy file name to clipboardExpand all lines: internal/cel/alias_test.go
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@ import (
44
"testing"
55
)
66

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+
718
func TestResolveAliases_Simple(t *testing.T) {
819
aliases := map[string]string{
920
"priority": "params.priority",
Collapse file

‎internal/cel/graphql_test.go‎

Copy file name to clipboardExpand all lines: internal/cel/graphql_test.go
+74-1Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ func TestParseGraphQLRequest_Subscription(t *testing.T) {
215215

216216
func TestParseGraphQLRequest_StringEscapesDecoded(t *testing.T) {
217217
// 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))
219219
mustValid(t, res)
220220
input := fieldsOf(t, res, "mutations")[0]["args"].(map[string]any)["input"].(map[string]any)
221221
if input["repositoryId"] != "R_ABC" {
@@ -388,6 +388,79 @@ func TestGraphQL_CEL_OriginalCase(t *testing.T) {
388388
}
389389
}
390390

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+
391464
func TestInjectOriginalParams_GraphQL(t *testing.T) {
392465
tests := []struct {
393466
in, want string
Collapse file

‎internal/cel/rewrite.go‎

Copy file name to clipboardExpand all lines: internal/cel/rewrite.go
+80-46Lines changed: 80 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -31,42 +31,29 @@ func InjectOriginalParams(expr string) string {
3131
}
3232

3333
func injectOriginalParamsForFunc(expr string, fnName string) string {
34-
prefix := fnName + "("
3534
result := expr
3635
offset := 0
3736

3837
for {
39-
idx := findCall(result, prefix, offset)
40-
if idx < 0 {
38+
start := findCallStart(result, fnName, offset)
39+
if start < 0 {
4140
break
4241
}
43-
start := idx + len(prefix) // position after opening paren
4442

4543
// Find the matching closing paren, respecting nesting and string literals.
4644
depth := 1
4745
commaFound := false
4846
i := start
4947
for i < len(result) && depth > 0 {
48+
if end := skipCELLiteralOrComment(result, i); end > i {
49+
i = end
50+
continue
51+
}
5052
c := result[i]
5153
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 == '{':
6855
depth++
69-
case c == ')':
56+
case c == ')' || c == ']' || c == '}':
7057
depth--
7158
case c == ',' && depth == 1:
7259
commaFound = true
@@ -91,9 +78,11 @@ func injectOriginalParamsForFunc(expr string, fnName string) string {
9178
// injecting the full _originalParams map.
9279
arg := result[start:closePos]
9380
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"):]
9786
inject = ", " + origArg
9887
} else {
9988
inject = ", _originalParams"
@@ -109,42 +98,87 @@ func injectOriginalParamsForFunc(expr string, fnName string) string {
10998
return result
11099
}
111100

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
114104
// (`'graphql(x)'`) or as the tail of a longer identifier or a method call
115105
// (`mygraphql(`, `x.graphql(`) are not call sites of the global function and
116106
// 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
119109
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]
127113
}
114+
i = end - 1
128115
continue
129116
}
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) {
135119
continue
136120
}
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+
}
139135
}
140-
return i
136+
previous = c
141137
}
142138
return -1
143139
}
144140

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)
148182
}
149183

150184
// PrepareWhen turns a rule's `when` expression into the source that is

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.