Skip to content

Return one HTTPError with the server's code and message from both clients - #36

Open
DzmitryHumianiuk wants to merge 6 commits into
fix/openapi-errorcode-integerfrom
fix/api-errors
Open

DzmitryHumianiuk wants to merge 6 commits into
fix/openapi-errorcode-integerfrom
fix/api-errors

Conversation

@DzmitryHumianiuk

@DzmitryHumianiuk DzmitryHumianiuk commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #35. Depends on #33 (stacked on fix/openapi-errorcode-integer; ErrorRS.errorCode is int64 there, which the error model in this PR relies on).

Every failed API call in goRP now returns a *gorp.HTTPError whose text has the request, the HTTP status and what the server said, and which works with errors.As and errors.Is. This applies to the Resty-based clients and to all 358 operations of the generated client, without regenerating pkg/openapi.

Live ReportPortal 6 server, read-only GETs, err.Error() before and after:

Case Before After
401 bad key, generated data failed to match schemas in oneOf(SaveAnalyticsSettings1401Response): json: cannot unmarshal object into Go value of type string GET https://<host>/api/v1/<project>/launch: 401 Unauthorized: invalid_token: Invalid access token
401 bad key, Resty status code error: 401\n{\n "error_description" : "Invalid access token",\n "error" : "invalid_token"\n} same as above
404 missing launch, generated 404 Not Found GET https://<host>/api/v1/<project>/launch/999999999: 404 Not Found: Launch '999999999' not found. Did you use correct Launch ID? (error code 4041)
404 missing project, Resty status code error: 404\n{"errorCode":4040,"message":"Project 'no-such-project-gorp' not found. Did you use correct project name?"} GET https://<host>/api/v1/no-such-project-gorp/launch: 404 Not Found: Project 'no-such-project-gorp' not found. Did you use correct project name? (error code 4040)
400 unknown sort, generated 400 Bad Request GET https://<host>/api/v1/<project>/launch: 400 Bad Request: Sorting parameter noSuchField is not defined (error code 40012)
400 unknown sort, Resty status code error: 400\n{"errorCode":40012,"message":"Sorting parameter noSuchField is not defined"} same as the line above
200 HTML (host + /nosuchservice), Resty <nil>, 0 launches GET https://<host>/nosuchservice/api/v1/<project>/launch: 200 OK: expected JSON but got an HTML page, the host or path is probably not the ReportPortal API

CLI after (before: see the issue):

$ GORP_API_KEY=<bogus> gorp launch list
level=ERROR msg="GET https://<host>/api/v1/<project>/launch: 401 Unauthorized: invalid_token: Invalid access token"
exit code 1
$ gorp quality-gate check --launch-uuid 00000000-0000-0000-0000-000000000000
quality gate check error: GET https://<host>/api/v1/<project>/launch/00000000-0000-0000-0000-000000000000: 404 Not Found: Launch '00000000-0000-0000-0000-000000000000' not found. Did you use correct Launch ID? (error code 4041)
exit code 10

Changes

  • pkg/gorp/errors.go (new): HTTPError moved here from client.go and extended.
    • Existing fields StatusCode and Response (raw body) keep their meaning.
    • New fields: Status, Method, URL, ErrorCode (ReportPortal code, e.g. 4041), Message, OAuthError.
    • Error() is one line: <METHOD> <URL without query>: <status>: <message> (error code N). Without a recognizable message it appends the body with whitespace collapsed and cut to 1024 bytes.
    • Unwrap() returns a *openapi.GenericOpenAPIError on the generated-client path.
    • Is() supports the new sentinels ErrUnauthorized (401), ErrForbidden (403), ErrNotFound (404), ErrNotAPIResponse (2xx HTML).
    • One tolerant parser, newHTTPError, handles every body shape listed in the issue and never fails; unknown shapes fall back to the raw body.
  • OpenAPIErrorMiddleware (exported) is set as Configuration.ResponseMiddleware in newAPIClient. The generated Execute functions call the middleware before their own status handling, so it covers undeclared statuses and the 401 OAuth body that the generated oneOf can't decode. It also rejects a 2xx text/html response, except for the 41 operations that don't return JSON (pkg/gorp/nonjson_operations.go, derived from the specification and checked against it by a test).
  • ChainResponseMiddleware (exported) combines a user's response middleware with OpenAPIErrorMiddleware in the generated client's single middleware slot.
  • defaultHTTPErrorHandler (Resty) builds the same error, and now also rejects a 2xx response with text/html / application/xhtml+xml.
  • pkg/gorp/oauth2.go: a failed token request of WithPasswordOwnerGrantAuth is converted into the same HTTPError, which unwraps to *oauth2.RetrieveError.
  • scripts/openapi-compat/compat.go.tmpl → pkg/openapi/compat.go: NewGenericOpenAPIError(status, body, model). The fields of GenericOpenAPIError are unexported, so this is the only way to keep errors.As(err, &genericErr) working. No generated file is touched.
  • Tests (pkg/gorp/errors_test.go): 11 response shapes × both clients against httptest, the 2xx HTML case on both Resty clients, the generated client's 2xx HTML check and its exemptions, the list of exempt operations recomputed from the specification, token failures of the password grant on all three callers, middleware chaining, error text details. The tests from openapi: decode ErrorRS.errorCode as an integer #33 (openapi_errors_test.go) and the existing HTTPError test pass unchanged.
  • README.md: "Errors" section in the library part. AGENTS.md: file table row and a design note.

Behaviour change for library users

  • Generated client: the dynamic error type is now *gorp.HTTPError.
    • errors.As(err, &genericErr) with *openapi.GenericOpenAPIError keeps working. Body() is the raw body and Error() of the unwrapped value is the status line.
    • Model() is now an ErrorRS value whenever the body is a ReportPortal error, for any status. Before, it was set only for statuses the spec declares. It is nil for other bodies; before, a Spring default body on a declared status gave an empty ErrorRS, and a 401 gave a decode error.
    • A direct type assertion err.(*openapi.GenericOpenAPIError) no longer matches. Use errors.As.
    • The *http.Response returned next to the error is unchanged.
  • Error text changed on both clients. The Resty text was status code error: <code>\n<raw body>. It is now one line with the request, status and message. The numeric status and the server's message are still in the text; the raw JSON is only in HTTPError.Response. Code that matches on the old text breaks.
  • HTTPError has new fields. Keyed literals and field access compile as before; an unkeyed literal HTTPError{404, "x"} doesn't.
  • A 2xx text/html response is now an error on both clients (errors.Is(err, gorp.ErrNotAPIResponse)), not an empty result (Resty) or undefined response type (generated).
    • On the generated client 41 of the 358 operations are exempt: those whose successful response is not JSON according to the specification (GetLaunchReport, GetFile, GetPublicFile, ExportProjects, DownloadAttachment, deletes that return nothing, …). They are recognised by the method and path of the answered request.
    • Only the Content-Type is checked. A page served without it, or as text/plain, still fails in the generated decoder as before.
  • A failed token request of WithPasswordOwnerGrantAuth is an HTTPError too. Text: failed to fetch token: POST <token URL>: <status>: <server's message>. The sentinels match it as well, so errors.Is(err, gorp.ErrNotFound) can mean a wrong token URL; HTTPError.URL tells which request failed. errors.As to *oauth2.RetrieveError keeps working; the old text oauth2: cannot fetch token: … is gone.
  • A user-set ResponseMiddleware still replaces OpenAPIErrorMiddleware, because the generated client reads that field on every call. Keep both with cfg.ResponseMiddleware = gorp.ChainResponseMiddleware(yours, gorp.OpenAPIErrorMiddleware). Middlewares run in the given order and the first error is returned.
  • errors.Is(err, gorp.ErrNotFound) is true for any 404, including a wrong path answered by Spring's default handler. ErrorCode != 0 tells a ReportPortal "entity not found" from a wrong endpoint.
  • The query string is left out of the error text (filters can be long or sensitive); HTTPError.URL has the full URL with any userinfo password redacted.

Not covered

  • All 41 exempt operations accept an HTML 2xx page silently, also from a wrong host. For the file and report operations a login page can't be told from a real HTML file by the response alone; the 37 that declare no response body at all (mostly deletes) have nothing to decode that would fail.
  • A network failure of the token request (no HTTP response) stays a plain wrapped error, not an HTTPError.
  • The *url.Error text that net/http puts in front of a token failure (Get "<API URL with query>": …) contains the query string of the API request. goRP strips the query only from its own part of the text.
  • ReportPortal 6 serves the password-grant endpoint at /api/sso/oauth/token; the /uat/sso/oauth/token URL used in pkg/gorp/reporting_flow_test.go:257 answers 405 on the live ReportPortal 6 server. goRP takes the token URL from the caller's oauth2.Config, so nothing in the library is wrong, but any documentation that names the /uat URL is out of date for ReportPortal 6.

Merge note: #34 also edits scripts/openapi-compat/compat.go.tmpl. This PR only appends one function at the end of the file, so the conflict, if any, is trivial.

Verification

  • go build ./..., go vet ./..., go vet -tags e2e ./e2e/...: clean
  • go test -race -count=1 -cover ./...: pass (pkg/gorp 95.2 %, was 94.7 % on fec2325; internal/commands 77.5 %)
  • go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 run ./...: 0 issues (the pinned version, run without Docker)
  • Live, read-only GETs, library and CLI, on 5a832e4 and on this commit: tables above
  • Not run: task e2e (writes to the server), task generate-openapi-client (needs Docker; not needed, compat.go was re-copied from the template with cp and diff shows them identical)

Investigation log

  1. Reproduce the problem on the base branch. git checkout -b fix/api-errors origin/fix/openapi-errorcode-integer (5a832e4). A small program (below) calls both clients with read-only GETs and prints err.Error(); a script (below) runs the CLI. Both were run on 5a832e4 (git checkout --detach 5a832e4) and on this commit; the outputs are the before/after tables. This confirmed first-hand: the oneOf text for 401, status-only for 404/400 on the generated client, the raw dump on Resty, nil for a 200 HTML page on Resty, and the CLI texts. Spec counts: jq '[.paths[][] | objects | .responses?["401"]?.content? // {} | .[]?.schema | select(.oneOf != null) | [.oneOf[] | (.["$ref"] // .type)] | sort | join(",")] | group_by(.) | map({k: .[0], n: length})' reportportal-api-docs.json → one group, …ErrorRS,string, n = 282; grep -c 'StatusCode == 404' pkg/openapi/api_launch.go → 0; grep -h -c 'StatusCode == 404' pkg/openapi/api_*.go | awk '{s+=$1} END{print s}' → 54.

    Library harness (run as go run ./internal/zzlive with RP_ENDPOINT, RP_PROJECT, RP_API_KEY set; not committed)
    // Read-only live check for the errors PR: prints err.Error() of failing GET requests on both clients.
    // Run with errors-live/run.sh <repo dir> <output file>.
    package main
    
    import (
    	"context"
    	"fmt"
    	"net/url"
    	"os"
    	"strings"
    
    	"github.com/reportportal/goRP/v5/pkg/gorp"
    )
    
    func main() {
    	ctx := context.Background()
    	host, project, key := os.Getenv("RP_ENDPOINT"), os.Getenv("RP_PROJECT"), os.Getenv("RP_API_KEY")
    	u, err := url.Parse(strings.TrimSuffix(strings.TrimRight(host, "/"), "/api"))
    	if err != nil || key == "" {
    		panic("RP_ENDPOINT / RP_API_KEY")
    	}
    	good := gorp.NewClient(u, gorp.WithApiKeyAuth(ctx, key))
    	bad := gorp.NewClient(u, gorp.WithApiKeyAuth(ctx, "00000000-not-a-real-key"))
    
    	show := func(name string, err error) {
    		if err == nil {
    			fmt.Printf("%s\n    <nil>\n", name)
    			return
    		}
    		msg := strings.ReplaceAll(err.Error(), key, "<KEY>")
    		msg = strings.ReplaceAll(msg, u.Host, "<host>")
    		msg = strings.ReplaceAll(msg, project, "<project>")
    		fmt.Printf("%s\n    %s\n", name, strings.ReplaceAll(msg, "\n", `\n`))
    	}
    
    	_, _, err = bad.LaunchAPI.GetProjectLaunches(ctx, project).Execute()
    	show("401 bad key, generated LaunchAPI.GetProjectLaunches:", err)
    	_, err = bad.GetLaunchesByFilterString(ctx, project, "page.size=1")
    	show("401 bad key, Resty GetLaunchesByFilterString:", err)
    
    	_, _, err = good.LaunchAPI.GetLaunch(ctx, "999999999", project).Execute()
    	show("404 missing launch, generated LaunchAPI.GetLaunch:", err)
    	_, err = good.GetLaunchesByFilterString(ctx, "no-such-project-gorp", "page.size=1")
    	show("404 missing project, Resty GetLaunchesByFilterString:", err)
    
    	_, _, err = good.LaunchAPI.GetProjectLaunches(ctx, project).PageSort("noSuchField,asc").Execute()
    	show("400 unknown sort, generated LaunchAPI.GetProjectLaunches:", err)
    	_, err = good.GetLaunchesByFilterString(ctx, project, "page.sort=noSuchField,asc")
    	show("400 unknown sort, Resty GetLaunchesByFilterString:", err)
    
    	// a host whose path lands on the UI, which answers 200 with its index.html
    	ui := gorp.NewClient(u.JoinPath("nosuchservice"), gorp.WithApiKeyAuth(ctx, key))
    	page, err := ui.GetLaunchesByFilterString(ctx, project, "page.size=1")
    	show(fmt.Sprintf("200 HTML (host + /nosuchservice), Resty GetLaunchesByFilterString, %d launches:", len(page.Content)), err)
    }
    CLI script
    #!/bin/sh
    # usage: cli.sh <repo dir> <output file>   (read-only GETs; the key goes through the environment only)
    set -u
    here=$(cd "$(dirname "$0")" && pwd)
    repo=$1
    out=$2
    . "$here/../rp.env"
    host=${RP_ENDPOINT%/}
    host=${host%/api}
    (cd "$repo" && go build -o "$here/gorp-cli" .) || exit 1
    echo '{}' > "$here/empty-config.json"
    export GORP_CONFIG="$here/empty-config.json" GORP_HOST="$host" GORP_PROJECT="$RP_PROJECT"
    redact() {
      sed -e "s#$host#https://<host>#g" -e "s#$RP_PROJECT#<project>#g" -e "s#$RP_API_KEY#<KEY>#g" -e 's/^time=[^ ]* //'
    }
    {
      echo '$ GORP_API_KEY=<bogus> gorp launch list'
      GORP_API_KEY=00000000-not-a-real-key "$here/gorp-cli" launch list 2>&1
      echo "exit code $?"
      echo '$ gorp quality-gate check --launch-uuid 00000000-0000-0000-0000-000000000000'
      GORP_API_KEY=$RP_API_KEY "$here/gorp-cli" quality-gate check --launch-uuid 00000000-0000-0000-0000-000000000000 2>&1
      echo "exit code $?"
    } | redact > "$out"
    rm -f "$here/gorp-cli" "$here/empty-config.json"
    cat "$out"
  2. Why the generated client shows only the status. pkg/openapi/client.go:779 (Error() returns e.error), :794 (formatErrorMessage reads only Title/Detail). The 401 branch decodes into SaveAnalyticsSettings1401Response and puts the decode error into the text: pkg/openapi/api_launch.go:3246-3256.

  3. Which hook exists. pkg/openapi/configuration.go:84,98: ResponseMiddleware func(*http.Response, []byte) error. Every Execute calls it after reading the body and before the StatusCode >= 300 branch, and returns its error together with the response: pkg/openapi/api_launch.go:3234-3239. Counted: grep -c "cfg.ResponseMiddleware(" pkg/openapi/api_*.go sums to 358, same as grep -c "Execute(r ". So one middleware covers all operations, declared status or not, with no regeneration. newAPIClient (pkg/gorp/client.go) did not set it.

  4. Extend HTTPError, no second type. HTTPError{StatusCode, Response} was already exported and matched with errors.As in pkg/gorp/reporting_flow_test.go:217. New fields are additive. The old test passes unchanged.

  5. Keeping errors.As(err, *openapi.GenericOpenAPIError). openapi: decode ErrorRS.errorCode as an integer #33's test (pkg/gorp/openapi_errors_test.go:110-124) relies on it, including Body(), the status in the text and Model() as an ErrorRS value. The struct fields are unexported (client.go:772-776), so a constructor has to live in package openapi. The only hand-written file there is compat.go, sourced from scripts/openapi-compat/compat.go.tmpl (Taskfile.yml:94 copies it). Added NewGenericOpenAPIError to the template and re-copied with cp; diff scripts/openapi-compat/compat.go.tmpl pkg/openapi/compat.go is empty. HTTPError.Unwrap() returns it. openapi: decode ErrorRS.errorCode as an integer #33's test passes unmodified.

  6. Model() semantics. Set only when the body has errorCode (or a bare message) and decodes into the generated ErrorRS; nil for OAuth, Spring default and non-JSON bodies. This removes the "empty non-nil model" trap for the Spring body. errorCode is read through json.RawMessage, so a string code still fills HTTPError.ErrorCode although the generated model (int64 after openapi: decode ErrorRS.errorCode as an integer #33) can't hold it; the test case "ErrorRS with the code as a string" covers that.

  7. Telling the JSON shapes apart. error is a string in both the OAuth and the Spring default body. OAuth is recognised by error_description, or by error without status/path; Spring default by status plus path or timestamp. The Spring body only repeats the status and path, so for a 404 the text gets the hint "no such endpoint, check the host and the path"; other statuses fall back to the raw body. The hint is not stored in Message, which holds only what the server said.

  8. Empty 401. The reason is only in WWW-Authenticate; error and error_description parameters are extracted with a regexp into OAuthError/Message, otherwise the header is shown in the text as is (as a hint, not in Message).

  9. Resty side. resty.dev/v3@v3.0.0-rc.4/middleware.go:545-590 (MiddlewareResponseAutoParse): for a JSON 4xx without a registered error type the body is not consumed, and for an unknown content type it is read with readAll; response.go:149-151,258-262 (Bytes() → readIfRequired). So the handler can read the body in every case; the tests check HTTPError.Response equals the sent body for JSON, text, HTML and empty bodies. The handler error is returned by the request through client.go:2569-2575.

  10. 2xx HTML: Resty only. Every Resty call in pkg/gorp uses SetResult with a JSON model (grep -n "SetResult" pkg/gorp/*.go), so HTML is never valid there. For the generated client I listed the Execute functions that send only Accept: application/json but return no model: awk '/^func \(a \*[A-Za-z]+\) [A-Za-z0-9]+Execute\(/{sig=$0} /localVarHTTPHeaderAccepts := \[\]string\{"application\/json"\}$/{print sig}' pkg/openapi/api_*.go | grep -v "Execute(r [A-Za-z0-9]*) (\*\?[A-Z\[m]". Among them: GetLaunchReportExecute, GetFileExecute, GetPublicFileExecute, ExportProjectsExecute, DownloadAttachmentExecute (*os.File) and others. A middleware sees only the response, so a blanket HTML check would break report and attachment downloads. Left as is and covered by TestOpenAPIErrorMiddlewareLeavesSuccessAlone. Superseded: see the follow-up comment, the middleware now matches the request against the operations that don't return JSON.

  11. Status threshold. The middleware acts from 300 up, matching the generated code (api_launch.go:3241). The Resty handler keeps its previous threshold of 400 (IsStatusFailure).

  12. CLI unaffected in logic. grep -rn "StatusCode" internal/commands/*.go finds only quality_gate.go:201 (isPermanentHTTPStatus reads the *http.Response, which is still returned). e2e/e2e_helpers_test.go:213-225 also reads resp.StatusCode. CLI output only gains the better text.

  13. Password grant. pkg/gorp/oauth2.go:21-25: a failed token request returns from Token() inside the OAuth2 transport, so no API response reaches either handler. Out of scope here. Superseded: see the follow-up comment.

  14. Sentinels. ErrUnauthorized, ErrForbidden, ErrNotFound, ErrNotAPIResponse through HTTPError.Is: three lines each and they give both clients one way to test a status. No error-code constants were added.

  15. Error text. One line (slog-friendly), request first, query string dropped, URL.Redacted() for userinfo. Raw body cut at 1024 bytes on a rune boundary only in the text.

  16. After. Same program and script on the commit (the "After" outputs). Lint: go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 run ./... → 0 issues; formatting with the same binary's fmt on the touched files.

🤖 Generated with Claude Code

ghDmitry and others added 6 commits November 27, 2026 16:51
…ents

A failed call through the generated client reported only the HTTP status
("404 Not Found"), or a oneOf decoding error instead of the status for a
rejected API key, while the Resty clients dumped the raw body.

gorp.HTTPError now carries the status, request, ReportPortal error code and
message, OAuth error and the raw body. Both clients build it with the same
tolerant parser: the generated client through Configuration.ResponseMiddleware
(all operations, declared status or not), the Resty clients through their
response handler. Errors of the generated client still unwrap to
*openapi.GenericOpenAPIError. errors.Is works with ErrUnauthorized,
ErrForbidden, ErrNotFound and ErrNotAPIResponse.

The Resty clients now fail on a 2xx text/html response (wrong host or path)
instead of returning an empty result.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A token request of WithPasswordOwnerGrantAuth fails inside the OAuth2
transport, before any API response exists, so neither client's response
handling saw it and the caller got the oauth2 package's two-line text.

The token source now converts *oauth2.RetrieveError into the same
HTTPError as a failed API call: request (the token endpoint), status,
OAuth error and description, or ReportPortal's error code and message
(ReportPortal 6 answers a wrong password with an ErrorRS body).
HTTPError.Unwrap returns the RetrieveError, so errors.As to it keeps
working. A token "error" answered with status 200 is not mistaken for
an HTML page: the 2xx HTML case moved out of newHTTPError into
newNotAPIError.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The generated client has a single ResponseMiddleware slot, read from
the Configuration on every call, so a middleware assigned by the user
silently replaced OpenAPIErrorMiddleware and brought the generated
error texts back.

ChainResponseMiddleware combines middlewares into one: they run in the
given order, nil entries are skipped, the first error wins. With the
user's middleware first it sees failed responses too and the call still
returns an HTTPError.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…tions

A wrong host or base path lands on the UI or a login page, which
answers 200 with HTML. The Resty clients already report that as
ErrNotAPIResponse; the generated client failed with "undefined response
type", because its middleware could not tell a JSON operation from one
that legitimately returns a file or an HTML report.

OpenAPIErrorMiddleware now matches the answered request (method + path
template, compared with the end of the path) against nonJSONOperations
and returns ErrNotAPIResponse for a 2xx text/html response of any other
operation. The list is derived from pkg/openapi/api/openapi.yaml: the
41 operations with no application/json content in a 2xx response, or
with that content declared as a binary string. A test recomputes it from
the YAML and prints the list to paste when it drifts; another one checks
that no JSON operation's path fits an exempt template.

go.yaml.in/yaml/v3 becomes a direct (test-only) dependency; it was
already in go.sum through testify.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
README "Errors": how to keep OpenAPIErrorMiddleware next to a middleware
of your own, which operations are exempt from the HTML check, what a
failed password-grant token request looks like. AGENTS.md: file table
row for nonjson_operations.go and the rule to update the list after
regenerating the client.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The oauth2 package reads the "error" field of any JSON body into
RetrieveError.ErrorCode. For a wrong token URL answered by Spring's
default handler ({"status":404,"error":"Not Found","path":…}) the
fallback in newTokenError copied it, and the text became
"404 Not Found: Not Found" instead of the "no such endpoint" hint.

The fallback now applies only to a body that is not a JSON object,
the form-encoded case it exists for. README: the status sentinels
match a token failure as well.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@DzmitryHumianiuk

Copy link
Copy Markdown
Member Author

Follow-up: the three gaps listed in the description are closed

Five new commits on top of fec2325, no force-push:

Commit What
0fa28f2 A failed password-grant token request is an HTTPError
8c2eda2 gorp.ChainResponseMiddleware keeps OpenAPIErrorMiddleware next to a user middleware
ee63cc6 The generated client rejects a 2xx HTML page, except for operations that don't return JSON
9f5c6ec README and AGENTS.md
89fc8a9 Token errors: error of a non-OAuth JSON body (Spring's default 404) is not taken for an OAuth error

Live ReportPortal 6 server, err.Error() on fec2325 and on 89fc8a9 (\n is a line break in the original text):

Case Before (fec2325) After (89fc8a9)
Password grant, wrong credentials, token URL /api/sso/oauth/token, both clients Get "https://<host>/api/v1/<project>/launch?page.size=1": failed to fetch token: oauth2: cannot fetch token: 400 Bad Request\nResponse: {"errorCode":4003,"message":"You do not have enough permissions. Bad credentials"}; errors.As(*gorp.HTTPError) false Get "https://<host>/api/v1/<project>/launch?page.size=1": failed to fetch token: POST https://<host>/api/sso/oauth/token: 400 Bad Request: You do not have enough permissions. Bad credentials (error code 4003); errors.As true for *gorp.HTTPError and for *oauth2.RetrieveError
Same, token URL /uat/sso/oauth/token (ReportPortal 5 location; nginx answers here) … failed to fetch token: oauth2: cannot fetch token: 405 Method Not Allowed\nResponse: <html>\n<head><title>405 Not Allowed</title></head>\n<body>\n… (8 lines) … failed to fetch token: POST https://<host>/uat/sso/oauth/token: 405 Method Not Allowed: <html> <head><title>405 Not Allowed</title></head> <body> <center><h1>405 Not Allowed</h1></center> <hr><center>nginx</center> </body> </html>
200 HTML (base path /nosuchservice/api), generated LaunchAPI.GetProjectLaunches undefined response type; not an HTTPError GET https://<host>/nosuchservice/api/v1/<project>/launch: 200 OK: expected JSON but got an HTML page, the host or path is probably not the ReportPortal API; errors.Is(err, gorp.ErrNotAPIResponse) true, errors.As(*openapi.GenericOpenAPIError) true
404 missing launch, user middleware chained before ours n/a (no chaining helper) user middleware saw 404 Not Found; error is GET https://<host>/api/v1/<project>/launch/999999999: 404 Not Found: Launch '999999999' not found. Did you use correct Launch ID? (error code 4041)

The leading Get "…?page.size=1": is the *url.Error that net/http puts around any transport failure. It is not
produced by goRP and it does contain the query string of the API request that needed the token.

Changes

  • Token errors (pkg/gorp/oauth2.go, pkg/gorp/errors.go)
    • passwordGrantTokenSource.Token converts an *oauth2.RetrieveError with newTokenError. The result is
      failed to fetch token: <HTTPError>; the prefix is unchanged.
    • The HTTPError has the token request (Method, URL), the status, the raw body, and whatever the body explains:
      ErrorCode + Message for a ReportPortal error body, OAuthError + Message for an OAuth one. For a
      form-encoded OAuth body, which only the oauth2 package parses, the two fields are copied from the RetrieveError.
      For a JSON body they are not: oauth2 reads error of any JSON into RetrieveError.ErrorCode, also from
      Spring's default {"status":404,"error":"Not Found","path":…}, which would give 404 Not Found: Not Found
      instead of the "no such endpoint" hint (89fc8a9, found in review, test case added first and seen failing).
    • HTTPError.Unwrap() returns the *oauth2.RetrieveError, so errors.As(err, &retrieveErr) keeps working.
    • Refactoring needed for that: the "2xx means HTML page" branch moved out of newHTTPError into newNotAPIError,
      and the part that doesn't read the body became baseHTTPError. The oauth2 package also returns a
      RetrieveError for a 200 response with an error field; without the move it would have been reported as
      "expected JSON but got an HTML page".
  • Chaining (pkg/gorp/errors.go)
    • New exported ChainResponseMiddleware(middlewares ...openapi.ResponseMiddlewareFunction) openapi.ResponseMiddlewareFunction.
      Runs them in the given order, skips nil, returns the first error and doesn't call the rest.
    • Usage: client.GetConfig().ResponseMiddleware = gorp.ChainResponseMiddleware(mine, gorp.OpenAPIErrorMiddleware).
    • Nothing else changes: NewClient still installs OpenAPIErrorMiddleware alone.
  • 2xx HTML on the generated client (pkg/gorp/errors.go, new pkg/gorp/nonjson_operations.go)
    • OpenAPIErrorMiddleware returns an HTTPError matching ErrNotAPIResponse for a 2xx response with
      Content-Type: text/html or application/xhtml+xml, unless the answered request is one of 41 operations in
      nonJSONOperations. The error unwraps to *openapi.GenericOpenAPIError like the other errors of this client.
    • nonJSONOperations holds METHOD /path/{template} strings. A request matches when the method is equal and the
      template fits the end of URL.EscapedPath() segment by segment ({…} fits any segment). The end is used
      because the base path (/api by default, Configuration.Servers) and any proxy prefix come first.
    • A response without Request passes, as before.
  • Dependency: go.yaml.in/yaml/v3 v3.0.5 moved from the indirect to the direct require block of go.mod. Only a
    test imports it. go.sum is unchanged (testify already required it).
  • Tests
    • TestPasswordGrantTokenFailureIsHTTPError: httptest token endpoint, 6 response shapes (ReportPortal 6 ErrorRS,
      OAuth JSON, form-encoded, error with status 200, HTML 502, Spring's default 404) × 3 callers (generated client, Resty Client,
      ReportingClient), through NewClient(…WithPasswordOwnerGrantAuth…). Asserts both errors.As targets, the
      fields, the text, and that no request reaches the API.
    • TestNonJSONOperationsMatchSpec: recomputes the list from pkg/openapi/api/openapi.yaml and compares for
      equality. On a difference the failure message prints the list ready to paste.
    • TestNonJSONOperationsDoNotShadowJSONOperations: no JSON operation's path fits an exempt template (empty today).
    • TestIsNonJSONOperation (17 URLs: prefix, trailing slash, query, %2F, wrong method),
      TestGeneratedClientRejectsHTMLSuccess (JSON operation, report and file operations, custom base path, redirect
      to a login page), TestOpenAPIErrorMiddlewarePassesWhatItCannotJudge, TestChainResponseMiddleware,
      TestUserResponseMiddlewareWithOpenAPIErrorMiddleware.
    • Removed: TestOpenAPIErrorMiddlewareLeavesSuccessAlone. It asserted the old behaviour (a JSON operation on an
      HTML page is not an HTTPError).

Behaviour change for library users

  • Generated client: a 2xx HTML response to a JSON operation is now *gorp.HTTPError (ErrNotAPIResponse).
    Before it was the generated undefined response type error. The *http.Response is still returned next to it.
  • Password grant: the text of a failed token request changed (table above), and the status sentinels now match
    it: errors.Is(err, gorp.ErrUnauthorized) / ErrForbidden / ErrNotFound are true when the token endpoint answers
    401 / 403 / 404. So ErrNotFound from GetLaunch can mean a wrong token URL, not a missing launch;
    HTTPError.URL tells which request failed. Code that matched oauth2: cannot fetch token in the text breaks;
    errors.As to *oauth2.RetrieveError does not.
  • ChainResponseMiddleware is new API. Assigning Configuration.ResponseMiddleware directly still replaces
    OpenAPIErrorMiddleware: the generated code reads that field on every call, so goRP can't prevent it.

Verification

  • go build ./..., go vet ./..., go vet -tags e2e ./e2e/...: clean
  • go test -race -count=1 -cover ./...: pass (pkg/gorp 95.2 %, internal/commands 77.5 %)
  • go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 run ./...: 0 issues. Also run on each of
    the first two commits' trees before committing; go test ./pkg/gorp/ passed there too.
  • Live, read-only: the table above (harness below). The token check sends one password-grant request per call with
    the made-up user gorp-no-such-user.
  • Live regression: the PR's original harness and CLI script re-run on 89fc8a9; output is byte-identical to the
    "After" outputs of the description (diff empty for both).

Investigation log

  1. Token errors: where they come from. pkg/gorp/oauth2.go:22 calls config.PasswordCredentialsToken. In
    golang.org/x/oauth2@v0.38.0/internal/token.go:269-327 a *RetrieveError{Response, Body, ErrorCode, ErrorDescription}
    is returned when the status is not 2xx or the parsed body has an error field ("some unorthodox servers
    respond 200 in error case", line 322). JSON is parsed by default, a query string for
    application/x-www-form-urlencoded and text/plain (lines 279-289).
    d=$(go list -m -f '{{.Dir}}' golang.org/x/oauth2); sed -n 264,330p $d/internal/token.go.
  2. Reuse of the body parser. RetrieveError.Response is the *http.Response of the token request, with
    Request set, and Body has the bytes. That is exactly what newHTTPError(resp, body) takes. Its < 300 branch
    had to go first (point 1, status 200), so the HTML case became newNotAPIError (pkg/gorp/errors.go:235) and is
    chosen by the two callers that know they have a 2xx HTML response.
  3. What ReportPortal 6 really answers. service-api
    src/main/java/com/epam/reportportal/base/ws/controller/AuthController.java:62 maps POST /sso/oauth/token in the
    API service and throws ReportPortalException for a bad request, so the error body is an ErrorRS, not an OAuth
    error. Live: /api/sso/oauth/token → 400 {"errorCode":4003,"message":"You do not have enough permissions. Bad credentials"};
    /uat/sso/oauth/token → 405 from nginx with an HTML body. Both are test cases now. newHTTPError already filled
    ErrorCode/Message for the first one.
  4. The error still reaches the caller through three wrappers. oauth2.Transport.RoundTrip returns the token
    error, http.Client.Do wraps it in *url.Error, then Resty or the generated client return it. The test goes through
    NewClient/NewReportingClient and asserts errors.As for both types on all three callers, plus
    errors.Unwrap(httpErr) == retrieveErr.
  5. 2xx HTML: which operations may return non-JSON. Rule: an operation is exempt when no 2xx response has
    application/json content, or that content's schema is format: binary. The first half gives 38 operations (37 with
    no content at all, 1 with application/octet-stream). The second half adds 3 that the specification labels as JSON
    but that are file downloads: GET /users/{user_id}/avatar,
    GET /v1/project/{projectKey}/tms/attachment/{attachmentId} (pkg/openapi/api/openapi.yaml, operation
    downloadAttachment, 200 → application/json → type: string, format: binary) and its /thumbnail. Cross-check
    against the generated code: grep -h "Execute(r .*os\.File" pkg/openapi/api_*.go lists exactly these three
    (DownloadAttachmentExecute, DownloadThumbnailExecute, GetUsersUserIdAvatarExecute). Total 41 of 358.
    To recompute: go test -run TestNonJSONOperationsMatchSpec ./pkg/gorp/ (delete a line of the list to see the
    printed replacement).
  6. Why match on the request. The middleware gets (*http.Response, []byte) only
    (pkg/openapi/configuration.go:84); the operation is not passed. resp.Request has the method and URL, and the
    generated code builds the URL as localBasePath + "/v1/{projectKey}/launch/…" (pkg/openapi/api_launch.go:69-74),
    localBasePath being Servers[0].URL = /api (configuration.go:107-109). A user may change Servers or sit
    behind a prefix, so templates are compared with the end of the path. EscapedPath() is used so that a %2F in a
    file name or id stays inside one segment.
  7. Can an exempt template swallow a JSON operation? It could if a JSON operation's path had fixed segments where
    an exempt template has parameters. Computed for all 317 JSON operations × 41 templates with the real matcher:
    none today. The test fails if a regenerated specification introduces one. If that ever happens the JSON operation
    only loses the HTML check (old behaviour), it does not gain a false error.
  8. Redirects. After a redirect resp.Request is the last request (net/http), e.g. /login. It matches no
    template, so a login page is an error even when the operation called was a report download. Covered by the
    "redirect to an HTML page" subtest.
  9. Chaining: why a helper and not automatic wrapping. a.client.cfg.ResponseMiddleware is a plain struct field
    read on every Execute (pkg/openapi/api_launch.go:120-121), and GetConfig() hands out the pointer. Whatever
    NewClient puts there, a later assignment replaces. ClientOption is func() *http.Client
    (pkg/gorp/client.go:33), so a constructor option would mean a new constructor. One composer function is the
    smallest API that solves it; the order is the caller's (user's first to observe failures, last to see only
    successes).
  10. Live. errors-live/gaps-run.sh <repo> <out> with gaps-main.go.txt on 89fc8a9 and with
    gaps-before-main.go.txt (the same minus the chaining part, which doesn't compile there) on
    git checkout --detach fec2325. Then the description's run.sh and cli.sh on 89fc8a9, diff against the
    earlier outputs: empty.
Harness (run as go run ./internal/zzlive with RP_ENDPOINT, RP_PROJECT, RP_API_KEY set; not committed)
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"

	"golang.org/x/oauth2"

	"github.com/reportportal/goRP/v5/pkg/gorp"
	"github.com/reportportal/goRP/v5/pkg/openapi"
)

func main() {
	ctx := context.Background()
	host, project, key := os.Getenv("RP_ENDPOINT"), os.Getenv("RP_PROJECT"), os.Getenv("RP_API_KEY")
	u, err := url.Parse(strings.TrimSuffix(strings.TrimRight(host, "/"), "/api"))
	if err != nil || key == "" {
		panic("RP_ENDPOINT / RP_API_KEY")
	}

	redact := func(s string) string {
		s = strings.ReplaceAll(s, key, "<KEY>")
		s = strings.ReplaceAll(s, u.Host, "<host>")
		s = strings.ReplaceAll(s, project, "<project>")

		return strings.ReplaceAll(s, "\n", `\n`)
	}
	show := func(name string, err error) {
		if err == nil {
			fmt.Printf("%s\n    <nil>\n", name)
			return
		}
		var httpErr *gorp.HTTPError
		var retrieveErr *oauth2.RetrieveError
		var apiErr *openapi.GenericOpenAPIError
		fmt.Printf("%s\n    %s\n    [HTTPError=%t ErrNotAPIResponse=%t RetrieveError=%t GenericOpenAPIError=%t]\n",
			name, redact(err.Error()), errors.As(err, &httpErr), errors.Is(err, gorp.ErrNotAPIResponse),
			errors.As(err, &retrieveErr), errors.As(err, &apiErr))
	}

	good := gorp.NewClient(u, gorp.WithApiKeyAuth(ctx, key))

	// 1. password grant with made-up credentials: the token request fails, no API request is made
	// (ReportPortal 6 serves the token endpoint from the API service; /uat is where ReportPortal 5 had it)
	for _, tokenPath := range []string{"api/sso/oauth/token", "uat/sso/oauth/token"} {
		oauthCfg := &oauth2.Config{
			ClientID:     "ui",
			ClientSecret: "uiman",
			Endpoint:     oauth2.Endpoint{TokenURL: u.JoinPath(tokenPath).String(), AuthStyle: oauth2.AuthStyleInHeader},
		}
		pw := gorp.NewClient(u, gorp.WithPasswordOwnerGrantAuth(ctx, oauthCfg, "gorp-no-such-user", "gorp-no-such-password"))
		_, _, err = pw.LaunchAPI.GetProjectLaunches(ctx, project).PageSize(1).Execute()
		show("password grant, bad credentials, token URL /"+tokenPath+", generated LaunchAPI.GetProjectLaunches:", err)
		_, err = pw.GetLaunchesByFilterString(ctx, project, "page.size=1")
		show("password grant, bad credentials, token URL /"+tokenPath+", Resty GetLaunchesByFilterString:", err)
	}

	// 2. 2xx HTML on the generated client: a base path that lands on the UI, which answers 200 with its index.html
	ui := gorp.NewClient(u, gorp.WithApiKeyAuth(ctx, key))
	ui.GetConfig().Servers = openapi.ServerConfigurations{{URL: "/nosuchservice/api"}}
	_, resp, err := ui.LaunchAPI.GetProjectLaunches(ctx, project).PageSize(1).Execute()
	show(fmt.Sprintf("200 HTML (base path /nosuchservice/api), generated LaunchAPI.GetProjectLaunches, response %s %q:",
		status(resp), contentType(resp)), err)

	// ... while a real HTML report of an existing launch is not an error
	page, _, err := good.LaunchAPI.GetProjectLaunches(ctx, project).PageSize(1).PageSort("startTime,desc").Execute()
	if err != nil || len(page.GetContent()) == 0 {
		show("no launch to take a report of:", err)
	} else {
		resp, err = good.LaunchAPI.GetLaunchReport(ctx, page.GetContent()[0].GetId(), project).View("html").Execute()
		show(fmt.Sprintf("HTML report of an existing launch, generated LaunchAPI.GetLaunchReport, response %s %q:",
			status(resp), contentType(resp)), err)
	}

	// 3. a middleware of the user's own chained before gorp's
	var seen []string
	chained := gorp.NewClient(u, gorp.WithApiKeyAuth(ctx, key))
	chained.GetConfig().ResponseMiddleware = gorp.ChainResponseMiddleware(
		func(resp *http.Response, _ []byte) error {
			seen = append(seen, resp.Status)
			return nil
		},
		gorp.OpenAPIErrorMiddleware,
	)
	_, _, err = chained.LaunchAPI.GetLaunch(ctx, "999999999", project).Execute()
	show(fmt.Sprintf("404 missing launch, chained middlewares, user's middleware saw %v:", seen), err)
	_, _, err = chained.LaunchAPI.GetProjectLaunches(ctx, project).PageSize(1).Execute()
	show(fmt.Sprintf("200 launch list, chained middlewares, user's middleware saw %v:", seen), err)
}

func status(resp *http.Response) string {
	if resp == nil {
		return "<no response>"
	}

	return resp.Status
}

func contentType(resp *http.Response) string {
	if resp == nil {
		return ""
	}

	return resp.Header.Get("Content-Type")
}

Not verified

  • A real HTML launch report against the live server. The project has no launches, so the harness printed
    "no launch to take a report of". Creating one for the check was attempted and denied by the permission system of the agent session (it is a write
    to the server; the live checks are read-only). The
    exemption is covered only by httptest (GetLaunchReport and GetFile on an HTML 200 return no error). A script
    that creates a gorp-wave-html-report launch, downloads its HTML report and deletes the launch is ready but was
    not run: errors-live/gaps-report-main.go.txt.
  • A real OAuth-shaped token error ({"error":"invalid_grant",…}). The ReportPortal 6 server answers with an
    ErrorRS body; the OAuth shapes are httptest only. No ReportPortal 5 server was available.
  • A successful password-grant login against the live server (no user password available). The success path is
    not touched by these commits.
  • task e2e (writes to the server) and task generate-openapi-client (needs Docker; pkg/openapi is not changed).

@DzmitryHumianiuk

Copy link
Copy Markdown
Member Author

Local ReportPortal 6.0.0 check (same build as demo): the prepared probe ran. It created a gorp-wave-html-report launch, called LaunchAPI.GetLaunchReport(…).View("html") through the generated client with OpenAPIErrorMiddleware, and deleted the launch. Result: 200 OK, Content-Type: text/html, err == nil. So the exemption list lets a real HTML report through, while a JSON operation answered with HTML is still rejected (shown earlier on demo).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants