Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,9 @@ func (s *SpecValidator) Validate(data any) (*Result, *Result) {
errs.Merge(s.validateNonEmptyPathParamNames())

// errs.Merge(s.validateRefNoSibling()) // warning only
errs.Merge(s.validateReferenced()) // warning only
errs.Merge(s.validateDubiousRefs()) // warning only
errs.Merge(s.validateReferenced()) // warning only
errs.Merge(s.validateDubiousRefs()) // warning only
errs.Merge(s.validateDubiousNames()) // warning only

return errs, warnings
}
Expand Down
10 changes: 10 additions & 0 deletions spec_messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,12 @@ const (
// may indicate an unsafe or adversarial spec.
DubiousMultipleHostsWarning = "$ref values point to %d distinct remote hosts (%s): a spec referencing multiple hosts may be unsafe"

// DubiousNameWarning flags a name declared by the spec that contains a line break (\n or \r).
// No name in Swagger 2.0 needs one. Code generators print names into comments and string
// literals of the generated source, where a line break ends a // comment and turns the rest of
// the name into code.
DubiousNameWarning = "%s %q contains a line break: code generated from this spec may be unsafe"

InvalidObject = "expected an object in %q.%s"
)

Expand Down Expand Up @@ -484,3 +490,7 @@ func dubiousAbsoluteRefMsg(ref string) errors.Error {
func dubiousMultipleHostsMsg(count int, hosts string) errors.Error {
return errors.New(errors.CompositeErrorCode, DubiousMultipleHostsWarning, count, hosts)
}

func dubiousNameMsg(kind, name string) errors.Error {
return errors.New(errors.CompositeErrorCode, DubiousNameWarning, kind, name)
}
181 changes: 181 additions & 0 deletions spec_name_warnings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
// SPDX-License-Identifier: Apache-2.0

package validate

import (
"strings"

"github.com/go-openapi/spec"
)

const (
swaggerName = "name"
swaggerTags = "tags"
swaggerSecurityDefinitions = "securityDefinitions"
securitySchemeAPIKey = "apiKey"
)

// Kinds of names, as warnings give them.
const (
nameKindTag = "tag"
nameKindSecurityDefinition = "security definition"
nameKindAPIKeyName = "api key name"
nameKindParameterKey = "parameter key"
nameKindParameter = "parameter"
nameKindResponseKey = "response key"
nameKindHeader = "header"
nameKindPath = "path"
nameKindOperationID = "operationId"
nameKindDefinition = "definition"
nameKindDiscriminator = "discriminator"
nameKindProperty = "property"
)

// validateDubiousNames emits warnings (never errors) for names declared by the spec that contain a
// line break (\n or \r).
//
// No name in Swagger 2.0 needs a line break. Code generators print names into the generated
// source, in comments and in string literals: a line feed ends a // comment there, and the rest of
// the name becomes code. A carriage return is flagged too, because other languages and many editors
// end a line on it.
//
// The names checked are:
//
// - path templates, the keys of paths;
// - operationId and the tags of each operation, and the names of the top-level tags;
// - parameter names, and the keys of the top-level parameters;
// - the keys of the top-level responses, and the response header names;
// - definition keys, property names and discriminators, in every schema [analysis.Spec] finds;
// - security definition keys, and the name of an apiKey scheme.
//
// Descriptions, examples, enum and default values are data that may span lines, and are not
// checked.
//
// All findings are warnings: they do not affect validity (see [Result.IsValid]).
func (s *SpecValidator) validateDubiousNames() *Result {
res := validatorPools.results.Borrow()
sp := s.spec.Spec()
if sp == nil {
return res
}

for _, key := range sortedKeys(sp.Parameters) {
at := newPathSegments(swaggerParameters, key)
checkName(at, nameKindParameterKey, key, res)
param := sp.Parameters[key]
checkName(at.child(swaggerName), nameKindParameter, param.Name, res)
}

for _, key := range sortedKeys(sp.Responses) {
at := newPathSegments(swaggerResponses, key)
checkName(at, nameKindResponseKey, key, res)
checkHeaderNames(at, sp.Responses[key].Headers, res)
}

for i, tag := range sp.Tags {
checkName(newPathSegments(swaggerTags).item(i).child(swaggerName), nameKindTag, tag.Name, res)
}

for _, key := range sortedKeys(sp.SecurityDefinitions) {
at := newPathSegments(swaggerSecurityDefinitions, key)
checkName(at, nameKindSecurityDefinition, key, res)
if scheme := sp.SecurityDefinitions[key]; scheme != nil && scheme.Type == securitySchemeAPIKey {
checkName(at.child(swaggerName), nameKindAPIKeyName, scheme.Name, res)
}
}

if sp.Paths != nil {
for _, path := range sortedKeys(sp.Paths.Paths) {
at := newPathSegments(swaggerPaths, path)
checkName(at, nameKindPath, path, res)

pathItem := sp.Paths.Paths[path]
checkParamNames(at, pathItem.Parameters, res)

operations := operationsOf(&pathItem)
for _, method := range sortedKeys(operations) {
if op := operations[method]; op != nil {
checkOperationNames(at.child(method), op, res)
}
}
}
}

s.checkSchemaNames(res)

return res
}

func checkOperationNames(at pathSegments, op *spec.Operation, res *Result) {
checkName(at.child(swaggerOperationID), nameKindOperationID, op.ID, res)

for i, tag := range op.Tags {
checkName(at.child(swaggerTags).item(i), nameKindTag, tag, res)
}

checkParamNames(at, op.Parameters, res)

for _, response := range responsesOf(op) {
checkHeaderNames(at.children(swaggerResponses, response.code), response.resp.Headers, res)
}
}

// checkParamNames checks the parameters declared at at. A parameter given by $ref has no name of
// its own: its name is checked where the document declares it.
func checkParamNames(at pathSegments, params []spec.Parameter, res *Result) {
for i := range params {
checkName(at.child(swaggerParameters).item(i).child(swaggerName), nameKindParameter, params[i].Name, res)
}
}

func checkHeaderNames(at pathSegments, headers map[string]spec.Header, res *Result) {
for _, name := range sortedKeys(headers) {
checkName(at.children(swaggerHeaders, name), nameKindHeader, name, res)
}
}

// checkSchemaNames checks every schema the analyzer found, inline ones included: the name of a
// definition or a property, and the discriminator.
//
// The analyzer files each schema under the pointer that locates it, so the member that holds the
// schema tells a definition from a property. The analyzer also files items, allOf members and the
// like, which carry an index or a keyword: those have no name to check.
//
// The pointer is read from the decoded fragment of the schema's reference: the reference itself is
// a URL, which escapes a line break as %0A.
func (s *SpecValidator) checkSchemaNames(res *Result) {
schemas := s.analyzer.AllDefinitions()
pointers := make(map[string]int, len(schemas))
for i, schema := range schemas {
u := schema.Ref.GetURL()
if u == nil { // Safeguard: the analyzer always builds a parseable reference
continue
}
pointers[u.Fragment] = i
}

for _, pointer := range sortedKeys(pointers) {
schema := schemas[pointers[pointer]]
at := localRefPath("#" + pointer)

switch at.beforeLast() {
case swaggerDefinitions:
checkName(at, nameKindDefinition, schema.Name, res)
case jsonProperties:
checkName(at, nameKindProperty, schema.Name, res)
}

if schema.Schema != nil {
checkName(at.child(jsonDiscriminator), nameKindDiscriminator, schema.Schema.Discriminator, res)
}
}
}

func checkName(at pathSegments, kind, name string, res *Result) {
if !strings.ContainsAny(name, "\n\r") {
return
}

res.addWarningsAt(at, dubiousNameMsg(kind, name))
}
146 changes: 146 additions & 0 deletions spec_name_warnings_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
// SPDX-License-Identifier: Apache-2.0

package validate

import (
"encoding/json"
"strings"
"testing"

"github.com/go-openapi/loads"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/testify/v2/assert"
"github.com/go-openapi/testify/v2/require"
)

// dubiousNamesDoc puts a line break in every kind of name validateDubiousNames checks.
// R and S reach D through a $ref: D is reported once, where it is declared.
const dubiousNamesDoc = `{
"swagger": "2.0",
"info": {"title": "t", "version": "1"},
"tags": [{"name": "t\n1"}],
"securityDefinitions": {
"k\ny": {"type": "apiKey", "name": "X-K\ny", "in": "header"}
},
"parameters": {
"p\nk": {"name": "gp\nn", "in": "query", "type": "string"}
},
"responses": {
"r\nk": {"description": "d", "headers": {"h\n1": {"type": "string"}}}
},
"paths": {
"/a\nb": {
"parameters": [{"name": "pp\nn", "in": "query", "type": "string"}],
"get": {
"operationId": "op\nid",
"tags": ["ot\n1"],
"parameters": [{"name": "op\nn", "in": "header", "type": "string"}],
"responses": {
"200": {
"description": "ok",
"headers": {"h\r2": {"type": "string"}},
"schema": {"type": "object", "properties": {"ip\nr": {"type": "string"}}}
}
}
}
}
},
"definitions": {
"D\nx": {
"type": "object",
"discriminator": "k\nd",
"required": ["k\nd"],
"properties": {"k\nd": {"type": "string"}, "p\r": {"type": "string"}}
},
"R": {"$ref": "#/definitions/D%0Ax"},
"S": {"type": "object", "properties": {"r": {"$ref": "#/definitions/D%0Ax"}}}
}
}`

// dubiousNamesWant maps the pointer of each finding in dubiousNamesDoc to the kind of name the
// message must give.
var dubiousNamesWant = map[string]string{
"/tags/0/name": nameKindTag,
"/securityDefinitions/k\ny": nameKindSecurityDefinition,
"/securityDefinitions/k\ny/name": nameKindAPIKeyName,
"/parameters/p\nk": nameKindParameterKey,
"/parameters/p\nk/name": nameKindParameter,
"/responses/r\nk": nameKindResponseKey,
"/responses/r\nk/headers/h\n1": nameKindHeader,
"/paths/~1a\nb": nameKindPath,
"/paths/~1a\nb/parameters/0/name": nameKindParameter,
"/paths/~1a\nb/get/operationId": nameKindOperationID,
"/paths/~1a\nb/get/tags/0": nameKindTag,
"/paths/~1a\nb/get/parameters/0/name": nameKindParameter,
"/paths/~1a\nb/get/responses/200/headers/h\r2": nameKindHeader,
"/paths/~1a\nb/get/responses/200/schema/properties/ip\nr": nameKindProperty,
"/definitions/D\nx": nameKindDefinition,
"/definitions/D\nx/discriminator": nameKindDiscriminator,
"/definitions/D\nx/properties/k\nd": nameKindProperty,
"/definitions/D\nx/properties/p\r": nameKindProperty,
}

func TestValidateDubiousNames(t *testing.T) {
t.Run("every kind of name is flagged where it is declared", func(t *testing.T) {
res := dubiousValidatorFromJSON(t, dubiousNamesDoc).validateDubiousNames()

assertDubiousNames(t, res.LocatedWarnings())
assert.Empty(t, res.Errors)
})

t.Run("names without a line break are not flagged", func(t *testing.T) {
clean := strings.NewReplacer(`\n`, "_", `\r`, "_").Replace(dubiousNamesDoc)
res := dubiousValidatorFromJSON(t, clean).validateDubiousNames()

assert.Empty(t, res.Warnings)
})

t.Run("a line break in a description is not flagged", func(t *testing.T) {
doc := `{
"swagger": "2.0",
"info": {"title": "t", "version": "1", "description": "line 1\nline 2"},
"paths": {},
"definitions": {"A": {"type": "string", "description": "a\nb", "enum": ["x\ny"]}}
}`
res := dubiousValidatorFromJSON(t, doc).validateDubiousNames()

assert.Empty(t, res.Warnings)
})

t.Run("Validate reports the findings as warnings and keeps the spec valid", func(t *testing.T) {
d, err := loads.Analyzed(json.RawMessage(dubiousNamesDoc), "")
require.NoError(t, err)

errs, warnings := NewSpecValidator(d.Schema(), strfmt.Default).Validate(d)
require.Truef(t, errs.IsValid(), "unexpected errors: %v", errs.Errors)

// Validate hands warnings back as the errors of its warnings-only result.
// The other checks warn about this document too: keep only ours.
var located []Located
for _, l := range warnings.LocatedErrors() {
if strings.Contains(l.Err.Error(), "contains a line break") {
located = append(located, l)
}
}

assertDubiousNames(t, located)
})
}

func assertDubiousNames(t *testing.T, located []Located) {
t.Helper()

got := make(map[string]string, len(located))
for _, l := range located {
got[l.Pointer] = l.Err.Error()
}

require.Lenf(t, got, len(dubiousNamesWant), "warnings: %v", got)
for pointer, kind := range dubiousNamesWant {
msg, found := got[pointer]
if assert.Truef(t, found, "no warning at %q", pointer) {
assert.Truef(t, strings.HasPrefix(msg, kind+" "), "warning at %q: %q, want kind %q", pointer, msg, kind)
}
}
}
Loading