Debian Codegraph @

pkg/endpoints/handlers/negotiation/negotiate.go

raw
1 /*
2 Copyright 2015 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package negotiation
18
19 import (
20 "mime"
21 "net/http"
22 "strconv"
23 "strings"
24
25 "github.com/munnerz/goautoneg"
26
27 "k8s.io/apimachinery/pkg/runtime"
28 "k8s.io/apimachinery/pkg/runtime/schema"
29 "k8s.io/apiserver/pkg/features"
30 utilfeature "k8s.io/apiserver/pkg/util/feature"
31 )
32
33 // MediaTypesForSerializer returns a list of media and stream media types for the server.
34 func MediaTypesForSerializer(ns runtime.NegotiatedSerializer) (mediaTypes, streamMediaTypes []string) {
35 for _, info := range ns.SupportedMediaTypes() {
36 mediaTypes = append(mediaTypes, info.MediaType)
37 if info.StreamSerializer != nil {
38 if utilfeature.DefaultFeatureGate.Enabled(features.CBORServingAndStorage) && info.MediaType == runtime.ContentTypeCBOR {
39 streamMediaTypes = append(streamMediaTypes, runtime.ContentTypeCBORSequence)
40 continue
41 }
42 // stream=watch is the existing mime-type parameter for watch
43 streamMediaTypes = append(streamMediaTypes, info.MediaType+";stream=watch")
44 }
45 }
46 return mediaTypes, streamMediaTypes
47 }
48
49 // NegotiateOutputMediaType negotiates the output structured media type and a serializer, or
50 // returns an error.
51 func NegotiateOutputMediaType(req *http.Request, ns runtime.NegotiatedSerializer, restrictions EndpointRestrictions) (MediaTypeOptions, runtime.SerializerInfo, error) {
52 mediaType, ok := NegotiateMediaTypeOptions(req.Header.Get("Accept"), ns.SupportedMediaTypes(), restrictions)
53 if !ok {
54 supported, _ := MediaTypesForSerializer(ns)
55 return mediaType, runtime.SerializerInfo{}, NewNotAcceptableError(supported)
56 }
57 // TODO: move into resthandler
58 info := mediaType.Accepted
59 if (mediaType.Pretty || isPrettyPrint(req)) && info.PrettySerializer != nil {
60 info.Serializer = info.PrettySerializer
61 }
62 return mediaType, info, nil
63 }
64
65 // NegotiateOutputMediaTypeStream returns a stream serializer for the given request.
66 func NegotiateOutputMediaTypeStream(req *http.Request, ns runtime.NegotiatedSerializer, restrictions EndpointRestrictions) (runtime.SerializerInfo, error) {
67 mediaType, ok := NegotiateMediaTypeOptions(req.Header.Get("Accept"), ns.SupportedMediaTypes(), restrictions)
68 if !ok || mediaType.Accepted.StreamSerializer == nil {
69 _, supported := MediaTypesForSerializer(ns)
70 return runtime.SerializerInfo{}, NewNotAcceptableError(supported)
71 }
72 return mediaType.Accepted, nil
73 }
74
75 // NegotiateInputSerializer returns the input serializer for the provided request.
76 func NegotiateInputSerializer(req *http.Request, streaming bool, ns runtime.NegotiatedSerializer) (runtime.SerializerInfo, error) {
77 mediaType := req.Header.Get("Content-Type")
78 return NegotiateInputSerializerForMediaType(mediaType, streaming, ns)
79 }
80
81 // NegotiateInputSerializerForMediaType returns the appropriate serializer for the given media type or an error.
82 func NegotiateInputSerializerForMediaType(mediaType string, streaming bool, ns runtime.NegotiatedSerializer) (runtime.SerializerInfo, error) {
83 mediaTypes := ns.SupportedMediaTypes()
84 if len(mediaType) == 0 {
85 mediaType = mediaTypes[0].MediaType
86 }
87 if mediaType, _, err := mime.ParseMediaType(mediaType); err == nil {
88 if info, ok := runtime.SerializerInfoForMediaType(mediaTypes, mediaType); ok {
89 return info, nil
90 }
91 }
92
93 supported, streamingSupported := MediaTypesForSerializer(ns)
94 if streaming {
95 return runtime.SerializerInfo{}, NewUnsupportedMediaTypeError(streamingSupported)
96 }
97 return runtime.SerializerInfo{}, NewUnsupportedMediaTypeError(supported)
98 }
99
100 // isPrettyPrint returns true if the "pretty" query parameter is true or if the User-Agent
101 // matches known "human" clients.
102 func isPrettyPrint(req *http.Request) bool {
103 // DEPRECATED: should be part of the content type
104 if req.URL != nil {
105 // avoid an allocation caused by parsing the URL query
106 if strings.Contains(req.URL.RawQuery, "pretty") {
107 pp := req.URL.Query().Get("pretty")
108 if len(pp) > 0 {
109 pretty, _ := strconv.ParseBool(pp)
110 return pretty
111 }
112 }
113 }
114 userAgent := req.UserAgent()
115 // This covers basic all browsers and cli http tools
116 if strings.HasPrefix(userAgent, "curl") || strings.HasPrefix(userAgent, "Wget") || strings.HasPrefix(userAgent, "Mozilla/5.0") {
117 return true
118 }
119 return false
120 }
121
122 // EndpointRestrictions is an interface that allows content-type negotiation
123 // to verify server support for specific options
124 type EndpointRestrictions interface {
125 // AllowsMediaTypeTransform returns true if the endpoint allows either the requested mime type
126 // or the requested transformation. If false, the caller should ignore this mime type. If the
127 // target is nil, the client is not requesting a transformation.
128 AllowsMediaTypeTransform(mimeType, mimeSubType string, target *schema.GroupVersionKind) bool
129 // AllowsServerVersion should return true if the specified version is valid
130 // for the server group.
131 AllowsServerVersion(version string) bool
132 // AllowsStreamSchema should return true if the specified stream schema is
133 // valid for the server group.
134 AllowsStreamSchema(schema string) bool
135 }
136
137 // DefaultEndpointRestrictions is the default EndpointRestrictions which allows
138 // content-type negotiation to verify server support for specific options
139 var DefaultEndpointRestrictions = emptyEndpointRestrictions{}
140
141 type emptyEndpointRestrictions struct{}
142
143 func (emptyEndpointRestrictions) AllowsMediaTypeTransform(mimeType string, mimeSubType string, gvk *schema.GroupVersionKind) bool {
144 return gvk == nil
145 }
146 func (emptyEndpointRestrictions) AllowsServerVersion(string) bool { return false }
147 func (emptyEndpointRestrictions) AllowsStreamSchema(s string) bool { return s == "watch" }
148
149 // MediaTypeOptions describes information for a given media type that may alter
150 // the server response
151 type MediaTypeOptions struct {
152 // pretty is true if the requested representation should be formatted for human
153 // viewing
154 Pretty bool
155
156 // stream, if set, indicates that a streaming protocol variant of this encoding
157 // is desired. The only currently supported value is watch which returns versioned
158 // events. In the future, this may refer to other stream protocols.
159 Stream string
160
161 // convert is a request to alter the type of object returned by the server from the
162 // normal response
163 Convert *schema.GroupVersionKind
164 // useServerVersion is an optional version for the server group
165 UseServerVersion string
166
167 // export is true if the representation requested should exclude fields the server
168 // has set
169 Export bool
170
171 // unrecognized is a list of all unrecognized keys
172 Unrecognized []string
173
174 // the accepted media type from the client
175 Accepted runtime.SerializerInfo
176 }
177
178 // acceptMediaTypeOptions returns an options object that matches the provided media type params. If
179 // it returns false, the provided options are not allowed and the media type must be skipped. These
180 // parameters are unversioned and may not be changed.
181 func acceptMediaTypeOptions(params map[string]string, accepts *runtime.SerializerInfo, endpoint EndpointRestrictions) (MediaTypeOptions, bool) {
182 var options MediaTypeOptions
183
184 // extract all known parameters
185 for k, v := range params {
186 switch k {
187
188 // controls transformation of the object when returned
189 case "as":
190 if options.Convert == nil {
191 options.Convert = &schema.GroupVersionKind{}
192 }
193 options.Convert.Kind = v
194 case "g":
195 if options.Convert == nil {
196 options.Convert = &schema.GroupVersionKind{}
197 }
198 options.Convert.Group = v
199 case "v":
200 if options.Convert == nil {
201 options.Convert = &schema.GroupVersionKind{}
202 }
203 options.Convert.Version = v
204
205 // controls the streaming schema
206 case "stream":
207 if len(v) > 0 && (accepts.StreamSerializer == nil || !endpoint.AllowsStreamSchema(v)) {
208 return MediaTypeOptions{}, false
209 }
210 options.Stream = v
211
212 // controls the version of the server API group used
213 // for generic output
214 case "sv":
215 if len(v) > 0 && !endpoint.AllowsServerVersion(v) {
216 return MediaTypeOptions{}, false
217 }
218 options.UseServerVersion = v
219
220 // if specified, the server should transform the returned
221 // output and remove fields that are always server specified,
222 // or which fit the default behavior.
223 case "export":
224 options.Export = v == "1"
225
226 // if specified, the pretty serializer will be used
227 case "pretty":
228 options.Pretty = v == "1"
229
230 default:
231 options.Unrecognized = append(options.Unrecognized, k)
232 }
233 }
234
235 if !endpoint.AllowsMediaTypeTransform(accepts.MediaTypeType, accepts.MediaTypeSubType, options.Convert) {
236 return MediaTypeOptions{}, false
237 }
238
239 options.Accepted = *accepts
240 return options, true
241 }
242
243 // NegotiateMediaTypeOptions returns the most appropriate content type given the accept header and
244 // a list of alternatives along with the accepted media type parameters.
245 func NegotiateMediaTypeOptions(header string, accepted []runtime.SerializerInfo, endpoint EndpointRestrictions) (MediaTypeOptions, bool) {
246 if len(header) == 0 && len(accepted) > 0 {
247 return MediaTypeOptions{
248 Accepted: accepted[0],
249 }, true
250 }
251
252 clauses := goautoneg.ParseAccept(header)
253 for i := range clauses {
254 clause := &clauses[i]
255 for i := range accepted {
256 accepts := &accepted[i]
257 switch {
258 case clause.Type == accepts.MediaTypeType && clause.SubType == accepts.MediaTypeSubType,
259 clause.Type == accepts.MediaTypeType && clause.SubType == "*",
260 clause.Type == "*" && clause.SubType == "*":
261 if retVal, ret := acceptMediaTypeOptions(clause.Params, accepts, endpoint); ret {
262 return retVal, true
263 }
264 }
265 }
266 }
267
268 return MediaTypeOptions{}, false
269 }