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 — Allow parsing of graphQL queries by dpup · Pull Request #14 · majorcontext/keep

Allow parsing of graphQL queries #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
dpup merged 4 commits into main from claude/moat-github-access-policy-b43vj7
Nov 2, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

Allow parsing of graphQL queries #14

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit Hold shift + click to select a range
1a47892
feat(cel): add graphql() request parser
claude Nov 2, 2026
eac28a5
feat(engine): add RequiresBodyFor
claude Nov 2, 2026
70b52f1
docs: add graphql() and RequiresBodyFor to CHANGELOG
claude Nov 2, 2026
4630cf0
fix: substitute defs when validating rule bytes
claude Nov 2, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
feat(engine): add RequiresBodyFor
Engine.RequiresBodyFor(scope, call) narrows RequiresBody by operation: a
rule that reads params.body counts only when its operation glob matches
the call (normalized as Evaluate normalizes it). Pinning a body rule to
one endpoint, e.g. `post api.github.com/graphql`, lets a gatekeeper
buffer bodies for that endpoint alone instead of making the whole scope
JSON-only. An unknown scope returns true.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0181tDqDyMAGnCcqMAd2JEWf
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@claude
claude committed Nov 2, 2026
commit eac28a50e6643a17f679250aabb6439c3e7c1c37

There are no files selected for viewing

19 changes: 19 additions & 0 deletions 19 docs/content/guides/06-go-library.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,25 @@ func middleware(engine *keep.Engine, scope string) http.HandlerFunc {

`RequiresBody` fails safe: it detects every idiomatic body reference (`params.body.x`, `params["body"]`, `has(params.body)`, comprehensions, the `in` operator), and for any unrecognized use of the `params` map -- or an unknown scope name -- it returns `true` so the body is buffered rather than silently skipped.

`RequiresBody` answers for the whole scope: one body rule makes every request in the scope need its body. When a body rule only applies to one endpoint, pin it with `operation` and call `Engine.RequiresBodyFor(scope, call)` instead. It counts a body rule only when the rule's `operation` glob matches the call (a body rule without `operation` still counts for every call), so other requests in the scope -- including ones with non-JSON bodies -- are never buffered:

```yaml
- name: no-issue-deletion
match:
operation: "post api.linear.app/graphql"
when: "graphql(params.body).mutations.exists(m, m.name == 'issueDelete')"
action: deny
```

```go
probe := keep.NewHTTPCall(r.Method, r.Host, r.URL.Path) // same operation, no body
if engine.RequiresBodyFor(scope, probe) {
// buffer and decode the body as above
}
```

The operation is normalized the same way `Evaluate` normalizes it, so `POST API.Linear.app/graphql` matches the lowercase pattern in a case-insensitive scope. Like `RequiresBody`, it returns `true` for an unknown scope.

## Handle decisions

`result.Decision` is one of three values:
Expand Down
42 changes: 40 additions & 2 deletions 42 internal/engine/eval.go
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ type Evaluator struct {
caseSensitive bool
judgeFunc JudgeHandler
requiresBody bool // precomputed: any rule references params.body
// bodyRuleOps holds the operation glob of every rule that references
// params.body ("" for a rule with no operation, which matches every call).
// Precomputed so RequiresBodyFor is a short glob scan per request.
bodyRuleOps []string
}

// SetJudgeFunc sets the judge handler for this evaluator.
Expand All @@ -153,14 +157,47 @@ func (ev *Evaluator) RequiresBody() bool {
return ev.requiresBody
}

// RequiresBodyFor reports whether evaluating a call with the given operation
// needs the request body. It narrows RequiresBody by each body rule's
// operation glob: a rule that references params.body only counts when its
// operation matches (a body rule with no operation counts for every call).
// The operation is normalized exactly as Evaluate normalizes it, so a pinned
// rule like `operation: "post api.example.com/graphql"` matches regardless of
// the case the caller used for method or host.
//
// Gatekeepers use this to buffer bodies only for the requests a body rule can
// actually inspect, instead of every request in the scope.
func (ev *Evaluator) RequiresBodyFor(operation string) bool {
if !ev.requiresBody {
return false
}
op := operation
if !ev.caseSensitive {
op = strings.ToLower(op)
}
for _, pattern := range ev.bodyRuleOps {
if GlobMatch(pattern, op) {
return true
}
}
return false
}

// computeRequiresBody reports whether any compiled rule references params.body.
func computeRequiresBody(rules []compiledRule) bool {
return len(bodyRuleOperations(rules)) > 0
}

// bodyRuleOperations returns the operation glob of every compiled rule that
// references params.body.
func bodyRuleOperations(rules []compiledRule) []string {
var ops []string
for _, cr := range rules {
if cr.program.ReferencesParam(ParamBody) {
return true
ops = append(ops, cr.rule.Match.Operation)
}
}
return false
return ops
}

// NewEvaluator creates an evaluator for a scope. Compiles all CEL expressions
Expand Down Expand Up @@ -227,6 +264,7 @@ func NewEvaluator(
secrets: detector,
caseSensitive: caseSensitive,
requiresBody: computeRequiresBody(compiled),
bodyRuleOps: bodyRuleOperations(compiled),
}, nil
}

Expand Down
59 changes: 59 additions & 0 deletions 59 internal/engine/requires_body_test.go
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,62 @@ func TestEvaluator_RequiresBody_ViaAlias(t *testing.T) {
t.Error("RequiresBody() = false, want true (body reference via alias)")
}
}

func TestEvaluator_RequiresBodyFor(t *testing.T) {
const graphqlOp = "POST api.github.com/graphql"
const pushOp = "POST github.com/o/r.git/git-receive-pack"

pinned := []config.Rule{
{Name: "path-only", Action: config.ActionDeny, Match: config.Match{When: "params.path.startsWith('/admin')"}},
{Name: "gql", Action: config.ActionDeny, Match: config.Match{
Operation: "post api.github.com/graphql",
When: "graphql(params.body).mutations.exists(m, m.name == 'deleteRef')",
}},
}
unpinned := []config.Rule{
{Name: "secrets", Action: config.ActionDeny, Match: config.Match{When: "hasSecrets(params.body)"}},
}
noBody := []config.Rule{
{Name: "method", Action: config.ActionDeny, Match: config.Match{Operation: "post *", When: "params.method == 'POST'"}},
}

tests := []struct {
name string
rules []config.Rule
caseSensitive bool
op string
want bool
}{
{"pinned rule matches its operation", pinned, false, graphqlOp, true},
{"pinned rule matches mixed-case method and host", pinned, false, "post API.GitHub.com/graphql", true},
{"pinned rule skips other operations", pinned, false, pushOp, false},
{"pinned rule skips other paths on the same host", pinned, false, "POST api.github.com/repos/o/r/pulls", false},
{"unpinned body rule applies to every call", unpinned, false, pushOp, true},
{"unpinned body rule applies to graphql too", unpinned, false, graphqlOp, true},
{"no body rules", noBody, false, graphqlOp, false},
{"case-sensitive scope matches exact case", []config.Rule{{Name: "gql", Action: config.ActionDeny, Match: config.Match{
Operation: "POST api.github.com/graphql", When: "graphql(params.body).valid == false"}}}, true, graphqlOp, true},
{"case-sensitive scope does not fold case", []config.Rule{{Name: "gql", Action: config.ActionDeny, Match: config.Match{
Operation: "POST api.github.com/graphql", When: "graphql(params.body).valid == false"}}}, true, "post api.github.com/graphql", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
env, err := keepcel.NewEnv()
if err != nil {
t.Fatal(err)
}
ev, err := NewEvaluator(env, "http", config.ModeEnforce, config.ErrorModeClosed, tt.rules, nil, nil, nil, tt.caseSensitive)
if err != nil {
t.Fatal(err)
}
if got := ev.RequiresBodyFor(tt.op); got != tt.want {
t.Errorf("RequiresBodyFor(%q) = %v, want %v", tt.op, got, tt.want)
}
// RequiresBodyFor never answers true where the scope-wide
// RequiresBody says no body rule exists.
if !ev.RequiresBody() && ev.RequiresBodyFor(tt.op) {
t.Error("RequiresBodyFor true while RequiresBody false")
}
})
}
}
23 changes: 23 additions & 0 deletions 23 keep.go
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,29 @@ func (e *Engine) RequiresBody(scope string) bool {
return ev.RequiresBody()
}

// RequiresBodyFor reports whether evaluating call in the given scope needs the
// request body (params.body). It narrows RequiresBody by operation: a rule that
// references params.body only counts when its `operation` glob matches
// call.Operation (normalized the way Evaluate normalizes it), and a body rule
// with no operation counts for every call.
//
// Gatekeepers should prefer it over RequiresBody so that pinning a body rule to
// an operation — e.g. `operation: "post api.github.com/graphql"` — buffers and
// parses bodies only for matching requests, leaving other requests in the scope
// (including ones with non-JSON bodies) untouched. Build call the same way it
// will be evaluated, without a body (e.g. NewHTTPCall).
//
// Like RequiresBody it fails safe: an unknown scope returns true.
func (e *Engine) RequiresBodyFor(scope string, call Call) bool {
e.mu.RLock()
ev, ok := e.evaluators[scope]
e.mu.RUnlock()
if !ok {
return true
}
return ev.RequiresBodyFor(call.Operation)
}

// Scopes returns the sorted list of loaded scope names.
func (e *Engine) Scopes() []string {
e.mu.RLock()
Expand Down
103 changes: 103 additions & 0 deletions 103 keep_test.go
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -1030,3 +1031,105 @@ func TestRuleSet_EmptyCompiles(t *testing.T) {
t.Errorf("Decision = %q, want allow", result.Decision)
}
}

// githubGraphQLPolicy pins a graphql() body rule to the GitHub GraphQL endpoint
// alongside a path-only rule, the shape a gatekeeper policy takes when it must
// inspect GraphQL bodies without buffering git smart-HTTP traffic.
const githubGraphQLPolicy = `
scope: http
mode: enforce
defs:
allowed_repo_ids: '["R_kgDOAbCd"]'
rules:
- name: graphql-invalid
match:
operation: "post api.github.com/graphql"
when: "!graphql(params.body).valid"
action: deny
message: "Unparseable GraphQL request."
- name: graphql-repo
match:
operation: "post api.github.com/graphql"
when: >
graphql(params.body).mutations.exists(m,
has(m.args.input) && has(m.args.input.repositoryId) &&
!(m.args.input.repositoryId in allowed_repo_ids))
action: deny
message: "Mutation targets a repository outside the allowlist."
- name: no-delete
match:
when: "params.method == 'delete'"
action: deny
`

func TestRequiresBodyFor(t *testing.T) {
eng, err := keep.LoadFromBytes([]byte(githubGraphQLPolicy))
if err != nil {
t.Fatalf("LoadFromBytes: %v", err)
}
defer eng.Close()

if !eng.RequiresBody("http") {
t.Fatal("RequiresBody(http) = false, want true (graphql(params.body) reads the body)")
}
if !eng.RequiresBodyFor("http", keep.NewHTTPCall("POST", "api.github.com", "/graphql")) {
t.Error("RequiresBodyFor(graphql) = false, want true")
}
// Companion: git smart-HTTP to github.com must not need a body, or a
// gatekeeper would fail closed on its non-JSON pack payload.
if eng.RequiresBodyFor("http", keep.NewHTTPCall("POST", "github.com", "/o/r.git/git-receive-pack")) {
t.Error("RequiresBodyFor(git-receive-pack) = true, want false")
}
if !eng.RequiresBodyFor("does-not-exist", keep.NewHTTPCall("GET", "example.com", "/")) {
t.Error("RequiresBodyFor(unknown scope) = false, want true (fail-safe)")
}
}

func TestGraphQLPolicy_EndToEnd(t *testing.T) {
for _, caseSensitive := range []bool{false, true} {
policy := githubGraphQLPolicy
if caseSensitive {
policy = strings.Replace(policy, "mode: enforce", "mode: enforce\ncase_sensitive: true", 1)
policy = strings.ReplaceAll(policy, `operation: "post api.github.com/graphql"`, `operation: "POST api.github.com/graphql"`)
}
eng, err := keep.LoadFromBytes([]byte(policy))
if err != nil {
t.Fatalf("LoadFromBytes(case_sensitive=%v): %v", caseSensitive, err)
}

mutation := func(repoID string) keep.Call {
return keep.NewHTTPCallWithBody("POST", "api.github.com", "/graphql", map[string]any{
"query": "mutation($input: CreatePullRequestInput!) { createPullRequest(input: $input) { clientMutationId } }",
"variables": map[string]any{"input": map[string]any{"repositoryId": repoID}},
})
}

cases := []struct {
name string
call keep.Call
want keep.Decision
}{
// Mixed-case node ID only matches when the original case is parsed,
// including in the default case-insensitive scope.
{"allowed repo", mutation("R_kgDOAbCd"), keep.Allow},
{"other repo", mutation("R_kgDOZzZz"), keep.Deny},
{"lowercased allowed id is a different id", mutation("r_kgdoabcd"), keep.Deny},
{"query", keep.NewHTTPCallWithBody("POST", "api.github.com", "/graphql",
map[string]any{"query": "{ viewer { login } }"}), keep.Allow},
{"unparseable", keep.NewHTTPCallWithBody("POST", "api.github.com", "/graphql",
map[string]any{"query": "mutation {"}), keep.Deny},
{"batched array body", keep.NewHTTPCallWithBody("POST", "api.github.com", "/graphql",
[]any{map[string]any{"query": "{ viewer { login } }"}}), keep.Deny},
}
for _, c := range cases {
res, err := eng.Evaluate(context.Background(), c.call, "http")
if err != nil {
t.Fatalf("case_sensitive=%v %s: Evaluate: %v", caseSensitive, c.name, err)
}
if res.Decision != c.want {
t.Errorf("case_sensitive=%v %s: decision = %s (rule %q), want %s", caseSensitive, c.name, res.Decision, res.Rule, c.want)
}
}
eng.Close()
}
}
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402809 — 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.