Hacktoberfest 2026: le issue che i maintainer hanno segnato per ottobre, aperte e adatte ai principianti. Sfoglia le issue Hacktoberfest

json-schema-guardrail validates a quoted JSON string when JSONPath points at message content, so object schemas always fail on OpenAI-shaped payloads

Aperta Adatta ai principianti
#3,916 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
78/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
go
Ambito
api, backend

Direzione di ricerca

Inizia in policies/json-schema-guardrail/jsonschemaguardrail.go, in corrispondenza di extractValueFromJSONPathForSchema, poi esegui go test . -run TestJSONPathStringContentValidatedAsQuotedString -v nella directory di quella policy. L’issue include il comportamento atteso e un test di regressione; il lavoro è completato quando le stringhe JSON che contengono oggetti o array vengono validate secondo questi schemi, mentre il testo semplice mantiene l’attuale validazione delle stringhe.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Description

The policy default JSONPaths are $.messages[-1].content (request) and $.choices[0].message.content (response) — the OpenAI chat fields that almost always hold a JSON string. extractValueFromJSONPathForSchema in wso2/gateway-controllers policies/json-schema-guardrail/jsonschemaguardrail.go re-marshals whatever JSONPath returns:

value, err := utils.ExtractValueFromJsonpath(jsonData, jsonPath)
// ...
valueBytes, err := json.Marshal(value)
documentLoader = gojsonschema.NewBytesLoader(valueBytes)

When content is the string {"name":"alice"}, json.Marshal produces the JSON string value "{\"name\":\"alice\"}". An object schema such as {"type":"object","required":["name"],...} then fails against a string document, and the guardrail returns 422. The same schema passes when content is already a JSON object (uncommon for chat completions).

So the advertised default path cannot validate structured content that tools and users place inside the message string — the primary use case for this guardrail on LLM APIs.

Steps to reproduce

  1. On gateway-controllers main (4cf9570), in policies/json-schema-guardrail:
func TestJSONPathStringContentValidatedAsQuotedString(t *testing.T) {
    schema := `{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}`
    p, err := GetPolicy(policy.PolicyMetadata{}, map[string]interface{}{
        "request": map[string]interface{}{
            "enabled":  true,
            "schema":   schema,
            "jsonPath": "$.messages[-1].content",
        },
    })
    if err != nil {
        t.Fatal(err)
    }
    // Typical OpenAI shape: content is a string that itself holds JSON.
    body := []byte(`{"messages":[{"role":"user","content":"{\"name\":\"alice\"}"}]}`)
    req := &policy.RequestContext{Body: &policy.Body{Content: body}}
    act := p.(*JSONSchemaGuardrailPolicy).OnRequestBody(context.Background(), req, nil)
    if _, ok := act.(policy.UpstreamRequestModifications); ok {
        t.Fatal("stringified JSON content unexpectedly passed object schema")
    }
    // Same schema with content already an object passes.
    body2 := []byte(`{"messages":[{"role":"user","content":{"name":"alice"}}]}`)
    req2 := &policy.RequestContext{Body: &policy.Body{Content: body2}}
    act2 := p.(*JSONSchemaGuardrailPolicy).OnRequestBody(context.Background(), req2, nil)
    if _, ok := act2.(policy.UpstreamRequestModifications); !ok {
        t.Fatalf("object content should pass, got %T", act2)
    }
}
  1. go test . -run TestJSONPathStringContentValidatedAsQuotedString -v

Expected behavior

When the JSONPath result is a string that parses as JSON, validate the parsed value (so the default OpenAI content path works with object/array schemas). If the string is not JSON, validate it as a JSON string (current behavior for plain text).

Actual behavior

Stringified JSON content is rejected with HTTP 422 JSON_SCHEMA_GUARDRAIL / "Violation of JSON schema detected." Object-typed content at the same path passes.

Environment

  • gateway-controllers commit: main @ 4cf9570 (filed against api-platform; gateway-controllers has issues disabled)
  • Policy: json-schema-guardrail v1.0.1 (policy-definition.yaml)
  • Go module: github.com/wso2/gateway-controllers/policies/json-schema-guardrail
  • OS: Linux x86_64

Related issues / PRs

#692 is a generic "JSON Schema Guardrail Policy Issue" pointer with no reproduction of this path. #3571 is JSONPath RFC 9535 support, not string decoding. #3413 covers upstream status masking and $.messages as a list path — different. No open/closed issue describes stringified message content vs object schema.

Possible Solution

In extractValueFromJSONPathForSchema, if value is a string, attempt json.Unmarshal into a temporary interface{} and marshal that on success; otherwise keep marshaling the string as today:

if s, ok := value.(string); ok {
    var parsed interface{}
    if err := json.Unmarshal([]byte(s), &parsed); err == nil {
        value = parsed
    }
}
valueBytes, err := json.Marshal(value)

Add the regression test above (string content fails today; object content passes).

I'm happy to send a PR.

Lingua principale
Go
Stelle
79
Fork
130
Merge medio
2g 2h
PR unite (30g)
157

Preparare l'ambiente

  • Nessun Dockerfile né file Docker Compose
  • Ha un modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di wso2/api-platform

Tutte le issue di wso2/api-platform

Issue simili

Altre issue su Go

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.