File: validation_error_encoder.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.110.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,932 kB
  • sloc: makefile: 3
file content (185 lines) | stat: -rw-r--r-- 5,568 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package openapi3filter

import (
	"context"
	"fmt"
	"net/http"
	"strings"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/routers"
)

// ValidationErrorEncoder wraps a base ErrorEncoder to handle ValidationErrors
type ValidationErrorEncoder struct {
	Encoder ErrorEncoder
}

// Encode implements the ErrorEncoder interface for encoding ValidationErrors
func (enc *ValidationErrorEncoder) Encode(ctx context.Context, err error, w http.ResponseWriter) {
	if e, ok := err.(*routers.RouteError); ok {
		cErr := convertRouteError(e)
		enc.Encoder(ctx, cErr, w)
		return
	}

	e, ok := err.(*RequestError)
	if !ok {
		enc.Encoder(ctx, err, w)
		return
	}

	var cErr *ValidationError
	if e.Err == nil {
		cErr = convertBasicRequestError(e)
	} else if e.Err == ErrInvalidRequired {
		cErr = convertErrInvalidRequired(e)
	} else if e.Err == ErrInvalidEmptyValue {
		cErr = convertErrInvalidEmptyValue(e)
	} else if innerErr, ok := e.Err.(*ParseError); ok {
		cErr = convertParseError(e, innerErr)
	} else if innerErr, ok := e.Err.(*openapi3.SchemaError); ok {
		cErr = convertSchemaError(e, innerErr)
	}

	if cErr != nil {
		enc.Encoder(ctx, cErr, w)
		return
	}
	enc.Encoder(ctx, err, w)
}

func convertRouteError(e *routers.RouteError) *ValidationError {
	status := http.StatusNotFound
	if e.Error() == routers.ErrMethodNotAllowed.Error() {
		status = http.StatusMethodNotAllowed
	}
	return &ValidationError{Status: status, Title: e.Error()}
}

func convertBasicRequestError(e *RequestError) *ValidationError {
	if strings.HasPrefix(e.Reason, prefixInvalidCT) {
		if strings.HasSuffix(e.Reason, `""`) {
			return &ValidationError{
				Status: http.StatusUnsupportedMediaType,
				Title:  "header Content-Type is required",
			}
		}
		return &ValidationError{
			Status: http.StatusUnsupportedMediaType,
			Title:  prefixUnsupportedCT + strings.TrimPrefix(e.Reason, prefixInvalidCT),
		}
	}
	return &ValidationError{
		Status: http.StatusBadRequest,
		Title:  e.Error(),
	}
}

func convertErrInvalidRequired(e *RequestError) *ValidationError {
	if e.Err == ErrInvalidRequired && e.Parameter != nil {
		return &ValidationError{
			Status: http.StatusBadRequest,
			Title:  fmt.Sprintf("parameter %q in %s is required", e.Parameter.Name, e.Parameter.In),
		}
	}
	return &ValidationError{
		Status: http.StatusBadRequest,
		Title:  e.Error(),
	}
}

func convertErrInvalidEmptyValue(e *RequestError) *ValidationError {
	if e.Err == ErrInvalidEmptyValue && e.Parameter != nil {
		return &ValidationError{
			Status: http.StatusBadRequest,
			Title:  fmt.Sprintf("parameter %q in %s is not allowed to be empty", e.Parameter.Name, e.Parameter.In),
		}
	}
	return &ValidationError{
		Status: http.StatusBadRequest,
		Title:  e.Error(),
	}
}

func convertParseError(e *RequestError, innerErr *ParseError) *ValidationError {
	// We treat path params of the wrong type like a 404 instead of a 400
	if innerErr.Kind == KindInvalidFormat && e.Parameter != nil && e.Parameter.In == "path" {
		return &ValidationError{
			Status: http.StatusNotFound,
			Title:  fmt.Sprintf("resource not found with %q value: %v", e.Parameter.Name, innerErr.Value),
		}
	} else if strings.HasPrefix(innerErr.Reason, prefixUnsupportedCT) {
		return &ValidationError{
			Status: http.StatusUnsupportedMediaType,
			Title:  innerErr.Reason,
		}
	} else if innerErr.RootCause() != nil {
		if rootErr, ok := innerErr.Cause.(*ParseError); ok &&
			rootErr.Kind == KindInvalidFormat && e.Parameter.In == "query" {
			return &ValidationError{
				Status: http.StatusBadRequest,
				Title: fmt.Sprintf("parameter %q in %s is invalid: %v is %s",
					e.Parameter.Name, e.Parameter.In, rootErr.Value, rootErr.Reason),
			}
		}
		return &ValidationError{
			Status: http.StatusBadRequest,
			Title:  innerErr.Reason,
		}
	}
	return nil
}

func convertSchemaError(e *RequestError, innerErr *openapi3.SchemaError) *ValidationError {
	cErr := &ValidationError{Title: innerErr.Reason}

	// Handle "Origin" error
	if originErr, ok := innerErr.Origin.(*openapi3.SchemaError); ok {
		cErr = convertSchemaError(e, originErr)
	}

	// Add http status code
	if e.Parameter != nil {
		cErr.Status = http.StatusBadRequest
	} else if e.RequestBody != nil {
		cErr.Status = http.StatusUnprocessableEntity
	}

	// Add error source
	if e.Parameter != nil {
		// We have a JSONPointer in the query param too so need to
		// make sure 'Parameter' check takes priority over 'Pointer'
		cErr.Source = &ValidationErrorSource{Parameter: e.Parameter.Name}
	} else if ptr := innerErr.JSONPointer(); ptr != nil {
		cErr.Source = &ValidationErrorSource{Pointer: toJSONPointer(ptr)}
	}

	// Add details on allowed values for enums
	if innerErr.SchemaField == "enum" {
		enums := make([]string, 0, len(innerErr.Schema.Enum))
		for _, enum := range innerErr.Schema.Enum {
			enums = append(enums, fmt.Sprintf("%v", enum))
		}
		cErr.Detail = fmt.Sprintf("value %v at %s must be one of: %s",
			innerErr.Value,
			toJSONPointer(innerErr.JSONPointer()),
			strings.Join(enums, ", "))
		value := fmt.Sprintf("%v", innerErr.Value)
		if e.Parameter != nil &&
			(e.Parameter.Explode == nil || *e.Parameter.Explode) &&
			(e.Parameter.Style == "" || e.Parameter.Style == "form") &&
			strings.Contains(value, ",") {
			parts := strings.Split(value, ",")
			cErr.Detail = fmt.Sprintf("%s; perhaps you intended '?%s=%s'",
				cErr.Detail,
				e.Parameter.Name,
				strings.Join(parts, "&"+e.Parameter.Name+"="))
		}
	}
	return cErr
}

func toJSONPointer(reversePath []string) string {
	return "/" + strings.Join(reversePath, "/")
}