Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ cio api /v1/environments/{environment_id}/campaigns \
| `--dry-run` | | Validate + print request, skip execution |
| `--api-url <url>` | | API base URL override |
| `--timeout <duration>` | `CIO_TIMEOUT` | HTTP request timeout (default: 30s) |
| | `CIO_RUN_REPORT` | Write a JSON summary of the run to this file |
| `--page <n>` | | Page number |
| `--limit <n>` | | Page size |
| `--page-all` | | Auto-paginate, emit NDJSON |
Expand All @@ -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 |
Expand Down
12 changes: 11 additions & 1 deletion cmd/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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
}
Expand All @@ -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")
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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])
Expand Down
24 changes: 20 additions & 4 deletions cmd/api_preflight_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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")
Expand All @@ -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":
Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions cmd/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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'.",
})
Expand All @@ -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
}
Expand All @@ -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))),
Expand Down
6 changes: 6 additions & 0 deletions cmd/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
19 changes: 9 additions & 10 deletions cmd/billing_add_funds.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -163,35 +164,33 @@ 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
}
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)
}
2 changes: 1 addition & 1 deletion cmd/billing_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand Down
3 changes: 2 additions & 1 deletion cmd/funds_warning.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)

Expand Down
41 changes: 28 additions & 13 deletions cmd/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Loading