forked from corazawaf/coraza
-
Notifications
You must be signed in to change notification settings - Fork 0
ENG-0000: GraphQL Body Processor Implementation #10
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.
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
Open
piyushroshan
wants to merge
8
commits into
traceable-main
Choose a base branch
from
gqlbodyprocessor
base: traceable-main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
bbdfaba
Add graphql body processor
piyushroshan 2f7d794
fix tests
piyushroshan 595926b
fix tests
piyushroshan 0de1e90
Add graphql test
piyushroshan 6ca5039
Fix concat get
piyushroshan 81635aa
Honour case sensitivity for concat too
piyushroshan a377bce
Fix gql processing
soujanyanmbri 9529c36
Fix gql processing
soujanyanmbri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| package bodyprocessors | ||
|
|
||
| var ReadJson = readJSON |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| // Copyright 2022 Juan Pablo Tosso and the OWASP Coraza contributors | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package bodyprocessors | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "strconv" | ||
| "strings" | ||
|
|
||
| "github.com/corazawaf/coraza/v3/collection" | ||
| "github.com/corazawaf/coraza/v3/experimental/plugins/plugintypes" | ||
| "github.com/graphql-go/graphql/language/ast" | ||
| "github.com/graphql-go/graphql/language/parser" | ||
| "github.com/tidwall/gjson" | ||
| ) | ||
|
|
||
| type graphqlBodyProcessor struct{} | ||
|
|
||
| type graphqlRequest struct { | ||
| Query string `json:"query"` | ||
| Variables map[string]interface{} `json:"variables"` | ||
| OperationName string `json:"operationName"` | ||
| } | ||
|
|
||
| var _ plugintypes.BodyProcessor = &graphqlBodyProcessor{} | ||
|
|
||
| func (gp *graphqlBodyProcessor) ProcessRequest(reader io.Reader, v plugintypes.TransactionVariables, _ plugintypes.BodyProcessorOptions) error { | ||
| bodyBytes, err := io.ReadAll(reader) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to read request body: %w", err) | ||
| } | ||
| bodyStr := strings.TrimSpace(string(bodyBytes)) | ||
|
|
||
| // Check for batch gql requests | ||
| if strings.HasPrefix(bodyStr, "[") { | ||
| if err := processBatchGraphQL(bodyStr, v); err == nil { | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| // Process single gql request | ||
| if err := processSingleGraphQL(bodyStr, v); err == nil { | ||
| return nil | ||
| } | ||
|
|
||
| // Fallback to processing as JsON | ||
| return processJSONRequest(bodyStr, v) | ||
| } | ||
|
|
||
| func processBatchGraphQL(bodyStr string, v plugintypes.TransactionVariables) error { | ||
| var requests []graphqlRequest | ||
| if err := json.Unmarshal([]byte(bodyStr), &requests); err != nil { | ||
| return fmt.Errorf("invalid gql batch request: %w", err) | ||
| } | ||
|
|
||
| for _, req := range requests { | ||
| if req.Query == "" { | ||
| continue | ||
| } | ||
| if err := processGraphQLRequest(req.Query, v); err != nil { | ||
| return fmt.Errorf("invalid gql batch request: %w", err) | ||
| } | ||
| processGraphQLVariables(req.Variables, v) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func processSingleGraphQL(bodyStr string, v plugintypes.TransactionVariables) error { | ||
| var req graphqlRequest | ||
| if err := json.Unmarshal([]byte(bodyStr), &req); err != nil { | ||
| return fmt.Errorf("invalid gql request: %w", err) | ||
| } | ||
|
|
||
| if req.Query == "" { | ||
| return fmt.Errorf("missing gql query") | ||
| } | ||
|
|
||
| if err := processGraphQLRequest(req.Query, v); err != nil { | ||
| return fmt.Errorf("invalid gql request: %w", err) | ||
| } | ||
|
|
||
| processGraphQLVariables(req.Variables, v) | ||
| return nil | ||
| } | ||
|
|
||
| func processJSONRequest(bodyStr string, v plugintypes.TransactionVariables) error { | ||
| items, err := parseJSON(bodyStr) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| col := v.ArgsPost() | ||
| for k, v := range items { | ||
| col.SetIndex(k, 0, v) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func processGraphQLVariables(variables map[string]interface{}, v plugintypes.TransactionVariables) { | ||
| if len(variables) == 0 { | ||
| return | ||
| } | ||
|
|
||
| col := v.ArgsPost() | ||
| for k, val := range variables { | ||
| switch v := val.(type) { | ||
| case string: | ||
| col.Add(k, v) | ||
| default: | ||
| jsonStr, _ := json.Marshal(v) | ||
| col.Add(k, string(jsonStr)) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func (gp *graphqlBodyProcessor) ProcessResponse(reader io.Reader, v plugintypes.TransactionVariables, _ plugintypes.BodyProcessorOptions) error { | ||
| col := v.ResponseArgs() | ||
| data, err := readJSON(reader) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| for key, value := range data { | ||
| col.SetIndex(key, 0, value) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func processGraphQLRequest(query string, v plugintypes.TransactionVariables) error { | ||
| doc, err := parser.Parse(parser.ParseParams{Source: query}) | ||
| if err != nil { | ||
| return fmt.Errorf("invalid GraphQL query: %w", err) | ||
| } | ||
|
|
||
| headersCol := v.RequestHeaders() | ||
| argsCol := v.ArgsPost() | ||
|
|
||
| for _, def := range doc.Definitions { | ||
| if opDef, ok := def.(*ast.OperationDefinition); ok { | ||
| operationName := opDef.Operation | ||
| if opDef.Name != nil { | ||
| operationName += opDef.Name.Value | ||
| } | ||
| headersCol.SetIndex("graphql.operation", 0, operationName) | ||
|
|
||
| if opDef.SelectionSet != nil { | ||
| for _, selection := range opDef.SelectionSet.Selections { | ||
| if field, ok := selection.(*ast.Field); ok { | ||
| headersCol.SetIndex("graphql.field", 0, field.Name.Value) | ||
| processGraphQLArguments(field.Arguments, argsCol) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func processGraphQLArguments(args []*ast.Argument, col collection.Map) { | ||
| for _, arg := range args { | ||
| valMap := flattenArgument(arg) | ||
| for k, v := range valMap { | ||
| col.Add(k, v) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func parseJSON(s string) (map[string]string, error) { | ||
| jsonParsed := gjson.Parse(s) | ||
| result := make(map[string]string) | ||
| key := []byte("") | ||
| readItems(jsonParsed, key, result) | ||
| return result, nil | ||
| } | ||
|
|
||
| func flattenArgument(arg *ast.Argument) map[string]string { | ||
| res := make(map[string]string) | ||
| key := []byte(arg.Name.Value) | ||
| readAstValue(key, arg.Value, res) | ||
| return res | ||
| } | ||
|
|
||
| func readAstValue(objKey []byte, value ast.Value, res map[string]string) { | ||
| switch v := value.(type) { | ||
| case *ast.StringValue: | ||
| res[string(objKey)] = v.Value | ||
| case *ast.IntValue: | ||
| res[string(objKey)] = v.Value | ||
| case *ast.FloatValue: | ||
| res[string(objKey)] = v.Value | ||
| case *ast.BooleanValue: | ||
| res[string(objKey)] = strconv.FormatBool(v.Value) | ||
| case *ast.EnumValue: | ||
| res[string(objKey)] = v.Value | ||
| case *ast.ListValue: | ||
| for i, val := range v.Values { | ||
| subKey := append(objKey, fmt.Sprintf(".[%d]", i)...) | ||
| readAstValue(subKey, val, res) | ||
| } | ||
| res[string(objKey)] = strconv.Itoa(len(v.Values)) | ||
| case *ast.ObjectValue: | ||
| for _, field := range v.Fields { | ||
| subKey := append(objKey, "."+field.Name.Value...) | ||
| readAstValue(subKey, field.Value, res) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func init() { | ||
| RegisterBodyProcessor("graphql", func() plugintypes.BodyProcessor { | ||
| return &graphqlBodyProcessor{} | ||
| }) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.