From 721bd3b4a8d56623a0cc82f9b595f520cf1b6518 Mon Sep 17 00:00:00 2001 From: "Customer.io Open Source Bot" Date: Mon, 23 Nov 2026 17:02:49 -0500 Subject: [PATCH] Add Customer.io CLI source CioCliPublicExport-RevId: 2a4c9f8e1b7e3077e9f41d94aa71b534064a5ffd --- README.md | 20 +++ cmd/api.go | 12 +- cmd/api_preflight_test.go | 24 ++- cmd/auth.go | 4 + cmd/auth_test.go | 6 + cmd/billing_add_funds.go | 19 ++- cmd/billing_status.go | 2 +- cmd/funds_warning.go | 3 +- cmd/helpers.go | 41 +++-- cmd/helpers_test.go | 118 ++++++++++++++ cmd/root.go | 33 +++- cmd/root_test.go | 88 +++++++++++ cmd/run_report.go | 93 +++++++++++ cmd/run_report_test.go | 246 ++++++++++++++++++++++++++++++ cmd/schema.go | 5 + cmd/selfheal.go | 2 + internal/client/client.go | 47 ++++-- internal/client/track.go | 2 +- internal/output/error.go | 17 ++- internal/output/process.go | 4 +- internal/routes/pathindex.go | 19 ++- internal/routes/pathindex_test.go | 15 ++ internal/runreport/report.go | 212 +++++++++++++++++++++++++ internal/runreport/report_test.go | 158 +++++++++++++++++++ internal/skills/skills.go | 7 +- internal/useragent/useragent.go | 3 + 26 files changed, 1143 insertions(+), 57 deletions(-) create mode 100644 cmd/helpers_test.go create mode 100644 cmd/run_report.go create mode 100644 cmd/run_report_test.go create mode 100644 internal/runreport/report.go create mode 100644 internal/runreport/report_test.go diff --git a/README.md b/README.md index 0cc02ed..001193e 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,7 @@ cio api /v1/environments/{environment_id}/campaigns \ | `--dry-run` | | Validate + print request, skip execution | | `--api-url ` | | API base URL override | | `--timeout ` | `CIO_TIMEOUT` | HTTP request timeout (default: 30s) | +| | `CIO_RUN_REPORT` | Write a JSON summary of the run to this file | | `--page ` | | Page number | | `--limit ` | | Page size | | `--page-all` | | Auto-paginate, emit NDJSON | @@ -287,6 +288,25 @@ caller deadline stops retries. Repeated timeouts can therefore take longer than and leaves any earlier pages in stdout; callers must check its exit status before using the output as a complete result. +## Run Report + +Set `CIO_RUN_REPORT` to a file path and each run writes one JSON object there as it exits, for tools +that run `cio` and log what happened. It never holds a value you passed (paths, parameters, bodies, +jq expressions) or error text. + +| Field | Meaning | +|---|---| +| `version` | CLI version | +| `command` | Command path below `cio`, such as `api` or `send email`; empty when the command was not recognized | +| `exit_code` | Process exit code | +| `error_code` | The command's structured error code (`VALIDATION_ERROR`, `API_ERROR`, ...); null on success | +| `reason` | Why the run failed, null on success: `not_in_spec`, `wrong_method`, `missing_path_param`, `invalid_params`, `invalid_json`, `jq_error`, `unknown_flag`, `arg_count`, `unknown_command`, `schema_not_found`, `http_error`, `auth`, `network` or `other` | +| `method` | HTTP method of the last request, or null | +| `route` | Spec path template of the last request, such as `/v1/environments/{environment_id}/campaigns`, or null | +| `route_match` | `matched`, `not_in_spec` (also when the path exists only for another method) or `not_checked` | +| `requests` | API requests and skills downloads sent, counting retries and `--page-all` pages; token exchanges, spec downloads and the CLI's own housekeeping calls are left out | +| `status` | HTTP status of the last request, or null when it got no response | + ## Exit Codes | Code | Meaning | diff --git a/cmd/api.go b/cmd/api.go index a0e296b..fbb3276 100644 --- a/cmd/api.go +++ b/cmd/api.go @@ -13,6 +13,7 @@ import ( "github.com/customerio/cli/internal/client" "github.com/customerio/cli/internal/output" "github.com/customerio/cli/internal/routes" + "github.com/customerio/cli/internal/runreport" "github.com/customerio/cli/internal/validate" "github.com/spf13/cobra" ) @@ -79,6 +80,7 @@ func runAPI(cmd *cobra.Command, args []string) error { // A {placeholder} is only filled in the path; after the ? it would go out as the literal text. if pathParamRegex.MatchString(inlineQuery) { err := fmt.Errorf("the query string in the path has a {placeholder}, which is only filled in the path: write the value itself, or pass it with --params") + runreport.Reason("invalid_params") output.PrintError(output.CodeValidationError, err.Error(), nil) return err } @@ -101,6 +103,7 @@ func runAPI(cmd *cobra.Command, args []string) error { } httpMethod := resolveMethod(methodFlag, jsonBody != nil || len(fileParts) > 0) + runreport.Method(httpMethod) // Parse --params: separate path params from query params. paramsRaw, _ := cmd.Flags().GetStringArray("params") @@ -291,13 +294,18 @@ func preflightPath(cmd *cobra.Command, c *client.Client, httpMethod, resolvedPat } } - if pathAllowed(idx, httpMethod, resolvedPath) { + if template, matched := idx.Lookup(httpMethod, resolvedPath); matched { + runreport.MatchedRoute(template) + return nil + } + if !idx.Covers(resolvedPath) { return nil } // The shape exists but not for this verb — a different mistake, and one // the caller fixes by changing -X rather than the path. if allowed := idx.MethodsFor(resolvedPath); len(allowed) > 0 { + runreport.RejectRoute("wrong_method") // Name the fix, not just the verb: the method is usually implicit here // (GET unless a body was passed), so the caller needs to be told to // set it rather than left to infer that from the list. @@ -372,6 +380,7 @@ func preflightPath(cmd *cobra.Command, c *client.Client, httpMethod, resolvedPat err = fmt.Errorf( "%s %s is not an endpoint in the API spec, so the request was not sent; %s", httpMethod, resolvedPath, hint) + runreport.RejectRoute("not_in_spec") output.PrintError(output.CodeValidationError, err.Error(), map[string]any{ "method": httpMethod, "path": resolvedPath, @@ -487,6 +496,7 @@ func resolvePathTemplate(pathTemplate string, pathParams map[string]string) (str // Check for unresolved placeholders. if matches := pathParamRegex.FindAllStringSubmatch(path, -1); len(matches) > 0 { + runreport.Reason("missing_path_param") var missing []string for _, m := range matches { missing = append(missing, m[1]) diff --git a/cmd/api_preflight_test.go b/cmd/api_preflight_test.go index 660d4be..9b0b84a 100644 --- a/cmd/api_preflight_test.go +++ b/cmd/api_preflight_test.go @@ -49,10 +49,11 @@ func preflightSpec() string { // the CLI, spec paths so a test can assert the check itself fetches nothing. type preflightServer struct { *httptest.Server - mu sync.Mutex - spec string - apiPaths []string - specPaths []string + mu sync.Mutex + spec string + tokenStatus int + apiPaths []string + specPaths []string } // setSpec changes the published Journeys spec, as a deploy would. @@ -84,6 +85,10 @@ func (p *preflightServer) forget() { // newPreflightServer starts the server without priming the spec cache, for // tests that care about a cold cache. func newPreflightServer(t *testing.T) *preflightServer { + return newPreflightServerWithAPI(t, nil) +} + +func newPreflightServerWithAPI(t *testing.T, api http.HandlerFunc) *preflightServer { t.Helper() t.Setenv("HOME", t.TempDir()) t.Setenv("CIO_TOKEN", "sa_live_test123") @@ -93,6 +98,13 @@ func newPreflightServer(t *testing.T) *preflightServer { p.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/v1/service_accounts/oauth/token": + p.mu.Lock() + status := p.tokenStatus + p.mu.Unlock() + if status != 0 { + w.WriteHeader(status) + return + } _, _ = w.Write([]byte(`{"access_token":"jwt-test-session","token_type":"Bearer","expires_in":3600}`)) return case "/v1/openapi.json", "/cdp/api/openapi.json": @@ -117,6 +129,10 @@ func newPreflightServer(t *testing.T) *preflightServer { p.mu.Lock() p.apiPaths = append(p.apiPaths, r.URL.Path) p.mu.Unlock() + if api != nil { + api(w, r) + return + } _, _ = w.Write([]byte(`{"ok":true}`)) })) t.Cleanup(p.Close) diff --git a/cmd/auth.go b/cmd/auth.go index aca7e58..1a6a187 100644 --- a/cmd/auth.go +++ b/cmd/auth.go @@ -13,6 +13,7 @@ import ( "github.com/customerio/cli/internal/client" "github.com/customerio/cli/internal/clipboard" "github.com/customerio/cli/internal/output" + "github.com/customerio/cli/internal/runreport" "github.com/mattn/go-isatty" "github.com/spf13/cobra" "golang.org/x/term" @@ -206,6 +207,7 @@ re-authenticates whichever profile is currently selected (see 'cio profile').`, // close, so the prompt would hang. Say what works instead. if !canPromptForToken(cmd.InOrStdin()) { err := fmt.Errorf("no terminal to paste a token into") + runreport.Reason("auth") output.PrintError(output.CodeValidationError, err.Error(), map[string]any{ "hint": "Run 'cio auth login --from-clipboard --wait' and have the user copy the token from the token page (see 'cio auth login --help'). To pipe a token in, use 'cio auth login --with-token'.", }) @@ -227,6 +229,7 @@ re-authenticates whichever profile is currently selected (see 'cio profile').`, if token == "" { err := fmt.Errorf("token must not be empty") + runreport.Reason("auth") output.PrintError(output.CodeValidationError, err.Error(), nil) return err } @@ -236,6 +239,7 @@ re-authenticates whichever profile is currently selected (see 'cio profile').`, client.ServiceAccountTokenPrefix, client.SandboxServiceAccountTokenPrefix, token[:min(len(token), 10)]) + runreport.Reason("auth") output.PrintError(output.CodeValidationError, err.Error(), map[string]any{ "hint": fmt.Sprintf("Service account tokens start with sa_live_. Copy the token from the token page (%s) or run cio auth signup for a new account.", resolveCLILoginURL(resolveLoginBaseURL(cmd))), diff --git a/cmd/auth_test.go b/cmd/auth_test.go index fee278f..93c0fcb 100644 --- a/cmd/auth_test.go +++ b/cmd/auth_test.go @@ -21,6 +21,12 @@ import ( // Keep tests independent of the developer's credential environment. func TestMain(m *testing.M) { + if len(os.Args) > 1 && os.Args[1] == "test-run-report" { + rootCmd.SetArgs(os.Args[2:]) + SetVersion("0.0.39") + Execute() + return + } _ = os.Unsetenv("CIO_CONFIG") _ = os.Unsetenv("CIO_TOKEN") os.Exit(m.Run()) diff --git a/cmd/billing_add_funds.go b/cmd/billing_add_funds.go index 6f25eea..65b4241 100644 --- a/cmd/billing_add_funds.go +++ b/cmd/billing_add_funds.go @@ -10,6 +10,7 @@ import ( "github.com/customerio/cli/internal/client" "github.com/customerio/cli/internal/output" + "github.com/customerio/cli/internal/runreport" "github.com/spf13/cobra" ) @@ -163,13 +164,10 @@ func printAddFundsResult(cmd *cobra.Command, result map[string]any) error { return output.FprintProcess(cmd.OutOrStdout(), json.RawMessage(data), GetJQFlag(cmd), GetRawFlag(cmd)) } -// handleAddFundsError passes on the server's reason for refusing a link, which -// says what plan and permission adding funds needs, where handleAPIError -// would reduce a 403 to "Insufficient permissions." func handleAddFundsError(err error) error { var apiErr *client.APIError if errors.As(err, &apiErr) && (apiErr.StatusCode == http.StatusBadRequest || apiErr.StatusCode == http.StatusForbidden) { - if detail := apiErrorDetail(apiErr.Body); detail != "" { + if _, detail := apiErrorDetail(apiErr.Body); detail != "" { code := output.CodeValidationError if apiErr.StatusCode == http.StatusForbidden { code = output.CodeAuthzError @@ -177,21 +175,22 @@ func handleAddFundsError(err error) error { output.PrintError(code, detail, map[string]any{ "status_code": apiErr.StatusCode, }) - return errors.New(detail) + return runreport.WithReason(errors.New(detail), "http_error") } } return handleAPIError(err) } -// apiErrorDetail reads the first message from an {"errors":[{"detail":...}]} body. -func apiErrorDetail(body []byte) string { +func apiErrorDetail(body []byte) (code, detail string) { var parsed struct { Errors []struct { - Detail string `json:"detail"` + Code json.RawMessage `json:"code"` + Detail string `json:"detail"` } `json:"errors"` } if json.Unmarshal(body, &parsed) != nil || len(parsed.Errors) == 0 { - return "" + return "", "" } - return strings.TrimSpace(parsed.Errors[0].Detail) + _ = json.Unmarshal(parsed.Errors[0].Code, &code) + return strings.TrimSpace(code), strings.TrimSpace(parsed.Errors[0].Detail) } diff --git a/cmd/billing_status.go b/cmd/billing_status.go index eee809b..086ce97 100644 --- a/cmd/billing_status.go +++ b/cmd/billing_status.go @@ -327,7 +327,7 @@ func handleBillingStatusError(err error) error { }) return errors.New(msg) case http.StatusBadRequest: - if detail := apiErrorDetail(apiErr.Body); detail != "" { + if _, detail := apiErrorDetail(apiErr.Body); detail != "" { output.PrintError(output.CodeValidationError, detail, map[string]any{ "status_code": apiErr.StatusCode, }) diff --git a/cmd/funds_warning.go b/cmd/funds_warning.go index a4b1323..76dbf51 100644 --- a/cmd/funds_warning.go +++ b/cmd/funds_warning.go @@ -13,6 +13,7 @@ import ( "github.com/customerio/cli/internal/client" "github.com/customerio/cli/internal/filelock" "github.com/customerio/cli/internal/routes" + "github.com/customerio/cli/internal/runreport" "github.com/customerio/cli/internal/validate" "github.com/spf13/cobra" ) @@ -68,7 +69,7 @@ func warnIfFundsLow(cmd *cobra.Command, sendPath, saToken string) { if ctx == nil { ctx = context.Background() } - ctx, cancel := context.WithTimeout(ctx, fundsCheckTimeout) + ctx, cancel := context.WithTimeout(runreport.Untracked(ctx), fundsCheckTimeout) defer cancel() c := fundsCheckClient(cmd, saToken) diff --git a/cmd/helpers.go b/cmd/helpers.go index 1356f71..ebfd2df 100644 --- a/cmd/helpers.go +++ b/cmd/helpers.go @@ -7,10 +7,12 @@ import ( "fmt" "io" "net/http" + "strings" "github.com/customerio/cli/internal/client" "github.com/customerio/cli/internal/output" "github.com/customerio/cli/internal/routes" + "github.com/customerio/cli/internal/runreport" "github.com/spf13/cobra" ) @@ -69,19 +71,24 @@ func specLoadOptions(ctx context.Context, c *client.Client) routes.LoadRegistryO // lookup should cost. The key matches the one specLoadOptions uses, so both // commands read and write the same directory. func specCacheOptions(c *client.Client) routes.LoadRegistryOptions { - var opts routes.LoadRegistryOptions if c == nil { - return opts + return routes.LoadRegistryOptions{} } - opts.BaseURL = c.BaseURL() - switch { - case c.ServiceAccountToken() != "": - opts.CacheKey = c.ServiceAccountToken() - case c.AccessToken() != "": - opts.CacheKey = specCacheKey(c.AccessToken()) + return routes.LoadRegistryOptions{ + BaseURL: c.BaseURL(), + CacheKey: specCacheIdentity(c.ServiceAccountToken(), c.AccessToken()), } - return opts +} + +func specCacheIdentity(serviceAccountToken, accessToken string) string { + if serviceAccountToken != "" { + return serviceAccountToken + } + if accessToken != "" { + return specCacheKey(accessToken) + } + return "" } // doPageAll runs auto-pagination and writes NDJSON to stdout. @@ -94,9 +101,10 @@ func doPageAll(cmd *cobra.Command, c *client.Client, path string, params map[str w = &filterWriter{w: cmd.OutOrStdout(), jq: jq, raw: raw} } + runreport.Method(http.MethodGet) err := c.PageAll(client.PageAllConfig{ Ctx: cmd.Context(), - Method: "GET", + Method: http.MethodGet, Path: path, Params: params, Limit: limit, @@ -154,9 +162,16 @@ func handleAPIError(err error) error { "status_code": apiErr.StatusCode, }) case http.StatusForbidden: - output.PrintError(output.CodeAuthzError, "Insufficient permissions.", map[string]any{ - "status_code": apiErr.StatusCode, - }) + code, detail := apiErrorDetail(apiErr.Body) + msg := "Insufficient permissions." + if detail != "" && !strings.EqualFold(detail, "forbidden") { + msg = detail + } + details := map[string]any{"status_code": apiErr.StatusCode} + if code != "" { + details["api_code"] = code + } + output.PrintError(output.CodeAuthzError, msg, details) default: output.PrintError(output.CodeAPIError, apiErr.Error(), map[string]any{ "status_code": apiErr.StatusCode, diff --git a/cmd/helpers_test.go b/cmd/helpers_test.go new file mode 100644 index 0000000..efd3b28 --- /dev/null +++ b/cmd/helpers_test.go @@ -0,0 +1,118 @@ +package cmd + +import ( + "encoding/json" + "net/http" + "testing" + + "github.com/customerio/cli/internal/client" + "github.com/customerio/cli/internal/output" +) + +func TestHandleAPIError_Forbidden(t *testing.T) { + cases := []struct { + desc string + body string + wantMessage string + wantAPICode string + }{ + { + desc: "given a coded 403 body, handleAPIError should pass on the detail and code", + body: `{"errors":[{"code":"update_requires_edit_permission","detail":"Updating this one-time send requires the Edit permission.","status":"403"}]}`, + wantMessage: "Updating this one-time send requires the Edit permission.", + wantAPICode: "update_requires_edit_permission", + }, + { + desc: "given a 403 body without a code, handleAPIError should pass on the detail alone", + body: `{"errors":[{"detail":"Only account admins can do this.","status":"403"}]}`, + wantMessage: "Only account admins can do this.", + }, + { + desc: "given a 403 body whose detail is a bare forbidden, handleAPIError should say permissions are insufficient", + body: `{"errors":[{"detail":" Forbidden ","status":"403"}]}`, + wantMessage: "Insufficient permissions.", + }, + { + desc: "given a coded 403 body whose detail is a bare forbidden, handleAPIError should say permissions are insufficient and pass on the code", + body: `{"errors":[{"code":"missing_permission","detail":"forbidden","status":"403"}]}`, + wantMessage: "Insufficient permissions.", + wantAPICode: "missing_permission", + }, + { + desc: "given an empty 403 body, handleAPIError should say permissions are insufficient", + wantMessage: "Insufficient permissions.", + }, + { + desc: "given a non-JSON 403 body, handleAPIError should say permissions are insufficient", + body: `Forbidden`, + wantMessage: "Insufficient permissions.", + }, + } + for _, tc := range cases { + t.Run(tc.desc, func(t *testing.T) { + stderr := captureStderr(t, func() { + _ = handleAPIError(&client.APIError{StatusCode: http.StatusForbidden, Body: []byte(tc.body)}) + }) + + var got struct { + Code string `json:"code"` + Message string `json:"message"` + Details struct { + StatusCode int `json:"status_code"` + APICode string `json:"api_code"` + } `json:"details"` + } + if err := json.Unmarshal([]byte(stderr), &got); err != nil { + t.Fatalf("stderr should be a JSON error: %v\n%s", err, stderr) + } + if got.Code != output.CodeAuthzError { + t.Errorf("code = %q, want %q", got.Code, output.CodeAuthzError) + } + if got.Message != tc.wantMessage { + t.Errorf("message = %q, want %q", got.Message, tc.wantMessage) + } + if got.Details.StatusCode != http.StatusForbidden { + t.Errorf("status_code = %d, want %d", got.Details.StatusCode, http.StatusForbidden) + } + if got.Details.APICode != tc.wantAPICode { + t.Errorf("api_code = %q, want %q", got.Details.APICode, tc.wantAPICode) + } + }) + } +} + +func TestAPIErrorDetail(t *testing.T) { + cases := []struct { + desc string + body string + wantCode string + wantDetail string + }{ + { + desc: "given a string code and a detail, apiErrorDetail should return both", + body: `{"errors":[{"code":"update_requires_edit_permission","detail":"Needs Edit."}]}`, + wantCode: "update_requires_edit_permission", + wantDetail: "Needs Edit.", + }, + { + desc: "given a numeric code and a detail, apiErrorDetail should return the detail without a code", + body: `{"errors":[{"code":400,"detail":"Add funds is only available on the Flex plan."}]}`, + wantDetail: "Add funds is only available on the Flex plan.", + }, + { + desc: "given a non-JSON body, apiErrorDetail should return nothing", + body: `Bad Request`, + }, + } + for _, tc := range cases { + t.Run(tc.desc, func(t *testing.T) { + code, detail := apiErrorDetail([]byte(tc.body)) + if code != tc.wantCode { + t.Errorf("code = %q, want %q", code, tc.wantCode) + } + if detail != tc.wantDetail { + t.Errorf("detail = %q, want %q", detail, tc.wantDetail) + } + }) + } +} diff --git a/cmd/root.go b/cmd/root.go index ec38233..a193d88 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -11,6 +11,7 @@ import ( "github.com/customerio/cli/internal/client" "github.com/customerio/cli/internal/output" + "github.com/customerio/cli/internal/runreport" "github.com/customerio/cli/internal/tui" "github.com/customerio/cli/internal/useragent" "github.com/customerio/cli/internal/validate" @@ -92,7 +93,7 @@ func init() { // send a request. CommandPath is built from command names alone, so // arguments and flag values stay out of the header. Dropping the root // name leaves bare `cio` with an empty command. - client.SetCommand(strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name())) + client.SetCommand(commandPathBelowRoot(cmd)) maybeHintSkillsInstall(cmd) @@ -108,6 +109,8 @@ func init() { client.SetActiveProfile(profile) } + reportBespokeRoutes(cmd) + // Bind environment variables as fallback defaults. if !cmd.Flags().Changed("timeout") { if v := os.Getenv("CIO_TIMEOUT"); v != "" { @@ -147,11 +150,13 @@ func init() { argjsonVals, _ := cmd.Flags().GetStringArray("argjson") argVals, err = resolveArgFileRefs("arg", argVals) if err != nil { + runreport.Reason("invalid_json") output.PrintError(output.CodeValidationError, err.Error(), map[string]string{"flag": "--arg"}) return err } argjsonVals, err = resolveArgFileRefs("argjson", argjsonVals) if err != nil { + runreport.Reason("invalid_json") output.PrintError(output.CodeValidationError, err.Error(), map[string]string{"flag": "--argjson"}) return err } @@ -159,6 +164,7 @@ func init() { if len(argVals) > 0 || len(argjsonVals) > 0 { built, buildErr := output.BuildJSON(resolved, argVals, argjsonVals) if buildErr != nil { + runreport.Reason("invalid_json") output.PrintError(output.CodeValidationError, buildErr.Error(), map[string]string{ "flag": "--json", }) @@ -172,7 +178,7 @@ func init() { if _, err := validate.ValidateJSONPayload(resolved); err != nil { valErr := err if strings.HasPrefix(jsonFlag, "@") { - valErr = fmt.Errorf("%s (from file %s)", err.Error(), jsonFlag[1:]) + valErr = fmt.Errorf("%w (from file %s)", err, jsonFlag[1:]) } output.PrintError(output.CodeValidationError, valErr.Error(), map[string]string{ "flag": "--json", @@ -371,8 +377,27 @@ func resolveArgFileRefs(flag string, bindings []string) ([]string, error) { // Execute runs the root command. func Execute() { - if err := rootCmd.Execute(); err != nil { - exitCode := output.PrintError(output.CodeGeneralError, err.Error(), nil) + reportPath := os.Getenv("CIO_RUN_REPORT") + if reportPath != "" { + runreport.Start(reportPath, useragent.Version()) + // Include the validators Cobra registers for shell completion. + rootCmd.InitDefaultCompletionCmd() + reportArgCounts(rootCmd) + } + + cmd, err := rootCmd.ExecuteC() + exitCode := 0 + if err != nil { + exitCode = output.PrintedExitCode() + if exitCode == 0 { + exitCode = output.PrintError(output.CodeGeneralError, err.Error(), nil) + } + } + if reportPath != "" { + reportCommandFailure(cmd, err) + runreport.Finish(commandPathBelowRoot(cmd), exitCode) + } + if exitCode != 0 { os.Exit(exitCode) } } diff --git a/cmd/root_test.go b/cmd/root_test.go index 2712795..e9fcddd 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -1,11 +1,18 @@ package cmd import ( + "bytes" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" "os" + "os/exec" "path/filepath" "strings" "testing" + "github.com/customerio/cli/internal/output" "github.com/customerio/cli/internal/useragent" ) @@ -67,3 +74,84 @@ func TestResolveArgFileRefs(t *testing.T) { t.Error("expected error for empty @ path") } } + +func TestExecuteHelperProcess(t *testing.T) { + if os.Getenv("CIO_EXECUTE_HELPER") != "1" { + return + } + args := os.Args + for i, arg := range args { + if arg == "--" { + args = args[i+1:] + break + } + } + rootCmd.SetArgs(args) + Execute() +} + +func TestExecute_PrintsAPIErrorOnce(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/v1/service_accounts/oauth/token": + _, _ = w.Write([]byte(`{"access_token":"jwt-test-session","token_type":"Bearer","expires_in":3600}`)) + case "/v1/forbidden": + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"errors":[{"code":"update_requires_edit_permission","detail":"Updating this one-time send requires the Edit permission.","status":"403"}]}`)) + default: + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"errors":[{"detail":"boom"}]}`)) + } + })) + defer server.Close() + + cases := []struct { + desc string + path string + wantCode string + wantExit int + }{ + { + desc: "given a coded 403, cio api should print one AUTHZ_ERROR and exit 4", + path: "/v1/forbidden", + wantCode: output.CodeAuthzError, + wantExit: output.ExitAuthz, + }, + { + desc: "given a 500, cio api should print one API_ERROR and exit 5", + path: "/v1/broken", + wantCode: output.CodeAPIError, + wantExit: output.ExitAPI, + }, + } + for _, tc := range cases { + t.Run(tc.desc, func(t *testing.T) { + cmd := exec.Command(os.Args[0], "-test.run=^TestExecuteHelperProcess$", "--", + "api", tc.path, "--no-preflight", "--api-url", server.URL, "--token", "sa_live_test123") + cmd.Env = append(os.Environ(), "CIO_EXECUTE_HELPER=1", "HOME="+t.TempDir()) + var stderr bytes.Buffer + cmd.Stderr = &stderr + + err := cmd.Run() + + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) { + t.Fatalf("expected a non-zero exit, got %v", err) + } + if exitErr.ExitCode() != tc.wantExit { + t.Errorf("exit code = %d, want %d", exitErr.ExitCode(), tc.wantExit) + } + lines := strings.Split(strings.TrimSpace(stderr.String()), "\n") + if len(lines) != 1 { + t.Fatalf("expected one stderr line, got %d:\n%s", len(lines), stderr.String()) + } + var got output.CLIError + if err := json.Unmarshal([]byte(lines[0]), &got); err != nil { + t.Fatalf("stderr should be a JSON error: %v\n%s", err, stderr.String()) + } + if got.Code != tc.wantCode { + t.Errorf("code = %q, want %q", got.Code, tc.wantCode) + } + }) + } +} diff --git a/cmd/run_report.go b/cmd/run_report.go new file mode 100644 index 0000000..a4a04c9 --- /dev/null +++ b/cmd/run_report.go @@ -0,0 +1,93 @@ +package cmd + +import ( + "errors" + "net/http" + "strings" + + "github.com/customerio/cli/internal/client" + "github.com/customerio/cli/internal/routes" + "github.com/customerio/cli/internal/runreport" + "github.com/customerio/cli/internal/validate" + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +func reportArgCounts(cmd *cobra.Command) { + // These commands' Args validators check positional argument counts. + if validate := cmd.Args; validate != nil { + cmd.Args = func(cmd *cobra.Command, args []string) error { + err := validate(cmd, args) + if err != nil { + runreport.Reason("arg_count") + } + return err + } + } + for _, sub := range cmd.Commands() { + reportArgCounts(sub) + } +} + +func reportBespokeRoutes(cmd *cobra.Command) { + if !runreport.Enabled() || cmd == apiCmd { + return + } + var idx *routes.PathIndex + loaded := false + runreport.SetRouteLookup(func(method, path string) (string, bool) { + if !loaded { + loaded = true + var opts routes.LoadRegistryOptions + if c := clientFromCmd(cmd); c != nil { + opts = specCacheOptions(c) + } else { + tokenFlag, _ := cmd.Flags().GetString("token") + opts.CacheKey = specCacheIdentity(client.ResolveServiceAccountToken(tokenFlag), client.ResolveAccessToken()) + } + idx, _ = routes.LoadPathIndexFromCache(opts) + } + if idx == nil { + return "", false + } + return idx.Lookup(method, path) + }) +} + +func reportCommandFailure(cmd *cobra.Command, err error) { + if err == nil { + return + } + var flagErr *pflag.NotExistError + var paramsErr *validate.ParamsValidationError + var jsonErr *validate.JSONValidationError + var apiErr *client.APIError + var nonJSON *client.NonJSONResponseError + reason := runreport.FailureReason(err) + switch { + case reason != "": + runreport.Reason(reason) + case cmd == rootCmd && cmd.CalledAs() == "": + // Cobra failed to resolve the command before its validators could run. + runreport.Reason("unknown_command") + case errors.As(err, &flagErr): + runreport.Reason("unknown_flag") + case errors.As(err, ¶msErr): + runreport.Reason("invalid_params") + case errors.As(err, &jsonErr): + runreport.Reason("invalid_json") + case errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized: + runreport.Reason("auth") + case errors.As(err, &apiErr): + runreport.Reason("http_error") + case errors.As(err, &nonJSON) && (nonJSON.StatusCode < http.StatusOK || nonJSON.StatusCode >= http.StatusMultipleChoices): + runreport.Reason("http_error") + } +} + +func commandPathBelowRoot(cmd *cobra.Command) string { + if cmd == rootCmd { + return "" + } + return strings.TrimPrefix(cmd.CommandPath(), rootCmd.CommandPath()+" ") +} diff --git a/cmd/run_report_test.go b/cmd/run_report_test.go new file mode 100644 index 0000000..76d099f --- /dev/null +++ b/cmd/run_report_test.go @@ -0,0 +1,246 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" +) + +type cliRun struct { + stdout, stderr string + exitCode int +} + +func runCLIForReport(t *testing.T, args ...string) cliRun { + t.Helper() + cmd := exec.Command(os.Args[0], append([]string{"test-run-report"}, args...)...) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + exitCode := 0 + if err != nil { + exit, ok := err.(*exec.ExitError) + if !ok { + t.Fatal(err) + } + exitCode = exit.ExitCode() + } + return cliRun{stdout.String(), stderr.String(), exitCode} +} + +func TestRunReport(t *testing.T) { + const ( + path = "/v1/environments/456/campaigns" + template = "/v1/environments/{environment_id}/campaigns" + itemTemplate = template + "/{campaign_id}" + email = "recipient@example.test" + name = "Private Query Name" + body = `{"body":"Private Request Body"}` + jq = `error("Private Projection Expression")` + ) + for _, tc := range []struct { + name string + command string + args []string + reason, code, method, route, match string + requests, status int + noToken, warmCache bool + }{ + {name: "matched", command: "api", args: []string{path}, method: "GET", route: template, requests: 1, status: 200}, + {name: "absent", command: "api", args: []string{path + "/42/absent"}, method: "GET", reason: "not_in_spec", code: "VALIDATION_ERROR", match: "not_in_spec"}, + {name: "wrong method", command: "api", args: []string{path, "-X", "DELETE"}, method: "DELETE", reason: "wrong_method", code: "VALIDATION_ERROR", match: "not_in_spec"}, + {name: "word matches parameter", command: "api", args: []string{path + "/card"}, method: "GET", route: itemTemplate, reason: "http_error", code: "API_ERROR", requests: 1, status: 404}, + {name: "precondition response", command: "api", args: []string{path + "/42"}, method: "GET", route: itemTemplate, reason: "http_error", code: "API_ERROR", requests: 1, status: 428}, + {name: "truncated error response", command: "api", args: []string{path}, method: "GET", route: template, reason: "http_error", code: "GENERAL_ERROR", requests: 1, status: 404}, + {name: "truncated success response", command: "api", args: []string{path}, method: "GET", route: template, reason: "network", code: "GENERAL_ERROR", requests: 1, status: 200}, + {name: "failed redirect", command: "api", args: []string{path}, method: "GET", route: template, reason: "http_error", code: "GENERAL_ERROR", requests: 1, status: 302}, + {name: "preflight disabled", command: "api", args: []string{path, "--no-preflight"}, method: "GET", requests: 1, status: 200, warmCache: true}, + {name: "spec unavailable", command: "api", args: []string{path}, method: "GET", requests: 1, status: 200}, + {name: "missing path parameter", command: "api", args: []string{itemTemplate}, method: "GET", reason: "missing_path_param", code: "VALIDATION_ERROR"}, + {name: "unknown flag", command: "api", args: []string{path, "--unknown-flag"}, reason: "unknown_flag", code: "GENERAL_ERROR"}, + {name: "wrong argument count", command: "api", reason: "arg_count", code: "GENERAL_ERROR"}, + {name: "nested argument count", command: "domains list", args: []string{"extra"}, reason: "arg_count", code: "GENERAL_ERROR"}, + {name: "unknown command", args: []string{"unknown-command"}, reason: "unknown_command", code: "GENERAL_ERROR"}, + {name: "invalid JSON", command: "api", args: []string{path, "--json", "{"}, reason: "invalid_json", code: "VALIDATION_ERROR"}, + {name: "invalid JSON binding", command: "api", args: []string{path, "--json", "$value", "--argjson", "value={"}, reason: "invalid_json", code: "VALIDATION_ERROR"}, + {name: "invalid bespoke JSON", command: "send email", args: []string{"--identifiers", "{"}, reason: "invalid_json", code: "VALIDATION_ERROR"}, + {name: "invalid params", command: "api", args: []string{path, "--params", `{"name":`}, reason: "invalid_params", code: "VALIDATION_ERROR"}, + {name: "invalid inline query", command: "api", args: []string{path + "?name=%XX"}, method: "GET", reason: "invalid_params", code: "VALIDATION_ERROR"}, + {name: "invalid jq syntax", command: "api", args: []string{path, "--jq", ".["}, method: "GET", route: template, reason: "jq_error", code: "GENERAL_ERROR", requests: 1, status: 200}, + {name: "jq evaluation keeps caller inputs private", command: "api", args: []string{path + "/" + email, "-X", "GET", "--params", `{"name":"` + name + `"}`, "--json", body, "--jq", jq}, method: "GET", route: itemTemplate, reason: "jq_error", code: "GENERAL_ERROR", requests: 1, status: 200}, + {name: "unknown schema resource", command: "schema", args: []string{"absent"}, reason: "schema_not_found", code: "VALIDATION_ERROR"}, + {name: "pagination", command: "api", args: []string{path, "--page-all"}, method: "GET", route: template, requests: 2, status: 201}, + {name: "retry", command: "api", args: []string{path}, method: "GET", route: template, requests: 2, status: 200}, + {name: "missing auth", command: "api", args: []string{path, "--no-preflight"}, method: "GET", reason: "auth", code: "GENERAL_ERROR", noToken: true}, + {name: "invalid login credential", command: "auth login", args: []string{"not-a-token"}, reason: "auth", code: "VALIDATION_ERROR"}, + {name: "rejected token exchange", command: "api", args: []string{path, "--no-preflight"}, method: "GET", reason: "auth", code: "GENERAL_ERROR"}, + {name: "token endpoint outage", command: "api", args: []string{path, "--no-preflight"}, method: "GET", reason: "http_error", code: "GENERAL_ERROR"}, + {name: "unreachable token endpoint", command: "api", args: []string{path, "--no-preflight"}, method: "GET", reason: "network", code: "GENERAL_ERROR"}, + {name: "unauthorized response", command: "api", args: []string{path}, method: "GET", route: template, reason: "auth", code: "AUTH_ERROR", requests: 2, status: 401}, + {name: "network failure", command: "api", args: []string{path, "-X", "POST"}, method: "POST", route: template, reason: "network", code: "GENERAL_ERROR", requests: 1}, + {name: "bespoke with cached match", command: "domains list", args: []string{"--env-id", "456"}, method: "GET", route: "/v1/environments/{environment_id}/domains", requests: 1, status: 200, warmCache: true}, + {name: "bespoke without cached match", command: "domains list", args: []string{"--env-id", "456"}, method: "GET", requests: 1, status: 200}, + {name: "other failure", command: "api", args: []string{path, "-X", "PRIVATE", "--read-only", "--no-preflight"}, reason: "other", code: "GENERAL_ERROR"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("CIO_CONFIG", "") + t.Setenv("CIO_PROFILE", "") + t.Setenv("CIO_TIMEOUT", "") + t.Setenv("CIO_MAX_RETRIES", "1") + var attempts atomic.Int32 + server := newPreflightServerWithAPI(t, func(w http.ResponseWriter, r *http.Request) { + switch tc.name { + case "word matches parameter", "precondition response", "unauthorized response": + w.WriteHeader(tc.status) + fmt.Fprint(w, `{"error":"private API error detail"}`) + return + case "truncated success response": + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusOK) + fmt.Fprint(w, "{") + return + case "truncated error response": + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "{") + return + case "failed redirect": + w.Header().Set("Location", "http://[invalid") + w.WriteHeader(http.StatusFound) + return + case "pagination": + if r.URL.Query().Get("page") == "2" { + w.WriteHeader(http.StatusCreated) + } + fmt.Fprint(w, `{"total_pages":2}`) + return + case "retry": + if attempts.Add(1) == 1 { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + case "network failure": + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + _ = conn.Close() + return + } + fmt.Fprint(w, `{"ok":true}`) + }) + if tc.noToken { + t.Setenv("CIO_TOKEN", "") + } + if tc.name == "rejected token exchange" { + server.mu.Lock() + server.tokenStatus = http.StatusUnauthorized + server.mu.Unlock() + } + if tc.name == "token endpoint outage" { + server.mu.Lock() + server.tokenStatus = http.StatusServiceUnavailable + server.mu.Unlock() + } + if tc.name == "spec unavailable" { + server.setSpec("unavailable") + } + if tc.name == "unreachable token endpoint" { + server.Close() + } + if tc.warmCache { + t.Setenv("CIO_RUN_REPORT", "") + server.setSpec(strings.ReplaceAll(preflightSpec(), "/all_metrics", "/domains")) + if run := runCLIForReport(t, "schema", "--api-url", server.URL); run.exitCode != 0 { + t.Fatal(run) + } + } + + reportPath := filepath.Join(t.TempDir(), "report.json") + t.Setenv("CIO_RUN_REPORT", reportPath) + if tc.name == "matched" { + if err := os.WriteFile(reportPath, bytes.Repeat([]byte("stale"), 100), 0o600); err != nil { + t.Fatal(err) + } + } + args := append(strings.Fields(tc.command), tc.args...) + run := runCLIForReport(t, append(args, "--api-url", server.URL)...) + data, err := os.ReadFile(reportPath) + if err != nil { + t.Fatal(err) + } + + var got map[string]any + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + + want := map[string]any{ + "version": "0.0.39", "command": tc.command, "exit_code": float64(0), + "error_code": nil, "reason": nil, "method": nil, "route": nil, + "route_match": "not_checked", "requests": float64(tc.requests), "status": nil, + } + if tc.code != "" { + if run.exitCode == 0 { + t.Fatalf("command succeeded, want %s", tc.code) + } + want["exit_code"], want["error_code"], want["reason"] = float64(run.exitCode), tc.code, tc.reason + if !strings.Contains(run.stderr, `"code":"`+tc.code+`"`) { + t.Errorf("command stderr missing %s: %s", tc.code, run.stderr) + } + } + if tc.method != "" { + want["method"] = tc.method + } + if tc.route != "" { + want["route"], want["route_match"] = tc.route, "matched" + } + if tc.match != "" { + want["route_match"] = tc.match + } + if tc.status != 0 { + want["status"] = float64(tc.status) + } + if !reflect.DeepEqual(got, want) { + t.Errorf("report = %s, want %v", data, want) + } + if run.exitCode != int(want["exit_code"].(float64)) { + t.Errorf("process exited %d, stderr: %s", run.exitCode, run.stderr) + } + if count := len(server.requested()); count != tc.requests { + t.Errorf("API received %d requests, want %d", count, tc.requests) + } + if tc.name == "jq evaluation keeps caller inputs private" { + for _, secret := range []string{email, name, "Private Request Body", "Private Projection Expression"} { + if strings.Contains(string(data), secret) { + t.Error("report contains caller input") + } + } + } + }) + } +} + +func TestRunReportWriteFailurePreservesCLIOutput(t *testing.T) { + for _, args := range [][]string{{"--version"}, {"api", "/any", "--json", "{"}} { + t.Setenv("CIO_RUN_REPORT", "") + without := runCLIForReport(t, args...) + dir := t.TempDir() + t.Setenv("CIO_RUN_REPORT", dir) + if with := runCLIForReport(t, args...); with != without { + t.Errorf("unwritable report changed invocation: got %+v, want %+v", with, without) + } + if entries, err := os.ReadDir(dir); err != nil || len(entries) != 0 { + t.Errorf("report path %s should stay an empty directory, got %v (%v)", dir, entries, err) + } + } +} diff --git a/cmd/schema.go b/cmd/schema.go index b6e0c7d..c326b9d 100644 --- a/cmd/schema.go +++ b/cmd/schema.go @@ -7,6 +7,7 @@ import ( "github.com/customerio/cli/internal/output" "github.com/customerio/cli/internal/routes" + "github.com/customerio/cli/internal/runreport" "github.com/spf13/cobra" ) @@ -165,6 +166,7 @@ func schemaForResource(cmd *cobra.Command, reg *routes.Registry, resource string rs, ok := reg.ByResource[resource] if !ok { err := fmt.Errorf("unknown resource: %s", resource) + runreport.Reason("schema_not_found") output.PrintError(output.CodeValidationError, err.Error(), map[string]any{ "resource": resource, "available_resources": reg.Resources(), @@ -183,6 +185,7 @@ func schemaForResource(cmd *cobra.Command, reg *routes.Registry, resource string func schemaForResourceMethod(cmd *cobra.Command, reg *routes.Registry, resource, method string, compact bool) error { route := reg.FindRoute(resource, method) if route == nil { + runreport.Reason("schema_not_found") suggestions := suggestRoutes(reg, resource, method) msg := fmt.Sprintf("unknown method: %s.%s", resource, method) if len(suggestions) > 0 { @@ -209,6 +212,7 @@ func schemaForPath(cmd *cobra.Command, reg *routes.Registry, path string, compac if len(matches) == 0 { err := fmt.Errorf("no endpoints found for path: %s", path) + runreport.Reason("schema_not_found") output.PrintError(output.CodeValidationError, err.Error(), nil) return err } @@ -229,6 +233,7 @@ func schemaForHTTPEndpoint(cmd *cobra.Command, reg *routes.Registry, method, pat } err := fmt.Errorf("unknown endpoint: %s %s", method, path) + runreport.Reason("schema_not_found") output.PrintError(output.CodeValidationError, err.Error(), nil) return err } diff --git a/cmd/selfheal.go b/cmd/selfheal.go index b4f03c4..685d509 100644 --- a/cmd/selfheal.go +++ b/cmd/selfheal.go @@ -8,6 +8,7 @@ import ( "time" "github.com/customerio/cli/internal/client" + "github.com/customerio/cli/internal/runreport" ) // sandboxPromoteThrottle bounds how often the CLI probes the promote endpoint @@ -32,6 +33,7 @@ func maybePromoteSandboxToken(ctx context.Context, c *client.Client, saToken str if readOnly || os.Getenv("CIO_TOKEN") != "" || !client.IsSandboxServiceAccountToken(saToken) { return } + ctx = runreport.Untracked(ctx) creds, err := client.ReadCredentials() if err != nil { diff --git a/internal/client/client.go b/internal/client/client.go index ca3bdd0..76097cc 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -5,6 +5,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -15,6 +16,7 @@ import ( "sync/atomic" "time" + "github.com/customerio/cli/internal/runreport" "github.com/customerio/cli/internal/useragent" ) @@ -200,7 +202,7 @@ func (c *Client) EnsureAccessToken(ctx context.Context) (string, error) { c.accessTokenExpiresAt = time.Time{} if c.serviceAccountToken == "" { - return "", fmt.Errorf("no service account token configured") + return "", runreport.WithReason(fmt.Errorf("no service account token configured"), "auth") } // Check the file cache. @@ -214,7 +216,7 @@ func (c *Client) EnsureAccessToken(ctx context.Context) (string, error) { // Exchange sa_live_ credential for a JWT. token, expiresIn, err := c.exchangeToken(ctx) if err != nil { - return "", fmt.Errorf("%w: %w", errTokenExchange, err) + return "", runreport.WithReason(fmt.Errorf("%w: %w", errTokenExchange, err), exchangeFailureReason(err)) } c.accessToken = token @@ -283,7 +285,7 @@ func exchangeTokenAt(ctx context.Context, httpClient *http.Client, baseURL, saTo body, err := io.ReadAll(resp.Body) if err != nil { - return "", 0, fmt.Errorf("read token response: %w", err) + return "", 0, runreport.WithReason(fmt.Errorf("read token response: %w", err), "network") } if resp.StatusCode != http.StatusOK { @@ -369,7 +371,7 @@ func DiscoverRegion(ctx context.Context, saToken string, tokenBaseURL string) (* accessToken, expiresIn, err := exchangeTokenAt(ctx, httpClient, exchangeURL, saToken, false, nil) if err != nil { - return nil, fmt.Errorf("token exchange failed: %w", err) + return nil, runreport.WithReason(fmt.Errorf("token exchange failed: %w", err), exchangeFailureReason(err)) } // Now discover the account's data center and ID via GET /v1/accounts/current. @@ -406,19 +408,19 @@ func fetchAccountInfo(ctx context.Context, httpClient *http.Client, baseURL, acc req.Header.Set("Accept", "application/json") setStandardHeaders(req) - resp, err := httpClient.Do(req) + resp, err := runreport.Do(httpClient, req) if err != nil { return "", "", err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { - return "", "", fmt.Errorf("GET /v1/accounts/current returned %d", resp.StatusCode) + return "", "", runreport.WithHTTPStatus(fmt.Errorf("GET /v1/accounts/current returned %d", resp.StatusCode), resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { - return "", "", err + return "", "", runreport.ReadFailure(err, resp.StatusCode) } var parsed struct { @@ -564,7 +566,7 @@ func sendTracked(httpClient *http.Client, req *http.Request) (*http.Response, er req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{ WroteHeaders: func() { sent.Store(true) }, })) - resp, err := httpClient.Do(req) + resp, err := runreport.Do(httpClient, req) if err != nil { if sent.Load() { return nil, fmt.Errorf("http request: %w: %w", errResponseLost, err) @@ -574,6 +576,27 @@ func sendTracked(httpClient *http.Client, req *http.Request) (*http.Response, er return resp, nil } +// exchangeFailureReason separates an exchange that never reached the token +// endpoint, an outage, from one the endpoint refused, a credential problem. +func exchangeFailureReason(err error) string { + if reason := runreport.FailureReason(err); reason != "" { + return reason + } + var urlErr *url.Error + if errors.As(err, &urlErr) { + return "network" + } + var apiErr *APIError + if errors.As(err, &apiErr) && (apiErr.StatusCode == http.StatusTooManyRequests || apiErr.StatusCode >= http.StatusInternalServerError) { + return "http_error" + } + return "auth" +} + +func responseReadError(err error, status int) error { + return runreport.ReadFailure(fmt.Errorf("read response: %w: %w", errResponseLost, err), status) +} + // doOnce executes a single HTTP request (no retry). func (c *Client) doOnce(ctx context.Context, method, rawURL, accessToken string, body *Body) (json.RawMessage, error) { var bodyReader io.Reader @@ -605,7 +628,7 @@ func (c *Client) doOnce(ctx context.Context, method, rawURL, accessToken string, respBody, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("read response: %w: %w", errResponseLost, err) + return nil, responseReadError(err, resp.StatusCode) } if resp.StatusCode >= http.StatusBadRequest { @@ -706,7 +729,7 @@ func PostAnonymous(ctx context.Context, baseURL, path string, body json.RawMessa respBody, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("read response: %w: %w", errResponseLost, err) + return nil, responseReadError(err, resp.StatusCode) } if resp.StatusCode >= http.StatusBadRequest { @@ -769,7 +792,7 @@ func MintLoginCLILink(ctx context.Context, baseURL, saToken, destination string, req.Header.Set("Authorization", "Bearer "+saToken) setStandardHeaders(req) - resp, err := httpClient.Do(req) + resp, err := runreport.Do(httpClient, req) if err != nil { return nil, fmt.Errorf("http request: %w", err) } @@ -777,7 +800,7 @@ func MintLoginCLILink(ctx context.Context, baseURL, saToken, destination string, respBody, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("read response: %w", err) + return nil, runreport.ReadFailure(fmt.Errorf("read response: %w", err), resp.StatusCode) } if resp.StatusCode >= http.StatusBadRequest { diff --git a/internal/client/track.go b/internal/client/track.go index 97b098d..6121d39 100644 --- a/internal/client/track.go +++ b/internal/client/track.go @@ -68,7 +68,7 @@ func DoTrack(ctx context.Context, req TrackRequest) (json.RawMessage, error) { const maxResponseSize = 10 << 20 // 10 MB respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseSize)) if err != nil { - return nil, fmt.Errorf("read response: %w: %w", errResponseLost, err) + return nil, responseReadError(err, resp.StatusCode) } if resp.StatusCode >= http.StatusBadRequest { diff --git a/internal/output/error.go b/internal/output/error.go index f31ffbb..e434060 100644 --- a/internal/output/error.go +++ b/internal/output/error.go @@ -5,6 +5,8 @@ import ( "fmt" "io" "os" + + "github.com/customerio/cli/internal/runreport" ) // Exit codes. @@ -49,11 +51,24 @@ type CLIError struct { Details any `json:"details,omitempty"` } +var printedExitCode int + // PrintError writes a structured JSON error to stderr and returns the // appropriate exit code. func PrintError(code, message string, details any) int { + runreport.ErrorCode(code) + if code == CodeAuthError { + runreport.Reason("auth") + } FprintError(os.Stderr, code, message, details) - return ExitCodeForError(code) + printedExitCode = ExitCodeForError(code) + return printedExitCode +} + +// PrintedExitCode returns the exit code of the last error PrintError wrote, +// or 0 when it has written none. +func PrintedExitCode() int { + return printedExitCode } // FprintError writes a structured JSON error to w. diff --git a/internal/output/process.go b/internal/output/process.go index 9dd0503..23aad92 100644 --- a/internal/output/process.go +++ b/internal/output/process.go @@ -3,6 +3,8 @@ package output import ( "encoding/json" "io" + + "github.com/customerio/cli/internal/runreport" ) // FprintProcess applies --jq filtering to data and prints to w. When raw is @@ -11,7 +13,7 @@ func FprintProcess(w io.Writer, data json.RawMessage, jqExpr string, raw bool) e if jqExpr != "" { results, err := ApplyJQ(data, jqExpr) if err != nil { - return err + return runreport.WithReason(err, "jq_error") } if raw { return FprintRaw(w, results) diff --git a/internal/routes/pathindex.go b/internal/routes/pathindex.go index 28344ee..e44e908 100644 --- a/internal/routes/pathindex.go +++ b/internal/routes/pathindex.go @@ -183,19 +183,28 @@ func (idx *PathIndex) Len() int { // Lookup returns the path template matching the given method and path, which // may be given in either template form ("/v1/environments/{environment_id}/campaigns") -// or resolved form ("/v1/environments/123/campaigns"). +// or resolved form ("/v1/environments/123/campaigns"). When several match, the +// one with the most literal segments wins (".../metrics/all_deliveries" over +// ".../metrics/{name}"), so the answer doesn't depend on the spec's map order. func (idx *PathIndex) Lookup(httpMethod, path string) (string, bool) { reqSegs := splitPathSegments(path) + best, bestLiterals := "", -1 for i := range idx.entries { e := &idx.entries[i] - if e.httpMethod != strings.ToUpper(httpMethod) { + if e.httpMethod != strings.ToUpper(httpMethod) || !segmentsMatch(e.segments, reqSegs) { continue } - if segmentsMatch(e.segments, reqSegs) { - return e.path, true + literals := 0 + for _, seg := range e.segments { + if !isPlaceholderSegment(seg) { + literals++ + } + } + if literals > bestLiterals || (literals == bestLiterals && e.path < best) { + best, bestLiterals = e.path, literals } } - return "", false + return best, bestLiterals >= 0 } // MethodsFor returns the HTTP methods the index holds for the given path diff --git a/internal/routes/pathindex_test.go b/internal/routes/pathindex_test.go index ee6bb77..fe27f6b 100644 --- a/internal/routes/pathindex_test.go +++ b/internal/routes/pathindex_test.go @@ -117,6 +117,21 @@ func TestPathIndexMethodsForDistinguishesWrongVerb(t *testing.T) { } } +func TestPathIndexLookupPrefersLiteralSegments(t *testing.T) { + const literal, param = "/v1/environments/{environment_id}/metrics/all_deliveries", "/v1/environments/{environment_id}/metrics/{name}" + for _, idx := range []*PathIndex{ + indexFixture(t, "GET "+literal, "GET "+param), + indexFixture(t, "GET "+param, "GET "+literal), + } { + if got, _ := idx.Lookup("GET", "/v1/environments/456/metrics/all_deliveries"); got != literal { + t.Errorf("Lookup = %q, want %q", got, literal) + } + if got, _ := idx.Lookup("GET", "/v1/environments/456/metrics/opens"); got != param { + t.Errorf("Lookup = %q, want %q", got, param) + } + } +} + func TestPathIndexLookupIsMethodCaseInsensitive(t *testing.T) { idx := campaignsIndex(t) diff --git a/internal/runreport/report.go b/internal/runreport/report.go new file mode 100644 index 0000000..d79fd58 --- /dev/null +++ b/internal/runreport/report.go @@ -0,0 +1,212 @@ +package runreport + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptrace" + "os" + "path/filepath" + "sync/atomic" +) + +type report struct { + Version string `json:"version"` + Command string `json:"command"` + ExitCode int `json:"exit_code"` + ErrorCode *string `json:"error_code"` + Reason *string `json:"reason"` + Method *string `json:"method"` + Route *string `json:"route"` + RouteMatch string `json:"route_match"` + Requests int `json:"requests"` + Status *int `json:"status"` + + path string + lookupRoute func(method, path string) (string, bool) +} + +// The CLI runs one command per process. An unset report keeps the hooks inert. +var active *report + +func Enabled() bool { return active != nil } + +// Start begins a report written to path at Finish. It removes any earlier +// report first, so a run killed before Finish leaves none rather than a stale one. +func Start(path, version string) { + if info, err := os.Lstat(path); err == nil && info.Mode().IsRegular() { + _ = os.Remove(path) + } + active = &report{path: path, Version: version, RouteMatch: "not_checked"} +} + +func Finish(command string, exitCode int) { + r := active + active = nil + r.Command = command + r.ExitCode = exitCode + if exitCode == 0 { + r.ErrorCode = nil + r.Reason = nil + } else if r.Reason == nil { + r.Reason = new("other") + } + data, _ := json.Marshal(r) + // Write beside the target and rename, so a reader or a second run sharing the path never + // sees a partly written report. + tmp, err := os.CreateTemp(filepath.Dir(r.path), ".cio-run-report-*") + if err != nil { + return + } + _, werr := tmp.Write(append(data, '\n')) + if cerr := tmp.Close(); werr != nil || cerr != nil || os.Rename(tmp.Name(), r.path) != nil { + _ = os.Remove(tmp.Name()) + } +} + +func ErrorCode(code string) { + if active != nil { + active.ErrorCode = &code + } +} + +func Reason(reason string) { + if active != nil { + active.Reason = &reason + } +} + +func Method(method string) { + if active == nil { + return + } + switch method { + case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: + active.Method = &method + default: + active.Method = nil + } +} + +func MatchedRoute(template string) { + if active != nil { + active.Route = &template + active.RouteMatch = "matched" + } +} + +func RejectRoute(reason string) { + if active != nil { + active.RouteMatch = "not_in_spec" + Reason(reason) + } +} + +func SetRouteLookup(lookup func(method, path string) (string, bool)) { + active.lookupRoute = lookup +} + +type failure struct { + error + reason string +} + +func (f *failure) Unwrap() error { return f.error } + +// WithReason keeps the cause attached to errors that may be retried or ignored. +func WithReason(err error, reason string) error { + if active == nil { + return err + } + return &failure{error: err, reason: reason} +} + +func FailureReason(err error) string { + var f *failure + if errors.As(err, &f) { + return f.reason + } + return "" +} + +// ReadFailure tags a response body that failed to arrive: a dropped connection on a success, the +// status's failure otherwise. +func ReadFailure(err error, status int) error { + if status >= http.StatusOK && status < http.StatusMultipleChoices { + return WithReason(err, "network") + } + return WithHTTPStatus(err, status) +} + +func WithHTTPStatus(err error, status int) error { + if status < http.StatusOK || status >= http.StatusMultipleChoices { + return WithReason(err, "http_error") + } + return err +} + +type responseObserver struct { + http.RoundTripper + status int +} + +func (o *responseObserver) RoundTrip(req *http.Request) (*http.Response, error) { + resp, err := o.RoundTripper.RoundTrip(req) + if resp != nil { + o.status = resp.StatusCode + } + return resp, err +} + +// Do observes API traffic at the send boundary. Token exchanges and spec +// downloads use their own HTTP calls. +type untrackedKey struct{} + +// Untracked marks requests that are the CLI's own housekeeping, such as a token promotion probe or a +// funds check after a send, so the report describes only the command's requests. +func Untracked(ctx context.Context) context.Context { + return context.WithValue(ctx, untrackedKey{}, true) +} + +func Do(c *http.Client, req *http.Request) (*http.Response, error) { + r := active + if r == nil || req.Context().Value(untrackedKey{}) != nil { + return c.Do(req) + } + // A failed connection has no request to count. WroteHeaders also covers + // attempts that reached the server but received no response. + var sent atomic.Int64 + req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{ + WroteHeaders: func() { sent.Add(1) }, + })) + // http.Client follows redirects, so its final return can omit a response + // already received by the transport if the redirect fails. + observer := &responseObserver{RoundTripper: c.Transport} + if observer.RoundTripper == nil { + observer.RoundTripper = http.DefaultTransport + } + observedClient := *c + observedClient.Transport = observer + resp, err := observedClient.Do(req) + r.Requests += int(sent.Load()) + if status := observer.status; status != 0 { + r.Status = &status + if err != nil { + err = WithHTTPStatus(err, status) + } + } else if err != nil { + r.Status = nil + err = WithReason(err, "network") + } + // Like the status, method and route describe the last request, so a command + // that reads before it writes reports the write. + if lookup := r.lookupRoute; lookup != nil { + Method(req.Method) + r.Route, r.RouteMatch = nil, "not_checked" + if template, ok := lookup(req.Method, req.URL.EscapedPath()); ok { + MatchedRoute(template) + } + } + return resp, err +} diff --git a/internal/runreport/report_test.go b/internal/runreport/report_test.go new file mode 100644 index 0000000..fb9098f --- /dev/null +++ b/internal/runreport/report_test.go @@ -0,0 +1,158 @@ +package runreport + +import ( + "context" + "encoding/json" + "errors" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +func TestStartRemovesAnEarlierReport(t *testing.T) { + path := filepath.Join(t.TempDir(), "report.json") + if err := os.WriteFile(path, []byte(`{"stale":true}`), 0o600); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { active = nil }) + + Start(path, "test") + + if _, err := os.Stat(path); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("earlier report still present after Start: %v", err) + } +} + +func TestReportDescribesTheLastRequest(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + w.WriteHeader(http.StatusPreconditionRequired) + } + })) + t.Cleanup(server.Close) + path := filepath.Join(t.TempDir(), "report.json") + templates := map[string]string{"GET /domains": "/domains", "DELETE /domains/7": "/domains/{domain_id}"} + + Start(path, "test") + SetRouteLookup(func(method, p string) (string, bool) { + template, ok := templates[method+" "+p] + return template, ok + }) + for _, step := range []struct{ method, path string }{{http.MethodGet, "/domains"}, {http.MethodDelete, "/domains/7"}} { + req, err := http.NewRequest(step.method, server.URL+step.path, nil) + if err != nil { + t.Fatal(err) + } + resp, err := Do(server.Client(), req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + } + Finish("domains delete", 1) + + var got struct { + Method string `json:"method"` + Route string `json:"route"` + Status int `json:"status"` + Requests int `json:"requests"` + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + if got.Method != http.MethodDelete || got.Route != "/domains/{domain_id}" || got.Status != http.StatusPreconditionRequired || got.Requests != 2 { + t.Errorf("report = %s, want the DELETE's method, route and status after 2 requests", data) + } +} + +func TestHousekeepingRequestsStayOutOfTheReport(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + t.Cleanup(server.Close) + path := filepath.Join(t.TempDir(), "report.json") + + Start(path, "test") + SetRouteLookup(func(method, p string) (string, bool) { return "/wallet", true }) + req, err := http.NewRequestWithContext(Untracked(context.Background()), http.MethodGet, server.URL+"/wallet", nil) + if err != nil { + t.Fatal(err) + } + resp, err := Do(server.Client(), req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + Finish("send email", 0) + + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var got struct { + Method *string `json:"method"` + Route *string `json:"route"` + Requests int `json:"requests"` + Status *int `json:"status"` + } + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + if got.Method != nil || got.Route != nil || got.Requests != 0 || got.Status != nil { + t.Errorf("report = %s, want the untracked request left out", data) + } +} + +func TestStatusClearsWhenTheLastAttemptGetsNoResponse(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + gone := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + gone.Close() + t.Cleanup(server.Close) + path := filepath.Join(t.TempDir(), "report.json") + + Start(path, "test") + for _, url := range []string{server.URL, gone.URL} { + req, err := http.NewRequest(http.MethodGet, url+"/campaigns", nil) + if err != nil { + t.Fatal(err) + } + if resp, err := Do(server.Client(), req); err == nil { + _ = resp.Body.Close() + } + } + Finish("api", 1) + + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var got struct { + Status *int `json:"status"` + } + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + if got.Status != nil { + t.Errorf("status = %d, want none for an attempt that got no response", *got.Status) + } +} + +func TestReadFailureNamesADroppedSuccessAsNetwork(t *testing.T) { + t.Cleanup(func() { active = nil }) + Start(filepath.Join(t.TempDir(), "report.json"), "test") + readErr := errors.New("unexpected EOF") + + if got := FailureReason(ReadFailure(readErr, http.StatusOK)); got != "network" { + t.Errorf("200 body read failure reason = %q, want network", got) + } + if got := FailureReason(ReadFailure(readErr, http.StatusNotFound)); got != "http_error" { + t.Errorf("404 body read failure reason = %q, want http_error", got) + } +} diff --git a/internal/skills/skills.go b/internal/skills/skills.go index 903a521..0071796 100644 --- a/internal/skills/skills.go +++ b/internal/skills/skills.go @@ -15,6 +15,7 @@ import ( "time" "github.com/customerio/cli/internal/filelock" + "github.com/customerio/cli/internal/runreport" "github.com/customerio/cli/internal/useragent" ) @@ -335,7 +336,7 @@ func downloadSkills(ctx context.Context, httpClient *http.Client, url, userAgent req.Header.Set("If-None-Match", etag) } - resp, err := httpClient.Do(req) + resp, err := runreport.Do(httpClient, req) if err != nil { return nil, "", fmt.Errorf("fetch %s: %w", url, err) } @@ -347,11 +348,11 @@ func downloadSkills(ctx context.Context, httpClient *http.Client, url, userAgent case http.StatusOK: body, err := io.ReadAll(io.LimitReader(resp.Body, skillsDownloadSize)) if err != nil { - return nil, "", fmt.Errorf("read response from %s: %w", url, err) + return nil, "", runreport.ReadFailure(fmt.Errorf("read response from %s: %w", url, err), resp.StatusCode) } return body, resp.Header.Get("ETag"), nil default: - return nil, "", fmt.Errorf("HTTP %d from %s", resp.StatusCode, url) + return nil, "", runreport.WithHTTPStatus(fmt.Errorf("HTTP %d from %s", resp.StatusCode, url), resp.StatusCode) } } diff --git a/internal/useragent/useragent.go b/internal/useragent/useragent.go index b668548..48636bd 100644 --- a/internal/useragent/useragent.go +++ b/internal/useragent/useragent.go @@ -13,6 +13,9 @@ func SetVersion(v string) { version = v } +// Version returns the CLI version used in outgoing requests. +func Version() string { return version } + // Get returns the User-Agent value used for outgoing CLI requests. func Get() string { return productName + "/" + version + " (+" + repositoryURL + ")"