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
3 changes: 2 additions & 1 deletion internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"github.com/tidbcloud/tidbcloud-cli/internal/iostream"
"github.com/tidbcloud/tidbcloud-cli/internal/log"
"github.com/tidbcloud/tidbcloud-cli/internal/prop"
"github.com/tidbcloud/tidbcloud-cli/internal/redact"
"github.com/tidbcloud/tidbcloud-cli/internal/service/aws/s3"
"github.com/tidbcloud/tidbcloud-cli/internal/service/cloud"
"github.com/tidbcloud/tidbcloud-cli/internal/service/github"
Expand Down Expand Up @@ -108,7 +109,7 @@ func Execute(ctx context.Context) {
ctx = telemetry.NewTelemetryContext(ctx)
if err := rootCmd.ExecuteContext(ctx); err != nil {
telemetry.FinishTrackingCommand(telemetry.TrackOptions{Err: err})
fmt.Fprint(h.IOStreams.Out, color.RedString("Error: %s\n", err.Error()))
fmt.Fprint(h.IOStreams.Out, color.RedString("Error: %s\n", redact.Text(err.Error())))
if errors.Is(err, util.InterruptError) {
os.Exit(130)
}
Expand Down
15 changes: 15 additions & 0 deletions internal/redact/redact.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"io"
"net/http"
"net/url"
"regexp"
"strings"
)

Expand Down Expand Up @@ -260,3 +261,17 @@ func (dt *DebugTransport) RoundTrip(r *http.Request) (*http.Response, error) {
}
return resp, err
}

var diagnosticURL = regexp.MustCompile(`[a-zA-Z][a-zA-Z0-9+.-]*://[^\s<>"']+`)

// Text masks credentials in URLs embedded in diagnostic messages. It does not
// attempt to identify arbitrary secrets in free text.
func Text(message string) string {
return diagnosticURL.ReplaceAllStringFunc(message, func(value string) string {
u, err := url.Parse(value)
if err != nil {
return Mask
}
return URL(u)
})
}
42 changes: 42 additions & 0 deletions internal/redact/text_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2026 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package redact

import (
"errors"
"fmt"
"net/url"
"testing"

"github.com/stretchr/testify/require"
)

func TestDiagnosticText(t *testing.T) {
uploadErr := fmt.Errorf("upload failed: %w", &url.Error{
Op: "Put",
URL: "https://storage.example/upload?partNumber=1&X-Amz-Signature=signature-secret&X-Amz-Credential=credential-secret&X-Amz-Security-Token=session-secret",
Err: errors.New("connection reset"),
})
message := Text(uploadErr.Error())
for _, secret := range []string{"signature-secret", "credential-secret", "session-secret"} {
require.NotContains(t, message, secret)
}
require.Contains(t, message, "storage.example/upload")
require.Contains(t, message, "partNumber=1")
require.Contains(t, message, "connection reset")
require.NotContains(t, Text("failed tidb://user:sql-secret@example.com:4000"), "sql-secret")
require.NotContains(t, Text("failed https://example.com/%xx?token=bad-secret"), "bad-secret")
require.Equal(t, "connection refused", Text("connection refused"))
}
2 changes: 1 addition & 1 deletion internal/service/cloud/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -873,7 +873,7 @@ func parseError(err error, resp *http.Response) error {
if resp.Header.Get("X-Debug-Trace-Id") != "" {
traceId = resp.Header.Get("X-Debug-Trace-Id")
}
return fmt.Errorf("%s[%s][%s] %s", path, err.Error(), traceId, body)
return fmt.Errorf("%s[%s][%s] %s", path, resp.Status, traceId, redact.JSON(body))
}

func (d *ClientDelegate) CreateChangefeed(ctx context.Context, clusterId string, body *cdc.ChangefeedServiceCreateChangefeedBody) (*cdc.Changefeed, error) {
Expand Down
44 changes: 44 additions & 0 deletions internal/service/cloud/api_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2026 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cloud

import (
"errors"
"io"
"net/http"
"strings"
"testing"

"github.com/stretchr/testify/require"
)

func TestAPIErrorBodyRedacted(t *testing.T) {
for _, body := range []string{
`{"password":"body-secret","message":"invalid request","nested":{"access_token":"token-secret"},"url":"https://example.com?X-Amz-Signature=url-secret"}`,
"unstructured body-secret",
} {
resp := &http.Response{
Status: "400 Bad Request",
Header: http.Header{"X-Debug-Trace-Id": []string{"trace-123"}},
Body: io.NopCloser(strings.NewReader(body)),
}
err := parseError(errors.New("SDK may duplicate body-secret"), resp)
for _, secret := range []string{"body-secret", "token-secret", "url-secret"} {
require.NotContains(t, err.Error(), secret)
}
require.Contains(t, err.Error(), "400 Bad Request")
require.Contains(t, err.Error(), "trace-123")
}
}
7 changes: 3 additions & 4 deletions internal/telemetry/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,12 @@ func withInstaller(installer *string) eventOpt {
}
}

func withError(err error) eventOpt {
func withError(_ error) eventOpt {
return func(event Event) {
event.Properties["result"] = "ERROR"

errorMessage := strings.Split(err.Error(), "\n")[0] // only first line

event.Properties["error"] = errorMessage
// Free-form errors may contain credentials or customer data. Report
// failure without transmitting the diagnostic message.
}
}

Expand Down
4 changes: 2 additions & 2 deletions internal/telemetry/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,11 +210,11 @@ func (suite *EventSuite) TestWithProjectID_NoFlag() {
}

func (suite *EventSuite) TestWithError() {
e := newEvent(withError(errors.New("test")))
e := newEvent(withError(errors.New("password=telemetry-secret\nsecond line")))

a := require.New(suite.T())
a.Equal("ERROR", e.Properties["result"])
a.Equal("test", e.Properties["error"])
a.NotContains(e.Properties, "error")
}

func TestEventSuite(t *testing.T) {
Expand Down
11 changes: 10 additions & 1 deletion internal/util/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ import (
"io"
"os"
"os/user"
"strings"

"github.com/tidbcloud/tidbcloud-cli/internal/redact"

"github.com/go-sql-driver/mysql"
isatty "github.com/mattn/go-isatty"
Expand Down Expand Up @@ -62,7 +65,7 @@ func ExecuteSqlDialog(ctx context.Context, clusterType, userName, host, port str
}

if err = h.Open(ctx, dsn); err != nil {
return fmt.Errorf("can't open connection to %s: %s", dsn, err.Error())
return connectionError(dsn, err)
}

if err = h.Run(); err != io.EOF {
Expand Down Expand Up @@ -114,3 +117,9 @@ func generateDsnWithoutPassword(clusterType string, userName string, host string
}
return dsn, err
}

func connectionError(dsn string, err error) error {
// The driver may also include the original DSN in its error.
detail := strings.ReplaceAll(err.Error(), dsn, "<DSN omitted>")
return fmt.Errorf("can't open connection: %s", redact.Text(detail))
}
34 changes: 34 additions & 0 deletions internal/util/shell_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2026 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package util

import (
"errors"
"testing"

"github.com/stretchr/testify/require"
)

func TestConnectionErrorOmitsDSN(t *testing.T) {
dsn, err := generateDsnWithPassword(SERVERLESS, "user", "example.com", "4000", "sql-secret")
require.NoError(t, err)
for _, cause := range []error{errors.New("connection refused"), errors.New("invalid connection " + dsn)} {
message := connectionError(dsn, cause).Error()
require.NotContains(t, message, "sql-secret")
require.NotContains(t, message, dsn)
require.Contains(t, message, "can't open connection")
}
require.Contains(t, connectionError(dsn, errors.New("connection refused")).Error(), "connection refused")
}
Loading