package testwire import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "os" "path/filepath" "strconv" "strings" "sync" "testing" ) // Checker validates HTTP exchanges against docs/openapi.yaml: the operation, // its query and header parameters, the JSON request body, the status code, and // the JSON or SSE response body. It records failures instead of stopping the // exchange, so a fake or a live daemon keeps answering while the test collects // every drift at the end. // // Wrap a fake daemon with [NewDaemon] (or [Checker.Handler]) and a client of a // real daemon with [Checker.Transport]. A fake that answers malformed or // undocumented bytes on purpose, to test a client's refusal, must not be // wrapped. type Checker struct { *Contract mu sync.Mutex failures []error } var shared = sync.OnceValues(func() (*Contract, error) { root, err := RepositoryRoot() if err != nil { return nil, err } return LoadContract(root) }) // RepositoryRoot finds the checkout holding docs/openapi.yaml from the working // directory, which `go test` sets to the package directory. func RepositoryRoot() (string, error) { dir, err := os.Getwd() if err != nil { return "", err } for { if _, err := os.Stat(filepath.Join(dir, "docs", "openapi.yaml")); err == nil { return dir, nil } parent := filepath.Dir(dir) if parent == dir { return "", errors.New("docs/openapi.yaml not found above the working directory") } dir = parent } } // NewChecker returns a checker over the repository's contract, loaded once per // test binary. func NewChecker() (*Checker, error) { contract, err := shared() if err != nil { return nil, err } return &Checker{Contract: contract}, nil } // Failures answers the drifts recorded so far. func (checker *Checker) Failures() []error { checker.mu.Lock() defer checker.mu.Unlock() return append([]error(nil), checker.failures...) } func (checker *Checker) record(method, path string, err error) { if err == nil { return } checker.mu.Lock() defer checker.mu.Unlock() checker.failures = append(checker.failures, fmt.Errorf("%s %s: %w", method, path, err)) } // NewDaemon starts an httptest server whose every exchange is checked, and // fails t at cleanup, after the server has closed, for each drift. Requests the // daemon would refuse (an undocumented route, query parameter, or body) fail as // well as responses a daemon could not send. func NewDaemon(t testing.TB, handler http.Handler) *httptest.Server { t.Helper() checker, err := NewChecker() if err != nil { t.Fatal(err) } server := httptest.NewServer(checker.Handler(handler)) t.Cleanup(func() { for _, failure := range checker.Failures() { t.Errorf("OpenAPI: %v", failure) } }) t.Cleanup(server.Close) return server } // Operation finds the documented operation for method and path. A literal // segment beats a parameter, as it does in routing, so a path like // /history/content is not read as /history/{entry_id}. func (checker *Checker) Operation(method, path string) (map[string]any, error) { paths := checker.Document["paths"].(map[string]any) var operation map[string]any var shared []any literals := -1 for template, definition := range paths { expected, actual := strings.Split(template, "/"), strings.Split(path, "/") if len(expected) != len(actual) { continue } matched, specific := true, 0 for index, segment := range expected { if strings.HasPrefix(segment, "{") { if actual[index] == "" { matched = false break } continue } if segment != actual[index] { matched = false break } specific++ } if matched && specific > literals { item := definition.(map[string]any) operation, _ = item[strings.ToLower(method)].(map[string]any) shared, _ = item["parameters"].([]any) literals = specific } } if operation == nil { return nil, fmt.Errorf("undocumented operation %s %s", method, path) } if len(shared) != 0 { own, _ := operation["parameters"].([]any) merged := make(map[string]any, len(operation)+1) for key, value := range operation { merged[key] = value } merged["parameters"] = append(append([]any(nil), shared...), own...) operation = merged } return operation, nil } // CheckRequest validates the query, the declared headers, and the body of a // request to operation. func (checker *Checker) CheckRequest(operation map[string]any, request *http.Request, body []byte) error { var problems []error query := request.URL.Query() declared := map[string]bool{} parameters, _ := operation["parameters"].([]any) for _, raw := range parameters { parameter := checker.Dereference(raw.(map[string]any)) name, _ := parameter["name"].(string) location, _ := parameter["in"].(string) required, _ := parameter["required"].(bool) schema, _ := parameter["schema"].(map[string]any) var values []string switch location { case "query": declared[name] = true values = query[name] case "header": values = request.Header.Values(name) default: continue } if len(values) == 0 { if required { problems = append(problems, fmt.Errorf("missing required %s parameter %s", location, name)) } continue } if schema != nil { if err := checker.Validate(schema, checker.parameterValue(schema, values)); err != nil { problems = append(problems, fmt.Errorf("%s parameter %s: %w", location, name, err)) } } } for name := range query { if !declared[name] { problems = append(problems, fmt.Errorf("undocumented query parameter %s", name)) } } definition, _ := operation["requestBody"].(map[string]any) if definition == nil { if len(bytes.TrimSpace(body)) != 0 { problems = append(problems, errors.New("body sent to an operation without a request body")) } return errors.Join(problems...) } definition = checker.Dereference(definition) if len(body) == 0 { if required, _ := definition["required"].(bool); required { problems = append(problems, errors.New("missing required request body")) } return errors.Join(problems...) } if !identity(request.Header) { return errors.Join(problems...) } content, _ := definition["content"].(map[string]any) mediaType, _, _ := strings.Cut(request.Header.Get("Content-Type"), ";") media, ok := content[strings.TrimSpace(mediaType)].(map[string]any) if !ok { problems = append(problems, fmt.Errorf("undocumented request media type %q", mediaType)) return errors.Join(problems...) } if schema, _ := media["schema"].(map[string]any); schema != nil && strings.HasSuffix(mediaType, "json") { problems = append(problems, checker.validateJSON(schema, body)) } return errors.Join(problems...) } // A query or header value arrives as text; read it as the schema's scalar type // so an integer limit or a boolean flag validates as one. func (checker *Checker) parameterValue(schema map[string]any, values []string) any { resolved := checker.Dereference(schema) if resolved["type"] == "array" { items, _ := resolved["items"].(map[string]any) result := make([]any, 0, len(values)) for _, value := range values { for part := range strings.SplitSeq(value, ",") { result = append(result, checker.scalar(items, part)) } } return result } return checker.scalar(resolved, values[0]) } func (checker *Checker) scalar(schema map[string]any, value string) any { if schema == nil { return value } switch checker.Dereference(schema)["type"] { case "integer": if parsed, err := strconv.ParseInt(value, 10, 64); err == nil { return parsed } case "number": if parsed, err := strconv.ParseFloat(value, 64); err == nil { return parsed } case "boolean": if parsed, err := strconv.ParseBool(value); err == nil { return parsed } } return value } func (checker *Checker) validateJSON(schema map[string]any, data []byte) error { var value any if err := json.Unmarshal(data, &value); err != nil { return err } return checker.Validate(schema, value) } // ResponseSchema finds the schema of a response to operation. It answers nil // for a documented response without a JSON or SSE body. func (checker *Checker) ResponseSchema(operation map[string]any, status int, contentType string) (schema map[string]any, stream bool, err error) { responses := operation["responses"].(map[string]any) definition, ok := responses[strconv.Itoa(status)].(map[string]any) if !ok { return nil, false, fmt.Errorf("undocumented response status %d", status) } definition = checker.Dereference(definition) content, ok := definition["content"].(map[string]any) if !ok { return nil, false, nil } mediaType, _, _ := strings.Cut(contentType, ";") mediaType = strings.TrimSpace(mediaType) media, ok := content[mediaType].(map[string]any) if !ok { return nil, false, fmt.Errorf("undocumented response media type %q", mediaType) } if mediaType == "text/event-stream" { return checker.Dereference(media["itemSchema"].(map[string]any)), true, nil } if mediaType != "application/json" && mediaType != "application/problem+json" { return nil, false, nil } schema, _ = media["schema"].(map[string]any) return schema, false, nil } // bodyCheck validates a response body as its bytes pass, so a stream is // checked frame by frame while it is still open. type bodyCheck struct { checker *Checker method string path string schema map[string]any stream bool pending []byte finished bool frame map[string]any data []string frameBytes int } func (body *bodyCheck) fail(err error) { body.checker.record(body.method, body.path, err) } func (body *bodyCheck) payload(data []byte) { schema := body.schema if body.stream { field := schema["properties"].(map[string]any)["data"].(map[string]any) schema, _ = field["contentSchema"].(map[string]any) if schema == nil { for _, variant := range field["anyOf"].([]any) { if candidate, ok := variant.(map[string]any)["contentSchema"].(map[string]any); ok { schema = candidate break } } } } body.fail(body.checker.validateJSON(schema, data)) } // Parse the SSE envelope as well as its JSON payload. Data lines join with // newline; comments are legal, while fields forbidden by the contract remain // visible to the envelope schema. func (body *bodyCheck) streamLine(line []byte) { body.frameBytes += len(line) + 1 if body.frameBytes > 1<<20 { body.fail(errors.New("SSE frame exceeds 1 MiB")) body.pending, body.frame, body.data, body.finished = nil, nil, nil, true return } if len(line) == 0 { if len(body.data) != 0 { body.frame["data"] = strings.Join(body.data, "\n") } if len(body.frame) != 0 { body.fail(body.checker.Validate(body.schema, body.frame)) if data, ok := body.frame["data"].(string); ok && data != "[DONE]" { body.payload([]byte(data)) } } body.frame, body.data, body.frameBytes = nil, nil, 0 return } if line[0] == ':' { return } name, value, _ := bytes.Cut(line, []byte(":")) value = bytes.TrimPrefix(value, []byte(" ")) if body.frame == nil { body.frame = make(map[string]any) } if string(name) == "data" { body.data = append(body.data, string(value)) } else { body.frame[string(name)] = string(value) } } func (body *bodyCheck) write(data []byte) { if body.finished { return } body.pending = append(body.pending, data...) if len(body.pending) > 1<<20 && !body.stream { body.fail(errors.New("response exceeds 1 MiB")) body.pending, body.finished = nil, true return } if !body.stream { return } for { line, remaining, found := bytes.Cut(body.pending, []byte("\n")) if !found { break } body.streamLine(bytes.TrimSuffix(line, []byte("\r"))) if body.finished { return } body.pending = remaining } } // finish checks a whole JSON body. complete is false when the reader closed a // body early, which only matters when what arrived is not yet a value. func (body *bodyCheck) finish(complete bool) { if body.finished || body.stream { body.finished = true return } body.finished = true if complete || json.Valid(body.pending) { body.payload(body.pending) } body.pending = nil } // A compressed body is checked by whoever decodes it, not here. func identity(header http.Header) bool { coding := header.Get("Content-Encoding") return coding == "" || coding == "identity" } // Transport checks every exchange a client makes through upstream. func (checker *Checker) Transport(upstream http.RoundTripper) http.RoundTripper { return checkedTransport{upstream: upstream, checker: checker} } type checkedTransport struct { upstream http.RoundTripper checker *Checker } func (transport checkedTransport) RoundTrip(request *http.Request) (*http.Response, error) { operation, err := transport.checker.Operation(request.Method, request.URL.Path) transport.checker.record(request.Method, request.URL.Path, err) if operation != nil { var body []byte if request.GetBody != nil { if reader, bodyErr := request.GetBody(); bodyErr == nil { body, _ = io.ReadAll(reader) _ = reader.Close() } } else if request.Body != nil && request.Body != http.NoBody { // The request is the caller's; send a copy carrying the bytes read. body, _ = io.ReadAll(request.Body) _ = request.Body.Close() request = request.Clone(request.Context()) request.Body = io.NopCloser(bytes.NewReader(body)) request.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } } transport.checker.record(request.Method, request.URL.Path, transport.checker.CheckRequest(operation, request, body)) } response, err := transport.upstream.RoundTrip(request) if err != nil || operation == nil { return response, err } schema, stream, err := transport.checker.ResponseSchema(operation, response.StatusCode, response.Header.Get("Content-Type")) transport.checker.record(request.Method, request.URL.Path, err) if schema == nil || err != nil || !identity(response.Header) { return response, nil } response.Body = &checkedBody{ReadCloser: response.Body, check: &bodyCheck{checker: transport.checker, method: request.Method, path: request.URL.Path, schema: schema, stream: stream}} return response, nil } func (transport checkedTransport) CloseIdleConnections() { if closer, ok := transport.upstream.(interface{ CloseIdleConnections() }); ok { closer.CloseIdleConnections() } } type checkedBody struct { io.ReadCloser check *bodyCheck } func (body *checkedBody) Read(target []byte) (int, error) { count, err := body.ReadCloser.Read(target) body.check.write(target[:count]) if err == io.EOF { body.check.finish(true) } return count, err } func (body *checkedBody) Close() error { body.check.finish(false) return body.ReadCloser.Close() } // Handler checks every exchange next serves. func (checker *Checker) Handler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { operation, err := checker.Operation(r.Method, r.URL.Path) checker.record(r.Method, r.URL.Path, err) body, _ := io.ReadAll(r.Body) _ = r.Body.Close() r.Body = io.NopCloser(bytes.NewReader(body)) if operation != nil { checker.record(r.Method, r.URL.Path, checker.CheckRequest(operation, r, body)) } recorder := &checkedWriter{ResponseWriter: w, request: r, checker: checker, operation: operation, method: r.Method, path: r.URL.Path} defer recorder.done() next.ServeHTTP(recorder, r) }) } type checkedWriter struct { http.ResponseWriter request *http.Request checker *Checker operation map[string]any method string path string status int sent bool check *bodyCheck hijacked bool } // WriteHeader holds the status until the body starts, so a fake that leaves // out the media type is read by what it writes. func (w *checkedWriter) WriteHeader(status int) { if w.status == 0 { w.status = status } } func (w *checkedWriter) send(first []byte) { if w.sent { return } w.sent = true if w.status == 0 { w.status = http.StatusOK } // A fake that leaves out the media type answers JSON the way the daemon // does, and a refusal as a problem; net/http would sniff it as text. if w.Header().Get("Content-Type") == "" && len(first) != 0 { if trimmed := bytes.TrimSpace(first); len(trimmed) != 0 && (trimmed[0] == '{' || trimmed[0] == '[') { if w.status >= 400 { w.Header().Set("Content-Type", "application/problem+json") } else { w.Header().Set("Content-Type", "application/json") } } else { w.Header().Set("Content-Type", http.DetectContentType(first)) } } if w.operation != nil { schema, stream, err := w.checker.ResponseSchema(w.operation, w.status, w.Header().Get("Content-Type")) w.checker.record(w.method, w.path, err) if schema != nil && err == nil && identity(w.Header()) { w.check = &bodyCheck{checker: w.checker, method: w.method, path: w.path, schema: schema, stream: stream} } } w.ResponseWriter.WriteHeader(w.status) } func (w *checkedWriter) Write(data []byte) (int, error) { w.send(data) if w.check != nil { w.check.write(data) } return w.ResponseWriter.Write(data) } func (w *checkedWriter) Flush() { w.send(nil) if flusher, ok := w.ResponseWriter.(http.Flusher); ok { flusher.Flush() } } func (w *checkedWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { w.hijacked = true return http.NewResponseController(w.ResponseWriter).Hijack() } func (w *checkedWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } func (w *checkedWriter) done() { // A client that left before any answer ended the exchange, not the fake. if w.hijacked || (!w.sent && w.request.Context().Err() != nil) { return } w.send(nil) if w.check != nil { w.check.finish(true) } }