Develop a schema validation gateway intercepting JSON, proto, and GraphQL payloads with…
- User
Develop a schema validation gateway intercepting JSON, proto, and GraphQL payloads with policy engines.
Assistant
Develop a schema validation gateway intercepting JSON, proto, and GraphQL payloads with policy engines.
The user wants a "schema validation gateway" that can intercept various payload formats (JSON, Protobuf, GraphQL) and validate them using policy engines. This is a request for a system design and implementation guide.
1. Deconstruct the Request:
2. Identify Key Components:
3. Architectural Strategy:
4. Handling Specific Payloads:
.proto schema, the gateway needs the .proto definitions to decode the binary payload into a structured object (or validate raw bytes, which is hard). Usually, you decode -> validate.{"query": "...", "variables": {...}}).
5. The Policy Aspect:
6. Structuring the Solution:
7. Refining the "Proto" Challenge:
.pb).8. Refining the "GraphQL" Challenge:
/graphql).9. Drafting the Code/Design (Go-centric):
Core Interface:
type Validator interface {
Validate(payload []byte, schema Schema, policy Policy) error
}
Component 1: OPA Integration. Use opa-go SDK.
Component 2: JSON Schema. Use github.com/xeipuuv/gojsonschema.
Component 3: Proto. Use protoreflect to dynamically parse messages if descriptors are available.
10. Creating the Output:
11. Self-Correction/Review during drafting:
12. Final Polish:
(Self-Correction during coding example): I should use a standard middleware pattern. For OPA, I'll pass the parsed JSON object as input. For Proto, I'll assume the request body is the binary proto message (in a gRPC context) or wrapped in JSON. Let's assume JSON for simplicity in a "Gateway" context, or explicitly handle gRPC decoding. Let's handle gRPC decoding as it's a requirement for "intercepting proto payloads".
Plan:
Let's write the response following this structure. This is a system design and implementation guide for a high-performance Schema Validation Gateway. This gateway acts as a middleware layer that inspects HTTP/gRPC traffic, parses payloads (JSON, Protobuf, GraphQL), and validates them against structural schemas and business logic policies.
We will build this as an API Gateway Middleware (potentially deployable as an Envoy External Processor or a standard Go HTTP Reverse Proxy).
The Core Components:
discount cannot exceed 50% if role is junior").github.com/xeipuuv/gojsonschemagoogle.golang.org/protobuf (Dynamic PB)github.com/graphql-go/graphqlThe gateway needs to know what to validate against. We define a registry that maps API endpoints to specific schema files.
package main
import (
"encoding/json"
"fmt"
"os"
)
// SchemaDefinition holds the raw definitions for a specific API endpoint
type SchemaDefinition struct {
Route string `json:"route"` // e.g., "/api/v1/users"
// JSON Schema specific
JsonSchema string `json:"json_schema,omitempty"`
// GraphQL specific (Query/Mutation name to validate)
GraphQLSchema string `json:"graphql_schema,omitempty"`
GraphQLOperation string `json:"graphql_operation,omitempty"`
// Protobuf specific (Method name)
ProtoDescriptorFile string `json:"proto_descriptor_file,omitempty"` // Binary .pb file
ProtoMessageName string `json:"proto_message_name,omitempty"`
// OPA Policy Module
PolicyRego string `json:"policy_rego,omitempty"`
}
type SchemaRegistry struct {
definitions map[string]SchemaDefinition
}
func NewSchemaRegistry() *SchemaRegistry {
return &SchemaRegistry{definitions: make(map[string]SchemaDefinition)}
}
func (r *SchemaRegistry) LoadConfig(path string) error {
// In production, this would watch a directory or talk to a DB
data, _ := os.ReadFile(path)
var defs []SchemaDefinition
if err := json.Unmarshal(data, &defs); err != nil {
return err
}
for _, d := range defs {
r.definitions[d.Route] = d
}
return nil
}
func (r *SchemaRegistry) Get(route string) (SchemaDefinition, error) {
def, exists := r.definitions[route]
if !exists {
return SchemaDefinition{}, fmt.Errorf("no schema defined for route %s", route)
}
return def, nil
}
This is where the heavy lifting happens. We handle the three formats differently.
JSON validation is straightforward schema matching.
import (
"github.com/xeipuuv/gojsonschema"
)
func ValidateJSON(payload string, schema string) (bool, []string, error) {
schemaLoader := gojsonschema.NewStringLoader(schema)
documentLoader := gojsonschema.NewStringLoader(payload)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return false, nil, err
}
if result.Valid() {
return true, nil, nil
}
var errors []string
for _, desc := range result.Errors() {
errors = append(errors, desc.String())
}
return false, errors, nil
}
Protobuf is binary. To validate it, we need the compiled .pb files (FileDescriptorSet) to unmarshal the raw bytes dynamically. If Unmarshal succeeds, the schema is valid.
import (
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/dynamicpb"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
descriptorpb "google.golang.org/protobuf/types/descriptorpb"
)
func ValidateProtobuf(payload []byte, descriptorPath string, msgName string) (bool, *dynamicpb.Message, error) {
// 1. Load FileDescriptorSet (compiled proto files)
b, err := os.ReadFile(descriptorPath)
if err != nil {
return false, nil, err
}
fds := &descriptorpb.FileDescriptorSet{}
if err := proto.Unmarshal(b, fds); err != nil {
return false, nil, err
}
// 2. Create a Resolver to find the message type
files, err := protodesc.NewFiles(fds)
if err != nil {
return false, nil, err
}
desc, err := files.FindDescriptorByName(protoreflect.FullName(msgName))
if err != nil {
return false, nil, err
}
msgDesc := desc.(protoreflect.MessageDescriptor)
// 3. Dynamic Unmarshal
dynMsg := dynamicpb.NewMessage(msgDesc)
if err := proto.Unmarshal(payload, dynMsg); err != nil {
// Schema validation failed (malformed binary or wrong type)
return false, nil, fmt.Errorf("proto validation failed: %v", err)
}
return true, dynMsg, nil
}
GraphQL usually arrives as JSON {"query": "...", "variables": {...}}. We validate the query structure against the schema.
import (
"github.com/graphql-go/graphql"
)
func ValidateGraphQL(requestBody string, schema string) (bool, map[string]interface{}, error) {
// Parse the incoming JSON body to get query and variables
var req struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}
if err := json.Unmarshal([]byte(requestBody), &req); err != nil {
return false, nil, err
}
// Parse Schema
gqlSchema, err := graphql.ParseSchema(schema, nil)
if err != nil {
return false, nil, err
}
// Validate Query
params := graphql.Params{
Schema: gqlSchema,
RequestString: req.Query,
VariableValues: req.Variables,
}
// We only validate, we don't execute (Do)
// In a real gateway, you might actually Do() if acting as a proxy,
// but here we just check syntax/validity via parsing logic or a separate validation step.
// For brevity, we'll use a lightweight validation approach:
// (Note: Production usually requires a more robust parser logic)
// To strictly validate without executing, we look at the parsing result.
// However, graphql-go executes to validate deeply.
// Let's assume validation passes if ParseSchema didn't fail and query looks parsable.
// A deeper implementation would use `gqlparser` directly.
// Returning the variables for Policy Engine
return true, req.Variables, nil
}
Once the schema is validated (ensuring the data structure is safe), we check the content using OPA.
Rego Policy Example (policy.rego):
package authz
default allow = false
# Policy: Allow unless the discount is too high for a non-VIP user
allow {
input.method == "POST"
input.path == "/api/v1/orders"
input.body.discount <= 50
input.user.role == "junior"
}
allow {
input.user.role == "admin"
}
Go Integration:
import (
"context"
"encoding/json"
"github.com/open-policy-agent/opa/rego"
)
type OPADecision struct {
Allow bool `json:"allow"`
}
func EvaluatePolicy(ctx context.Context, regoQuery string, input map[string]interface{}) (bool, error) {
r := rego.New(
rego.Query("data.authz.allow"),
rego.Module("policy.rego", regoQuery),
)
query, err := r.PrepareForEval(ctx)
if err != nil {
return false, err
}
rs, err := query.Eval(ctx, rego.EvalInput(input))
if err != nil {
return false, err
}
if len(rs) == 0 || len(rs[0].Expressions) == 0 {
return false, nil
}
return rs[0].Expressions[0].Value.(bool), nil
}
This ties everything together.
import (
"encoding/json"
"io"
"net/http"
)
type ValidationGateway struct {
Registry *SchemaRegistry
}
func (g *ValidationGateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 1. Lookup Schema
def, err := g.Registry.Get(r.URL.Path)
if err != nil {
http.Error(w, "Route not configured", http.StatusNotFound)
return
}
// Read Body
bodyBytes, _ := io.ReadAll(r.Body)
r.Body.Close() // Important to close
var dataForPolicy interface{}
var valid bool
// 2. Schema Validation
contentType := r.Header.Get("Content-Type")
switch {
case contentType == "application/json" && def.JsonSchema != "":
valid, _, err = ValidateJSON(string(bodyBytes), def.JsonSchema)
if err != nil { http.Error(w, "JSON Schema Error", http.StatusBadRequest); return }
// Parse to map for OPA
json.Unmarshal(bodyBytes, &dataForPolicy)
case contentType == "application/x-protobuf":
// Assuming we push the descriptor path from config
valid, dynMsg, err := ValidateProtobuf(bodyBytes, def.ProtoDescriptorFile, def.ProtoMessageName)
if err != nil { http.Error(w, "Proto Validation Error", http.StatusBadRequest); return }
// Convert DynMsg to Map for OPA
dataForPolicy = dynMsg
case contentType == "application/json" && def.GraphQLSchema != "":
// GraphQL usually comes in JSON wrapper
var gqlReq struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}
json.Unmarshal(bodyBytes, &gqlReq)
// Here you would validate the gqlReq.Query string
// ... implementation details omitted for brevity ...
dataForPolicy = gqlReq.Variables
}
if !valid {
http.Error(w, "Schema Validation Failed", http.StatusBadRequest)
return
}
// 3. Policy Validation (OPA)
// Construct input context
input := map[string]interface{}{
"user": map[string]interface{}{ // Mock user context
"role": r.Header.Get("X-User-Role"),
},
"method": r.Method,
"path": r.URL.Path,
"body": dataForPolicy,
}
allowed, err := EvaluatePolicy(r.Context(), def.PolicyRego, input)
if err != nil {
http.Error(w, "Policy Evaluation Error", http.StatusInternalServerError)
return
}
if !allowed {
http.Error(w, "Forbidden by Policy", http.StatusForbidden)
return
}
// 4. Forward or Success
// In a real gateway, we would forward the request to the upstream service here.
// For this example, we return a success message.
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status": "validated and authorized"}`))
}
To make this robust for production:
envoy.service.ext_proc.v3.ExternalProcessor interface.
ALLOW or DENY.GetOrLoad pattern.SchemaRegistry should watch a file system or a Kubernetes ConfigMap. When schemas change, reload the definitions without restarting the gateway pods.