diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml new file mode 100644 index 0000000..e0ecbc7 --- /dev/null +++ b/.github/workflows/go.yml @@ -0,0 +1,34 @@ +name: Go CI +on: + pull_request: + paths: ['go/**', 'spec/**', 'conformance/**', '.github/workflows/go.yml'] + push: + branches: [main] + paths: ['go/**', 'spec/**', 'conformance/**', '.github/workflows/go.yml'] + workflow_dispatch: +permissions: + contents: read +defaults: + run: + working-directory: go +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + matrix: + go: ['1.26.x', 'stable'] + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: ${{ matrix.go }} + cache: false + - run: test -z "$(gofmt -l .)" + - run: go vet ./... + - run: go test -mod=readonly -race ./... + - run: go mod verify + - if: matrix.go == 'stable' + run: go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 ./... + - if: matrix.go == 'stable' + run: go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 ./... diff --git a/go/EXPORTS.md b/go/EXPORTS.md new file mode 100644 index 0000000..dcf7b8a --- /dev/null +++ b/go/EXPORTS.md @@ -0,0 +1,13 @@ +# TypeScript to Go export map + +| TypeScript | Go | +| --- | --- | +| HttpError, HttpErrorOptions | Error, Options, New | +| HttpError.from(error), isHttpErrorLike | From, errors.As with *Error or an error implementing StatusCode() int | +| HttpError.from(response or problem) | FromResponse, Parse | +| HttpError.toJSON, ProblemDetails | json.Marshal through Error.MarshalJSON, with json.RawMessage extension values | +| HttpError.getResponse | Error.Write(http.ResponseWriter) | +| status, title, detail, expose, headers | StatusCode(), Title(), Detail(), Exposed(), Headers() | +| message, cause | Error(), errors.Unwrap | +| type, instance, extensions | Options fields on construction and exact-name JSON members on output | +| StatusCode, STATUS_CODE, STATUS_TEXT | int and net/http status constants. The error's Title() gives the package's canonical error title. | diff --git a/go/PORTING.md b/go/PORTING.md new file mode 100644 index 0000000..5b3a8b8 --- /dev/null +++ b/go/PORTING.md @@ -0,0 +1,14 @@ +# Porting HTTP errors to Go + +The module is `github.com/udibo/http-error/go`, with package name `httperror`. +It uses the standard library and supports Go 1.26 and later. + +| Decision | Reason | +| --- | --- | +| `New(Options) (*Error, error)` | A zero-value options struct describes a 500. The integer status rejects fractions at the type boundary. Pointers distinguish an omitted status, detail or expose option from an explicit zero, empty string or false. For example, use `Status: new(404)`. | +| `Error()` for diagnostics, `Detail()` for clients | A parsed detail is a diagnostic message subject to the status exposure rule. A caller may supply an explicitly public detail in the constructor. | +| `errors.As` and `Unwrap` | Wrapped HTTP errors retain their status. Converting an error with `From` or parsing an HTTP response starts a fresh set of headers. Writing an error directly preserves its own headers, including repeated fields. | +| `map[string]json.RawMessage` for extensions | Every key and JSON type survives unmarshaling, including null and case variants of standard names. Numbers retain their JSON precision. Carry large identifiers as decimal strings for I-JSON interoperability. | +| `FromResponse` and `Write` | The HTTP client owns the response body and request context. The server writes to its ordinary response writer. Applications can inspect the JSON alone with `json.Marshal`. | + +Run `go test -race ./...` and `go vet ./...` from this directory. The vector tests read the repository's shared fixtures directly. diff --git a/go/conformance_test.go b/go/conformance_test.go new file mode 100644 index 0000000..3e40b76 --- /dev/null +++ b/go/conformance_test.go @@ -0,0 +1,220 @@ +package httperror_test + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "reflect" + "strconv" + "testing" + + httperror "github.com/udibo/http-error/go" +) + +type headers http.Header + +func (h *headers) UnmarshalJSON(data []byte) error { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + result := http.Header{} + for name, value := range fields { + var many []string + if err := json.Unmarshal(value, &many); err != nil { + var one string + if err := json.Unmarshal(value, &one); err != nil { + return err + } + many = []string{one} + } + for _, s := range many { + result.Add(name, s) + } + } + *h = headers(result) + return nil +} + +func sameJSON(t *testing.T, got, want []byte) { + t.Helper() + decode := func(v []byte) any { + dec := json.NewDecoder(bytes.NewReader(v)) + dec.UseNumber() + var result any + if err := dec.Decode(&result); err != nil { + t.Fatal(err) + } + return result + } + if !reflect.DeepEqual(decode(got), decode(want)) { + t.Fatalf("got %s, want %s", got, want) + } +} + +func TestVectors(t *testing.T) { + file, err := os.Open("../conformance/vectors/problem-details.json") + if err != nil { + t.Fatal(err) + } + defer file.Close() + var vectors struct { + Description string + Serialize []struct { + Name, Error string + Input json.RawMessage + Expected struct { + Status int + Expose bool + Headers headers + Body json.RawMessage + } + } + Parse []struct { + Name string + Input struct { + Status int + Body string + Hex *string `json:"body_hex"` + } + Expected struct { + Status int + Expose bool + Title, Detail, Type, Instance string + Extensions map[string]json.RawMessage + } + } + Defaults []struct { + Status int + Title, Detail string + } + } + dec := json.NewDecoder(file) + dec.DisallowUnknownFields() + if err := dec.Decode(&vectors); err != nil { + t.Fatal(err) + } + if len(vectors.Serialize) == 0 || len(vectors.Parse) == 0 || len(vectors.Defaults) != 200 { + t.Fatal("incomplete fixture") + } + for _, v := range vectors.Serialize { + t.Run("serialize/"+v.Name, func(t *testing.T) { + var in struct { + httperror.Options + Headers headers + } + dec := json.NewDecoder(bytes.NewReader(v.Input)) + dec.DisallowUnknownFields() + err := dec.Decode(&in) + // A fractional status cannot enter the typed constructor. + var typeErr *json.UnmarshalTypeError + if v.Error == "invalid status" && errors.As(err, &typeErr) && typeErr.Type == reflect.TypeFor[int]() { + return + } + if err != nil { + t.Fatal(err) + } + in.Options.Headers = http.Header(in.Headers) + e, err := httperror.New(in.Options) + if v.Error != "" { + if err == nil || v.Error != "invalid status" { + t.Fatalf("want %s, got %v", v.Error, err) + } + return + } + if err != nil { + t.Fatal(err) + } + w := httptest.NewRecorder() + if err := e.Write(w); err != nil { + t.Fatal(err) + } + if w.Code != v.Expected.Status || e.Exposed() != v.Expected.Expose || !reflect.DeepEqual(w.Result().Header, http.Header(v.Expected.Headers)) { + t.Fatalf("status %d, expose %v, headers %v", w.Code, e.Exposed(), w.Header()) + } + sameJSON(t, w.Body.Bytes(), v.Expected.Body) + }) + } + for _, v := range vectors.Parse { + t.Run("parse/"+v.Name, func(t *testing.T) { + body := []byte(v.Input.Body) + if v.Input.Hex != nil { + var err error + body, err = hex.DecodeString(*v.Input.Hex) + if err != nil { + t.Fatal(err) + } + } + e := httperror.FromResponse(&http.Response{StatusCode: v.Input.Status, Body: io.NopCloser(bytes.NewReader(body))}) + want := make(map[string]any) + for k, raw := range v.Expected.Extensions { + want[k] = raw + } + want["status"], want["title"], want["detail"] = v.Expected.Status, v.Expected.Title, v.Expected.Detail + if v.Expected.Type != "" { + want["type"] = v.Expected.Type + } + if v.Expected.Instance != "" { + want["instance"] = v.Expected.Instance + } + expected, err := json.Marshal(want) + if err != nil { + t.Fatal(err) + } + got, err := json.Marshal(e) + if err != nil { + t.Fatal(err) + } + sameJSON(t, got, expected) + if e.Exposed() != v.Expected.Expose { + t.Fatalf("expose = %v", e.Exposed()) + } + }) + } + for i, v := range vectors.Defaults { + t.Run("defaults/"+strconv.Itoa(v.Status), func(t *testing.T) { + e, err := httperror.New(httperror.Options{Status: &v.Status, Expose: new(false)}) + if err != nil { + t.Fatal(err) + } + if v.Status != i+400 || e.Title() != v.Title || e.Detail() != v.Detail { + t.Fatalf("got %d %q %q", e.StatusCode(), e.Title(), e.Detail()) + } + }) + } +} + +func TestFromAndOwnership(t *testing.T) { + cause := errors.New("database unavailable") + h := http.Header{"Set-Cookie": {"a=1", "b=2"}} + value := json.RawMessage(`"secretary"`) + e, err := httperror.New(httperror.Options{Status: new(503), Message: cause.Error(), Cause: cause, Headers: h, Extensions: map[string]json.RawMessage{"role": value}}) + if err != nil { + t.Fatal(err) + } + h["Set-Cookie"][0] = "changed" + e.Headers()["Set-Cookie"][1] = "changed" + value[1] = 'x' + if !reflect.DeepEqual(e.Headers().Values("Set-Cookie"), []string{"a=1", "b=2"}) { + t.Fatal(e.Headers()) + } + p := httperror.From(e) + if len(p.Headers().Values("Set-Cookie")) != 0 || !errors.Is(p, cause) || p.Detail() == cause.Error() { + t.Fatal("conversion relayed private data or lost cause") + } + b, err := json.Marshal(p) + if err != nil || !bytes.Contains(b, []byte(`"role":"secretary"`)) { + t.Fatalf("%s: %v", b, err) + } +} + +func TestExplicitZeroStatus(t *testing.T) { + if _, err := httperror.New(httperror.Options{Status: new(0)}); err == nil { + t.Fatal("accepted an explicit zero status") + } +} diff --git a/go/error.go b/go/error.go new file mode 100644 index 0000000..6394951 --- /dev/null +++ b/go/error.go @@ -0,0 +1,184 @@ +// Package httperror represents HTTP failures as RFC 9457 Problem Details. +package httperror + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "maps" + "net/http" +) + +// Options describes an error. An omitted status defaults to 500. Detail, when +// supplied, is public even when the diagnostic Message is hidden. +type Options struct { + Status *int + Message, Title, Type, Instance string + Detail *string + Expose *bool + Extensions map[string]json.RawMessage + Headers http.Header + Cause error +} + +// Error carries diagnostic information and the corresponding public problem. +// Construct one with New. +type Error struct { + status int + message, title, detail, problemType, instance string + expose bool + cause error + headers http.Header + extensions map[string]json.RawMessage +} + +// New builds a problem with its own copies of the headers and extensions. +func New(o Options) (*Error, error) { + status := http.StatusInternalServerError + if o.Status != nil { + status = *o.Status + } + if !validStatus(status) { + return nil, fmt.Errorf("invalid HTTP error status %d", status) + } + e := build(status, o) + e.headers = make(http.Header, len(o.Headers)+1) + for field, values := range o.Headers { + for _, value := range values { + e.headers.Add(field, value) + } + } + if _, set := e.headers["Content-Type"]; !set { + e.headers.Set("Content-Type", mediaType) + } + for name, value := range o.Extensions { + if standard(name) { + continue + } + if value == nil { + value = json.RawMessage("null") + } + if !json.Valid(value) { + return nil, fmt.Errorf("invalid JSON in extension %q", name) + } + e.extensions[name] = bytes.Clone(value) + } + return e, nil +} + +const mediaType = "application/problem+json" + +func build(status int, o Options) *Error { + title, detail := defaults(status) + expose := status < 500 + if o.Expose != nil { + expose = *o.Expose + } + if o.Title != "" { + title = o.Title + } + if o.Detail != nil { + detail = *o.Detail + } else if expose && o.Message != "" { + detail = o.Message + } + message := o.Message + if message == "" && o.Detail != nil { + message = *o.Detail + } + return &Error{status: status, title: title, detail: detail, message: message, + expose: expose, cause: o.Cause, problemType: o.Type, instance: o.Instance, + headers: http.Header{"Content-Type": {mediaType}}, extensions: make(map[string]json.RawMessage)} +} + +func validStatus(n int) bool { return n >= 400 && n <= 599 } + +func standard(name string) bool { + switch name { + case "type", "title", "detail", "status", "instance": + return true + } + return false +} + +// Error returns the diagnostic message for logs. +func (e *Error) Error() string { + if e.message == "" { + return e.title + } + return e.title + ": " + e.message +} + +// Unwrap returns the original diagnostic cause. +func (e *Error) Unwrap() error { return e.cause } + +// StatusCode returns the HTTP response status. +func (e *Error) StatusCode() int { return e.status } + +// Title returns the short public summary. +func (e *Error) Title() string { return e.title } + +// Detail returns the public explanation. +func (e *Error) Detail() string { return e.detail } + +// Exposed reports whether the diagnostic message may supply the public detail. +func (e *Error) Exposed() bool { return e.expose } + +// Headers returns an independent copy of the response headers. +func (e *Error) Headers() http.Header { return e.headers.Clone() } + +// From converts a Go error to an HTTP error and strips source headers. +// Wrapped errors implementing StatusCode() int retain a valid HTTP error status. +func From(err error) *Error { + var problem *Error + if errors.As(err, &problem) && problem != nil { + copy := *problem + copy.headers = http.Header{"Content-Type": {mediaType}} + return © + } + status := http.StatusInternalServerError + o := Options{Cause: err} + if err != nil { + o.Message = err.Error() + } + var source interface { + error + StatusCode() int + } + if errors.As(err, &source) { + if n := source.StatusCode(); validStatus(n) { + status = n + o.Message = source.Error() + } + } + return build(status, o) +} + +// MarshalJSON encodes only the public problem members and its extensions. +func (e *Error) MarshalJSON() ([]byte, error) { + problem := make(map[string]any, len(e.extensions)+5) + problem["status"], problem["title"], problem["detail"] = e.status, e.title, e.detail + if e.problemType != "" { + problem["type"] = e.problemType + } + if e.instance != "" { + problem["instance"] = e.instance + } + for name, value := range e.extensions { + problem[name] = value + } + return json.Marshal(problem) +} + +// Write writes the response, preserving repeated fields in order. +func (e *Error) Write(w http.ResponseWriter) error { + body, err := e.MarshalJSON() + if err != nil { + return err + } + maps.Copy(w.Header(), e.Headers()) + w.WriteHeader(e.status) + _, err = w.Write(body) + return err +} diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..877d9bd --- /dev/null +++ b/go/go.mod @@ -0,0 +1,3 @@ +module github.com/udibo/http-error/go + +go 1.26 diff --git a/go/parse.go b/go/parse.go new file mode 100644 index 0000000..3772c46 --- /dev/null +++ b/go/parse.go @@ -0,0 +1,73 @@ +package httperror + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "unicode/utf8" +) + +// Parse reads a UTF-8 problem document. Malformed bodies produce an unexposed +// problem with the response status, or 500 if that status is outside 400–599. +func Parse(status int, body []byte) *Error { + body = bytes.TrimPrefix(body, []byte{0xef, 0xbb, 0xbf}) + if !utf8.Valid(body) { + return unreadable(status, errors.New("invalid UTF-8 in problem details")) + } + var members map[string]json.RawMessage + if err := json.Unmarshal(body, &members); err != nil { + return unreadable(status, err) + } + present := func(name string) bool { + v := members[name] + return v != nil && !bytes.Equal(v, []byte("null")) + } + if !present("status") && !present("title") && !present("type") { + return unreadable(status, errors.New("missing problem details members")) + } + var n float64 + if err := json.Unmarshal(members["status"], &n); err == nil && n >= 400 && n <= 599 && n == float64(int(n)) { + status = int(n) + } + if !validStatus(status) { + status = 500 + } + member := func(name string) string { + var s string + _ = json.Unmarshal(members[name], &s) + return s + } + e := build(status, Options{Title: member("title"), Message: member("detail"), Type: member("type"), Instance: member("instance")}) + for name, value := range members { + if !standard(name) { + e.extensions[name] = value + } + } + return e +} + +func unreadable(status int, cause error) *Error { + if !validStatus(status) { + status = 500 + } + expose := false + return build(status, Options{Message: "could not read problem details", Expose: &expose, Cause: cause}) +} + +// FromResponse consumes the body without closing it. The caller owns the body +// and controls its size and lifetime through the originating HTTP request. +func FromResponse(response *http.Response) *Error { + if response == nil { + return unreadable(500, errors.New("missing HTTP response")) + } + if response.Body == nil { + return unreadable(response.StatusCode, io.EOF) + } + body, err := io.ReadAll(response.Body) + if err != nil { + return unreadable(response.StatusCode, err) + } + return Parse(response.StatusCode, body) +} diff --git a/go/status.go b/go/status.go new file mode 100644 index 0000000..cbc3e3c --- /dev/null +++ b/go/status.go @@ -0,0 +1,90 @@ +package httperror + +func defaults(status int) (title, detail string) { + switch status { + case 400: + return "Bad Request", "The server cannot process the request due to a client error." + case 401: + return "Unauthorized", "Authentication is required to access this resource." + case 402: + return "Payment Required", "Payment is required to access this resource." + case 403: + return "Forbidden", "You do not have permission to access this resource." + case 404: + return "Not Found", "The requested resource could not be found." + case 405: + return "Method Not Allowed", "The request method is not supported for this resource." + case 406: + return "Not Acceptable", "The server cannot produce a response matching the acceptable values." + case 407: + return "Proxy Authentication Required", "Proxy authentication is required." + case 408: + return "Request Timeout", "The server timed out waiting for the request." + case 409: + return "Conflict", "The request conflicts with the current state of the resource." + case 410: + return "Gone", "The requested resource is no longer available." + case 411: + return "Length Required", "The request requires a Content-Length header." + case 412: + return "Precondition Failed", "A precondition in the request headers was not met." + case 413: + return "Content Too Large", "The request body is larger than the server is willing to process." + case 414: + return "URI Too Long", "The request URI is longer than the server is willing to process." + case 415: + return "Unsupported Media Type", "The request uses a media type that is not supported." + case 416: + return "Range Not Satisfiable", "The requested range cannot be satisfied." + case 417: + return "Expectation Failed", "The expectation in the Expect header cannot be met." + case 418: + return "I'm a teapot", "The server refuses to brew coffee because it is a teapot." + case 421: + return "Misdirected Request", "The request was directed at a server unable to produce a response." + case 422: + return "Unprocessable Content", "The request was well-formed but contained semantic errors." + case 423: + return "Locked", "The requested resource is locked." + case 424: + return "Failed Dependency", "The request failed due to a previous request failure." + case 425: + return "Too Early", "The server is unwilling to process a request that might be replayed." + case 426: + return "Upgrade Required", "The client must upgrade to a different protocol." + case 428: + return "Precondition Required", "The request must be conditional." + case 429: + return "Too Many Requests", "Too many requests have been sent in a given amount of time." + case 431: + return "Request Header Fields Too Large", "The request headers are too large." + case 451: + return "Unavailable For Legal Reasons", "The resource is unavailable for legal reasons." + case 500: + return "Internal Server Error", "The server encountered an unexpected condition." + case 501: + return "Not Implemented", "The server does not support the functionality required." + case 502: + return "Bad Gateway", "The server received an invalid response from an upstream server." + case 503: + return "Service Unavailable", "The server is currently unavailable." + case 504: + return "Gateway Timeout", "The server did not receive a timely response from an upstream server." + case 505: + return "HTTP Version Not Supported", "The HTTP version used in the request is not supported." + case 506: + return "Variant Also Negotiates", "The server has an internal configuration error." + case 507: + return "Insufficient Storage", "The server has insufficient storage to complete the request." + case 508: + return "Loop Detected", "The server detected an infinite loop while processing the request." + case 510: + return "Not Extended", "Further extensions to the request are required." + case 511: + return "Network Authentication Required", "Network authentication is required to access this resource." + } + if status < 500 { + return "Unknown Client Error", "A client error occurred." + } + return "Unknown Server Error", "A server error occurred." +}