diff --git a/go.mod b/go.mod index 1087687d5..75de573b0 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/gdamore/tcell/v2 v2.13.9 github.com/go-gormigrate/gormigrate/v2 v2.1.5 github.com/go-openapi/errors v0.22.7 - github.com/go-openapi/runtime v0.29.5 + github.com/go-openapi/runtime v0.30.0 github.com/go-openapi/strfmt v0.26.2 github.com/go-openapi/swag v0.26.0 github.com/golang-jwt/jwt/v5 v5.3.1 @@ -57,6 +57,7 @@ require ( github.com/go-openapi/jsonpointer v0.23.1 // indirect github.com/go-openapi/jsonreference v0.21.5 // indirect github.com/go-openapi/loads v0.23.3 // indirect + github.com/go-openapi/runtime/server-middleware v0.30.0 // indirect github.com/go-openapi/spec v0.22.4 // indirect github.com/go-openapi/swag/cmdutils v0.26.0 // indirect github.com/go-openapi/swag/conv v0.26.0 // indirect diff --git a/go.sum b/go.sum index f64a8772c..acacfba09 100644 --- a/go.sum +++ b/go.sum @@ -50,8 +50,10 @@ github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw= github.com/go-openapi/loads v0.23.3 h1:g5Xap1JfwKkUnZdn+S0L3SzBDpcTIYzZ5Qaag0YDkKQ= github.com/go-openapi/loads v0.23.3/go.mod h1:NOH07zLajXo8y55hom0omlHWDVVvCwBM/S+csCK8LqA= -github.com/go-openapi/runtime v0.29.5 h1:uc5+/TtqLIfDBTUxnF3uppoGMt+9DzonwUWsviINlrY= -github.com/go-openapi/runtime v0.29.5/go.mod h1:D9IUbWccdYv+km8QwmAm90FZvDcQk47vP2Y7y5as/D8= +github.com/go-openapi/runtime v0.30.0 h1:1llnyZcqkjm77VhM4FPO1O1rt2SzLZIRPkZAY4wv4mw= +github.com/go-openapi/runtime v0.30.0/go.mod h1:QtJGUq+1S0VWPP+LQldH6o4tcqGsjzTVjn/wIWEn9o4= +github.com/go-openapi/runtime/server-middleware v0.30.0 h1:8rPoJ/xv7JL8BsovaqboKETlpWBArVh8n+0L/GyePog= +github.com/go-openapi/runtime/server-middleware v0.30.0/go.mod h1:OYNT/TxNvB/VK5oe4htM2jDTwlEXuejVJmu0DVZfAMs= github.com/go-openapi/spec v0.22.4 h1:4pxGjipMKu0FzFiu/DPwN3CTBRlVM2yLf/YTWorYfDQ= github.com/go-openapi/spec v0.22.4/go.mod h1:WQ6Ai0VPWMZgMT4XySjlRIE6GP1bGQOtEThn3gcWLtQ= github.com/go-openapi/strfmt v0.26.2 h1:ysjheCh4i1rmFEo2LanhELDNucNzfWTZhUDKgWWPaFM= diff --git a/vendor/github.com/go-openapi/runtime/.gitignore b/vendor/github.com/go-openapi/runtime/.gitignore index bbdffea78..c0bc15beb 100644 --- a/vendor/github.com/go-openapi/runtime/.gitignore +++ b/vendor/github.com/go-openapi/runtime/.gitignore @@ -4,3 +4,4 @@ .env .mcp.json go.work.sum +.worktrees/ diff --git a/vendor/github.com/go-openapi/runtime/.golangci.yml b/vendor/github.com/go-openapi/runtime/.golangci.yml index 0087ed311..a4f3df5a4 100644 --- a/vendor/github.com/go-openapi/runtime/.golangci.yml +++ b/vendor/github.com/go-openapi/runtime/.golangci.yml @@ -53,6 +53,7 @@ linters: - legacy - std-error-handling paths: + - .worktrees - third_party$ - builtin$ - examples$ @@ -63,6 +64,7 @@ formatters: exclusions: generated: lax paths: + - .worktrees - third_party$ - builtin$ - examples$ diff --git a/vendor/github.com/go-openapi/runtime/CONTRIBUTORS.md b/vendor/github.com/go-openapi/runtime/CONTRIBUTORS.md index 4a717770c..7d2d8218e 100644 --- a/vendor/github.com/go-openapi/runtime/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/runtime/CONTRIBUTORS.md @@ -4,12 +4,12 @@ | Total Contributors | Total Contributions | | --- | --- | -| 70 | 491 | +| 70 | 510 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | | @casualjim | 268 | | -| @fredbi | 69 | | +| @fredbi | 88 | | | @youyuanwu | 19 | | | @josephwoodward | 13 | | | @kenjones-cisco | 12 | | diff --git a/vendor/github.com/go-openapi/runtime/README.md b/vendor/github.com/go-openapi/runtime/README.md index befd3d641..2d5011839 100644 --- a/vendor/github.com/go-openapi/runtime/README.md +++ b/vendor/github.com/go-openapi/runtime/README.md @@ -16,9 +16,44 @@ A runtime for go OpenAPI toolkit. The runtime component for use in code generation or as untyped usage. - + +**Changes to the API surface in `v0.30.0`**: + +* utility package `header` has now moved to `github.com/go-openapi/runtime/server-middleware/negotiate/header` + +> A shim is provided to support existing programs, with a deprecation notice. + +**Changes in semantics in `v0.30.0`**: + +Function `negotiate.NegotiateContentType` (available as an alias for backward compatibility as `middleware.NegotiateContentType` +now performs a full match considering MIME parameters. + +The previous behavior (matching in order of appearance after stripping parameters) may be enabled explicitly with +option `negotiate.WithIgnoreParameters`. + +* **2026-05-05** : exposed content negotiation methods as a separate, dependency-free module + +> Users may reuse these utilities to support content-negotiation without extra dependencies. +> +> Newly available module: `github.com/go-openapi/runtime/server-middleware` +> +> Newly available packages: `github.com/go-openapi/runtime/server-middleware/negotiate` and +> `github.com/go-openapi/runtime/server-middleware/mediatype`. + +* **2026-05-07** : exposed UI and Spec middleware as a separate, dependency-free module. + +> Newly available package: `github.com/go-openapi/runtime/server-middleware/docui` that now holds our +> UI and spec serve middleware. +> +> A shim is available in `github.com/go-openapi/runtime/middleware` to bridge the older UI options to the new ones, +> with a deprecation notice. +> +> Methods that were unduly exported and purely used to manipulate options (e.g. `SwaggerUIOpts.EnsureDefaults`) have been +> removed. New options in `docui` should be used instead. + +> Users may reuse this middleware to serve a Redoc, Rapidoc or SwaggerUI documentation without +> importing the complete go-openapi scaffolding. ## Status @@ -34,18 +69,21 @@ go get github.com/go-openapi/runtime See -For pre-v0.30.0 releases see [release notes](docs/NOTES.md). +For v0.29.0 release see [release notes](docs/NOTES.md). +From that release onwards, changes are tracked in the github release notes. **What coming next?** Moving forward, we want to : -* [ ] continue narrowing down the scope of dependencies: - * yaml support in an independent module +* [x] fix a few known issues with some file upload requests (e.g. #286) +* [] continue narrowing down the scope of dependencies: + * [x] split middleware and other useful utilities as a separate dependency-free module + * yaml support in an independent module (v2) * introduce more up-to-date support for opentelemetry as a separate module that evolves independently from the main package (to avoid breaking changes, the existing API - will remain maintained, but evolve at a slower pace than opentelemetry). -* [ ] fix a few known issues with some file upload requests (e.g. #286) + will remain maintained, but evolve at a slower pace than opentelemetry). (v2) +* [] publish proper documentation and examples ## Licensing diff --git a/vendor/github.com/go-openapi/runtime/bytestream.go b/vendor/github.com/go-openapi/runtime/bytestream.go index 8701c8e3d..a1f246578 100644 --- a/vendor/github.com/go-openapi/runtime/bytestream.go +++ b/vendor/github.com/go-openapi/runtime/bytestream.go @@ -97,7 +97,7 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { } default: // check for the underlying type to be pointer to []byte or string, - if ptr := reflect.TypeOf(data); ptr.Kind() != reflect.Ptr { + if ptr := reflect.TypeOf(data); ptr.Kind() != reflect.Pointer { return errors.New("destination must be a pointer") } diff --git a/vendor/github.com/go-openapi/runtime/client/internal/request/request.go b/vendor/github.com/go-openapi/runtime/client/internal/request/request.go new file mode 100644 index 000000000..410f4359e --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/client/internal/request/request.go @@ -0,0 +1,909 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package request + +import ( + "bytes" + "context" + "fmt" + "io" + "log" + "mime" + "mime/multipart" + "net/http" + "net/textproto" + "net/url" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +var _ runtime.ClientRequest = new(Request) // ensure compliance to the interface + +// Request represents a swagger client request. +// It binds parameters to a HTTP request. +// +// The main purpose of this struct is to hide the machinery of adding OpenAPI v2 parameters to a transport request. +// +// A generated client only implements what is necessary to turn a parameter into a valid value for these methods. +// +// There is no parameter validation here, it is assumed to be used after a spec has been validated. +// +// # Request binding +// +// The binding of parameters is carried out by method [Request.BuildHTTPContext]. +// +// It analyzes parameters, which may come in different flavors: +// +// - a file or multipart form containing a file +// - a body which is a [io.Reader] +// - a buffered body (regular schema body, including urlencoded form) +// +// In all cases, we may also have query or path parameters encoded in the URL, or header parameters. +// +// The result is a [http.Request], with the following properties: +// +// - file, multipart form or io.Reader body: a streaming request with an attached go routine that consumes the [io.Reader]. +// - buffered body: a simple request +// +// The caller passes the parent [context.Context] to [Request.BuildHTTPContext] and receives back a cancel +// function to release the resources held by the derived request context once the response is consumed. +// +// # Authentication +// +// Authentication is built in the request by using a [runtime.ClientAuthInfoWriter]. +// This helper may need to inspect the body of the request before sending authentication info. +// To cover that case, streaming bodies use a copy of the body [io.Reader] for the [runtime.ClientAuthInfoWriter] +// to consume if it wants to. +// +// # Content negotiation +// +// The [Request] detects `multipart/form-data` to switch to streamed request. +// +// `application/x-www-form-urlencoded` is also honored, even for file parameters, which are not streamed in this case. +// File parameters default behavior is `multipart/form-data`. +// +// The natural way to define the `Content-Type` header is to use the `contentType` parameter to switch to the map of +// available body producers. +// +// For buffered requests, this setting override any `Content-Type` header possibly set by calling [Request.SetHeaderParam]. +// +// For streamed requests, users may want more flexibility, as we enter custom territory, with use-cases not supported by OpenAPI v2. +// +// The `Content-Type` header of a streamed request is defined using the following sequence: +// +// 1. if the caller sets an explicit value already in header — the user set it via +// [Request.SetHeaderParam] during WriteToRequest, and we treat that as an intentional escape hatch +// 2. use payload's [runtime.ContentTyper] declaration (in this case, the produced payload knows its content type) +// 3. use `application/octet-stream` if it is available in the registered producers +// 4. otherwise ser the picker's mediaType +// +// For multi-part requests, the content type of each part is auto-detected using the following sequence: +// +// 1. use [runtime.ContentTyper] declaration (in this case, the file payload knows its content type) +// 2. use [http.DetectContentType] on the first 512 bytes of the file +// +// # Concurrency +// +// A [Request] is a disposable object that is NOT intended to be reused or called concurrently. +// +// # Future evolutions +// +// There might be other similar structs that convert to other transports. +type Request struct { + pathPattern string + method string + writer runtime.ClientRequestWriter + + pathParams map[string]string + header http.Header + query url.Values + formFields url.Values + fileFields map[string][]runtime.NamedReadCloser + payload any + // consumes carries the operation's full ConsumesMediaTypes list so + // that buildHTTP — which runs after the writer populates the payload + // — can apply payload-aware fallback rules (see streamFallbackMime). + // + // This i by Runtime.createHttpRequest. + consumes []string + timeout time.Duration + buf *bytes.Buffer + + getBody func(r *Request) []byte +} + +// New creates a new http client [Request] to handle OpenAPI v2 parameters. +func New(method, pathPattern string, writer runtime.ClientRequestWriter) *Request { + return &Request{ + pathPattern: pathPattern, + method: method, + writer: writer, + header: make(http.Header), + query: make(url.Values), + timeout: 0, + getBody: getRequestBuffer, + } +} + +// GetMethod yields the method being used. +func (r *Request) GetMethod() string { + return r.method +} + +// GetPath yields the URL path being used. +func (r *Request) GetPath() string { + pth := r.pathPattern + for k, v := range r.pathParams { + pth = strings.ReplaceAll(pth, "{"+k+"}", v) + } + + return pth +} + +// GetBody returns the request body, if any. +// +// For streaming requests, this is a copy of the original [io.Reader]. +func (r *Request) GetBody() []byte { + return r.getBody(r) +} + +// SetHeaderParam adds a header parameter to the request. +// +// The header key is always canonicalized. +// +// - when there is only 1 value provided, it will set it. +// - when there are several values provided, it will add all of those (no overriding). +func (r *Request) SetHeaderParam(name string, values ...string) error { + if r.header == nil { + r.header = make(http.Header) + } + r.header[http.CanonicalHeaderKey(name)] = values + + return nil +} + +// GetHeaderParams returns all headers currently set for the request. +func (r *Request) GetHeaderParams() http.Header { + return r.header +} + +// SetQueryParam adds a query parameter to the request. +// +// - when there is only 1 value provided, it will set it. +// - when there are several values provided, it will add all of those (no overriding). +func (r *Request) SetQueryParam(name string, values ...string) error { + if r.query == nil { + r.query = make(url.Values) + } + r.query[name] = values + + return nil +} + +// GetQueryParams returns a copy of all query params currently set for the request. +func (r *Request) GetQueryParams() url.Values { + result := make(url.Values, len(r.query)) + for key, values := range r.query { + result[key] = append([]string{}, values...) + } + + return result +} + +// SetFormParam adds a forn param to the request. +// +// - when there is only 1 value provided, it will set it. +// - when there are several values provided, it will add all of those (no overriding). +func (r *Request) SetFormParam(name string, values ...string) error { + if r.formFields == nil { + r.formFields = make(url.Values) + } + r.formFields[name] = values + + return nil +} + +// SetPathParam adds a path param to the request. +func (r *Request) SetPathParam(name string, value string) error { + if r.pathParams == nil { + r.pathParams = make(map[string]string) + } + + r.pathParams[name] = value + + return nil +} + +// SetFileParam adds a file parameter to the request. +// +// Files must implement [runtime.NamedReadCloser]. +// +// [runtime.File] is proposed as the default concrete implementation. +func (r *Request) SetFileParam(name string, files ...runtime.NamedReadCloser) error { + for _, file := range files { + if actualFile, ok := file.(*os.File); ok { + fi, err := os.Stat(actualFile.Name()) + if err != nil { + return err + } + + if fi.IsDir() { + return fmt.Errorf("%q is a directory, only files are supported", file.Name()) + } + } + } + + if r.fileFields == nil { + r.fileFields = make(map[string][]runtime.NamedReadCloser) + } + + if r.formFields == nil { + r.formFields = make(url.Values) + } + + r.fileFields[name] = files + + return nil +} + +// GetFileParam yields all file parameters. +func (r *Request) GetFileParam() map[string][]runtime.NamedReadCloser { + return r.fileFields +} + +// SetBodyParam sets a body parameter on the request. +// +// This does not yet serialize the object: actual serialization happens as late as possible. +func (r *Request) SetBodyParam(payload any) error { + r.payload = payload + + return nil +} + +// GetBodyParam returns the body payload. +func (r *Request) GetBodyParam() any { + return r.payload +} + +// GetTimeout sets the timeout for a request. +func (r *Request) GetTimeout() time.Duration { + return r.timeout +} + +// SetTimeout sets the timeout for a request. +func (r *Request) SetTimeout(timeout time.Duration) error { + r.timeout = timeout + + return nil +} + +// SetConsumes sets the list of registered consumed content for a request. +func (r *Request) SetConsumes(consumers []string) { + r.consumes = consumers +} + +// BuildHTTPContext binds the request parameters and returns a ready-to-send [http.Request]. +// +// Dispatch picks one of two end-to-end builders based on whether: +// +// - the body source is a stream (multipart pipe or stream payload) +// - or a buffer (urlencoded form, producer output, or no body) +// +// It starts by writing the request, then proceed with adding authentication, +// then finally assembling URL or header parameters. +// +// The split mirrors the auth question: streaming bodies require a lazy body-copy closure during AuthenticateRequest, +// whereas buffered bodies do not. +// +// The returned [http.Request] carries a context derived from parentCtx that: +// +// - inherits any deadline or cancellation already set on parentCtx; +// - additionally honors the per-request timeout set via [Request.SetTimeout] +// (the [runtime.ClientRequestWriter] may override the runtime default during +// WriteToRequest, which is why the derivation happens here rather than +// at the call site). +// +// The returned cancel must be invoked by the caller (typically deferred) +// once the response has been fully read; otherwise resources held by the +// derived context — including any timeout timer — are leaked. +// +// On error the cancel is invoked internally and a no-op cancel is returned, +// so callers can defer cancel unconditionally. +func (r *Request) BuildHTTPContext(parentCtx context.Context, mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, context.CancelFunc, error) { + if err := r.writer.WriteToRequest(r, registry); err != nil { + return nil, noop, err + } + + ctx, cancel := deriveRequestContext(parentCtx, r.timeout) + r.buf = bytes.NewBuffer(nil) + + var ( + httpReq *http.Request + err error + ) + if r.usesStreamingBody(mediaType) { + httpReq, err = r.buildStreamingRequest(ctx, mediaType, basePath, producers, registry, auth) + } else { + httpReq, err = r.buildBufferedRequest(ctx, mediaType, basePath, producers, registry, auth) + } + if err != nil { + cancel() + return nil, noop, err + } + return httpReq, cancel, nil +} + +func noop() {} + +// deriveRequestContext returns a child of parent bounded by timeout. +// If timeout == 0 the child is only canceled when the caller invokes +// cancel; any deadline already on parent is preserved. If timeout > 0 +// the child uses the shortest of timeout and parent's existing deadline. +func deriveRequestContext(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) { + if timeout == 0 { + return context.WithCancel(parent) + } + return context.WithTimeout(parent, timeout) +} + +// usesStreamingBody reports whether the request body must be assembled +// as a stream (an io.Pipe for multipart, or the payload's own reader +// for stream payloads). +// +// The complementary case is a fully buffered body in r.buf — urlencoded form, producer output, or no body at all. +func (r *Request) usesStreamingBody(mediaType string) bool { + if (len(r.formFields) > 0 || len(r.fileFields) > 0) && r.isMultipart(mediaType) { + return true + } + if r.payload != nil { + if _, ok := r.payload.(io.Reader); ok { + return true + } + } + return false +} + +func (r *Request) isMultipart(mediaType string) bool { + // Strip media-type parameters before comparing: callers may legally + // pass `multipart/form-data; boundary=…` or + // `application/x-www-form-urlencoded; charset=utf-8` per RFC 7231, + // and a bare-string compare would route those to the wrong flow. + // + // mime.ParseMediaType lowercases the type/subtype and is + // case-insensitive on input, so plain == against our (lowercase) + // constants is sufficient on the happy path. + base, _, err := mime.ParseMediaType(mediaType) + if err != nil { + // Malformed mediaType: only the file-presence shortcut can + // fire — by definition we cannot recognize either canonical + // form mime in unparseable input. + return len(r.fileFields) > 0 + } + + // An explicit application/x-www-form-urlencoded choice is honored even when + // file fields are present: the spec allows files to travel as URL-encoded + // form values, although it does not stream and is discouraged. Without this + // short-circuit, picking urlencoded with files would silently fall back to + // multipart and emit an inconsistent Content-Type. + if base == runtime.URLencodedFormMime { + return false + } + + if len(r.fileFields) > 0 { + return true + } + + return base == runtime.MultipartFormMime +} + +// buildBufferedRequest assembles a request whose body is fully +// buffered in r.buf before AuthenticateRequest runs — urlencoded form, +// producer-serialized payload, or no body. +// +// Auth is trivial in this flow because the buffer is already populated when the auth helper +// asks for the body via r.GetBody(). +func (r *Request) buildBufferedRequest(ctx context.Context, mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) { + var body io.Reader + var err error + + switch { + case len(r.formFields) > 0 || len(r.fileFields) > 0: + body, err = r.writeURLEncodedBody(mediaType) + case r.payload != nil: + body, err = r.writeNonStreamPayload(mediaType, producers) + } + if err != nil { + return nil, err + } + + if runtime.CanHaveBody(r.method) && body != nil && r.header.Get(runtime.HeaderContentType) == "" { + r.header.Set(runtime.HeaderContentType, mediaType) + } + + if auth != nil { + if err := auth.AuthenticateRequest(r, registry); err != nil { + return nil, err + } + } + + return r.assembleRequest(ctx, basePath, body) +} + +// buildStreamingRequest assembles a request whose body is a stream — +// either an io.Pipe filled by the multipart goroutine, or the +// payload's own io.Reader. +// +// AuthenticateRequest consumes the body lazily through the getBody closure installed by +// applyAuthWithBodyCopy, which buffers the stream into r.buf so the http.Request can use the buffered copy. +// +// On any error path before the http.Request takes ownership of body, we close the body to release +// the underlying resource. +// +// For multipart this unblocks the spawned writer goroutine +// (it would otherwise park forever on pw.Write with no reader). +// +// For stream payloads it closes the user-provided io.ReadCloser. +func (r *Request) buildStreamingRequest(ctx context.Context, mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (req *http.Request, retErr error) { + var body io.Reader + if len(r.formFields) > 0 || len(r.fileFields) > 0 { + body = r.writeMultipartBody(ctx, mediaType) + } else { + body = r.writeStreamPayload(mediaType, producers) + } + + defer func() { + if retErr == nil { + return + } + if c, ok := body.(io.Closer); ok { + _ = c.Close() + } + }() + + if runtime.CanHaveBody(r.method) && body != nil && r.header.Get(runtime.HeaderContentType) == "" { + r.header.Set(runtime.HeaderContentType, mediaType) + } + + body, err := r.applyAuthWithBodyCopy(auth, body, registry) + if err != nil { + return nil, err + } + + return r.assembleRequest(ctx, basePath, body) +} + +// assembleRequest is the shared tail of both flows: build the URL +// path, create the http.Request, merge static query parameters, and +// finalize headers/query. +func (r *Request) assembleRequest(ctx context.Context, basePath string, body io.Reader) (*http.Request, error) { + urlPath, staticQueryParams, err := r.resolveURLPath(basePath) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, r.method, urlPath, body) + if err != nil { + return nil, err + } + + if err := r.mergeStaticQuery(staticQueryParams); err != nil { + return nil, err + } + + req.URL.RawQuery = r.query.Encode() + req.Header = r.header + + return req, nil +} + +// resolveURLPath builds the final url path string and returns the static +// query parameters extracted from basePath and r.pathPattern. +// +// Static query parameters from the path pattern take precedence over those +// from the base path; merging with r.query is the caller's responsibility +// (see [request.mergeStaticQuery]). +// +// The path is assembled from basePath + pathPattern with path-param +// substitution and trailing-slash preservation when the original +// pathPattern carried one. +func (r *Request) resolveURLPath(basePath string) (string, url.Values, error) { + basePathURL, err := url.Parse(basePath) + if err != nil { + return "", nil, err + } + staticQueryParams := basePathURL.Query() + + pathPatternURL, err := url.Parse(r.pathPattern) + if err != nil { + return "", nil, err + } + for name, values := range pathPatternURL.Query() { + if _, present := staticQueryParams[name]; present { + staticQueryParams.Del(name) + } + for _, value := range values { + staticQueryParams.Add(name, value) + } + } + + // path.Join strips trailing slashes; reinstate one whenever the + // pathPattern carried it, including the bare-root case ("/" under a + // non-empty basePath, which path.Join would collapse to "/basepath"). + // The HasSuffix check on urlPath keeps the rewrite idempotent and + // avoids producing "//" when basePath is "/" or empty. + reinstateSlash := strings.HasSuffix(pathPatternURL.Path, "/") + + urlPath := path.Join(basePathURL.Path, pathPatternURL.Path) + for k, v := range r.pathParams { + urlPath = strings.ReplaceAll(urlPath, "{"+k+"}", url.PathEscape(v)) + } + if reinstateSlash && !strings.HasSuffix(urlPath, "/") { + urlPath += "/" + } + + return urlPath, staticQueryParams, nil +} + +// applyAuthWithBodyCopy runs auth.AuthenticateRequest for the +// streaming flow, where the http.Request body is a pipe or a payload +// reader rather than r.buf. If AuthenticateRequest asks for the body +// via r.GetBody(), the lazy closure copies the stream into r.buf on +// demand and reassigns body to r.buf so the post-auth source passed +// to http.NewRequestWithContext is the buffered copy. +// +// The closure is registered lazily because there is no way to know +// ahead of time whether AuthenticateRequest will read the body. +// +// On error precedence: a copy error is reported in preference to the +// AuthenticateRequest error, because a mis-read body may have +// interfered with auth. +// +// No-op when auth is nil; returns body unchanged. +func (r *Request) applyAuthWithBodyCopy(auth runtime.ClientAuthInfoWriter, body io.Reader, registry strfmt.Registry) (io.Reader, error) { + if auth == nil { + return body, nil + } + + var copyErr error + var copied bool + r.getBody = func(r *Request) []byte { + if copied { + return getRequestBuffer(r) + } + + defer func() { + copied = true + }() + + if _, copyErr = io.Copy(r.buf, body); copyErr != nil { + return nil + } + + if closer, ok := body.(io.ReadCloser); ok { + if copyErr = closer.Close(); copyErr != nil { + return nil + } + } + + body = r.buf + return getRequestBuffer(r) + } + + authErr := auth.AuthenticateRequest(r, registry) + + // On error we return body alongside the error so the caller's + // cleanup defer (in buildStreamingRequest) can close the + // underlying pipe/stream. Caller treats body as ignorable when + // err != nil per Go convention; the defer reads it via closure. + if copyErr != nil { + return body, fmt.Errorf("error retrieving the response body: %v", copyErr) + } + + if authErr != nil { + return body, authErr + } + + return body, nil +} + +// mergeStaticQuery overlays staticQuery onto r.query. On conflict r.query +// wins — the parameters set by the client take precedence over the ones +// extracted from basePath / pathPattern. +func (r *Request) mergeStaticQuery(staticQuery url.Values) error { + originalParams := r.GetQueryParams() + for k, v := range staticQuery { + if _, present := originalParams[k]; present { + continue + } + if err := r.SetQueryParam(k, v...); err != nil { + return err + } + } + return nil +} + +// writeURLEncodedBody serializes form fields (and any file fields, per +// Swagger 2.0 fallback semantics) into r.buf as +// application/x-www-form-urlencoded. Sets Content-Type to mediaType and +// returns r.buf as the body source. +// +// Per Swagger 2.0, file form parameters can be sent under +// application/x-www-form-urlencoded by including the file content as a +// regular form-field value. The whole form is then percent-encoded as +// usual. This buffers the entire payload and does not preserve a +// per-file Content-Type — multipart/form-data is preferred when both +// are advertised by the operation. +func (r *Request) writeURLEncodedBody(mediaType string) (io.Reader, error) { + r.header.Set(runtime.HeaderContentType, mediaType) + values := url.Values{} + for k, vs := range r.formFields { + values[k] = append(values[k], vs...) + } + for fn, ff := range r.fileFields { + for _, fi := range ff { + data, ferr := io.ReadAll(fi) + if cerr := fi.Close(); cerr != nil && ferr == nil { + ferr = cerr + } + if ferr != nil { + return nil, ferr + } + values.Add(fn, string(data)) + } + } + r.buf.WriteString(values.Encode()) + return r.buf, nil +} + +// writeMultipartBody assembles a multipart/form-data body via an +// io.Pipe. A goroutine streams form fields and files into the pipe +// writer; the pipe reader is returned as the body. Sets Content-Type to +// the multipart media type with the writer's boundary parameter. +// +// The goroutine owns the pipe writer's lifecycle: it closes the +// multipart writer (flushing the closing boundary) and the pipe writer +// when it finishes or hits an error. +func (r *Request) writeMultipartBody(ctx context.Context, mediaType string) io.Reader { + pr, pw := io.Pipe() + mp := multipart.NewWriter(pw) + r.header.Set(runtime.HeaderContentType, mangleContentType(mediaType, mp.Boundary())) + + go r.streamMultipartParts(ctx, mp, pw) + + return pr +} + +// streamMultipartParts writes form fields then file fields to mp, +// closing mp and pw when done. +// +// Errors are reported by closing pw with the error so the consumer of pr observes them on its next Read. +// +// Context cancellation is observed at iteration boundaries (between +// fields and between files) and during file copy via a context-aware +// reader. When ctx is canceled the pipe writer is closed with ctx.Err() +// so the body consumer surfaces the cancellation as the read error. +func (r *Request) streamMultipartParts(ctx context.Context, mp *multipart.Writer, pw *io.PipeWriter) { + defer func() { + mp.Close() + pw.Close() + }() + + for fn, v := range r.formFields { + for _, vi := range v { + if err := ctx.Err(); err != nil { + _ = pw.CloseWithError(err) + return + } + if err := mp.WriteField(fn, vi); err != nil { + logClose(err, pw) + return + } + } + } + + defer func() { + for _, ff := range r.fileFields { + for _, ffi := range ff { + ffi.Close() + } + } + }() + + for fn, f := range r.fileFields { + for _, fi := range f { + if err := ctx.Err(); err != nil { + _ = pw.CloseWithError(err) + return + } + + var fileContentType string + if p, ok := fi.(runtime.ContentTyper); ok { + fileContentType = p.ContentType() + } else { + // Need to read the data so that we can detect the content type + const contentTypeBufferSize = 512 + buf := make([]byte, contentTypeBufferSize) + size, err := fi.Read(buf) + if err != nil && err != io.EOF { + logClose(err, pw) + return + } + fileContentType = http.DetectContentType(buf) + fi = runtime.NamedReader(fi.Name(), io.MultiReader(bytes.NewReader(buf[:size]), fi)) + } + + // Create the MIME headers for the new part + h := make(textproto.MIMEHeader) + h.Set("Content-Disposition", + fmt.Sprintf(`form-data; name="%s"; filename="%s"`, + escapeQuotes(fn), escapeQuotes(filepath.Base(fi.Name())))) + h.Set("Content-Type", fileContentType) + + wrtr, err := mp.CreatePart(h) + if err != nil { + logClose(err, pw) + return + } + if _, err := io.Copy(wrtr, &ctxReader{ctx: ctx, r: fi}); err != nil { + logClose(err, pw) + return + } + } + } +} + +// ctxReader wraps an [io.Reader] with a context check on each Read. Once +// ctx is done, subsequent Reads return ctx.Err() instead of delegating +// to the underlying reader. It does not preempt a Read already in flight +// — that is the source's responsibility (e.g. *os.File honors Close from +// another goroutine, network sources honor SetDeadline). +type ctxReader struct { + ctx context.Context //nolint:containedctx // io.Reader's Read method has no ctx parameter, so the wrapper must carry it on the struct + r io.Reader +} + +func (cr *ctxReader) Read(p []byte) (int, error) { + if err := cr.ctx.Err(); err != nil { + return 0, err + } + return cr.r.Read(p) +} + +// writeStreamPayload handles a stream payload (io.Reader / +// io.ReadCloser). The bytes flow through verbatim — no producer is +// invoked. The wire Content-Type is resolved via setStreamContentType +// (priority: existing header, payload's ContentTyper, +// streamFallbackMime, mediaType). +// +// Caller must ensure r.payload satisfies io.Reader (see +// [request.usesStreamingBody]). +func (r *Request) writeStreamPayload(mediaType string, producers map[string]runtime.Producer) io.Reader { + setStreamContentType(r.header, r.payload, mediaType, r.consumes, producers) + if rdr, ok := r.payload.(io.ReadCloser); ok { + return rdr + } + return r.payload.(io.Reader) +} + +// writeNonStreamPayload runs the producer registered for mediaType +// against r.payload, writing into r.buf. The Content-Type header +// reflects the picker. +// +// SetHeaderParam("Content-Type", …) is intentionally NOT honored on +// the producer path because the producer is dispatched off mediaType — +// the wire header would otherwise misrepresent the body. +// +// The same reasoning applies to the form/multipart branch. +func (r *Request) writeNonStreamPayload(mediaType string, producers map[string]runtime.Producer) (io.Reader, error) { + r.header.Set(runtime.HeaderContentType, mediaType) + producer := producers[mediaType] + if err := producer.Produce(r.buf, r.payload); err != nil { + return nil, err + } + return r.buf, nil +} + +func escapeQuotes(s string) string { + return strings.NewReplacer("\\", "\\\\", `"`, "\\\"").Replace(s) +} + +// setStreamContentType resolves and writes the wire Content-Type for a +// stream payload (io.Reader / io.ReadCloser). Priority: +// +// 1. an explicit value already in header — the user set it via +// SetHeaderParam during [ClientRequestWriter.WriteToRequest], and we treat that as an +// intentional escape hatch; +// 2. payload's [runtime.ContentTyper] declaration; +// 3. [streamFallbackMime] (Stage-2 octet-stream upgrade); +// 4. the picker's mediaType (passed in as the chain's terminal +// fallback). +// +// Does not apply to non-stream payloads or to form/multipart bodies — +// see the comment above the call site in [request.buildHTTP]. +func setStreamContentType( + header http.Header, + payload any, + mediaType string, + candidates []string, + producers map[string]runtime.Producer, +) { + if header.Get(runtime.HeaderContentType) != "" { + return + } + fallback := streamFallbackMime(mediaType, candidates, producers) + header.Set(runtime.HeaderContentType, payloadContentType(payload, fallback)) +} + +// payloadContentType returns the payload's declared content type when +// it implements [runtime.ContentTyper] with a non-empty result, and +// fallback otherwise. Mirrors the per-file convention already used for +// multipart upload parts (see [request.buildHTTP] file-fields branch). +func payloadContentType(payload any, fallback string) string { + if t, ok := payload.(runtime.ContentTyper); ok { + if ct := t.ContentType(); ct != "" { + return ct + } + } + + return fallback +} + +// streamFallbackMime selects a wire content-type for a stream payload +// (io.Reader / io.ReadCloser) that has neither implemented +// `ContentType() string` nor declared an explicit value. +// +// The picker (Stage 1) ran without seeing the payload, so its choice +// may be wildly wrong for raw bytes — e.g. picking application/json +// for a payload that is just a stream of opaque data. When the +// candidate consumes list also offers application/octet-stream and +// the runtime has an octet-stream producer registered, that's a +// safer wire type than the picker's choice: it advertises "raw bytes" +// rather than making a structural claim about the body. +// +// If octet-stream is unavailable in either the candidate list or the +// producer set, the picker's choice is preserved. The wire header +// then continues to misrepresent the body — but no correct +// alternative exists and we cannot infer one without more +// information from the caller. +func streamFallbackMime(picked string, candidates []string, producers map[string]runtime.Producer) string { + if strings.EqualFold(picked, runtime.DefaultMime) { + return picked + } + + for _, c := range candidates { + if strings.EqualFold(c, runtime.DefaultMime) { + if _, ok := producers[runtime.DefaultMime]; ok { + return runtime.DefaultMime + } + } + } + + return picked +} + +func getRequestBuffer(r *Request) []byte { + if r.buf == nil { + return nil + } + return r.buf.Bytes() +} + +func logClose(err error, pw *io.PipeWriter) { + log.Println(err) + closeErr := pw.CloseWithError(err) + if closeErr != nil { + log.Println(closeErr) + } +} + +func mangleContentType(_, boundary string) string { + // Proposal for enhancement: honor caller's boundary if specified + return "multipart/form-data; boundary=" + boundary +} diff --git a/vendor/github.com/go-openapi/runtime/client/keepalive.go b/vendor/github.com/go-openapi/runtime/client/keepalive.go index 3bac5e272..6b6097d20 100644 --- a/vendor/github.com/go-openapi/runtime/client/keepalive.go +++ b/vendor/github.com/go-openapi/runtime/client/keepalive.go @@ -34,20 +34,20 @@ func (k *keepAliveTransport) RoundTrip(r *http.Request) (*http.Response, error) type drainingReadCloser struct { rdr io.ReadCloser - seenEOF uint32 + seenEOF atomic.Uint32 } func (d *drainingReadCloser) Read(p []byte) (n int, err error) { n, err = d.rdr.Read(p) if err == io.EOF || n == 0 { - atomic.StoreUint32(&d.seenEOF, 1) + d.seenEOF.Store(1) } return } func (d *drainingReadCloser) Close() error { // drain buffer - if atomic.LoadUint32(&d.seenEOF) != 1 { + if d.seenEOF.Load() != 1 { // If the reader side (a HTTP server) is misbehaving, it still may send // some bytes, but the closer ignores them to keep the underling // connection open. diff --git a/vendor/github.com/go-openapi/runtime/client/opentelemetry.go b/vendor/github.com/go-openapi/runtime/client/opentelemetry.go index 5054878c0..694267459 100644 --- a/vendor/github.com/go-openapi/runtime/client/opentelemetry.go +++ b/vendor/github.com/go-openapi/runtime/client/opentelemetry.go @@ -23,6 +23,47 @@ const ( tracerName = "go-openapi" ) +// WithOpenTelemetry adds opentelemetry support to the provided runtime. +// A new client span is created for each request. +// If the context of the client operation does not contain an active span, no span is created. +// The provided opts are applied to each spans - for example to add global tags. +func (r *Runtime) WithOpenTelemetry(opts ...OpenTelemetryOpt) runtime.ClientTransport { + return newOpenTelemetryTransport(r, r.Host, opts) +} + +// WithOpenTracing adds opentracing support to the provided runtime. +// A new client span is created for each request. +// If the context of the client operation does not contain an active span, no span is created. +// The provided opts are applied to each spans - for example to add global tags. +// +// Deprecated: use [WithOpenTelemetry] instead, as opentracing is now archived and superseded by opentelemetry. +// +// # Deprecation notice +// +// The [Runtime.WithOpenTracing] method has been deprecated in favor of [Runtime.WithOpenTelemetry]. +// +// The method is still around so programs calling it will still build. However, it will return +// an opentelemetry transport. +// +// If you have a strict requirement on using opentracing, you may still do so by importing +// module [github.com/go-openapi/runtime/client-[middleware]/opentracing] and using +// [github.com/go-openapi/runtime/client-[middleware]/opentracing.WithOpenTracing] with your +// usual opentracing options and opentracing-enabled transport. +// +// Passed options are ignored unless they are of type [OpenTelemetryOpt]. +func (r *Runtime) WithOpenTracing(opts ...any) runtime.ClientTransport { + otelOpts := make([]OpenTelemetryOpt, 0, len(opts)) + for _, o := range opts { + otelOpt, ok := o.(OpenTelemetryOpt) + if !ok { + continue + } + otelOpts = append(otelOpts, otelOpt) + } + + return r.WithOpenTelemetry(otelOpts...) +} + type config struct { Tracer trace.Tracer Propagator propagation.TextMapPropagator diff --git a/vendor/github.com/go-openapi/runtime/client/request.go b/vendor/github.com/go-openapi/runtime/client/request.go deleted file mode 100644 index 0ad2da44b..000000000 --- a/vendor/github.com/go-openapi/runtime/client/request.go +++ /dev/null @@ -1,494 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers -// SPDX-License-Identifier: Apache-2.0 - -package client - -import ( - "bytes" - "context" - "fmt" - "io" - "log" - "mime/multipart" - "net/http" - "net/textproto" - "net/url" - "os" - "path" - "path/filepath" - "strings" - "time" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" -) - -var _ runtime.ClientRequest = new(request) // ensure compliance to the interface - -// Request represents a swagger client request. -// -// This Request struct converts to a HTTP request. -// There might be others that convert to other transports. -// There is no error checking here, it is assumed to be used after a spec has been validated. -// so impossible combinations should not arise (hopefully). -// -// The main purpose of this struct is to hide the machinery of adding params to a transport request. -// The generated code only implements what is necessary to turn a param into a valid value for these methods. -type request struct { - pathPattern string - method string - writer runtime.ClientRequestWriter - - pathParams map[string]string - header http.Header - query url.Values - formFields url.Values - fileFields map[string][]runtime.NamedReadCloser - payload any - timeout time.Duration - buf *bytes.Buffer - - getBody func(r *request) []byte -} - -// NewRequest creates a new swagger http client request. -func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) *request { - return &request{ - pathPattern: pathPattern, - method: method, - writer: writer, - header: make(http.Header), - query: make(url.Values), - timeout: DefaultTimeout, - getBody: getRequestBuffer, - } -} - -// BuildHTTP creates a new http request based on the data from the params. -func (r *request) BuildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry) (*http.Request, error) { - return r.buildHTTP(mediaType, basePath, producers, registry, nil) -} - -func (r *request) GetMethod() string { - return r.method -} - -func (r *request) GetPath() string { - path := r.pathPattern - for k, v := range r.pathParams { - path = strings.ReplaceAll(path, "{"+k+"}", v) - } - return path -} - -func (r *request) GetBody() []byte { - return r.getBody(r) -} - -// SetHeaderParam adds a header param to the request -// when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding). -func (r *request) SetHeaderParam(name string, values ...string) error { - if r.header == nil { - r.header = make(http.Header) - } - r.header[http.CanonicalHeaderKey(name)] = values - return nil -} - -// GetHeaderParams returns the all headers currently set for the request. -func (r *request) GetHeaderParams() http.Header { - return r.header -} - -// SetQueryParam adds a query param to the request -// when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding). -func (r *request) SetQueryParam(name string, values ...string) error { - if r.query == nil { - r.query = make(url.Values) - } - r.query[name] = values - return nil -} - -// GetQueryParams returns a copy of all query params currently set for the request. -func (r *request) GetQueryParams() url.Values { - var result = make(url.Values) - for key, value := range r.query { - result[key] = append([]string{}, value...) - } - return result -} - -// SetFormParam adds a forn param to the request -// when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding). -func (r *request) SetFormParam(name string, values ...string) error { - if r.formFields == nil { - r.formFields = make(url.Values) - } - r.formFields[name] = values - return nil -} - -// SetPathParam adds a path param to the request. -func (r *request) SetPathParam(name string, value string) error { - if r.pathParams == nil { - r.pathParams = make(map[string]string) - } - - r.pathParams[name] = value - return nil -} - -// SetFileParam adds a file param to the request. -func (r *request) SetFileParam(name string, files ...runtime.NamedReadCloser) error { - for _, file := range files { - if actualFile, ok := file.(*os.File); ok { - fi, err := os.Stat(actualFile.Name()) - if err != nil { - return err - } - if fi.IsDir() { - return fmt.Errorf("%q is a directory, only files are supported", file.Name()) - } - } - } - - if r.fileFields == nil { - r.fileFields = make(map[string][]runtime.NamedReadCloser) - } - if r.formFields == nil { - r.formFields = make(url.Values) - } - - r.fileFields[name] = files - return nil -} - -func (r *request) GetFileParam() map[string][]runtime.NamedReadCloser { - return r.fileFields -} - -// SetBodyParam sets a body parameter on the request. -// This does not yet serialze the object, this happens as late as possible. -func (r *request) SetBodyParam(payload any) error { - r.payload = payload - return nil -} - -func (r *request) GetBodyParam() any { - return r.payload -} - -// SetTimeout sets the timeout for a request. -func (r *request) SetTimeout(timeout time.Duration) error { - r.timeout = timeout - return nil -} - -func (r *request) isMultipart(mediaType string) bool { - // An explicit application/x-www-form-urlencoded choice is honored even when - // file fields are present: the spec allows files to travel as URL-encoded - // form values, although it does not stream and is discouraged. Without this - // short-circuit, picking urlencoded with files would silently fall back to - // multipart and emit an inconsistent Content-Type. - if strings.EqualFold(mediaType, runtime.URLencodedFormMime) { - return false - } - if len(r.fileFields) > 0 { - return true - } - - return runtime.MultipartFormMime == mediaType -} - -func (r *request) buildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) { //nolint:gocyclo,maintidx - // build the data - if err := r.writer.WriteToRequest(r, registry); err != nil { - return nil, err - } - - // Our body must be an io.Reader. - // When we create the http.Request, if we pass it a - // bytes.Buffer then it will wrap it in an io.ReadCloser - // and set the content length automatically. - var body io.Reader - var pr *io.PipeReader - var pw *io.PipeWriter - - r.buf = bytes.NewBuffer(nil) - if r.payload != nil || len(r.formFields) > 0 || len(r.fileFields) > 0 { - body = r.buf - if r.isMultipart(mediaType) { - pr, pw = io.Pipe() - body = pr - } - } - - // check if this is a form type request - if len(r.formFields) > 0 || len(r.fileFields) > 0 { - if !r.isMultipart(mediaType) { - r.header.Set(runtime.HeaderContentType, mediaType) - values := url.Values{} - for k, vs := range r.formFields { - values[k] = append(values[k], vs...) - } - // Per Swagger 2.0, file form parameters can be sent under - // application/x-www-form-urlencoded by including the file content as a - // regular form-field value. The whole form is then percent-encoded as - // usual. This buffers the entire payload and does not preserve a - // per-file Content-Type — multipart/form-data is preferred when both - // are advertised by the operation. - for fn, ff := range r.fileFields { - for _, fi := range ff { - data, ferr := io.ReadAll(fi) - if cerr := fi.Close(); cerr != nil && ferr == nil { - ferr = cerr - } - if ferr != nil { - return nil, ferr - } - values.Add(fn, string(data)) - } - } - r.buf.WriteString(values.Encode()) - goto DoneChoosingBodySource - } - - mp := multipart.NewWriter(pw) - r.header.Set(runtime.HeaderContentType, mangleContentType(mediaType, mp.Boundary())) - - go func() { - defer func() { - mp.Close() - pw.Close() - }() - - for fn, v := range r.formFields { - for _, vi := range v { - if err := mp.WriteField(fn, vi); err != nil { - logClose(err, pw) - return - } - } - } - - defer func() { - for _, ff := range r.fileFields { - for _, ffi := range ff { - ffi.Close() - } - } - }() - for fn, f := range r.fileFields { - for _, fi := range f { - var fileContentType string - if p, ok := fi.(interface { - ContentType() string - }); ok { - fileContentType = p.ContentType() - } else { - // Need to read the data so that we can detect the content type - const contentTypeBufferSize = 512 - buf := make([]byte, contentTypeBufferSize) - size, err := fi.Read(buf) - if err != nil && err != io.EOF { - logClose(err, pw) - return - } - fileContentType = http.DetectContentType(buf) - fi = runtime.NamedReader(fi.Name(), io.MultiReader(bytes.NewReader(buf[:size]), fi)) - } - - // Create the MIME headers for the new part - h := make(textproto.MIMEHeader) - h.Set("Content-Disposition", - fmt.Sprintf(`form-data; name="%s"; filename="%s"`, - escapeQuotes(fn), escapeQuotes(filepath.Base(fi.Name())))) - h.Set("Content-Type", fileContentType) - - wrtr, err := mp.CreatePart(h) - if err != nil { - logClose(err, pw) - return - } - if _, err := io.Copy(wrtr, fi); err != nil { - logClose(err, pw) - } - } - } - }() - - goto DoneChoosingBodySource - } - - // if there is payload, use the producer to write the payload, and then - // set the header to the content-type appropriate for the payload produced - if r.payload != nil { - // Enhancement proposal: https://github.com/go-openapi/runtime/issues/387 - r.header.Set(runtime.HeaderContentType, mediaType) - if rdr, ok := r.payload.(io.ReadCloser); ok { - body = rdr - goto DoneChoosingBodySource - } - - if rdr, ok := r.payload.(io.Reader); ok { - body = rdr - goto DoneChoosingBodySource - } - - producer := producers[mediaType] - if err := producer.Produce(r.buf, r.payload); err != nil { - return nil, err - } - } - -DoneChoosingBodySource: - - if runtime.CanHaveBody(r.method) && body != nil && r.header.Get(runtime.HeaderContentType) == "" { - r.header.Set(runtime.HeaderContentType, mediaType) - } - - if auth != nil { - // If we're not using r.buf as our http.Request's body, - // either the payload is an io.Reader or io.ReadCloser, - // or we're doing a multipart form/file. - // - // In those cases, if the AuthenticateRequest call asks for the body, - // we must read it into a buffer and provide that, then use that buffer - // as the body of our http.Request. - // - // This is done in-line with the GetBody() request rather than ahead - // of time, because there's no way to know if the AuthenticateRequest - // will even ask for the body of the request. - // - // If for some reason the copy fails, there's no way to return that - // error to the GetBody() call, so return it afterwards. - // - // An error from the copy action is prioritized over any error - // from the AuthenticateRequest call, because the mis-read - // body may have interfered with the auth. - // - var copyErr error - if buf, ok := body.(*bytes.Buffer); body != nil && (!ok || buf != r.buf) { - var copied bool - r.getBody = func(r *request) []byte { - if copied { - return getRequestBuffer(r) - } - - defer func() { - copied = true - }() - - if _, copyErr = io.Copy(r.buf, body); copyErr != nil { - return nil - } - - if closer, ok := body.(io.ReadCloser); ok { - if copyErr = closer.Close(); copyErr != nil { - return nil - } - } - - body = r.buf - return getRequestBuffer(r) - } - } - - authErr := auth.AuthenticateRequest(r, registry) - - if copyErr != nil { - return nil, fmt.Errorf("error retrieving the response body: %v", copyErr) - } - - if authErr != nil { - return nil, authErr - } - } - - // In case the basePath or the request pathPattern include static query parameters, - // parse those out before constructing the final path. The parameters themselves - // will be merged with the ones set by the client, with the priority given first to - // the ones set by the client, then the path pattern, and lastly the base path. - basePathURL, err := url.Parse(basePath) - if err != nil { - return nil, err - } - staticQueryParams := basePathURL.Query() - - pathPatternURL, err := url.Parse(r.pathPattern) - if err != nil { - return nil, err - } - for name, values := range pathPatternURL.Query() { - if _, present := staticQueryParams[name]; present { - staticQueryParams.Del(name) - } - for _, value := range values { - staticQueryParams.Add(name, value) - } - } - - // create http request - var reinstateSlash bool - if pathPatternURL.Path != "" && pathPatternURL.Path != "/" && pathPatternURL.Path[len(pathPatternURL.Path)-1] == '/' { - reinstateSlash = true - } - - urlPath := path.Join(basePathURL.Path, pathPatternURL.Path) - for k, v := range r.pathParams { - urlPath = strings.ReplaceAll(urlPath, "{"+k+"}", url.PathEscape(v)) - } - if reinstateSlash { - urlPath += "/" - } - - req, err := http.NewRequestWithContext(context.Background(), r.method, urlPath, body) - if err != nil { - return nil, err - } - - originalParams := r.GetQueryParams() - - // Merge the query parameters extracted from the basePath with the ones set by - // the client in this struct. In case of conflict, the client wins. - for k, v := range staticQueryParams { - _, present := originalParams[k] - if !present { - if err = r.SetQueryParam(k, v...); err != nil { - return nil, err - } - } - } - - req.URL.RawQuery = r.query.Encode() - req.Header = r.header - - return req, nil -} - -func escapeQuotes(s string) string { - return strings.NewReplacer("\\", "\\\\", `"`, "\\\"").Replace(s) -} - -func getRequestBuffer(r *request) []byte { - if r.buf == nil { - return nil - } - return r.buf.Bytes() -} - -func logClose(err error, pw *io.PipeWriter) { - log.Println(err) - closeErr := pw.CloseWithError(err) - if closeErr != nil { - log.Println(closeErr) - } -} - -func mangleContentType(_, boundary string) string { - return "multipart/form-data; boundary=" + boundary -} diff --git a/vendor/github.com/go-openapi/runtime/client/runtime.go b/vendor/github.com/go-openapi/runtime/client/runtime.go index f41818ea5..2d6273659 100644 --- a/vendor/github.com/go-openapi/runtime/client/runtime.go +++ b/vendor/github.com/go-openapi/runtime/client/runtime.go @@ -5,25 +5,19 @@ package client import ( "context" - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "errors" "fmt" "mime" "net/http" "net/http/httputil" - "os" "strings" "sync" "time" "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/client/internal/request" "github.com/go-openapi/runtime/logger" "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/server-middleware/mediatype" "github.com/go-openapi/runtime/yamlpc" "github.com/go-openapi/strfmt" ) @@ -36,184 +30,6 @@ const ( // DefaultTimeout the default request timeout. var DefaultTimeout = 30 * time.Second -// TLSClientOptions to configure client authentication with mutual TLS. -type TLSClientOptions struct { - // Certificate is the path to a PEM-encoded certificate to be used for - // client authentication. If set then Key must also be set. - Certificate string - - // LoadedCertificate is the certificate to be used for client authentication. - // This field is ignored if Certificate is set. If this field is set, LoadedKey - // is also required. - LoadedCertificate *x509.Certificate - - // Key is the path to an unencrypted PEM-encoded private key for client - // authentication. This field is required if Certificate is set. - Key string - - // LoadedKey is the key for client authentication. This field is required if - // LoadedCertificate is set. - LoadedKey crypto.PrivateKey - - // CA is a path to a PEM-encoded certificate that specifies the root certificate - // to use when validating the TLS certificate presented by the server. If this field - // (and LoadedCA) is not set, the system certificate pool is used. This field is ignored if LoadedCA - // is set. - CA string - - // LoadedCA specifies the root certificate to use when validating the server's TLS certificate. - // If this field (and CA) is not set, the system certificate pool is used. - LoadedCA *x509.Certificate - - // LoadedCAPool specifies a pool of RootCAs to use when validating the server's TLS certificate. - // If set, it will be combined with the other loaded certificates (see LoadedCA and CA). - // If neither LoadedCA or CA is set, the provided pool with override the system - // certificate pool. - // The caller must not use the supplied pool after calling TLSClientAuth. - LoadedCAPool *x509.CertPool - - // ServerName specifies the hostname to use when verifying the server certificate. - // If this field is set then InsecureSkipVerify will be ignored and treated as - // false. - ServerName string - - // InsecureSkipVerify controls whether the certificate chain and hostname presented - // by the server are validated. If true, any certificate is accepted. - InsecureSkipVerify bool - - // VerifyPeerCertificate, if not nil, is called after normal - // certificate verification. It receives the raw ASN.1 certificates - // provided by the peer and also any verified chains that normal processing found. - // If it returns a non-nil error, the handshake is aborted and that error results. - // - // If normal verification fails then the handshake will abort before - // considering this callback. If normal verification is disabled by - // setting InsecureSkipVerify then this callback will be considered but - // the verifiedChains argument will always be nil. - VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error - - // VerifyConnection, if not nil, is called after normal certificate - // verification and after [TLSClientOptions.VerifyPeerCertificate] by either a TLS client or - // server. It receives the [tls.ConnectionState] which may be inspected. - // - // Unlike VerifyPeerCertificate, this callback is invoked on every - // connection, including resumed ones, making it suitable for checks - // that must always apply (e.g. certificate pinning). - // - // If it returns a non-nil error, the handshake is aborted and that error results. - VerifyConnection func(tls.ConnectionState) error - - // SessionTicketsDisabled may be set to true to disable session ticket and - // PSK (resumption) support. Note that on clients, session ticket support is - // also disabled if ClientSessionCache is nil. - SessionTicketsDisabled bool - - // ClientSessionCache is a cache of ClientSessionState entries for TLS - // session resumption. It is only used by clients. - ClientSessionCache tls.ClientSessionCache - - // Prevents callers using unkeyed fields. - _ struct{} -} - -// TLSClientAuth creates a [tls.Config] for mutual auth. -func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { - // create client tls config - cfg := &tls.Config{ - MinVersion: tls.VersionTLS12, - } - - // load client cert if specified - if opts.Certificate != "" { - cert, err := tls.LoadX509KeyPair(opts.Certificate, opts.Key) - if err != nil { - return nil, fmt.Errorf("tls client cert: %v", err) - } - cfg.Certificates = []tls.Certificate{cert} - } else if opts.LoadedCertificate != nil { - block := pem.Block{Type: "CERTIFICATE", Bytes: opts.LoadedCertificate.Raw} - certPem := pem.EncodeToMemory(&block) - - var keyBytes []byte - switch k := opts.LoadedKey.(type) { - case *rsa.PrivateKey: - keyBytes = x509.MarshalPKCS1PrivateKey(k) - case *ecdsa.PrivateKey: - var err error - keyBytes, err = x509.MarshalECPrivateKey(k) - if err != nil { - return nil, fmt.Errorf("tls client priv key: %v", err) - } - default: - return nil, errors.New("tls client priv key: unsupported key type") - } - - block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes} - keyPem := pem.EncodeToMemory(&block) - - cert, err := tls.X509KeyPair(certPem, keyPem) - if err != nil { - return nil, fmt.Errorf("tls client cert: %v", err) - } - cfg.Certificates = []tls.Certificate{cert} - } - - cfg.InsecureSkipVerify = opts.InsecureSkipVerify - - cfg.VerifyPeerCertificate = opts.VerifyPeerCertificate - cfg.VerifyConnection = opts.VerifyConnection - cfg.SessionTicketsDisabled = opts.SessionTicketsDisabled - cfg.ClientSessionCache = opts.ClientSessionCache - - // When no CA certificate is provided, default to the system cert pool - // that way when a request is made to a server known by the system trust store, - // the name is still verified - switch { - case opts.LoadedCA != nil: - caCertPool := basePool(opts.LoadedCAPool) - caCertPool.AddCert(opts.LoadedCA) - cfg.RootCAs = caCertPool - case opts.CA != "": - // load ca cert - caCert, err := os.ReadFile(opts.CA) - if err != nil { - return nil, fmt.Errorf("tls client ca: %v", err) - } - caCertPool := basePool(opts.LoadedCAPool) - caCertPool.AppendCertsFromPEM(caCert) - cfg.RootCAs = caCertPool - case opts.LoadedCAPool != nil: - cfg.RootCAs = opts.LoadedCAPool - } - - // apply servername overrride - if opts.ServerName != "" { - cfg.InsecureSkipVerify = false - cfg.ServerName = opts.ServerName - } - - return cfg, nil -} - -// TLSTransport creates a [http] client transport suitable for mutual [tls] auth. -func TLSTransport(opts TLSClientOptions) (http.RoundTripper, error) { - cfg, err := TLSClientAuth(opts) - if err != nil { - return nil, err - } - - return &http.Transport{TLSClientConfig: cfg}, nil -} - -// TLSClient creates a [http.Client] for mutual auth. -func TLSClient(opts TLSClientOptions) (*http.Client, error) { - transport, err := TLSTransport(opts) - if err != nil { - return nil, err - } - return &http.Client{Transport: transport}, nil -} - // Runtime represents an API client that uses the transport // to make [http] requests based on a swagger specification. type Runtime struct { @@ -233,6 +49,14 @@ type Runtime struct { Debug bool logger logger.Logger + // MatchSuffix enables RFC 6839 structured-syntax suffix tolerance + // for codec lookup. When true, a response with Content-Type + // "application/problem+json" finds the JSON consumer registered + // under "application/json"; with the default false, the lookup + // is strict and falls through to the "*/*" wildcard if present. + // See [mediatype.AllowSuffix] for the semantics. + MatchSuffix bool + clientOnce *sync.Once client *http.Client schemes []string @@ -294,47 +118,6 @@ func NewWithClient(host, basePath string, schemes []string, client *http.Client) return rt } -// WithOpenTracing adds opentracing support to the provided runtime. -// A new client span is created for each request. -// If the context of the client operation does not contain an active span, no span is created. -// The provided opts are applied to each spans - for example to add global tags. -// -// Deprecated: use [WithOpenTelemetry] instead, as opentracing is now archived and superseded by opentelemetry. -// -// # Deprecation notice -// -// The [Runtime.WithOpenTracing] method has been deprecated in favor of [Runtime.WithOpenTelemetry]. -// -// The method is still around so programs calling it will still build. However, it will return -// an opentelemetry transport. -// -// If you have a strict requirement on using opentracing, you may still do so by importing -// module [github.com/go-openapi/runtime/client-[middleware]/opentracing] and using -// [github.com/go-openapi/runtime/client-[middleware]/opentracing.WithOpenTracing] with your -// usual opentracing options and opentracing-enabled transport. -// -// Passed options are ignored unless they are of type [OpenTelemetryOpt]. -func (r *Runtime) WithOpenTracing(opts ...any) runtime.ClientTransport { - otelOpts := make([]OpenTelemetryOpt, 0, len(opts)) - for _, o := range opts { - otelOpt, ok := o.(OpenTelemetryOpt) - if !ok { - continue - } - otelOpts = append(otelOpts, otelOpt) - } - - return r.WithOpenTelemetry(otelOpts...) -} - -// WithOpenTelemetry adds opentelemetry support to the provided runtime. -// A new client span is created for each request. -// If the context of the client operation does not contain an active span, no span is created. -// The provided opts are applied to each spans - for example to add global tags. -func (r *Runtime) WithOpenTelemetry(opts ...OpenTelemetryOpt) runtime.ClientTransport { - return newOpenTelemetryTransport(r, r.Host, opts) -} - // EnableConnectionReuse drains the remaining body from a response // so that go will reuse the TCP connections. // @@ -357,70 +140,70 @@ func (r *Runtime) EnableConnectionReuse() { ) } +// CreateHTTPRequestContext creates the requests and bind the parameters, but does not send it over the wire +// like [Runtime.SubmitContext]. +// +// The [http.Request] is complete with authentication, headers and body (including streamed body) and ready for callers +// to submit it to a [http.Client] of their choice, then consume the [http.Response]. +// +// Most users would simply use [Runtime.SubmitContext], which wraps all these operations in one call. +func (r *Runtime) CreateHTTPRequestContext(ctx context.Context, operation *runtime.ClientOperation) (req *http.Request, cancel context.CancelFunc, err error) { + req, cancel, err = r.createHTTPRequestContext(ctx, operation) + return +} + +// CreateHttpRequestContext is like [Runtime.CreateHTTPRequestContext], but picks its context from the +// [ClientOperation.Context] or from the [Runtime.Context] is they are defined. +// +// # Change in behavior with v0.30.0. +// +// Callers who define a non-zero timeout set by the [ClientOperation.Params] ([runtime.ClientRequestWriter]), +// MUST move to [CreateHTTPRequestContext] in order to retrieve the proper cancellation function, +// and thus avoid a systematic leak of the context cancellation channel. +// +// In previous versions, the value of this timeout was simply ignored here (was only honored by [Runtime.Submit]. +// +// Callers not using timeouts this way are not affected. +// +// Deprecated: use [CreateHTTPRequestContext] instead, with appropriate control of the request cancellation. func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *http.Request, err error) { //nolint:revive - _, req, err = r.createHttpRequest(operation) + req, _, err = r.createHTTPRequestContext(context.Background(), operation) return } // Submit a request and when there is a body on success it will turn that into the result // all other things are turned into an api error for swagger which retains the status code. +// +// This call inherits the context possibly put in the operation, otherwise the one possibly put in the [Runtime]. +// If none are set, use [context.Background]. +// +// Any timeout set by parameters is honored. func (r *Runtime) Submit(operation *runtime.ClientOperation) (any, error) { - _, readResponse, _ := operation.Params, operation.Reader, operation.AuthInfo + return r.SubmitContext(r.ensureContext(operation), operation) +} - request, req, err := r.createHttpRequest(operation) +// SubmitContext submits a request and returns the result. +// +// Errors are turned into an api error for swagger which retains the status code. +// +// Unlike [Submit], [SubmitContext] only injects the context provided by the caller: +// contexts possibly cached in operation or runtime are ignored. +// +// On the other hand, a timeout set by parameters is honored. +func (r *Runtime) SubmitContext(parentCtx context.Context, operation *runtime.ClientOperation) (any, error) { + req, cancel, err := r.createHTTPRequestContext(parentCtx, operation) if err != nil { return nil, err } + defer cancel() - r.clientOnce.Do(func() { - r.client = &http.Client{ - Transport: r.Transport, - Jar: r.Jar, - } - }) - - if r.Debug { - b, err2 := httputil.DumpRequestOut(req, true) - if err2 != nil { - return nil, err2 - } - r.logger.Debugf("%s\n", string(b)) - } - - var parentCtx context.Context - switch { - case operation.Context != nil: - parentCtx = operation.Context - case r.Context != nil: - parentCtx = r.Context - default: - parentCtx = context.Background() - } + r.ensureClient() - var ( - ctx context.Context - cancel context.CancelFunc - ) - if request.timeout == 0 { - // There may be a deadline in the context passed to the operation. - // Otherwise, there is no timeout set. - ctx, cancel = context.WithCancel(parentCtx) - } else { - // Sets the timeout passed from request params (by default runtime.DefaultTimeout). - // If there is already a deadline in the parent context, the shortest will - // apply. - ctx, cancel = context.WithTimeout(parentCtx, request.timeout) + if err := r.dumpRequest(req); err != nil { + return nil, err } - defer cancel() - var client *http.Client - if operation.Client != nil { - client = operation.Client - } else { - client = r.client - } - req = req.WithContext(ctx) - res, err := client.Do(req) // make requests, by default follows 10 redirects before failing + res, err := r.pickClient(operation).Do(req) if err != nil { return nil, err } @@ -431,31 +214,16 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (any, error) { ct = r.DefaultMediaType } - if r.Debug { - printBody := true - if ct == runtime.DefaultMime { - printBody = false // Spare the terminal from a binary blob. - } - b, err2 := httputil.DumpResponse(res, printBody) - if err2 != nil { - return nil, err2 - } - r.logger.Debugf("%s\n", string(b)) + if err := r.dumpResponse(res, ct); err != nil { + return nil, err } - mt, _, err := mime.ParseMediaType(ct) + cons, err := r.resolveConsumer(ct) if err != nil { - return nil, fmt.Errorf("parse content type: %s", err) + return nil, err } - cons, ok := r.Consumers[mt] - if !ok { - if cons, ok = r.Consumers["*/*"]; !ok { - // scream about not knowing what to do - return nil, fmt.Errorf("no consumer: %q", ct) - } - } - return readResponse.ReadResponse(r.response(res), cons) + return operation.Reader.ReadResponse(r.response(res), cons) } // SetDebug changes the debug flag. @@ -482,6 +250,17 @@ func (r *Runtime) SetResponseReader(f ClientResponseFunc) { r.response = f } +func (r *Runtime) ensureContext(operation *runtime.ClientOperation) context.Context { + switch { + case operation.Context != nil: + return operation.Context + case r.Context != nil: + return r.Context + default: + return context.Background() + } +} + func (r *Runtime) pickScheme(schemes []string) string { if v := r.selectScheme(r.schemes); v != "" { return v @@ -518,16 +297,121 @@ func transportOrDefault(left, right http.RoundTripper) http.RoundTripper { return left } -// takes a client operation and creates equivalent http.Request. -func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*request, *http.Request, error) { //nolint:revive +// ensureClient lazily initializes r.client from r.Transport and r.Jar +// on first use. Safe under concurrent calls via sync.Once. +func (r *Runtime) ensureClient() { + r.clientOnce.Do(func() { + r.client = &http.Client{ + Transport: r.Transport, + Jar: r.Jar, + } + }) +} + +// pickClient returns the http.Client to use for this operation: the +// per-operation override if set, else the runtime's shared client. +func (r *Runtime) pickClient(operation *runtime.ClientOperation) *http.Client { + if operation.Client != nil { + return operation.Client + } + return r.client +} + +// dumpRequest writes the outgoing request to the debug logger when +// r.Debug is enabled. No-op otherwise. Returns the dump error so the +// caller can decide whether to abort the submit. +func (r *Runtime) dumpRequest(req *http.Request) error { + if !r.Debug { + return nil + } + b, err := httputil.DumpRequestOut(req, true) + if err != nil { + return err + } + r.logger.Debugf("%s\n", string(b)) + return nil +} + +// dumpResponse writes the incoming response to the debug logger when +// r.Debug is enabled. The body is omitted for runtime.DefaultMime +// (binary blob). No-op otherwise. +func (r *Runtime) dumpResponse(res *http.Response, ct string) error { + if !r.Debug { + return nil + } + printBody := ct != runtime.DefaultMime // Spare the terminal from a binary blob. + b, err := httputil.DumpResponse(res, printBody) + if err != nil { + return err + } + r.logger.Debugf("%s\n", string(b)) + return nil +} + +// resolveConsumer parses ct and returns the registered Consumer for +// that media type. Lookup is alias-aware (RFC 9512 §2.1 — yaml +// aliases) and, when [Runtime.MatchSuffix] is true, also tolerates +// RFC 6839 structured-syntax suffix media types (+json, +xml, +yaml). +// Falls back to the "*/*" entry if no match found. +func (r *Runtime) resolveConsumer(ct string) (runtime.Consumer, error) { + if _, _, err := mime.ParseMediaType(ct); err != nil { + return nil, fmt.Errorf("parse content type: %s", err) + } + if cons, ok := mediatype.Lookup(r.Consumers, ct, r.matchOpts()...); ok { + return cons, nil + } + if cons, ok := r.Consumers["*/*"]; ok { + return cons, nil + } + // scream about not knowing what to do + return nil, fmt.Errorf("no consumer: %q", ct) +} + +// matchOpts builds the mediatype.MatchOption slice for codec +// lookups on the Runtime, currently just the AllowSuffix opt-in. +func (r *Runtime) matchOpts() []mediatype.MatchOption { + if !r.MatchSuffix { + return nil + } + + return []mediatype.MatchOption{mediatype.AllowSuffix()} +} + +// createHTTPRequestContext is the context-aware builder of a [http.Request]. +// +// The returned [http.Request] carries a context derived from parentCtx that +// honors the per-request timeout set during WriteToRequest. Callers must +// invoke cancel once the response is fully read. +func (r *Runtime) createHTTPRequestContext(parentCtx context.Context, operation *runtime.ClientOperation) (*http.Request, context.CancelFunc, error) { + req, cmt, auth, err := r.prepareRequest(operation) + if err != nil { + return nil, nil, err + } + + httpReq, cancel, err := req.BuildHTTPContext(parentCtx, cmt, r.BasePath, r.Producers, r.Formats, auth) + if err != nil { + return nil, nil, err + } + + r.applyHostScheme(httpReq, operation) + + return httpReq, cancel, nil +} + +// prepareRequest performs the operation-to-request setup that is +// independent of how the http.Request is finally assembled: parameters, +// headers, default authentication, and consumes-media-type selection. +func (r *Runtime) prepareRequest(operation *runtime.ClientOperation) (*request.Request, string, runtime.ClientAuthInfoWriter, error) { params, _, auth := operation.Params, operation.Reader, operation.AuthInfo - request := newRequest(operation.Method, operation.PathPattern, params) + req := request.New(operation.Method, operation.PathPattern, params) + _ = req.SetTimeout(DefaultTimeout) // the timeout may be overridden by ClientRequestWriter + req.SetConsumes(operation.ConsumesMediaTypes) accept := make([]string, 0, len(operation.ProducesMediaTypes)) accept = append(accept, operation.ProducesMediaTypes...) - if err := request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil { - return nil, nil, err + if err := req.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil { + return nil, "", nil, err } if auth == nil && r.DefaultAuthentication != nil { @@ -538,53 +422,75 @@ func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*reques return r.DefaultAuthentication.AuthenticateRequest(req, reg) }) } - // if auth != nil { - // if err := auth.AuthenticateRequest(request, r.Formats); err != nil { - // return nil, err - // } - //} - - // Enhancement proposal: https://github.com/go-openapi/runtime/issues/386 - cmt := pickConsumesMediaType(operation.ConsumesMediaTypes, r.DefaultMediaType) - if _, ok := r.Producers[cmt]; !ok && cmt != runtime.MultipartFormMime && cmt != runtime.URLencodedFormMime { - return nil, nil, fmt.Errorf("none of producers: %v registered. try %s", r.Producers, cmt) + cmt := pickConsumesMediaType(operation.ConsumesMediaTypes, r.Producers, r.DefaultMediaType, r.matchOpts()...) + if _, ok := mediatype.Lookup(r.Producers, cmt, r.matchOpts()...); !ok && cmt != runtime.MultipartFormMime && cmt != runtime.URLencodedFormMime { + return nil, "", nil, fmt.Errorf("none of producers: %v registered. try %s", r.Producers, cmt) } - req, err := request.buildHTTP(cmt, r.BasePath, r.Producers, r.Formats, auth) - if err != nil { - return nil, nil, err - } - req.URL.Scheme = r.pickScheme(operation.Schemes) - req.URL.Host = r.Host - req.Host = r.Host - return request, req, nil + return req, cmt, auth, nil +} + +// applyHostScheme stamps the runtime's host and the operation-selected +// scheme onto the freshly built http.Request. +func (r *Runtime) applyHostScheme(httpReq *http.Request, operation *runtime.ClientOperation) { + httpReq.URL.Scheme = r.pickScheme(operation.Schemes) + httpReq.URL.Host = r.Host + httpReq.Host = r.Host } // pickConsumesMediaType selects which Content-Type the client will send. // -// When the operation advertises multipart/form-data alongside other types -// (typically application/x-www-form-urlencoded), multipart is preferred because -// it streams and preserves per-file Content-Type. Otherwise the first non-empty -// entry wins, falling back to def. This makes the choice independent of the -// order produced by codegen. -func pickConsumesMediaType(consumes []string, def string) string { +// Selection rules, in priority order: +// +// 1. multipart/form-data if any consumes entry advertises it (it streams +// and preserves per-file Content-Type, regardless of codegen ordering; +// resolves issue #286); +// 2. the first non-empty entry whose mime is either structural +// (multipart/form-data or application/x-www-form-urlencoded — these +// do not need a producer in the map) or has a producer registered in +// producers — this lets the client gracefully skip unregistered +// spec entries instead of erroring at the gate that follows; +// 3. the first non-empty entry overall (preserves the historical error +// path: the gate at the call site reports "none of producers" with +// the unregistered mime, so the diagnostic is unchanged when nothing +// in consumes is registered); +// 4. def, if consumes is empty or all empty strings. +// +// Step 2 closes part of issues #32 and #386: an operation declaring +// `consumes: [application/x-vendor, application/json]` with no vendor +// producer registered now silently uses JSON instead of erroring. +func pickConsumesMediaType(consumes []string, producers map[string]runtime.Producer, def string, opts ...mediatype.MatchOption) string { for _, mt := range consumes { if strings.EqualFold(mt, runtime.MultipartFormMime) { return mt } } + var firstNonEmpty string for _, mt := range consumes { - if mt != "" { + if mt == "" { + continue + } + if firstNonEmpty == "" { + firstNonEmpty = mt + } + if isStructuralMime(mt) { + return mt + } + if _, ok := mediatype.Lookup(producers, mt, opts...); ok { return mt } } + if firstNonEmpty != "" { + return firstNonEmpty + } return def } -func basePool(pool *x509.CertPool) *x509.CertPool { - if pool == nil { - return x509.NewCertPool() - } - return pool +// isStructuralMime reports whether mt is a media type whose body shape +// is owned by the runtime (multipart envelope, urlencoded form). These +// do not require an entry in the producers map. +func isStructuralMime(mt string) bool { + return strings.EqualFold(mt, runtime.MultipartFormMime) || + strings.EqualFold(mt, runtime.URLencodedFormMime) } diff --git a/vendor/github.com/go-openapi/runtime/client/tls.go b/vendor/github.com/go-openapi/runtime/client/tls.go new file mode 100644 index 000000000..cd1f1ed53 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/client/tls.go @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package client + +import ( + "crypto" + "crypto/ecdsa" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "net/http" + "os" +) + +// TLSClientOptions to configure client authentication with mutual TLS. +type TLSClientOptions struct { + // Certificate is the path to a PEM-encoded certificate to be used for + // client authentication. If set then Key must also be set. + Certificate string + + // LoadedCertificate is the certificate to be used for client authentication. + // This field is ignored if Certificate is set. If this field is set, LoadedKey + // is also required. + LoadedCertificate *x509.Certificate + + // Key is the path to an unencrypted PEM-encoded private key for client + // authentication. This field is required if Certificate is set. + Key string + + // LoadedKey is the key for client authentication. This field is required if + // LoadedCertificate is set. + LoadedKey crypto.PrivateKey + + // CA is a path to a PEM-encoded certificate that specifies the root certificate + // to use when validating the TLS certificate presented by the server. If this field + // (and LoadedCA) is not set, the system certificate pool is used. This field is ignored if LoadedCA + // is set. + CA string + + // LoadedCA specifies the root certificate to use when validating the server's TLS certificate. + // If this field (and CA) is not set, the system certificate pool is used. + LoadedCA *x509.Certificate + + // LoadedCAPool specifies a pool of RootCAs to use when validating the server's TLS certificate. + // If set, it will be combined with the other loaded certificates (see LoadedCA and CA). + // If neither LoadedCA or CA is set, the provided pool with override the system + // certificate pool. + // The caller must not use the supplied pool after calling TLSClientAuth. + LoadedCAPool *x509.CertPool + + // ServerName specifies the hostname to use when verifying the server certificate. + // If this field is set then InsecureSkipVerify will be ignored and treated as + // false. + ServerName string + + // InsecureSkipVerify controls whether the certificate chain and hostname presented + // by the server are validated. If true, any certificate is accepted. + InsecureSkipVerify bool + + // VerifyPeerCertificate, if not nil, is called after normal + // certificate verification. It receives the raw ASN.1 certificates + // provided by the peer and also any verified chains that normal processing found. + // If it returns a non-nil error, the handshake is aborted and that error results. + // + // If normal verification fails then the handshake will abort before + // considering this callback. If normal verification is disabled by + // setting InsecureSkipVerify then this callback will be considered but + // the verifiedChains argument will always be nil. + VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error + + // VerifyConnection, if not nil, is called after normal certificate + // verification and after [TLSClientOptions.VerifyPeerCertificate] by either a TLS client or + // server. It receives the [tls.ConnectionState] which may be inspected. + // + // Unlike VerifyPeerCertificate, this callback is invoked on every + // connection, including resumed ones, making it suitable for checks + // that must always apply (e.g. certificate pinning). + // + // If it returns a non-nil error, the handshake is aborted and that error results. + VerifyConnection func(tls.ConnectionState) error + + // SessionTicketsDisabled may be set to true to disable session ticket and + // PSK (resumption) support. Note that on clients, session ticket support is + // also disabled if ClientSessionCache is nil. + SessionTicketsDisabled bool + + // ClientSessionCache is a cache of ClientSessionState entries for TLS + // session resumption. It is only used by clients. + ClientSessionCache tls.ClientSessionCache + + // Prevents callers using unkeyed fields. + _ struct{} +} + +// TLSClientAuth creates a [tls.Config] for mutual auth. +func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { + // create client tls config + cfg := &tls.Config{ + MinVersion: tls.VersionTLS12, + } + + // load client cert if specified + if opts.Certificate != "" { + cert, err := tls.LoadX509KeyPair(opts.Certificate, opts.Key) + if err != nil { + return nil, fmt.Errorf("tls client cert: %v", err) + } + cfg.Certificates = []tls.Certificate{cert} + } else if opts.LoadedCertificate != nil { + block := pem.Block{Type: "CERTIFICATE", Bytes: opts.LoadedCertificate.Raw} + certPem := pem.EncodeToMemory(&block) + + var keyBytes []byte + switch k := opts.LoadedKey.(type) { + case *rsa.PrivateKey: + keyBytes = x509.MarshalPKCS1PrivateKey(k) + case *ecdsa.PrivateKey: + var err error + keyBytes, err = x509.MarshalECPrivateKey(k) + if err != nil { + return nil, fmt.Errorf("tls client priv key: %v", err) + } + default: + return nil, errors.New("tls client priv key: unsupported key type") + } + + block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes} + keyPem := pem.EncodeToMemory(&block) + + cert, err := tls.X509KeyPair(certPem, keyPem) + if err != nil { + return nil, fmt.Errorf("tls client cert: %v", err) + } + cfg.Certificates = []tls.Certificate{cert} + } + + cfg.InsecureSkipVerify = opts.InsecureSkipVerify + + cfg.VerifyPeerCertificate = opts.VerifyPeerCertificate + cfg.VerifyConnection = opts.VerifyConnection + cfg.SessionTicketsDisabled = opts.SessionTicketsDisabled + cfg.ClientSessionCache = opts.ClientSessionCache + + // When no CA certificate is provided, default to the system cert pool + // that way when a request is made to a server known by the system trust store, + // the name is still verified + switch { + case opts.LoadedCA != nil: + caCertPool := basePool(opts.LoadedCAPool) + caCertPool.AddCert(opts.LoadedCA) + cfg.RootCAs = caCertPool + case opts.CA != "": + // load ca cert + caCert, err := os.ReadFile(opts.CA) + if err != nil { + return nil, fmt.Errorf("tls client ca: %v", err) + } + caCertPool := basePool(opts.LoadedCAPool) + caCertPool.AppendCertsFromPEM(caCert) + cfg.RootCAs = caCertPool + case opts.LoadedCAPool != nil: + cfg.RootCAs = opts.LoadedCAPool + } + + // apply servername overrride + if opts.ServerName != "" { + cfg.InsecureSkipVerify = false + cfg.ServerName = opts.ServerName + } + + return cfg, nil +} + +// TLSTransport creates a [http] client transport suitable for mutual [tls] auth. +func TLSTransport(opts TLSClientOptions) (http.RoundTripper, error) { + cfg, err := TLSClientAuth(opts) + if err != nil { + return nil, err + } + + return &http.Transport{TLSClientConfig: cfg}, nil +} + +// TLSClient creates a [http.Client] for mutual auth. +func TLSClient(opts TLSClientOptions) (*http.Client, error) { + transport, err := TLSTransport(opts) + if err != nil { + return nil, err + } + return &http.Client{Transport: transport}, nil +} + +func basePool(pool *x509.CertPool) *x509.CertPool { + if pool == nil { + return x509.NewCertPool() + } + return pool +} diff --git a/vendor/github.com/go-openapi/runtime/constants.go b/vendor/github.com/go-openapi/runtime/constants.go index 80de6c808..ea86cfadb 100644 --- a/vendor/github.com/go-openapi/runtime/constants.go +++ b/vendor/github.com/go-openapi/runtime/constants.go @@ -21,8 +21,12 @@ const ( DefaultMime = "application/octet-stream" // JSONMime the json mime type. JSONMime = "application/json" - // YAMLMime the [yaml] mime type. - YAMLMime = "application/x-yaml" + // YAMLMime the [yaml] mime type. Set to the canonical RFC 9512 + // name (application/yaml). Legacy forms application/x-yaml, + // text/yaml, and text/x-yaml — per RFC 9512 §2.1 "Deprecated + // alias names for this type" — resolve to the same codec via + // the mediatype alias bridge. + YAMLMime = "application/yaml" // XMLMime the [xml] mime type. XMLMime = "application/xml" // TextMime the text mime type. diff --git a/vendor/github.com/go-openapi/runtime/csv.go b/vendor/github.com/go-openapi/runtime/csv.go index 558d0cb99..33f3af1ae 100644 --- a/vendor/github.com/go-openapi/runtime/csv.go +++ b/vendor/github.com/go-openapi/runtime/csv.go @@ -100,7 +100,7 @@ func CSVConsumer(opts ...CSVOpt) Consumer { default: // support *[][]string, *[]byte, *string - if ptr := reflect.TypeOf(data); ptr.Kind() != reflect.Ptr { + if ptr := reflect.TypeOf(data); ptr.Kind() != reflect.Pointer { return errors.New("destination must be a pointer") } diff --git a/vendor/github.com/go-openapi/runtime/go.work b/vendor/github.com/go-openapi/runtime/go.work index efa29dcac..bfc5db223 100644 --- a/vendor/github.com/go-openapi/runtime/go.work +++ b/vendor/github.com/go-openapi/runtime/go.work @@ -1,6 +1,7 @@ use ( . ./client-middleware/opentracing + ./server-middleware ) go 1.25.0 diff --git a/vendor/github.com/go-openapi/runtime/interfaces.go b/vendor/github.com/go-openapi/runtime/interfaces.go index a8b4b318d..2d0f2d2bb 100644 --- a/vendor/github.com/go-openapi/runtime/interfaces.go +++ b/vendor/github.com/go-openapi/runtime/interfaces.go @@ -99,3 +99,25 @@ type Validatable interface { type ContextValidatable interface { ContextValidate(context.Context, strfmt.Registry) error } + +// ContentTyper is implemented by values that declare their own MIME +// content type. The client runtime consults it in two places: +// +// - on a body payload set via SetBodyParam: when the payload is a +// stream (io.Reader, io.ReadCloser) and ContentType returns a +// non-empty value, that value becomes the wire Content-Type +// header instead of the operation's picked consumes entry. +// +// - on individual file values inside a multipart upload: their per- +// part Content-Type header is taken from ContentType() rather +// than sniffed via http.DetectContentType. +// +// An empty string return is treated as "no opinion" and the runtime +// falls back to its default selection. Values that have no content +// type to declare may simply not implement the interface. +// +// See docs/MEDIA_TYPES.md for the full client-side selection +// algorithm. +type ContentTyper interface { + ContentType() string +} diff --git a/vendor/github.com/go-openapi/runtime/middleware/context.go b/vendor/github.com/go-openapi/runtime/middleware/context.go index 728c73308..a26f1576d 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/context.go +++ b/vendor/github.com/go-openapi/runtime/middleware/context.go @@ -7,8 +7,6 @@ import ( stdContext "context" "fmt" "net/http" - "net/url" - "path" "strings" "sync" @@ -23,14 +21,15 @@ import ( "github.com/go-openapi/runtime/logger" "github.com/go-openapi/runtime/middleware/untyped" "github.com/go-openapi/runtime/security" + "github.com/go-openapi/runtime/server-middleware/docui" + "github.com/go-openapi/runtime/server-middleware/mediatype" + "github.com/go-openapi/runtime/server-middleware/negotiate" ) // Debug when true turns on verbose logging. var Debug = logger.DebugEnabled() // Logger is the standard library logger used for printing debug messages. -// -// (Note: The correct spelling is "library", not "libra". "Libra" is a zodiac sign/constellation and wouldn't make sense in this context.) var Logger logger.Logger = logger.StandardLogger{} func debugLogfFunc(lg logger.Logger) func(string, ...any) { @@ -76,11 +75,103 @@ func (fn ResponderFunc) WriteResponse(rw http.ResponseWriter, pr runtime.Produce // used throughout to store request context with the standard context attached // to the [http.Request]. type Context struct { - spec *loads.Document - analyzer *analysis.Spec - api RoutableAPI - router Router - debugLogf func(string, ...any) // a logging function to debug context and all components using it + spec *loads.Document + analyzer *analysis.Spec + api RoutableAPI + router Router + debugLogf func(string, ...any) // a logging function to debug context and all components using it + ignoreParameters bool // see SetIgnoreParameters / WithIgnoreParameters + matchSuffix bool // see SetMatchSuffix / WithMatchSuffix +} + +// NewRoutableContext creates a new context for a routable API. +// +// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. +func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Router) *Context { + var an *analysis.Spec + if spec != nil { + an = analysis.New(spec.Spec()) + } + + return NewRoutableContextWithAnalyzedSpec(spec, an, routableAPI, routes) +} + +// NewRoutableContextWithAnalyzedSpec is like [NewRoutableContext] but takes as input an already analysed spec. +// +// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. +func NewRoutableContextWithAnalyzedSpec(spec *loads.Document, an *analysis.Spec, routableAPI RoutableAPI, routes Router) *Context { + // Either there are no spec doc and analysis, or both of them. + if (spec != nil || an != nil) && (spec == nil || an == nil) { + panic(fmt.Errorf("%d: %s", http.StatusInternalServerError, "routable context requires either both spec doc and analysis, or none of them")) + } + + return &Context{ + spec: spec, + api: routableAPI, + analyzer: an, + router: routes, + debugLogf: debugLogfFunc(nil), + } +} + +// NewContext creates a new context wrapper. +// +// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. +func NewContext(spec *loads.Document, api *untyped.API, routes Router) *Context { + var an *analysis.Spec + if spec != nil { + an = analysis.New(spec.Spec()) + } + ctx := &Context{ + spec: spec, + analyzer: an, + router: routes, + debugLogf: debugLogfFunc(nil), + } + ctx.api = newRoutableUntypedAPI(spec, api, ctx) + + return ctx +} + +// Serve serves the specified spec with the specified api registrations as a [http.Handler]. +func Serve(spec *loads.Document, api *untyped.API) http.Handler { + return ServeWithBuilder(spec, api, PassthroughBuilder) +} + +// SetIgnoreParameters toggles the legacy parameter-stripping behaviour for +// Accept negotiation server-wide. When set, every internal call to +// [NegotiateContentType] from this Context applies [WithIgnoreParameters]. +// +// Returns the receiver for fluent configuration: +// +// ctx := middleware.NewContext(spec, api, nil).SetIgnoreParameters(true) +// +// See [WithIgnoreParameters] for the rationale and an example. +func (c *Context) SetIgnoreParameters(ignore bool) *Context { + c.ignoreParameters = ignore + + return c +} + +// SetMatchSuffix toggles RFC 6839 structured-syntax suffix tolerance +// server-wide. When enabled, both Accept negotiation and codec lookup +// fall back through the suffix base for the recognised suffixes +// (+json, +xml, +yaml) — so an operation declaring +// consumes: [application/json] also accepts request bodies sent with +// Content-Type: application/vnd.api+json (or any other +json variant). +// +// Default: strict (false). Use only when interoperating with clients +// that do not strictly abide by the spec. +// +// Returns the receiver for fluent configuration: +// +// ctx := middleware.NewContext(spec, api, nil).SetMatchSuffix(true) +// +// See [negotiate.WithMatchSuffix] for the per-call form and rationale. +func (c *Context) SetMatchSuffix(enable bool) *Context { + c.matchSuffix = enable + + return c } type routableUntypedAPI struct { @@ -193,60 +284,6 @@ func (r *routableUntypedAPI) DefaultConsumes() string { return r.defaultConsumes } -// NewRoutableContext creates a new context for a routable API. -// -// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. -func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Router) *Context { - var an *analysis.Spec - if spec != nil { - an = analysis.New(spec.Spec()) - } - - return NewRoutableContextWithAnalyzedSpec(spec, an, routableAPI, routes) -} - -// NewRoutableContextWithAnalyzedSpec is like [NewRoutableContext] but takes as input an already analysed spec. -// -// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. -func NewRoutableContextWithAnalyzedSpec(spec *loads.Document, an *analysis.Spec, routableAPI RoutableAPI, routes Router) *Context { - // Either there are no spec doc and analysis, or both of them. - if (spec != nil || an != nil) && (spec == nil || an == nil) { - panic(fmt.Errorf("%d: %s", http.StatusInternalServerError, "routable context requires either both spec doc and analysis, or none of them")) - } - - return &Context{ - spec: spec, - api: routableAPI, - analyzer: an, - router: routes, - debugLogf: debugLogfFunc(nil), - } -} - -// NewContext creates a new context wrapper. -// -// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. -func NewContext(spec *loads.Document, api *untyped.API, routes Router) *Context { - var an *analysis.Spec - if spec != nil { - an = analysis.New(spec.Spec()) - } - ctx := &Context{ - spec: spec, - analyzer: an, - router: routes, - debugLogf: debugLogfFunc(nil), - } - ctx.api = newRoutableUntypedAPI(spec, api, ctx) - - return ctx -} - -// Serve serves the specified spec with the specified api registrations as a [http.Handler]. -func Serve(spec *loads.Document, api *untyped.API) http.Handler { - return ServeWithBuilder(spec, api, PassthroughBuilder) -} - // ServeWithBuilder serves the specified spec with the specified api registrations as a [http.Handler] that is decorated // by the Builder. func ServeWithBuilder(spec *loads.Document, api *untyped.API, builder Builder) http.Handler { @@ -334,7 +371,7 @@ func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, b res = append(res, err) } if len(res) == 0 { - cons, ok := route.Consumers[ct] + cons, ok := mediatype.Lookup(route.Consumers, ct, c.matchOpts()...) if !ok { res = append(res, errors.New(http.StatusInternalServerError, "no consumer registered for %s", ct)) } else { @@ -353,7 +390,7 @@ func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, b requestContentType = "*/*" } - if str := NegotiateContentType(request, route.Produces, requestContentType); str == "" { + if str := negotiate.ContentType(request, route.Produces, requestContentType, c.negotiateOpts()...); str == "" { res = append(res, errors.InvalidResponseFormat(request.Header.Get(runtime.HeaderAccept), route.Produces)) } } @@ -432,7 +469,7 @@ func (c *Context) ResponseFormat(r *http.Request, offers []string) (string, *htt return v, r } - format := NegotiateContentType(r, offers, "") + format := negotiate.ContentType(r, offers, "", c.negotiateOpts()...) if format != "" { c.debugLogf("[%s %s] set response format %q in context", r.Method, r.URL.Path, format) r = r.WithContext(stdContext.WithValue(rCtx, ctxResponseFormat, format)) @@ -619,57 +656,76 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st // // This handler includes a swagger spec, router and the contract defined in the swagger spec. // -// A spec UI ([SwaggerUI]) is served at {API base path}/docs and the spec document at /swagger.json -// (these can be modified with uiOptions). +// A spec UI ([docui.SwaggerUI]) is served at {API base path}/docs and the spec document at /swagger.json +// (these can be modified with combined [UIOption]). +// +// Deprecated: use [Context.APIHandlerWithUI] with [docui.SwaggerUI] middleware instead. func (c *Context) APIHandlerSwaggerUI(builder Builder, opts ...UIOption) http.Handler { - b := builder - if b == nil { - b = PassthroughBuilder - } - - specPath, uiOpts, specOpts := c.uiOptionsForHandler(opts) - var swaggerUIOpts SwaggerUIOpts - fromCommonToAnyOptions(uiOpts, &swaggerUIOpts) - - return Spec(specPath, c.spec.Raw(), SwaggerUI(swaggerUIOpts, c.RoutesHandler(b)), specOpts...) + return c.APIHandlerWithUI(builder, docui.UseSwaggerUI, c.uiOptionsForHandler(opts)...) } // APIHandlerRapiDoc returns a handler to serve the API. // // This handler includes a swagger spec, router and the contract defined in the swagger spec. // -// A spec UI ([RapiDoc]) is served at {API base path}/docs and the spec document at /swagger.json -// (these can be modified with uiOptions). +// A spec UI ([docui.RapiDoc]) is served at {API base path}/docs and the spec document at /swagger.json +// (these can be modified with combined [UIOption]). +// +// Deprecated: use [Context.APIHandlerWithUI] with [docui.UseRapiDoc] middleware instead. func (c *Context) APIHandlerRapiDoc(builder Builder, opts ...UIOption) http.Handler { - b := builder - if b == nil { - b = PassthroughBuilder - } - - specPath, uiOpts, specOpts := c.uiOptionsForHandler(opts) - var rapidocUIOpts RapiDocOpts - fromCommonToAnyOptions(uiOpts, &rapidocUIOpts) - - return Spec(specPath, c.spec.Raw(), RapiDoc(rapidocUIOpts, c.RoutesHandler(b)), specOpts...) + return c.APIHandlerWithUI(builder, docui.UseRapiDoc, c.uiOptionsForHandler(opts)...) } // APIHandler returns a handler to serve the API. // // This handler includes a swagger spec, router and the contract defined in the swagger spec. // -// A spec UI ([Redoc]) is served at {API base path}/docs and the spec document at /swagger.json -// (these can be modified with uiOptions). +// A spec UI ([docui.Redoc]) is served at {API base path}/docs and the spec document at /swagger.json +// (these can be modified with combined [UIOption]). +// +// Notice that you may use [Context.APIHandlerWithUI] to use an alternate UI-serving middleware. func (c *Context) APIHandler(builder Builder, opts ...UIOption) http.Handler { + return c.APIHandlerWithUI(builder, docui.UseRedoc, c.uiOptionsForHandler(opts)...) +} + +// APIHandlerWithUI returns a handler to serve the API with a swagger spec and a UI. +// +// This handler includes a swagger spec, router and the contract defined in the swagger spec. +// +// A spec UI is served at {API base path}/docs and the spec document at /swagger.json +// (these can be modified with combined [UIOption]). +// +// Notice that any function that accepts the [docui.Option] set and returns a valid middleware may be injected here. +// +// [Context.APIHandlerWithUI] extends [Context.APIHandler], and supersedes [Context.APIHandlerRapiDoc] and [Context.APIHandlerSwaggerUI]. +func (c *Context) APIHandlerWithUI(builder Builder, uiMiddleware docui.UIMiddleware, opts ...docui.Option) http.Handler { b := builder if b == nil { b = PassthroughBuilder } - specPath, uiOpts, specOpts := c.uiOptionsForHandler(opts) - var redocOpts RedocOpts - fromCommonToAnyOptions(uiOpts, &redocOpts) + // the UI titles defaults to the title in the spec + const extraOptions = 2 + prepend := make([]docui.Option, 0, len(opts)+extraOptions) + var title string + + sp := c.spec.Spec() + if sp != nil && sp.Info != nil && sp.Info.Title != "" { + title = sp.Info.Title + } + if title != "" { + prepend = append(prepend, docui.WithUITitle(title)) + } + + prepend = append(prepend, docui.WithUIBasePath(c.BasePath())) + prepend = append(prepend, opts...) - return Spec(specPath, c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b)), specOpts...) + // aligns spec serve path with UI setting to fetch spec document. + return docui.UseSpec(c.spec.Raw(), docui.WithSpecPathFromOptions(prepend...))( + uiMiddleware(prepend...)( + c.RoutesHandler(b), + ), + ) } // RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec. @@ -681,37 +737,35 @@ func (c *Context) RoutesHandler(builder Builder) http.Handler { return NewRouter(c, b(NewOperationExecutor(c))) } -func (c Context) uiOptionsForHandler(opts []UIOption) (string, uiOptions, []SpecOption) { - var title string - sp := c.spec.Spec() - if sp != nil && sp.Info != nil && sp.Info.Title != "" { - title = sp.Info.Title - } +// uiOptionsForHandler bridges the deprecated [UIOption] set to the new [docui.Option] set. +func (c Context) uiOptionsForHandler(opts []UIOption) []docui.Option { + uiOpts := uiOptionsWithDefaults(opts) - // default options (may be overridden) - const baseOptions = 2 - optsForContext := make([]UIOption, 0, len(opts)+baseOptions) - optsForContext = append(optsForContext, - WithUIBasePath(c.BasePath()), - WithUITitle(title), - ) - optsForContext = append(optsForContext, opts...) - uiOpts := uiOptionsWithDefaults(optsForContext) + return uiOpts.toFuncOptions() +} - // If spec URL is provided, there is a non-default path to serve the spec. - // This makes sure that the UI middleware is aligned with the Spec middleware. - u, _ := url.Parse(uiOpts.SpecURL) - var specPath string - if u != nil { - specPath = u.Path +func (c *Context) negotiateOpts() []negotiate.Option { + var opts []negotiate.Option + if c.ignoreParameters { + opts = append(opts, negotiate.WithIgnoreParameters(true)) + } + if c.matchSuffix { + opts = append(opts, negotiate.WithMatchSuffix(true)) } - pth, doc := path.Split(specPath) - if pth == "." { - pth = "" + return opts +} + +// matchOpts builds the mediatype.MatchOption slice that the +// codec-lookup and Content-Type validation paths apply server-wide. +// Mirrors negotiateOpts but at the mediatype level (without going +// through the negotiate.Option wrapper). +func (c *Context) matchOpts() []mediatype.MatchOption { + if !c.matchSuffix { + return nil } - return pth, uiOpts, []SpecOption{WithSpecDocument(doc)} + return []mediatype.MatchOption{mediatype.AllowSuffix()} } func cantFindProducer(format string) string { diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go index f89d761cf..82ee80c84 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go @@ -9,6 +9,7 @@ package denco import ( "errors" "fmt" + "slices" "sort" "strings" ) @@ -213,8 +214,8 @@ func (da *doubleArray) lookup(path string, params []Param, idx int) (*node, []Pa } BACKTRACKING: - for j := len(indices) - 1; j >= 0; j-- { - i, idx := int(indices[j]>>indexOffset), int(indices[j]&indexMask) + for _, j := range slices.Backward(indices) { + i, idx := int(j>>indexOffset), int(j&indexMask) if da.bc[idx].IsSingleParam() { nextIdx := nextIndex(da.bc[idx].Base(), ParamCharacter) if nextIdx >= len(da.bc) { diff --git a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go b/vendor/github.com/go-openapi/runtime/middleware/negotiate.go deleted file mode 100644 index cb0a85283..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers -// SPDX-License-Identifier: Apache-2.0 - -// Copyright 2013 The Go Authors. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file or at -// https://developers.google.com/open-source/licenses/bsd. - -// this file was taken from the github.com/golang/gddo repository - -package middleware - -import ( - "net/http" - "strings" - - "github.com/go-openapi/runtime/middleware/header" -) - -// NegotiateContentEncoding returns the best offered content encoding for the -// request's Accept-Encoding header. If two offers match with equal weight and -// then the offer earlier in the list is preferred. If no offers are -// acceptable, then "" is returned. -func NegotiateContentEncoding(r *http.Request, offers []string) string { - bestOffer := "identity" - bestQ := -1.0 - specs := header.ParseAccept(r.Header, "Accept-Encoding") - for _, offer := range offers { - for _, spec := range specs { - if spec.Q > bestQ && - (spec.Value == "*" || spec.Value == offer) { - bestQ = spec.Q - bestOffer = offer - } - } - } - if bestQ == 0 { - bestOffer = "" - } - return bestOffer -} - -// NegotiateContentType returns the best offered content type for the request's -// Accept header. If two offers match with equal weight, then the more specific -// offer is preferred. For example, text/* trumps */*. If two offers match -// with equal weight and specificity, then the offer earlier in the list is -// preferred. If no offers match, then defaultOffer is returned. -func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string { - bestOffer := defaultOffer - bestQ := -1.0 - bestWild := 3 - specs := header.ParseAccept(r.Header, "Accept") - for _, rawOffer := range offers { - offer := normalizeOffer(rawOffer) - // No Accept header: just return the first offer. - if len(specs) == 0 { - return rawOffer - } - for _, spec := range specs { - switch { - case spec.Q == 0.0: - // ignore - case spec.Q < bestQ: - // better match found - case spec.Value == "*/*": - if spec.Q > bestQ || bestWild > 2 { - bestQ = spec.Q - bestWild = 2 - bestOffer = rawOffer - } - case strings.HasSuffix(spec.Value, "/*"): - if strings.HasPrefix(offer, spec.Value[:len(spec.Value)-1]) && - (spec.Q > bestQ || bestWild > 1) { - bestQ = spec.Q - bestWild = 1 - bestOffer = rawOffer - } - default: - if spec.Value == offer && - (spec.Q > bestQ || bestWild > 0) { - bestQ = spec.Q - bestWild = 0 - bestOffer = rawOffer - } - } - } - } - return bestOffer -} - -func normalizeOffers(orig []string) (norm []string) { - for _, o := range orig { - norm = append(norm, normalizeOffer(o)) - } - return -} - -func normalizeOffer(orig string) string { - const maxParts = 2 - return strings.SplitN(orig, ";", maxParts)[0] -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/parameter.go b/vendor/github.com/go-openapi/runtime/middleware/parameter.go index a9d2a3646..224fdd731 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/parameter.go +++ b/vendor/github.com/go-openapi/runtime/middleware/parameter.go @@ -101,14 +101,14 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams } if err != nil { - return errors.InvalidContentType("", []string{"multipart/form-data", "application/x-www-form-urlencoded"}) + return errors.InvalidContentType("", []string{runtime.MultipartFormMime, runtime.URLencodedFormMime}) } - if mt != "multipart/form-data" && mt != "application/x-www-form-urlencoded" { - return errors.InvalidContentType(mt, []string{"multipart/form-data", "application/x-www-form-urlencoded"}) + if mt != runtime.MultipartFormMime && mt != runtime.URLencodedFormMime { + return errors.InvalidContentType(mt, []string{runtime.MultipartFormMime, runtime.URLencodedFormMime}) } - if mt == "multipart/form-data" { + if mt == runtime.MultipartFormMime { if err = request.ParseMultipartForm(defaultMaxMemory); err != nil { return errors.NewParseError(p.Name, p.parameter.In, "", err) } @@ -394,8 +394,8 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue an target.SetString(value) } - case reflect.Ptr: - if data == "" && defVal.Kind() == reflect.Ptr { + case reflect.Pointer: + if data == "" && defVal.Kind() == reflect.Pointer { if target.CanSet() { target.Set(defVal) } diff --git a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go b/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go deleted file mode 100644 index 1574defb4..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go +++ /dev/null @@ -1,83 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers -// SPDX-License-Identifier: Apache-2.0 - -package middleware - -import ( - "bytes" - "fmt" - "html/template" - "net/http" - "path" -) - -// RapiDocOpts configures the [RapiDoc] middlewares. -type RapiDocOpts struct { - // BasePath for the UI, defaults to: / - BasePath string - - // Path combines with BasePath to construct the path to the UI, defaults to: "docs". - Path string - - // SpecURL is the URL of the spec document. - // - // Defaults to: /swagger.json - SpecURL string - - // Title for the documentation site, default to: API documentation - Title string - - // Template specifies a custom template to serve the UI - Template string - - // RapiDocURL points to the js asset that generates the rapidoc site. - // - // Defaults to https://unpkg.com/rapidoc/dist/rapidoc-min.js - RapiDocURL string -} - -func (r *RapiDocOpts) EnsureDefaults() { - common := toCommonUIOptions(r) - common.EnsureDefaults() - fromCommonToAnyOptions(common, r) - - // rapidoc-specifics - if r.RapiDocURL == "" { - r.RapiDocURL = rapidocLatest - } - if r.Template == "" { - r.Template = rapidocTemplate - } -} - -// RapiDoc creates a [middleware] to serve a documentation site for a swagger spec. -// -// This allows for altering the spec before starting the [http] listener. -func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler { - opts.EnsureDefaults() - - pth := path.Join(opts.BasePath, opts.Path) - tmpl := template.Must(template.New("rapidoc").Parse(opts.Template)) - assets := bytes.NewBuffer(nil) - if err := tmpl.Execute(assets, opts); err != nil { - panic(fmt.Errorf("cannot execute template: %w", err)) - } - - return serveUI(pth, assets.Bytes(), next) -} - -const ( - rapidocLatest = "https://unpkg.com/rapidoc/dist/rapidoc-min.js" - rapidocTemplate = ` - - - {{ .Title }} - - - - - - - -` -) diff --git a/vendor/github.com/go-openapi/runtime/middleware/redoc.go b/vendor/github.com/go-openapi/runtime/middleware/redoc.go deleted file mode 100644 index 1007409a3..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/redoc.go +++ /dev/null @@ -1,97 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers -// SPDX-License-Identifier: Apache-2.0 - -package middleware - -import ( - "bytes" - "fmt" - "html/template" - "net/http" - "path" -) - -// RedocOpts configures the [Redoc] middlewares. -type RedocOpts struct { - // BasePath for the UI, defaults to: / - BasePath string - - // Path combines with BasePath to construct the path to the UI, defaults to: "docs". - Path string - - // SpecURL is the URL of the spec document. - // - // Defaults to: /swagger.json - SpecURL string - - // Title for the documentation site, default to: API documentation - Title string - - // Template specifies a custom template to serve the UI - Template string - - // RedocURL points to the js that generates the redoc site. - // - // Defaults to: https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js - RedocURL string -} - -// EnsureDefaults in case some options are missing. -func (r *RedocOpts) EnsureDefaults() { - common := toCommonUIOptions(r) - common.EnsureDefaults() - fromCommonToAnyOptions(common, r) - - // redoc-specifics - if r.RedocURL == "" { - r.RedocURL = redocLatest - } - if r.Template == "" { - r.Template = redocTemplate - } -} - -// Redoc creates a [middleware] to serve a documentation site for a swagger spec. -// -// This allows for altering the spec before starting the [http] listener. -func Redoc(opts RedocOpts, next http.Handler) http.Handler { - opts.EnsureDefaults() - - pth := path.Join(opts.BasePath, opts.Path) - tmpl := template.Must(template.New("redoc").Parse(opts.Template)) - assets := bytes.NewBuffer(nil) - if err := tmpl.Execute(assets, opts); err != nil { - panic(fmt.Errorf("cannot execute template: %w", err)) - } - - return serveUI(pth, assets.Bytes(), next) -} - -const ( - redocLatest = "https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js" - redocTemplate = ` - - - {{ .Title }} - - - - - - - - - - - - - -` -) diff --git a/vendor/github.com/go-openapi/runtime/middleware/seam.go b/vendor/github.com/go-openapi/runtime/middleware/seam.go new file mode 100644 index 000000000..390d39355 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/middleware/seam.go @@ -0,0 +1,481 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package middleware + +import ( + "net/http" + "path" + "strings" + + "github.com/go-openapi/runtime/server-middleware/docui" + "github.com/go-openapi/runtime/server-middleware/negotiate" +) + +/////////////////////////////////////////////////////////: +// Seam to the negotiate options introduced in v0.29.5 +/////////////////////////////////////////////////////////: + +// NegotiateOption configures [NegotiateContentType] behaviour. +// +// Deprecated: moved to the [negotiate] package. Use [negotiate.Option] instead. +type NegotiateOption = negotiate.Option + +// NegotiateContentType returns the best offered content type for the +// request's Accept header. +// +// Deprecated: moved to the [negotiate] package. Use [negotiate.ContentType] instead. +func NegotiateContentType(r *http.Request, offers []string, defaultOffer string, opts ...NegotiateOption) string { + return negotiate.ContentType(r, offers, defaultOffer, opts...) +} + +// NegotiateContentEncoding returns the best offered content encoding for +// the request's Accept-Encoding header. +// +// Deprecated: moved to the [negotiate] package. Use [negotiate.ContentEncoding] instead. +func NegotiateContentEncoding(r *http.Request, offers []string) string { + return negotiate.ContentEncoding(r, offers) +} + +// WithIgnoreParameters returns a [NegotiateOption] that strips MIME-type +// parameters from both Accept entries and offers before matching, +// restoring the pre-v0.30 behaviour. +// +// Deprecated: moved to the [negotiate] package. Use [negotiate.WithIgnoreParameters] instead. +func WithIgnoreParameters(ignore bool) NegotiateOption { + return negotiate.WithIgnoreParameters(ignore) +} + +/////////////////////////////////////////////////////////: +// Seam to the UI options +/////////////////////////////////////////////////////////: + +// RapiDoc creates a [http.Handler] to serve a documentation site for a swagger spec. +// +// This allows for altering the spec before starting the [http] listener. +// +// Deprecated: moved to the [docui] package. Use [docui.RapiDoc] instead. +func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler { + return docui.RapiDoc(next, opts.toFuncOptions()...) +} + +// Redoc creates a [http.Handler] to serve a documentation site for a swagger spec. +// +// This allows for altering the spec before starting the [http] listener. +// +// Deprecated: moved to the [docui] package. Use [docui.Redoc] instead. +func Redoc(opts RedocOpts, next http.Handler) http.Handler { + return docui.Redoc(next, opts.toFuncOptions()...) +} + +// SwaggerUI creates a [http.Handler] to serve a documentation site for a swagger spec. +// +// This allows for altering the spec before starting the [http] listener. +// +// Deprecated: moved to the [docui] package. Use [docui.SwaggerUI] instead. +func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler { + return docui.SwaggerUI(next, opts.toFuncOptions()...) +} + +// SwaggerUIOAuth2Callback creates a middleware that serves the OAuth2 callback page used by Swagger UI. +// +// Deprecated: moved to the [docui] package. Use [docui.SwaggerUIOAuth2Callback] instead. +func SwaggerUIOAuth2Callback(opts SwaggerUIOpts, next http.Handler) http.Handler { + return docui.SwaggerUIOAuth2Callback(next, opts.toFuncOptions()...) +} + +/////////////////////////////////////////////////////////: +// Seam to the spec middleware options +/////////////////////////////////////////////////////////: + +// SpecOption can be applied to the [Spec] serving [middleware]. +// +// Deprecated: moved to the [docui] package. Use [docui.SpecOption] instead. +type SpecOption func(*specOptions) + +type specOptions struct { + BasePath string + Path string + Document string +} + +func (o specOptions) fullPath() string { + return path.Join(o.BasePath, o.Path, o.Document) +} + +func specOptionsWithDefaults(basePath string, opts []SpecOption) specOptions { + o := specOptions{ + BasePath: "/", + Path: "", + Document: "swagger.json", + } + + for _, apply := range opts { + apply(&o) + } + if basePath != "" { + o.BasePath = basePath + } + + return o +} + +// Spec creates a [middleware] to serve a swagger spec as a JSON document. +// +// This allows for altering the spec before starting the [http] listener. +// +// The basePath argument indicates the path of the spec document (defaults to "/"). +// Additional [SpecOption] can be used to change the name of the document (defaults to "swagger.json"). +// +// Deprecated: moved to the [docui] package as [docui.ServeSpec]. +func Spec(basePath string, spec []byte, next http.Handler, opts ...SpecOption) http.Handler { + o := specOptionsWithDefaults(basePath, opts) + + return docui.ServeSpec(spec, next, docui.WithSpecPath(o.fullPath())) + +} + +// WithSpecPath sets the path to be joined to the base path of the [ServeSpec] [middleware]. +// +// This is empty by default. +func WithSpecPath(pth string) SpecOption { + return func(o *specOptions) { + o.Path = pth + } +} + +// WithSpecDocument sets the name of the JSON document served as a spec. +// +// By default, this is "swagger.json". +func WithSpecDocument(doc string) SpecOption { + return func(o *specOptions) { + if doc == "" { + return + } + + o.Document = doc + } +} + +// UIOptions defines common options for UI serving middlewares. +// +// Deprecated: use instead the function options provided by [docui]. +type UIOptions struct { + // BasePath for the UI, defaults to: / + BasePath string + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". + Path string + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json + SpecURL string + + // Title for the documentation site, default to: API documentation + Title string + + // Template specifies a custom template to serve the UI + Template string +} + +// toFuncOptions bridges the deprecated options struct with the newer function options in [docui]. +func (o UIOptions) toFuncOptions() []docui.Option { + const structMembers = 5 + opts := make([]docui.Option, 0, structMembers) + + if o.BasePath != "" { + opts = append(opts, docui.WithUIBasePath(o.BasePath)) + } + + if o.Path != "" { + opts = append(opts, docui.WithUIPath(o.Path)) + } + + if o.SpecURL != "" { + opts = append(opts, docui.WithSpecURL(o.SpecURL)) + } + + if o.Title != "" { + opts = append(opts, docui.WithUITitle(o.Title)) + } + + if o.Template != "" { + opts = append(opts, docui.WithUITemplate(o.Template)) + } + + return opts +} + +// RapiDocOpts configures the [RapiDoc] middlewares. +// +// Deprecated: use instead the function options provided by [docui]. +type RapiDocOpts struct { + // BasePath for the UI, defaults to: / + BasePath string + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". + Path string + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json + SpecURL string + + // Title for the documentation site, default to: API documentation + Title string + + // Template specifies a custom template to serve the UI + Template string + + // RapiDocURL points to the js asset that generates the rapidoc site. + // + // Defaults to https://unpkg.com/rapidoc/dist/rapidoc-min.js + RapiDocURL string +} + +func (o RapiDocOpts) toFuncOptions() []docui.Option { + const structMembers = 6 + opts := make([]docui.Option, 0, structMembers) + + if o.BasePath != "" { + opts = append(opts, docui.WithUIBasePath(o.BasePath)) + } + + if o.Path != "" { + opts = append(opts, docui.WithUIPath(o.Path)) + } + + if o.SpecURL != "" { + opts = append(opts, docui.WithSpecURL(o.SpecURL)) + } + + if o.Title != "" { + opts = append(opts, docui.WithUITitle(o.Title)) + } + + if o.Template != "" { + opts = append(opts, docui.WithUITemplate(o.Template)) + } + + if o.RapiDocURL != "" { + opts = append(opts, docui.WithUIAssetsURL(o.RapiDocURL)) + } + + return opts +} + +// RedocOpts configures the [Redoc] middlewares. +// +// Deprecated: use instead the function options provided by [docui]. +type RedocOpts struct { + // BasePath for the UI, defaults to: / + BasePath string + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". + Path string + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json + SpecURL string + + // Title for the documentation site, default to: API documentation + Title string + + // Template specifies a custom template to serve the UI + Template string + + // RedocURL points to the js that generates the redoc site. + // + // Defaults to: https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js + RedocURL string +} + +func (o RedocOpts) toFuncOptions() []docui.Option { + const structMembers = 6 + opts := make([]docui.Option, 0, structMembers) + + if o.BasePath != "" { + opts = append(opts, docui.WithUIBasePath(o.BasePath)) + } + + if o.Path != "" { + opts = append(opts, docui.WithUIPath(o.Path)) + } + + if o.SpecURL != "" { + opts = append(opts, docui.WithSpecURL(o.SpecURL)) + } + + if o.Title != "" { + opts = append(opts, docui.WithUITitle(o.Title)) + } + + if o.Template != "" { + opts = append(opts, docui.WithUITemplate(o.Template)) + } + + if o.RedocURL != "" { + opts = append(opts, docui.WithUIAssetsURL(o.RedocURL)) + } + + return opts +} + +// SwaggerUIOpts configures the [SwaggerUI] [middleware]. +// +// Deprecated: use instead the function options provided by [docui]. +type SwaggerUIOpts struct { + // BasePath for the API, defaults to: / + BasePath string + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". + Path string + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json + SpecURL string + + // Title for the documentation site, default to: API documentation + Title string + + // Template specifies a custom template to serve the UI + Template string + + // OAuthCallbackURL the url called after OAuth2 login + // + // NOTE: in the new [docui.SwaggerUIOptions] type, this field is named `OAuth2CallbackURL`, + // which is more appropriate. + OAuthCallbackURL string + + // The three components needed to embed swagger-ui + + // SwaggerURL points to the js that generates the SwaggerUI site. + // + // Defaults to: https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js + SwaggerURL string + + SwaggerPresetURL string + SwaggerStylesURL string + + Favicon32 string + Favicon16 string +} + +func (o SwaggerUIOpts) toFuncOptions() []docui.Option { + const structMembers = 6 + opts := make([]docui.Option, 0, structMembers) + + if o.BasePath != "" { + opts = append(opts, docui.WithUIBasePath(o.BasePath)) + } + + if o.Path != "" { + opts = append(opts, docui.WithUIPath(o.Path)) + } + + if o.SpecURL != "" { + opts = append(opts, docui.WithSpecURL(o.SpecURL)) + } + + if o.Title != "" { + opts = append(opts, docui.WithUITitle(o.Title)) + } + + if o.Template != "" { + opts = append(opts, docui.WithUITemplate(o.Template)) + } + + if o.SwaggerURL != "" { + opts = append(opts, docui.WithUIAssetsURL(o.SwaggerURL)) + } + + var empty SwaggerUIOpts + if o != empty { + swaggeruiOpts := docui.SwaggerUIOptions{ + OAuth2CallbackURL: o.OAuthCallbackURL, + SwaggerPresetURL: o.SwaggerPresetURL, + SwaggerStylesURL: o.SwaggerStylesURL, + Favicon32: o.Favicon32, + Favicon16: o.Favicon16, + } + opts = append(opts, docui.WithSwaggerUIOptions(swaggeruiOpts)) + } + + return opts +} + +// UIOption can be applied to UI serving [middleware] to alter the default +// behavior. +// +// Deprecated: use instead the function options provided by [docui]. +type UIOption func(*UIOptions) + +// uiOptionsWithDefaults applies the given options on top of an empty +// [UIOptions]. Per-flavor handlers ([SwaggerUI], [Redoc], [RapiDoc]) +// fill in the remaining defaults via [UIOptions.EnsureDefaults] when +// the option struct is used. +func uiOptionsWithDefaults(opts []UIOption) UIOptions { + var o UIOptions + for _, apply := range opts { + apply(&o) + } + + return o +} + +// WithUIBasePath sets the base path from where to serve the UI assets. +// +// Deprecated: use instead the function options provided by [docui]. +func WithUIBasePath(base string) UIOption { + return func(o *UIOptions) { + if !strings.HasPrefix(base, "/") { + base = "/" + base + } + o.BasePath = base + } +} + +// WithUIPath sets the path from where to serve the UI assets (i.e. /{basepath}/{path}. +// +// Deprecated: use instead the function options provided by [docui]. +func WithUIPath(pth string) UIOption { + return func(o *UIOptions) { + o.Path = pth + } +} + +// WithUISpecURL sets the path from where to serve swagger spec document. +// +// This may be specified as a full URL or a path. +// +// By default, this is "/swagger.json". +// +// Deprecated: use instead the function options provided by [docui]. +func WithUISpecURL(specURL string) UIOption { + return func(o *UIOptions) { + o.SpecURL = specURL + } +} + +// WithUITitle sets the title of the UI. +// +// Deprecated: use instead the function options provided by [docui]. +func WithUITitle(title string) UIOption { + return func(o *UIOptions) { + o.Title = title + } +} + +// WithTemplate allows to set a custom template for the UI. +// +// UI [middleware] will panic if the template does not parse or execute properly. +// +// Deprecated: use instead the function options provided by [docui]. +func WithTemplate(tpl string) UIOption { + return func(o *UIOptions) { + o.Template = tpl + } +} diff --git a/vendor/github.com/go-openapi/runtime/middleware/spec.go b/vendor/github.com/go-openapi/runtime/middleware/spec.go deleted file mode 100644 index 0a64a9572..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/spec.go +++ /dev/null @@ -1,91 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers -// SPDX-License-Identifier: Apache-2.0 - -package middleware - -import ( - "net/http" - "path" -) - -const ( - contentTypeHeader = "Content-Type" - applicationJSON = "application/json" -) - -// SpecOption can be applied to the Spec serving [middleware]. -type SpecOption func(*specOptions) - -var defaultSpecOptions = specOptions{ - Path: "", - Document: "swagger.json", -} - -type specOptions struct { - Path string - Document string -} - -func specOptionsWithDefaults(opts []SpecOption) specOptions { - o := defaultSpecOptions - for _, apply := range opts { - apply(&o) - } - - return o -} - -// Spec creates a [middleware] to serve a swagger spec as a JSON document. -// -// This allows for altering the spec before starting the [http] listener. -// -// The basePath argument indicates the path of the spec document (defaults to "/"). -// Additional [SpecOption] can be used to change the name of the document (defaults to "swagger.json"). -func Spec(basePath string, b []byte, next http.Handler, opts ...SpecOption) http.Handler { - if basePath == "" { - basePath = "/" - } - o := specOptionsWithDefaults(opts) - pth := path.Join(basePath, o.Path, o.Document) - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if path.Clean(r.URL.Path) == pth { - rw.Header().Set(contentTypeHeader, applicationJSON) - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write(b) - - return - } - - if next != nil { - next.ServeHTTP(rw, r) - - return - } - - rw.Header().Set(contentTypeHeader, applicationJSON) - rw.WriteHeader(http.StatusNotFound) - }) -} - -// WithSpecPath sets the path to be joined to the base path of the Spec [middleware]. -// -// This is empty by default. -func WithSpecPath(pth string) SpecOption { - return func(o *specOptions) { - o.Path = pth - } -} - -// WithSpecDocument sets the name of the JSON document served as a spec. -// -// By default, this is "swagger.json". -func WithSpecDocument(doc string) SpecOption { - return func(o *specOptions) { - if doc == "" { - return - } - - o.Document = doc - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go b/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go deleted file mode 100644 index 14ed37ced..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go +++ /dev/null @@ -1,178 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers -// SPDX-License-Identifier: Apache-2.0 - -package middleware - -import ( - "bytes" - "fmt" - "html/template" - "net/http" - "path" -) - -// SwaggerUIOpts configures the [SwaggerUI] [middleware]. -type SwaggerUIOpts struct { - // BasePath for the API, defaults to: / - BasePath string - - // Path combines with BasePath to construct the path to the UI, defaults to: "docs". - Path string - - // SpecURL is the URL of the spec document. - // - // Defaults to: /swagger.json - SpecURL string - - // Title for the documentation site, default to: API documentation - Title string - - // Template specifies a custom template to serve the UI - Template string - - // OAuthCallbackURL the url called after OAuth2 login - OAuthCallbackURL string - - // The three components needed to embed swagger-ui - - // SwaggerURL points to the js that generates the SwaggerUI site. - // - // Defaults to: https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js - SwaggerURL string - - SwaggerPresetURL string - SwaggerStylesURL string - - Favicon32 string - Favicon16 string -} - -// EnsureDefaults in case some options are missing. -func (r *SwaggerUIOpts) EnsureDefaults() { - r.ensureDefaults() - - if r.Template == "" { - r.Template = swaggeruiTemplate - } -} - -func (r *SwaggerUIOpts) EnsureDefaultsOauth2() { - r.ensureDefaults() - - if r.Template == "" { - r.Template = swaggerOAuthTemplate - } -} - -func (r *SwaggerUIOpts) ensureDefaults() { - common := toCommonUIOptions(r) - common.EnsureDefaults() - fromCommonToAnyOptions(common, r) - - // swaggerui-specifics - if r.OAuthCallbackURL == "" { - r.OAuthCallbackURL = path.Join(r.BasePath, r.Path, "oauth2-callback") - } - if r.SwaggerURL == "" { - r.SwaggerURL = swaggerLatest - } - if r.SwaggerPresetURL == "" { - r.SwaggerPresetURL = swaggerPresetLatest - } - if r.SwaggerStylesURL == "" { - r.SwaggerStylesURL = swaggerStylesLatest - } - if r.Favicon16 == "" { - r.Favicon16 = swaggerFavicon16Latest - } - if r.Favicon32 == "" { - r.Favicon32 = swaggerFavicon32Latest - } -} - -// SwaggerUI creates a [middleware] to serve a documentation site for a swagger spec. -// -// This allows for altering the spec before starting the [http] listener. -func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler { - opts.EnsureDefaults() - - pth := path.Join(opts.BasePath, opts.Path) - tmpl := template.Must(template.New("swaggerui").Parse(opts.Template)) - assets := bytes.NewBuffer(nil) - if err := tmpl.Execute(assets, opts); err != nil { - panic(fmt.Errorf("cannot execute template: %w", err)) - } - - return serveUI(pth, assets.Bytes(), next) -} - -const ( - swaggerLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js" - swaggerPresetLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui-standalone-preset.js" - swaggerStylesLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui.css" - swaggerFavicon32Latest = "https://unpkg.com/swagger-ui-dist/favicon-32x32.png" - swaggerFavicon16Latest = "https://unpkg.com/swagger-ui-dist/favicon-16x16.png" - swaggeruiTemplate = ` - - - - - {{ .Title }} - - - - - - - - -
- - - - - - -` -) diff --git a/vendor/github.com/go-openapi/runtime/middleware/typeutils.go b/vendor/github.com/go-openapi/runtime/middleware/typeutils.go new file mode 100644 index 000000000..3f7d7976a --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/middleware/typeutils.go @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package middleware + +import "strings" + +// normalizeOffer strips the parameter section (";...") from a media-type +// string. +func normalizeOffer(orig string) string { + // NOTE(maintainers): Despite its name (kept for historical reasons), this helper is + // not about Accept negotiation — it is used to derive the bare type that + // keys the producer/consumer maps registered on a [RoutableAPI]. + // Those maps are looked up by the bare media type, so an entry registered as + // "application/json" satisfies a route that declares "application/json; + // charset=utf-8" and vice-versa. + const maxParts = 2 + + return strings.SplitN(orig, ";", maxParts)[0] +} + +// normalizeOffers is the slice form of [normalizeOffer]. +func normalizeOffers(orig []string) []string { + norm := make([]string, 0, len(orig)) + for _, o := range orig { + norm = append(norm, normalizeOffer(o)) + } + + return norm +} diff --git a/vendor/github.com/go-openapi/runtime/middleware/ui_options.go b/vendor/github.com/go-openapi/runtime/middleware/ui_options.go deleted file mode 100644 index ed255426a..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/ui_options.go +++ /dev/null @@ -1,176 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers -// SPDX-License-Identifier: Apache-2.0 - -package middleware - -import ( - "bytes" - "encoding/gob" - "fmt" - "net/http" - "path" - "strings" -) - -const ( - // constants that are common to all UI-serving middlewares. - defaultDocsPath = "docs" - defaultDocsURL = "/swagger.json" - defaultDocsTitle = "API Documentation" -) - -// uiOptions defines common options for UI serving middlewares. -type uiOptions struct { - // BasePath for the UI, defaults to: / - BasePath string - - // Path combines with BasePath to construct the path to the UI, defaults to: "docs". - Path string - - // SpecURL is the URL of the spec document. - // - // Defaults to: /swagger.json - SpecURL string - - // Title for the documentation site, default to: API documentation - Title string - - // Template specifies a custom template to serve the UI - Template string -} - -// toCommonUIOptions converts any UI option type to retain the common options. -// -// This uses gob encoding/decoding to convert common fields from one struct to another. -func toCommonUIOptions(opts any) uiOptions { - var buf bytes.Buffer - enc := gob.NewEncoder(&buf) - dec := gob.NewDecoder(&buf) - var o uiOptions - err := enc.Encode(opts) - if err != nil { - panic(err) - } - - err = dec.Decode(&o) - if err != nil { - panic(err) - } - - return o -} - -func fromCommonToAnyOptions[T any](source uiOptions, target *T) { - var buf bytes.Buffer - enc := gob.NewEncoder(&buf) - dec := gob.NewDecoder(&buf) - err := enc.Encode(source) - if err != nil { - panic(err) - } - - err = dec.Decode(target) - if err != nil { - panic(err) - } -} - -// UIOption can be applied to UI serving [middleware], such as Context.[APIHandler] or -// Context.[APIHandlerSwaggerUI] to alter the default behavior. -type UIOption func(*uiOptions) - -func uiOptionsWithDefaults(opts []UIOption) uiOptions { - var o uiOptions - for _, apply := range opts { - apply(&o) - } - - return o -} - -// WithUIBasePath sets the base path from where to serve the UI assets. -// -// By default, Context [middleware] sets this value to the API base path. -func WithUIBasePath(base string) UIOption { - return func(o *uiOptions) { - if !strings.HasPrefix(base, "/") { - base = "/" + base - } - o.BasePath = base - } -} - -// WithUIPath sets the path from where to serve the UI assets (i.e. /{basepath}/{path}. -func WithUIPath(pth string) UIOption { - return func(o *uiOptions) { - o.Path = pth - } -} - -// WithUISpecURL sets the path from where to serve swagger spec document. -// -// This may be specified as a full URL or a path. -// -// By default, this is "/swagger.json". -func WithUISpecURL(specURL string) UIOption { - return func(o *uiOptions) { - o.SpecURL = specURL - } -} - -// WithUITitle sets the title of the UI. -// -// By default, Context [middleware] sets this value to the title found in the API spec. -func WithUITitle(title string) UIOption { - return func(o *uiOptions) { - o.Title = title - } -} - -// WithTemplate allows to set a custom template for the UI. -// -// UI [middleware] will panic if the template does not parse or execute properly. -func WithTemplate(tpl string) UIOption { - return func(o *uiOptions) { - o.Template = tpl - } -} - -// EnsureDefaults in case some options are missing. -func (r *uiOptions) EnsureDefaults() { - if r.BasePath == "" { - r.BasePath = "/" - } - if r.Path == "" { - r.Path = defaultDocsPath - } - if r.SpecURL == "" { - r.SpecURL = defaultDocsURL - } - if r.Title == "" { - r.Title = defaultDocsTitle - } -} - -// serveUI creates a middleware that serves a templated asset as text/html. -func serveUI(pth string, assets []byte, next http.Handler) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if path.Clean(r.URL.Path) == pth { - rw.Header().Set(contentTypeHeader, "text/html; charset=utf-8") - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write(assets) - - return - } - - if next != nil { - next.ServeHTTP(rw, r) - - return - } - - rw.Header().Set(contentTypeHeader, "text/plain") - rw.WriteHeader(http.StatusNotFound) - _, _ = fmt.Fprintf(rw, "%q not found", pth) - }) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation.go b/vendor/github.com/go-openapi/runtime/middleware/validation.go index 8dca105be..c583e191d 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/validation.go +++ b/vendor/github.com/go-openapi/runtime/middleware/validation.go @@ -4,12 +4,13 @@ package middleware import ( - "mime" "net/http" "strings" "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/server-middleware/mediatype" ) type validation struct { @@ -20,61 +21,30 @@ type validation struct { bound map[string]any } -// ContentType validates the content type of a request. +// validateContentType maps [mediatype.MatchFirst] to the runtime's +// validation errors: +// +// - actual fails to parse → HTTP 400 ([errors.NewParseError]). +// - actual is well-formed but +// no allowed entry accepts it → HTTP 415 ([errors.InvalidContentType]). // -// An allowed entry may carry MIME type parameters (e.g. "text/plain;charset=utf-8"). -// In that case every parameter the client sends must be present on the allowed entry -// with the same value; the allowed entry may carry additional parameters the client -// omits. An allowed entry without parameters accepts any client parameters. -// "*/*" and "type/*" wildcards are matched on the bare type only. -func validateContentType(allowed []string, actual string) error { +// In the standard runtime flow, malformed Content-Type headers are +// already caught upstream by [runtime.ContentType] (which itself returns +// a 400 [errors.ParseError]). This function therefore only sees the +// malformed case when invoked directly by callers that have bypassed +// that step. +func validateContentType(allowed []string, actual string, opts ...mediatype.MatchOption) error { if len(allowed) == 0 { return nil } - actualType, actualParams, err := mime.ParseMediaType(actual) - if err != nil { - return errors.InvalidContentType(actual, allowed) - } - typeWildcard := "" - if slash := strings.IndexByte(actualType, '/'); slash > 0 { - typeWildcard = actualType[:slash] + "/*" - } - for _, a := range allowed { - if strings.EqualFold(a, "*/*") { - return nil - } - if typeWildcard != "" && strings.EqualFold(a, typeWildcard) { - return nil - } - if mediaTypeMatches(a, actualType, actualParams) { - return nil - } + _, ok, err := mediatype.MatchFirst(allowed, actual, opts...) + if ok { + return nil } - return errors.InvalidContentType(actual, allowed) -} - -// mediaTypeMatches reports whether the actual client media type satisfies the -// server-side allowed media type, with parameter-aware comparison. -func mediaTypeMatches(allowed, actualType string, actualParams map[string]string) bool { - allowedType, allowedParams, err := mime.ParseMediaType(allowed) if err != nil { - // Fall back to a case-insensitive bare match if the configured value - // can't be parsed as a media type. - return strings.EqualFold(allowed, actualType) - } - if !strings.EqualFold(allowedType, actualType) { - return false + return errors.NewParseError(runtime.HeaderContentType, "header", actual, err) } - if len(allowedParams) == 0 { - return true - } - for k, v := range actualParams { - sv, ok := allowedParams[k] - if !ok || !strings.EqualFold(sv, v) { - return false - } - } - return true + return errors.InvalidContentType(actual, allowed) } func validateRequest(ctx *Context, request *http.Request, route *MatchedRoute) *validation { @@ -126,12 +96,12 @@ func (v *validation) contentType() { if len(v.result) == 0 { v.debugLogf("validating content type for %q against [%s]", ct, strings.Join(v.route.Consumes, ", ")) - if err := validateContentType(v.route.Consumes, ct); err != nil { + if err := validateContentType(v.route.Consumes, ct, v.context.matchOpts()...); err != nil { v.result = append(v.result, err) } } if ct != "" && v.route.Consumer == nil { - cons, ok := v.route.Consumers[ct] + cons, ok := mediatype.Lookup(v.route.Consumers, ct, v.context.matchOpts()...) if !ok { v.result = append(v.result, errors.New(http.StatusInternalServerError, "no consumer registered for %s", ct)) } else { @@ -142,7 +112,7 @@ func (v *validation) contentType() { } func (v *validation) responseFormat() { - // if the route provides values for Produces and no format could be identify then return an error. + // if the route provides values for Produces and no format could be identified then return an error. // if the route does not specify values for Produces then treat request as valid since the API designer // choose not to specify the format for responses. if str, rCtx := v.context.ResponseFormat(v.request, v.route.Produces); str == "" && len(v.route.Produces) > 0 { diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/LICENSE b/vendor/github.com/go-openapi/runtime/server-middleware/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/docui/doc.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/doc.go new file mode 100644 index 000000000..809296d5c --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/doc.go @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package docui provides standalone HTTP middlewares that serve OpenAPI +// documentation UIs (Swagger UI, ReDoc, RapiDoc) and the spec document +// itself. +// +// The package is stdlib-only and has no transitive dependency on any +// OpenAPI spec, loading or validation library, so it may be imported by +// any net/http application that simply wants to mount a documentation +// site. +package docui diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/docui/options.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/options.go new file mode 100644 index 000000000..c9e45f779 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/options.go @@ -0,0 +1,253 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package docui + +import ( + "net/http" + "net/url" + "strings" +) + +const ( + // constants that are common to all UI-serving middlewares. + defaultDocsPath = "docs" + defaultDocsURL = "/swagger.json" + defaultDocsTitle = "API Documentation" + + contentTypeHeader = "Content-Type" + applicationJSON = "application/json" +) + +// UIMiddleware is a function returning a http middleware which accepts UI [Option]. +type UIMiddleware func(...Option) func(http.Handler) http.Handler + +// Option to tune your swagger documentation UI middleware. +// +// Options may be combined to alter the route at which the UI asset is served, +// the URL of the spec document, the source URL of the UI asset and the title of the UI page. +// +// The embedded js scriptlet served may be modified using [WithUITemplate]. +type Option func(*options) + +// SpecOption can be applied to the [ServeSpec] middleware. +type SpecOption func(*specOptions) + +// SwaggerUIOptions define a group of extra options specific to the SwaggerUI component. +type SwaggerUIOptions struct { + // OAuth2CallbackURL sets the URL called after OAuth2 login + OAuth2CallbackURL string + + // Defines the URL of the swagger UI assets with presets. + // + // Default: https://unpkg.com/swagger-ui-dist/swagger-ui-standalone-preset.js + SwaggerPresetURL string + + // Defines style sheet URL. + // + // Default: https://unpkg.com/swagger-ui-dist/swagger-ui.css + SwaggerStylesURL string + + // Define the favicons URLs. + // + // Defaults: + // + // - 16x16: https://unpkg.com/swagger-ui-dist/favicon-16x16.png + // - 32x32: https://unpkg.com/swagger-ui-dist/favicon-32x32.png + Favicon32 string + Favicon16 string +} + +func (o *SwaggerUIOptions) applySwaggerUIDefaults() { + if o.SwaggerPresetURL == "" { + o.SwaggerPresetURL = swaggerPresetLatest + } + if o.SwaggerStylesURL == "" { + o.SwaggerStylesURL = swaggerStylesLatest + } + if o.Favicon16 == "" || o.Favicon32 == "" { + o.Favicon16 = swaggerFavicon16Latest + o.Favicon32 = swaggerFavicon32Latest + } +} + +type ( + options struct { + SwaggerUIOptions + + // BasePath for the UI, defaults to: / + BasePath string + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". + Path string + + // SpecURL is the URL of the spec document. + SpecURL string + + // Title for the documentation site, default to: API documentation + Title string + + // Template specifies a custom template to serve the UI + Template string + + // AssetsURL points to the js asset that generates the documentation page. + AssetsURL string + } + + specOptions struct { + Path string + Document string + } +) + +//////////////////////////////////////////////////////////// +// Common UI options +//////////////////////////////////////////////////////////// + +// WithUIBasePath sets the base path from where to serve the UI assets. +// +// Default: "/" +func WithUIBasePath(base string) Option { + return func(o *options) { + if !strings.HasPrefix(base, "/") { + base = "/" + base + } + o.BasePath = base + } +} + +// WithUIPath sets the path from where to serve the UI assets (i.e. /{basepath}/{path}). +// +// Default: "docs" +func WithUIPath(pth string) Option { + return func(o *options) { + o.Path = pth + } +} + +// WithUITitle sets the title of the UI. +// +// Default: "API documentation" +func WithUITitle(title string) Option { + return func(o *options) { + o.Title = title + } +} + +// WithUIAssetsURL sets the URL from where to fetch the js assets. +// +// Defaults: +// +// - for Redoc: https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js +// - for RapiDoc, this defaults to: https://unpkg.com/rapidoc/dist/rapidoc-min.js +// - for SwaggerUI: https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js +func WithUIAssetsURL(assets string) Option { + return func(o *options) { + o.AssetsURL = assets + } +} + +// WithUITemplate allows to set a custom template for the UI. +// +// This allows the caller to fully customize the rendered UI, using the advanced options +// provided by any UI. +// +// The UI [middleware] will panic if the template does not parse or execute properly. +// +// Reference documentations to customize your js scriptlet: +// +// - for Redoc: https://github.com/Redocly/redoc/blob/main/docs/deployment/html.md +// - for RapiDoc: https://github.com/rapi-doc/RapiDoc +// - for SwaggerUI: https://github.com/swagger-api/swagger-ui +func WithUITemplate[StringOrBytes ~string | ~[]byte](tpl StringOrBytes) Option { + return func(o *options) { + o.Template = string(tpl) + } +} + +// WithSpecURL sets the URL of the spec document. +// +// Defaults to: /swagger.json +func WithSpecURL(u string) Option { + return func(o *options) { + o.SpecURL = u + } +} + +//////////////////////////////////////////////////////////// +// SwaggerUI UI options +//////////////////////////////////////////////////////////// + +func WithSwaggerUIOptions(opts SwaggerUIOptions) Option { + return func(o *options) { + o.SwaggerUIOptions = opts + } +} + +//////////////////////////////////////////////////////////// +// Spec options +//////////////////////////////////////////////////////////// + +// WithSpecPath sets the path of the spec document. +// +// This is "/swagger.json" by default. +func WithSpecPath(pth string) SpecOption { + return func(o *specOptions) { + if pth == "" { + return + } + + o.Path = pth + } +} + +// WithSpecPathFromOptions reuses the same SpecPath as the one specified in +// a set of UI [Option] (extract the path from the URL provided by [WithSpecURL]). +func WithSpecPathFromOptions(opts ...Option) SpecOption { + return func(o *specOptions) { + uiOpts := optionsWithDefaults(opts) + + // If the spec URL is provided, there is a non-default path to serve the spec. + // + // This makes sure that the UI middleware is aligned with the Spec middleware. + u, _ := url.Parse(uiOpts.SpecURL) + + if u.Path == "" { + return + } + + o.Path = u.Path + } +} + +func optionsWithDefaults(opts []Option, prepend ...Option) options { + o := options{ + BasePath: "/", + Path: defaultDocsPath, + SpecURL: defaultDocsURL, + Title: defaultDocsTitle, + } + + prepend = append(prepend, opts...) + for _, apply := range prepend { + apply(&o) + } + + return o +} + +func specOptionsWithDefaults(opts []SpecOption) specOptions { + o := specOptions{ + Path: defaultDocsURL, + } + + for _, apply := range opts { + apply(&o) + } + + if !strings.HasPrefix(o.Path, "/") { + o.Path = "/" + o.Path + } + + return o +} diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/docui/rapidoc.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/rapidoc.go new file mode 100644 index 000000000..c050331b4 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/rapidoc.go @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package docui + +import ( + "bytes" + "fmt" + "html/template" + "net/http" + "path" +) + +// UseRapiDoc creates a middleware to serve a documentation site for a swagger spec using [RapidDoc]. +// +// [RapiDoc]: https://github.com/rapi-doc/RapiDoc +func UseRapiDoc(opts ...Option) func(next http.Handler) http.Handler { + pth, assets := rapiDocSetup(opts) + return func(next http.Handler) http.Handler { + return serveUI(pth, assets, next) + } +} + +// RapiDoc creates a [http.Handler] to serve a documentation site for a swagger spec using [RapidDoc]. +// +// By default, the UI is served at route "/docs" +// +// This allows for altering the spec before starting the [http] listener. +// +// [RapiDoc]: https://github.com/rapi-doc/RapiDoc +func RapiDoc(next http.Handler, opts ...Option) http.Handler { + pth, assets := rapiDocSetup(opts) + + return serveUI(pth, assets, next) +} + +func rapiDocSetup(opts []Option) (pth string, assets []byte) { + o := optionsWithDefaults(opts, + // defaults for rapiDoc + WithUITemplate(rapidocTemplate), + WithUIAssetsURL(rapidocLatest), + ) + pth = path.Join(o.BasePath, o.Path) + tmpl := template.Must(template.New("rapidoc").Parse(o.Template)) + buf := bytes.NewBuffer(nil) + if err := tmpl.Execute(buf, o); err != nil { + panic(fmt.Errorf("cannot execute template: %w", err)) + } + + return pth, buf.Bytes() +} + +const ( + rapidocLatest = "https://unpkg.com/rapidoc/dist/rapidoc-min.js" + rapidocTemplate = ` + + + {{ .Title }} + + + + + + + +` +) diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/docui/redoc.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/redoc.go new file mode 100644 index 000000000..31054a247 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/redoc.go @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package docui + +import ( + "bytes" + "fmt" + "html/template" + "net/http" + "path" +) + +// UseRedoc creates a middleware to serve a documentation site for a swagger spec using [Redoc]. +// +// [Redoc]: https://redocly.com/docs/redoc +func UseRedoc(opts ...Option) func(next http.Handler) http.Handler { + pth, assets := redocSetup(opts) + + return func(next http.Handler) http.Handler { + return serveUI(pth, assets, next) + } +} + +// Redoc creates a [http.Handler] to serve a documentation site for a swagger spec using [Redoc]. +// +// By default, the UI is served at route "/docs" +// +// This allows for altering the spec before starting the [http] listener. +// +// [Redoc]: https://redocly.com/docs/redoc +func Redoc(next http.Handler, opts ...Option) http.Handler { + pth, assets := redocSetup(opts) + + return serveUI(pth, assets, next) +} + +func redocSetup(opts []Option) (pth string, assets []byte) { + o := optionsWithDefaults(opts, + // defaults for redoc + WithUITemplate(redocTemplate), + WithUIAssetsURL(redocLatest), + ) + + pth = path.Join(o.BasePath, o.Path) + tmpl := template.Must(template.New("redoc").Parse(o.Template)) + buf := bytes.NewBuffer(nil) + if err := tmpl.Execute(buf, o); err != nil { + panic(fmt.Errorf("cannot execute template: %w", err)) + } + + return pth, buf.Bytes() +} + +const ( + redocLatest = "https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js" // "https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js" + redocTemplate = ` + + + {{ .Title }} + + + + + + + + + + + + + +` +) diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/docui/render.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/render.go new file mode 100644 index 000000000..1fb744fd0 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/render.go @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package docui + +import ( + "fmt" + "net/http" + "path" +) + +// serveUI creates a [http.Handler] that serves a templated asset as text/html. +func serveUI(pth string, assets []byte, next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if path.Clean(r.URL.Path) == pth { + rw.Header().Set(contentTypeHeader, "text/html; charset=utf-8") + rw.WriteHeader(http.StatusOK) + _, _ = rw.Write(assets) + + return + } + + if next != nil { + next.ServeHTTP(rw, r) + + return + } + + rw.Header().Set(contentTypeHeader, "text/plain") + rw.WriteHeader(http.StatusNotFound) + _, _ = fmt.Fprintf(rw, "%q not found", pth) + }) +} diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/docui/spec.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/spec.go new file mode 100644 index 000000000..59780199d --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/spec.go @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package docui + +import ( + "net/http" + "path" +) + +// UseSpec creates a middleware to serve a swagger spec as a JSON document. +func UseSpec(spec []byte, opts ...SpecOption) func(next http.Handler) http.Handler { + o := specOptionsWithDefaults(opts) + + return func(next http.Handler) http.Handler { + return handleSpec(o.Path, spec, next) + } +} + +// ServeSpec creates a [http.Handler] to serve a swagger spec as a JSON document. +// +// This allows for altering the spec before starting the [http] listener. +// +// Additional [SpecOption] can be used to change the path and the name of the document (defaults to "/swagger.json"). +func ServeSpec(spec []byte, next http.Handler, opts ...SpecOption) http.Handler { + o := specOptionsWithDefaults(opts) + + return handleSpec(o.Path, spec, next) +} + +func handleSpec(pth string, spec []byte, next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if path.Clean(r.URL.Path) == pth { + rw.Header().Set(contentTypeHeader, applicationJSON) + rw.WriteHeader(http.StatusOK) + _, _ = rw.Write(spec) + + return + } + + if next != nil { + next.ServeHTTP(rw, r) + + return + } + + rw.Header().Set(contentTypeHeader, applicationJSON) + rw.WriteHeader(http.StatusNotFound) + }) +} diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/docui/swaggerui.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/swaggerui.go new file mode 100644 index 000000000..db0aa05e6 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/swaggerui.go @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package docui + +import ( + "bytes" + "fmt" + "html/template" + "net/http" + "path" +) + +// UseSwaggerUI creates a middleware to serve a documentation site for a swagger spec using [SwaggerUI]. +// +// [SwaggerUI]: https://swagger.io/tools/swagger-ui +func UseSwaggerUI(opts ...Option) func(next http.Handler) http.Handler { + pth, assets := swaggeruiSetup(opts) + + return func(next http.Handler) http.Handler { + return serveUI(pth, assets, next) + } +} + +// SwaggerUI creates a [http.Handler] to serve a documentation site for a swagger spec using [SwaggerUI]. +// +// By default, the UI is served at route "/docs" +// +// This allows for altering the spec before starting the [http] listener. +// +// [SwaggerUI]: https://swagger.io/tools/swagger-ui +func SwaggerUI(next http.Handler, opts ...Option) http.Handler { + pth, assets := swaggeruiSetup(opts) + + return serveUI(pth, assets, next) +} + +func swaggeruiSetup(opts []Option) (pth string, assets []byte) { + o := optionsWithDefaults(opts, + // defaults for SwaggerUI + WithUITemplate(swaggeruiTemplate), + WithUIAssetsURL(swaggerLatest), + ) + o.applySwaggerUIDefaults() + if o.OAuth2CallbackURL == "" { + o.OAuth2CallbackURL = path.Join(o.BasePath, o.Path, "oauth2-callback") + } + + pth = path.Join(o.BasePath, o.Path) + tmpl := template.Must(template.New("swaggerui").Parse(o.Template)) + buf := bytes.NewBuffer(nil) + if err := tmpl.Execute(buf, o); err != nil { + panic(fmt.Errorf("cannot execute template: %w", err)) + } + + return pth, buf.Bytes() +} + +const ( + swaggerLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js" + swaggerPresetLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui-standalone-preset.js" + swaggerStylesLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui.css" + swaggerFavicon32Latest = "https://unpkg.com/swagger-ui-dist/favicon-32x32.png" + swaggerFavicon16Latest = "https://unpkg.com/swagger-ui-dist/favicon-16x16.png" + swaggeruiTemplate = ` + + + + + {{ .Title }} + + {{- if .SwaggerStylesURL }} + + {{- end }} + {{- if .Favicon32 }} + + {{- end }} + {{- if .Favicon16 }} + + {{- end }} + + + + +
+ + + {{- if .SwaggerPresetURL }} + + {{- end }} + + + +` +) diff --git a/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go b/vendor/github.com/go-openapi/runtime/server-middleware/docui/swaggerui_oauth2.go similarity index 70% rename from vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go rename to vendor/github.com/go-openapi/runtime/server-middleware/docui/swaggerui_oauth2.go index 879bdbaad..a38e408f1 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go +++ b/vendor/github.com/go-openapi/runtime/server-middleware/docui/swaggerui_oauth2.go @@ -1,30 +1,56 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 -package middleware +package docui import ( "bytes" "fmt" "net/http" + "path" "text/template" ) -func SwaggerUIOAuth2Callback(opts SwaggerUIOpts, next http.Handler) http.Handler { - opts.EnsureDefaultsOauth2() +// UseSwaggerUIOAuth2Callback creates a middleware that serves a callback URL to complete +// a OAuth2 token handshake. +func UseSwaggerUIOAuth2Callback(opts ...Option) func(next http.Handler) http.Handler { + pth, assets := swaggeruiOAuth2Setup(opts) - pth := opts.OAuthCallbackURL - tmpl := template.Must(template.New("swaggeroauth").Parse(opts.Template)) - assets := bytes.NewBuffer(nil) - if err := tmpl.Execute(assets, opts); err != nil { + return func(next http.Handler) http.Handler { + return serveUI(pth, assets, next) + } +} + +// SwaggerUIOAuth2Callback creates a [http.Handler] that serves a callback URL to complete +// a OAuth2 token handshake. +func SwaggerUIOAuth2Callback(next http.Handler, opts ...Option) http.Handler { + pth, assets := swaggeruiOAuth2Setup(opts) + + return serveUI(pth, assets, next) +} + +func swaggeruiOAuth2Setup(opts []Option) (pth string, assets []byte) { + o := optionsWithDefaults(opts, + // defaults for SwaggerUI OAuth2 callback endpoint + WithUITemplate(swaggerOAuth2Template), + WithUIAssetsURL(swaggerLatest), + ) + o.applySwaggerUIDefaults() + if o.OAuth2CallbackURL == "" { + o.OAuth2CallbackURL = path.Join(o.BasePath, o.Path, "oauth2-callback") + } + + pth = o.OAuth2CallbackURL + tmpl := template.Must(template.New("swaggeroauth2").Parse(o.Template)) + buf := bytes.NewBuffer(nil) + if err := tmpl.Execute(buf, o); err != nil { panic(fmt.Errorf("cannot execute template: %w", err)) } - return serveUI(pth, assets.Bytes(), next) + return pth, buf.Bytes() } -const ( - swaggerOAuthTemplate = ` +const swaggerOAuth2Template = ` @@ -105,4 +131,3 @@ const ( ` -) diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/doc.go b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/doc.go new file mode 100644 index 000000000..6f8aa3135 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/doc.go @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package mediatype provides a typed value for media types +// defined by RFC 7231 and RFC 2045. +// +// The matching/selection primitives used by both server-side +// validation and Accept-header negotiation. +// +// The package is stdlib-only. +// +// # The matching rule +// +// [MediaType.Matches] is asymmetric. The receiver acts as the "bound" +// (an allowed entry on the server side, or a candidate offer when +// matching against an Accept entry); the argument is the constraint +// (the actual incoming request, or the Accept entry being satisfied). +// +// - bare type/subtype must agree, with wildcard handling on either +// side ("*/*" matches anything; "type/*" matches any subtype); +// - if the receiver carries no parameters, any constraint is +// accepted regardless of its parameters; +// - otherwise every (key,value) pair on the constraint must be +// present on the receiver, with case-insensitive value +// comparison. The receiver may carry additional parameters the +// constraint does not list. +// +// q-values are NOT considered by [MediaType.Matches] — they are the +// negotiator's concern, handled inside [Set.BestMatch]. +package mediatype diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/lookup.go b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/lookup.go new file mode 100644 index 000000000..598b60aca --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/lookup.go @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mediatype + +// Lookup finds the entry in m matching mediaType, with alias-aware +// fallback. It is the canonical seam for codec-map lookups in both +// the client and server runtimes — placing the fallback policy here +// keeps alias definitions (and any future lookup tolerances) in one +// place. +// +// Lookup tries the following, in order, returning the first hit: +// +// 1. mediaType verbatim (fast path for callers that already pass a +// canonical, parameter-free string and store map keys in the +// same form). +// 2. An alias-aware walk against the parsed "type/subtype" form: +// a direct map hit on the parsed key, on its alias canonical +// if any, and finally an O(len(m)) scan returning any map +// entry whose key alias-canonicalizes to the same target. +// Catches both "map keyed by canonical, query uses alias" and +// "map keyed by one alias, query uses another alias of the +// same canonical". +// 3. When [AllowSuffix] is passed in opts: the same alias-aware +// walk against the RFC 6839 structured-syntax suffix base. +// Catches the "spec/traffic divergence" case (request for +// application/vnd.api+json finds a JSON consumer registered +// under application/json). Query-side suffix fold only — no +// map-side suffix folding. +// +// Lookup does NOT fall back to "*/*". Callers that want wildcard +// behavior (the historical resolveConsumer pattern in the client +// runtime) chain that themselves after a Lookup miss — keeping +// wildcard semantics explicit at each call site. +// +// Map keys are expected in canonical "type/subtype" form (no +// parameters). The runtime's default Consumers / Producers maps +// follow this convention. +// +// Returns (zero, false) when: +// +// - m is empty; +// - mediaType fails to parse and is not present verbatim; +// - none of the active steps hits. +// +// The malformed-vs-not-found distinction is intentionally elided: +// codec-lookup callers treat both as the same "no codec" error path. +func Lookup[T any](m map[string]T, mediaType string, opts ...MatchOption) (T, bool) { + var zero T + if len(m) == 0 { + return zero, false + } + o := applyMatchOptions(opts) + // Fast path: raw key (preserves any caller behaviour that stored + // non-canonical strings as map keys, and skips parsing in the + // common already-canonical case). + if v, ok := m[mediaType]; ok { + return v, true + } + mt, err := Parse(mediaType) + if err != nil { + return zero, false + } + key := mt.Type + "/" + mt.Subtype + if v, ok := findByCanonical(m, key); ok { + return v, true + } + if o.allowSuffix && mt.Suffix != "" { + base := mt.Base() + if baseKey := base.Type + "/" + base.Subtype; baseKey != key { + if v, ok := findByCanonical(m, baseKey); ok { + return v, true + } + } + } + return zero, false +} + +// findByCanonical returns the first entry in m whose key +// alias-canonicalizes to the same value as target. +// +// Tries direct hits before the O(len(m)) walk: +// +// 1. m[target] — map keyed by the same string. +// 2. m[aliases[target]] — map keyed by the canonical when target +// is an alias. +// 3. Walk m: return any entry where canonical(k) == canonical(target). +// Catches the "map keyed by an alias different from the query +// side" case (e.g. registered under text/yaml, queried as +// application/x-yaml — both canonicalize to application/yaml). +// +// Map size is single-digit for the runtime's codec maps, so the +// walk is negligible. +func findByCanonical[T any](m map[string]T, target string) (T, bool) { + if v, ok := m[target]; ok { + return v, true + } + canonTarget := target + if canon, ok := aliases[target]; ok { + canonTarget = canon + if v, ok := m[canonTarget]; ok { + return v, true + } + } + for k, v := range m { + kCanon := k + if c, ok := aliases[k]; ok { + kCanon = c + } + if kCanon == canonTarget { + return v, true + } + } + var zero T + return zero, false +} diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/match.go b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/match.go new file mode 100644 index 000000000..6a16d0b6f --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/match.go @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mediatype + +// MatchFirst reports whether actual matches any entry in allowed, +// using [MediaType.Match] — the param-aware RFC 7231 rule plus the +// alias bridge from the package-internal alias table. +// +// The scan is multi-pass and tier-ordered: the first pass returns +// the first allowed entry that matches under [MatchExact] (RFC 7231 +// semantics); the second pass looks for a [MatchAlias] match; when +// [AllowSuffix] is in opts a third pass looks for a [MatchSuffix] +// match. This preserves the "stronger tier wins" ordering from +// [Set.BestMatch] while keeping the "first match wins" semantics +// within each tier. +// +// Return values: +// +// - (matched, true, nil) — the first allowed entry that +// matches, with exact matches preferred over alias matches. +// - (zero, false, nil) — actual is well-formed but no +// allowed entry accepts it. Maps to an HTTP 415 outcome. +// - (zero, false, err) — actual fails to parse. err +// wraps [ErrMalformed], so callers can use [errors.Is] to +// distinguish this case. Maps to an HTTP 400 outcome. +// +// Allowed entries that themselves fail to parse are skipped (they +// cannot match any well-formed actual), and no error is surfaced +// for them. +// +// An empty allowed list returns (zero, false, nil). MatchFirst is +// the primitive; callers decide what no-constraints means in their +// context. +func MatchFirst(allowed []string, actual string, opts ...MatchOption) (MediaType, bool, error) { + if len(allowed) == 0 { + return MediaType{}, false, nil + } + actualMT, err := Parse(actual) + if err != nil { + return MediaType{}, false, err + } + o := applyMatchOptions(opts) + // Tier-ordered passes over the allowed list. The list is + // typically short (an operation's Consumes set), so re-parsing + // each entry on every pass is cheaper than caching parses across + // passes. + tiers := []MatchKind{MatchExact, MatchAlias} + if o.allowSuffix { + tiers = append(tiers, MatchSuffix) + } + for _, want := range tiers { + for _, a := range allowed { + allowedMT, perr := Parse(a) + if perr != nil { + continue + } + if allowedMT.Match(actualMT) == want { + return allowedMT, true, nil + } + } + } + + return MediaType{}, false, nil +} diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/mediatype.go b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/mediatype.go new file mode 100644 index 000000000..2138b8266 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/mediatype.go @@ -0,0 +1,379 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mediatype + +import ( + "fmt" + "mime" + "strconv" + "strings" +) + +const wildcard = "*" + +// Internal constants for the suffixBase table and any future +// in-package references to the well-known base media types. +const ( + typeApplication = "application" + subtypeJSON = "json" + subtypeXML = "xml" + subtypeYAML = "yaml" + + mtYAML = typeApplication + "/" + subtypeYAML +) + +// Specificity scores returned by [MediaType.Specificity], ordered from +// least to most specific. +const ( + SpecificityAny = iota // "*/*" + SpecificityType // "type/*" + SpecificityExact // "type/subtype" (no params) + SpecificityExactWithParams // "type/subtype;k=v" +) + +// MatchKind classifies the strength of a match between two media +// types. Larger values represent stronger matches and win in +// negotiation tie-breaks. +// +// MatchExact covers direct subtype or wildcard agreement under RFC +// 7231 rules; MatchAlias is returned when the strict comparison +// fails but the two values agree after canonicalization through the +// internal alias table (see [MediaType.Canonical]); MatchSuffix is +// returned only when both alias and exact comparisons fail but the +// two values agree after folding the RFC 6839 structured-syntax +// suffix (see [MediaType.Base]). +// +// MatchSuffix matches are off by default at the negotiation / +// lookup callers — they count only when [AllowSuffix] is passed to +// [Set.BestMatch], [MatchFirst], or [Lookup]. The opt-in is the +// single user-visible knob; [MediaType.Match] itself always returns +// the strongest tier that succeeds. +type MatchKind int + +// MatchKind values. Returned by [MediaType.Match]. +const ( + MatchNone MatchKind = iota // no match + MatchSuffix // matched via the RFC 6839 suffix base + MatchAlias // matched via the alias table + MatchExact // matched directly (RFC 7231 semantics) +) + +// MatchOption configures the matching tolerances used by +// [Set.BestMatch], [MatchFirst], and [Lookup]. The zero behaviour +// is strict: only [MatchAlias] and [MatchExact] count. +type MatchOption func(*matchOptions) + +type matchOptions struct { + allowSuffix bool +} + +func applyMatchOptions(opts []MatchOption) matchOptions { + var o matchOptions + for _, opt := range opts { + opt(&o) + } + return o +} + +// AllowSuffix returns a [MatchOption] that lets the caller count +// [MatchSuffix] results as valid matches. Use this to opt into +// RFC 6839 structured-syntax suffix tolerance for situations where +// the client/server traffic does not strictly abide by the spec +// (typical example: server returning application/problem+json +// against operations that only declare application/json in +// produces). +func AllowSuffix() MatchOption { + return func(o *matchOptions) { + o.allowSuffix = true + } +} + +type mediaTypeError string + +func (e mediaTypeError) Error() string { + return string(e) +} + +// ErrMalformed is the sentinel returned (wrapped) by [Parse] when its input +// cannot be parsed as an RFC 7231 media type. +// +// Callers can test for it with [errors.Is] to distinguish a client-side +// malformed Content-Type header (an HTTP 400 outcome) from a well-formed +// value that simply matches no allowed entry (an HTTP 415 outcome). +const ErrMalformed mediaTypeError = "mediatype: malformed" + +// MediaType is a parsed RFC 7231 media type with optional parameters and +// an optional q-value (used by Accept negotiation). +// +// Type, Subtype and the keys of Params are lowercased. Parameter values +// are preserved verbatim; comparisons are case-insensitive (matching the +// pre-v0.30 behaviour and the common convention for charset, version, etc.). +// +// Suffix exposes the RFC 6839 structured syntax suffix (the token after +// the final '+' in Subtype) as a parallel hint. Subtype itself retains +// the full wire value, so existing callers comparing Subtype against a +// string see no change. +type MediaType struct { + Type string + Subtype string + Suffix string + Params map[string]string + Q float64 +} + +// suffixBase maps a known RFC 6839 / RFC 9512 structured syntax +// suffix (without the leading '+', lowercased) to its base media +// type. It is the authoritative table consulted by [MediaType.Base]. +// +// The table is intentionally small: only suffixes whose base type +// has a codec in the default runtime maps are listed. CBOR, zip, +// BER, DER, FastInfoset and WBXML are registered by IANA but have +// no default codec in this runtime; adding them is gated on having +// something to do with them. +// +// Package-internal by design: the external API is [MediaType.Base]. +// If users ever need to extend the table, a Register-style function +// is the right answer, not an exported mutable map. +var suffixBase = map[string]MediaType{ + subtypeJSON: {Type: typeApplication, Subtype: subtypeJSON}, + subtypeXML: {Type: typeApplication, Subtype: subtypeXML}, + subtypeYAML: {Type: typeApplication, Subtype: subtypeYAML}, +} + +// aliases maps a deprecated or legacy media-type name to its +// canonical registered equivalent. Keys are the lowercased +// "type/subtype" form with no parameters; values are the canonical +// "type/subtype" form, also without parameters. +// +// Entries are limited to media types whose authoritative RFC +// explicitly names the alias. The seed entries cite RFC 9512 §2.1, +// which enumerates "Deprecated alias names for this type: +// application/x-yaml, text/yaml, and text/x-yaml" as part of the +// IANA registration template for application/yaml. +// +// Pull requests adding entries need an analogous citation in the +// commit message; entries without authoritative backing belong in +// caller-side canonicalization, not here. +// +// Package-internal by design: the external API is +// [MediaType.Canonical] and [MediaType.Match]. If users ever need +// to register their own aliases, a Register-style function is the +// right answer, not an exported mutable map. +var aliases = map[string]string{ + "application/x-yaml": mtYAML, // RFC 9512 §2.1 + "text/yaml": mtYAML, // RFC 9512 §2.1 + "text/x-yaml": mtYAML, // RFC 9512 §2.1 +} + +// Parse parses a single media type. The input may carry parameters and a +// q-value; the q-value is extracted into [MediaType.Q] and removed from +// [MediaType.Params]. +// +// An empty input returns an error. +func Parse(s string) (MediaType, error) { + s = strings.TrimSpace(s) + if s == "" { + return MediaType{}, fmt.Errorf("%w: empty value", ErrMalformed) + } + full, params, err := mime.ParseMediaType(s) + if err != nil { + return MediaType{}, fmt.Errorf("%w: %w", ErrMalformed, err) + } + slash := strings.IndexByte(full, '/') + if slash <= 0 || slash == len(full)-1 { + return MediaType{}, fmt.Errorf("%w: %q has no subtype", ErrMalformed, s) + } + mt := MediaType{ + Type: full[:slash], + Subtype: full[slash+1:], + Q: 1.0, + } + // RFC 6839: structured syntax suffix is the trailing '+'-delimited + // token of the subtype. Only the last '+' counts ("foo+bar+json" → + // suffix "json"). A trailing '+' with nothing after it is not a + // valid suffix and is ignored. mime.ParseMediaType has already + // lowercased the subtype, so no further ToLower is needed. + if plus := strings.LastIndexByte(mt.Subtype, '+'); plus >= 0 && plus < len(mt.Subtype)-1 { + mt.Suffix = mt.Subtype[plus+1:] + } + if q, ok := params["q"]; ok { + if qf, perr := strconv.ParseFloat(q, 64); perr == nil { + if qf < 0 { + qf = 0 + } + if qf > 1 { + qf = 1 + } + mt.Q = qf + } + delete(params, "q") + } + if len(params) > 0 { + mt.Params = params + } + + return mt, nil +} + +// String renders the canonical "type/subtype;k=v;k=v" form. Parameters are +// emitted in lexicographic key order (the standard library guarantees this) +// so the result is stable. The q-value is NOT emitted — it is meta, not +// part of the media type identity. +func (m MediaType) String() string { + if m.Type == "" && m.Subtype == "" { + return "" + } + + return mime.FormatMediaType(m.Type+"/"+m.Subtype, m.Params) +} + +// Matches reports whether the receiver accepts other, per the package +// documentation: the receiver is the bound, other is the constraint. +func (m MediaType) Matches(other MediaType) bool { + if !typeAgrees(m.Type, other.Type) { + return false + } + if !subtypeAgrees(m.Type, m.Subtype, other.Type, other.Subtype) { + return false + } + if len(m.Params) == 0 { + return true + } + for k, v := range other.Params { + sv, ok := m.Params[k] + if !ok || !strings.EqualFold(sv, v) { + return false + } + } + + return true +} + +// Specificity returns a numeric score for ordering matches. Higher is more +// specific. The returned value is one of [SpecificityAny], +// [SpecificityType], [SpecificityExact] or [SpecificityExactWithParams]. +func (m MediaType) Specificity() int { + if m.Type == wildcard && m.Subtype == wildcard { + return SpecificityAny + } + if m.Subtype == wildcard { + return SpecificityType + } + if len(m.Params) == 0 { + return SpecificityExact + } + + return SpecificityExactWithParams +} + +// typeAgrees reports whether two top-level types match, allowing "*" on +// either side. A type of "*" without a "*" subtype is rejected per RFC +// 7231 §5.3.2 ("*/sub" is not valid), but Parse never produces such a +// shape — it goes through mime.ParseMediaType. +func typeAgrees(a, b string) bool { + return a == wildcard || b == wildcard || a == b +} + +// subtypeAgrees handles the "type/*" wildcard: the bare type must match +// (a "*/*" pair has already been accepted by typeAgrees above). +func subtypeAgrees(at, asub, bt, bsub string) bool { + if at == wildcard || bt == wildcard { + // at least one side is "*/*" or "*/sub". With typeAgrees having + // returned true, we accept. + return true + } + if asub == wildcard || bsub == wildcard { + return true + } + + return asub == bsub +} + +// StripParams returns a copy of m with no parameters. Q is preserved +// because it drives negotiation ordering, not media-type identity. +// +// Useful for the legacy "ignore parameters" negotiation mode. +func (m MediaType) StripParams() MediaType { + return MediaType{Type: m.Type, Subtype: m.Subtype, Suffix: m.Suffix, Q: m.Q} +} + +// Base returns the base media type implied by the RFC 6839 structured +// syntax suffix, or m unchanged when: +// +// - Suffix is empty; +// - Suffix is not present in the package-internal suffix→base table. +// +// The returned value represents the structural base only: it carries +// no parameters and no q-value. Use it to find a codec for the +// underlying wire format — for example, "application/vnd.api+json" +// resolves to "application/json". +// +// Base does not mutate the receiver. +func (m MediaType) Base() MediaType { + if m.Suffix == "" { + return m + } + base, ok := suffixBase[m.Suffix] + if !ok { + return m + } + return base +} + +// Canonical returns m rewritten to its canonical media type via +// the package-internal alias table, or m unchanged when +// (Type, Subtype) is not a known alias. Params and Q are preserved on the returned value; Suffix +// is recomputed from the canonical Subtype (none of the current +// entries carry a suffix, but the contract is forward-safe). +// +// Canonical does not mutate the receiver. +func (m MediaType) Canonical() MediaType { + key := m.Type + "/" + m.Subtype + canon, ok := aliases[key] + if !ok { + return m + } + slash := strings.IndexByte(canon, '/') + out := m + out.Type = canon[:slash] + out.Subtype = canon[slash+1:] + out.Suffix = "" + if plus := strings.LastIndexByte(out.Subtype, '+'); plus >= 0 && plus < len(out.Subtype)-1 { + out.Suffix = out.Subtype[plus+1:] + } + return out +} + +// Match reports how m matches other, classifying the result by +// [MatchKind]. Used by negotiation to rank candidate offers: +// stronger tiers win when both apply. +// +// Returns, strongest first: +// +// - MatchExact when m.Matches(other) is true under the strict +// RFC 7231 rules (including wildcards and the param subset +// rule). +// - MatchAlias when m.Canonical().Matches(other.Canonical()) +// is true but the strict comparison failed. +// - MatchSuffix when m.Base().Canonical().Matches( +// other.Base().Canonical()) is true but the alias comparison +// failed (RFC 6839 structured-syntax suffix fold). +// - MatchNone otherwise. +// +// The asymmetric "bound vs constraint" rule of [MediaType.Matches] +// is preserved at every tier. Match itself is always lenient — the +// opt-in to count MatchSuffix lives one level up at [Set.BestMatch], +// [MatchFirst], and [Lookup] via [AllowSuffix]. +func (m MediaType) Match(other MediaType) MatchKind { + if m.Matches(other) { + return MatchExact + } + if m.Canonical().Matches(other.Canonical()) { + return MatchAlias + } + if m.Base().Canonical().Matches(other.Base().Canonical()) { + return MatchSuffix + } + return MatchNone +} diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/set.go b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/set.go new file mode 100644 index 000000000..70f62a18d --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/mediatype/set.go @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mediatype + +import ( + "strings" +) + +// Set is a list of media types — typically the parsed value of an Accept +// header, or a list of server-side offers. +type Set []MediaType + +// ParseAccept parses a comma-separated list of media types, as found in +// the Accept, Accept-Charset (etc.) HTTP headers. Malformed entries are +// skipped silently — be liberal in what you accept. +// +// An empty input returns nil. +func ParseAccept(s string) Set { + parts := splitTopLevel(s) + if len(parts) == 0 { + return nil + } + out := make(Set, 0, len(parts)) + for _, p := range parts { + mt, err := Parse(p) + if err != nil { + continue + } + out = append(out, mt) + } + + return out +} + +// BestMatch picks the offer most acceptable to the receiver's Accept +// entries. Selection follows RFC 7231 §5.3.2 plus tier-aware +// ranking: +// +// - highest q-value wins; +// - ties on q broken by the highest [MediaType.Specificity] of the +// matching Accept entry; +// - ties on specificity broken by [MatchKind] (MatchExact beats +// MatchAlias beats MatchSuffix); +// - ties on match kind broken by earliest position in offered. +// +// Accept entries with q=0 are treated as exclusions and never match. +// MatchSuffix results are only counted when [AllowSuffix] is passed. +// Returns ok=false if no offer matched any non-zero-q entry. +func (s Set) BestMatch(offered Set, opts ...MatchOption) (best MediaType, ok bool) { + if len(s) == 0 || len(offered) == 0 { + return MediaType{}, false + } + o := applyMatchOptions(opts) + bestQ := -1.0 + bestSpec := -1 + bestKind := MatchNone + bestIdx := -1 + for i, offer := range offered { + for _, entry := range s { + if entry.Q == 0 { + continue + } + kind := offer.Match(entry) + if kind == MatchNone { + continue + } + if kind == MatchSuffix && !o.allowSuffix { + continue + } + spec := entry.Specificity() + switch { + case entry.Q > bestQ: + best, ok = offer, true + bestQ = entry.Q + bestSpec = spec + bestKind = kind + bestIdx = i + case entry.Q < bestQ: + // not better + case spec > bestSpec: + best, ok = offer, true + bestSpec = spec + bestKind = kind + bestIdx = i + case spec < bestSpec: + // not better + case kind > bestKind: + best, ok = offer, true + bestKind = kind + bestIdx = i + case kind < bestKind: + // not better + case bestIdx < 0 || i < bestIdx: + best, ok = offer, true + bestIdx = i + } + } + } + + return best, ok +} + +// splitTopLevel splits s on top-level commas, respecting double-quoted +// strings (RFC 7230 §3.2.6 — quoted-string). +func splitTopLevel(s string) []string { + if strings.IndexByte(s, ',') < 0 { + if t := strings.TrimSpace(s); t != "" { + return []string{t} + } + return nil + } + var out []string + start := 0 + inQuote := false + escape := false + for i := range len(s) { + c := s[i] + switch { + case escape: + escape = false + case inQuote && c == '\\': + escape = true + case c == '"': + inQuote = !inQuote + case c == ',' && !inQuote: + if t := strings.TrimSpace(s[start:i]); t != "" { + out = append(out, t) + } + start = i + 1 + } + } + if t := strings.TrimSpace(s[start:]); t != "" { + out = append(out, t) + } + + return out +} diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/negotiate/doc.go b/vendor/github.com/go-openapi/runtime/server-middleware/negotiate/doc.go new file mode 100644 index 000000000..a9f278c31 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/negotiate/doc.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package negotiate provides server-side HTTP content negotiation +// helpers — selecting the response Content-Type from an Accept header +// and the response Content-Encoding from an Accept-Encoding header. +// +// The package is stdlib-only (modulo the typed [mediatype.MediaType] +// values it consumes). +// +// The exported [ContentType] honours MIME-type parameters by default; +// use [WithIgnoreParameters] to restore the pre-v0.30 looser match. +package negotiate diff --git a/vendor/github.com/go-openapi/runtime/middleware/header/header.go b/vendor/github.com/go-openapi/runtime/server-middleware/negotiate/header/header.go similarity index 100% rename from vendor/github.com/go-openapi/runtime/middleware/header/header.go rename to vendor/github.com/go-openapi/runtime/server-middleware/negotiate/header/header.go diff --git a/vendor/github.com/go-openapi/runtime/server-middleware/negotiate/negotiate.go b/vendor/github.com/go-openapi/runtime/server-middleware/negotiate/negotiate.go new file mode 100644 index 000000000..c36ad5ada --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/server-middleware/negotiate/negotiate.go @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package negotiate + +import ( + "net/http" + "strings" + + "github.com/go-openapi/runtime/server-middleware/mediatype" + "github.com/go-openapi/runtime/server-middleware/negotiate/header" +) + +// Option configures [ContentType] behaviour. +type Option func(*options) + +type options struct { + ignoreParameters bool + matchSuffix bool +} + +func optionsWithDefaults(opts []Option) options { + var o options + for _, apply := range opts { + apply(&o) + } + + return o +} + +// WithIgnoreParameters returns an [Option] that strips MIME-type +// parameters from both Accept entries and offers before matching, restoring +// the behaviour the runtime had before v0.30. +// +// New code should leave parameters honoured (the default). This option +// exists for applications that depend on the looser pre-v0.30 match — +// most often because their producers and Accept clients use mismatched +// charset or version params that they treat as informational. +// +// Example — per-call opt-out: +// +// chosen := negotiate.ContentType(r, offers, "", +// negotiate.WithIgnoreParameters(true), +// ) +// +// Example — server-wide opt-out (via [middleware.Context]): +// +// ctx := middleware.NewContext(spec, api, nil).SetIgnoreParameters(true) +func WithIgnoreParameters(ignore bool) Option { + return func(o *options) { + o.ignoreParameters = ignore + } +} + +// WithMatchSuffix returns an [Option] that extends content +// negotiation to tolerate RFC 6839 structured-syntax suffix media +// types. When enabled, an Accept entry of "application/json" +// matches an offer of "application/vnd.api+json" and vice versa, +// for the suffixes recognised by the runtime (+json, +xml, +yaml). +// +// Default: strict (false). Use only when interoperating with +// clients or servers that do not strictly abide by the spec — for +// example, servers returning application/problem+json error +// responses against operations that only declare application/json +// in produces. +// +// Suffix matches always lose to exact and alias matches when those +// are on offer; see [mediatype.MatchKind] for the tier ordering. +// +// Example — per-call opt-in: +// +// chosen := negotiate.ContentType(r, offers, "", +// negotiate.WithMatchSuffix(true), +// ) +// +// Example — server-wide opt-in (via [middleware.Context]): +// +// ctx := middleware.NewContext(spec, api, nil).SetMatchSuffix(true) +func WithMatchSuffix(enable bool) Option { + return func(o *options) { + o.matchSuffix = enable + } +} + +// ContentEncoding returns the best offered content encoding for the +// request's Accept-Encoding header. If two offers match with equal +// weight then the offer earlier in the list is preferred. If no offers +// are acceptable, then "" is returned. +// +// Encoding tokens have no parameters, so this function is unaffected by +// the v0.30 parameter-honouring change to [ContentType]. +func ContentEncoding(r *http.Request, offers []string) string { + bestOffer := "identity" + bestQ := -1.0 + specs := header.ParseAccept(r.Header, "Accept-Encoding") + for _, offer := range offers { + for _, spec := range specs { + if spec.Q > bestQ && + (spec.Value == "*" || spec.Value == offer) { + bestQ = spec.Q + bestOffer = offer + } + } + } + if bestQ == 0 { + bestOffer = "" + } + + return bestOffer +} + +// ContentType returns the best offered content type for the request's +// Accept header. If two offers match with equal weight, then the more +// specific offer is preferred (text/* trumps */*; type/subtype trumps +// type/*). If two offers match with equal weight and specificity, then +// the offer earlier in the list is preferred. If no offers match, then +// defaultOffer is returned. +// +// As of v0.30 the matching rule honours MIME-type parameters: an Accept +// entry of "text/plain;charset=utf-8" matches an offer of bare +// "text/plain" (offer carries no constraint), but it does NOT match an +// offer of "text/plain;charset=ascii" (charset values disagree). Pass +// [WithIgnoreParameters](true) to restore the pre-v0.30 behaviour where +// parameters were stripped before matching — see [WithIgnoreParameters] +// for details and an example. +// +// When the Accept header is absent, the first offer is returned +// unchanged (param-stripping is irrelevant in that case). +func ContentType(r *http.Request, offers []string, defaultOffer string, opts ...Option) string { + if len(offers) == 0 { + return defaultOffer + } + o := optionsWithDefaults(opts) + + // Per RFC 7230 §3.2.2, multiple Accept headers are equivalent to a + // single comma-joined value. Join before parsing so we don't drop + // later entries. + acceptValues := r.Header.Values("Accept") + if len(acceptValues) == 0 { + return offers[0] + } + acceptSet := mediatype.ParseAccept(strings.Join(acceptValues, ", ")) + if len(acceptSet) == 0 { + return defaultOffer + } + + offerSet := make(mediatype.Set, 0, len(offers)) + rawByIdx := make([]string, 0, len(offers)) + for _, raw := range offers { + mt, err := mediatype.Parse(raw) + if err != nil { + continue + } + offerSet = append(offerSet, mt) + rawByIdx = append(rawByIdx, raw) + } + if len(offerSet) == 0 { + return defaultOffer + } + + if o.ignoreParameters { + acceptSet = stripSet(acceptSet) + offerSet = stripSet(offerSet) + } + + var matchOpts []mediatype.MatchOption + if o.matchSuffix { + matchOpts = append(matchOpts, mediatype.AllowSuffix()) + } + best, ok := acceptSet.BestMatch(offerSet, matchOpts...) + if !ok { + return defaultOffer + } + // Return the original raw offer string so callers receive the value + // they declared, with its parameters preserved. + for i, mt := range offerSet { + if mt.Type == best.Type && mt.Subtype == best.Subtype && sameParams(mt.Params, best.Params) { + return rawByIdx[i] + } + } + + return best.String() +} + +func stripSet(s mediatype.Set) mediatype.Set { + out := make(mediatype.Set, len(s)) + for i, m := range s { + out[i] = m.StripParams() + } + + return out +} + +func sameParams(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if b[k] != v { + return false + } + } + + return true +} diff --git a/vendor/github.com/go-openapi/runtime/text.go b/vendor/github.com/go-openapi/runtime/text.go index 1252ac88c..24e7eaf5a 100644 --- a/vendor/github.com/go-openapi/runtime/text.go +++ b/vendor/github.com/go-openapi/runtime/text.go @@ -43,7 +43,7 @@ func TextConsumer() Consumer { } t := reflect.TypeOf(data) - if data != nil && t.Kind() == reflect.Ptr { + if data != nil && t.Kind() == reflect.Pointer { v := reflect.Indirect(reflect.ValueOf(data)) if t.Elem().Kind() == reflect.String { v.SetString(string(b)) diff --git a/vendor/modules.txt b/vendor/modules.txt index 3feca3b27..c31169c72 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -106,17 +106,23 @@ github.com/go-openapi/jsonreference/internal # github.com/go-openapi/loads v0.23.3 ## explicit; go 1.24.0 github.com/go-openapi/loads -# github.com/go-openapi/runtime v0.29.5 +# github.com/go-openapi/runtime v0.30.0 ## explicit; go 1.25.0 github.com/go-openapi/runtime github.com/go-openapi/runtime/client +github.com/go-openapi/runtime/client/internal/request github.com/go-openapi/runtime/logger github.com/go-openapi/runtime/middleware github.com/go-openapi/runtime/middleware/denco -github.com/go-openapi/runtime/middleware/header github.com/go-openapi/runtime/middleware/untyped github.com/go-openapi/runtime/security github.com/go-openapi/runtime/yamlpc +# github.com/go-openapi/runtime/server-middleware v0.30.0 +## explicit; go 1.25.0 +github.com/go-openapi/runtime/server-middleware/docui +github.com/go-openapi/runtime/server-middleware/mediatype +github.com/go-openapi/runtime/server-middleware/negotiate +github.com/go-openapi/runtime/server-middleware/negotiate/header # github.com/go-openapi/spec v0.22.4 ## explicit; go 1.24.0 github.com/go-openapi/spec