Skip to content
Open
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
25 changes: 25 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,28 @@ jobs:
exit (100 * covered < minimum * total)
}
' coverage.out

ruleguard:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with:
go-version-file: tools/check/ruleguard_test/go.mod
cache-dependency-path: tools/check/ruleguard_test/go.sum
- name: Check Ruleguard diagnostics
working-directory: tools/check/ruleguard_test
shell: bash
run: |
status=0
output=$(./run-golangci-lint.sh --uniq-by-line=false --show-stats=false \
--output.text.colors=false --output.text.print-issued-lines=false) || status=$?
if [[ $status -ne 1 ]]; then
printf 'Expected golangci-lint to exit with status 1, got %s\n%s\n' "$status" "$output" >&2
exit 1
fi

diff -u - <(printf '%s\n' "$output") <<'EXPECTED'
sample.go:13:15: ruleguard: Use FastGenByArgs for template arguments. Call FastGenWithCause() with no arguments to render a wrapped cause. (gocritic)
sample.go:14:15: ruleguard: Use GenWithStackByArgs for template arguments. Call GenWithStackByCause() with no arguments to render a wrapped cause. (gocritic)
EXPECTED
24 changes: 20 additions & 4 deletions normalize.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,23 +360,39 @@ func (e *Error) Cause() error {
return root
}

// FastGenWithCause generates a stackless error with the same class and code,
// using the cause's error text as a literal message without formatting arguments.
// Only use it as errorTemplate.Wrap(err).FastGenWithCause(),
// and errorTemplate should not expect any arguments.
// To format the template with arguments, use FastGenByArgs instead.
func (e *Error) FastGenWithCause(args ...any) error {
// Handle deprecated usage.
if len(args) > 0 {
return e.FastGenByArgs(args...)
}
err := *e
if e.cause != nil {
err.message = e.cause.Error()
}
err.args = freezeHackedStringArgs(args)
RedactErrorArg(err.args, e.redactArgsPos)
err.args = nil
return SuspendStack(&err)
}

// GenWithStackByCause generates an error with a stack trace and the same class
// and code, using the cause's error text as a literal message without formatting arguments.
// Only use it as errorTemplate.Wrap(err).GenWithStackByCause(),
// and errorTemplate should not expect any arguments.
// To format the template with arguments, use GenWithStackByArgs instead.
func (e *Error) GenWithStackByCause(args ...any) error {
// Handle deprecated usage.
if len(args) > 0 {
return e.GenWithStackByArgs(args...)
}
err := *e
if e.cause != nil {
err.message = e.cause.Error()
}
err.args = freezeHackedStringArgs(args)
RedactErrorArg(err.args, e.redactArgsPos)
err.args = nil
err.fillLineAndFile(1)
return AddStack(&err)
}
Expand Down
88 changes: 26 additions & 62 deletions normalize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,8 @@ func TestFastGenByArgsRedaction(t *testing.T) {
func TestGenWithStackByCauseRedaction(t *testing.T) {
previousMode := RedactLogEnabled.Load()
t.Cleanup(func() { RedactLogEnabled.Store(previousMode) })
prototype := Normalize("template %s, public %s", RFCCodeText("Internal:Test"), RedactArgs([]int{0, 5}))
cause := stderrors.New("cause %s, public %s")
wrapped := prototype.Wrap(cause)
prototype := Normalize("unused template", RFCCodeText("Internal:Test"), RedactArgs([]int{0}))
causeTemplate := Normalize("cause %s, public %s, 95%% full, %%1000000[1]d", RFCCodeText("Internal:Cause"), RedactArgs([]int{0}))

for _, tc := range []struct {
mode string
Expand All @@ -256,29 +255,29 @@ func TestGenWithStackByCauseRedaction(t *testing.T) {
} {
t.Run(tc.mode, func(t *testing.T) {
RedactLogEnabled.Store(tc.mode)
origin := []byte("secret‹›")
err := wrapped.GenWithStackByCause(hackedStringArg{raw: origin}, "visible")
fallback := prototype.GenWithStackByCause(hackedStringArg{raw: origin}, "visible")
copy(origin, "modified")
cause := causeTemplate.GenWithStackByArgs("secret‹›", "visible")
err := prototype.Wrap(cause).GenWithStackByCause()
want := "[Internal:Cause]cause " + tc.arg + ", public visible, 95% full, %1000000[1]d"
got := err.(*withStack).error.(*Error)
require.Equal(t, "cause "+tc.arg+", public visible", got.GetMsg())
require.Same(t, cause, got.Unwrap())
require.Equal(t, prototype.ID(), got.ID())
require.True(t, HasStack(err))
require.Contains(t, fmt.Sprintf("%+v", err), "TestGenWithStackByCauseRedaction")
require.EqualError(t, fallback, "[Internal:Test]template "+tc.arg+", public visible")
require.Equal(t, "template %s, public %s", wrapped.message)
require.Empty(t, wrapped.args)
require.Equal(t, want, got.GetMsg())
require.EqualError(t, err, "[Internal:Test]"+want+": "+want)
})
}
}

func TestFastGenWithCauseDeprecatedArgs(t *testing.T) {
// Note: using the *Cause() functions with args is deprecated.
// The following tests ensure that the deprecated usage still behave as expected.
errTest := Normalize("foo %s", RFCCodeText("Internal:Test"))
require.EqualError(t, errTest.FastGenWithCause("bar"), "[Internal:Test]foo bar")
require.EqualError(t, errTest.GenWithStackByCause("baz"), "[Internal:Test]foo baz")
}

func TestFastGenWithCauseRedaction(t *testing.T) {
previousMode := RedactLogEnabled.Load()
t.Cleanup(func() { RedactLogEnabled.Store(previousMode) })
prototype := Normalize("template %s, public %s", RFCCodeText("Internal:Test"), RedactArgs([]int{0, 5}))
cause := stderrors.New("cause %s, public %s")
wrapped := prototype.Wrap(cause)
prototype := Normalize("unused template", RFCCodeText("Internal:Test"), RedactArgs([]int{0}))
causeTemplate := Normalize("cause %s, public %s, 95%% full, %%1000000[1]d", RFCCodeText("Internal:Cause"), RedactArgs([]int{0}))

for _, tc := range []struct {
mode string
Expand All @@ -290,21 +289,12 @@ func TestFastGenWithCauseRedaction(t *testing.T) {
} {
t.Run(tc.mode, func(t *testing.T) {
RedactLogEnabled.Store(tc.mode)
origin := []byte("secret‹›")
err := wrapped.FastGenWithCause(hackedStringArg{raw: origin}, "visible")
fallback := prototype.FastGenWithCause(hackedStringArg{raw: origin}, "visible")
copy(origin, "modified")
cause := causeTemplate.GenWithStackByArgs("secret‹›", "visible")
err := prototype.Wrap(cause).FastGenWithCause()
want := "[Internal:Cause]cause " + tc.arg + ", public visible, 95% full, %1000000[1]d"
got := err.(*withStack).error.(*Error)
require.Equal(t, "cause "+tc.arg+", public visible", got.GetMsg())
require.Same(t, cause, got.Unwrap())
require.Equal(t, prototype.ID(), got.ID())
require.False(t, HasStack(err))
file, line := got.Location()
require.Empty(t, file)
require.Zero(t, line)
require.EqualError(t, fallback, "[Internal:Test]template "+tc.arg+", public visible")
require.Equal(t, "template %s, public %s", wrapped.message)
require.Empty(t, wrapped.args)
require.Equal(t, want, got.GetMsg())
require.EqualError(t, err, "[Internal:Test]"+want+": "+want)
})
}
}
Expand Down Expand Up @@ -384,6 +374,8 @@ func TestGenWithStackByArgsFreezeHackedStringArg(t *testing.T) {
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
wrapped := errTest.Wrap(err).GenWithStackByCause()
require.Equal(t, err.Error(), wrapped.(*withStack).error.(*Error).GetMsg())
}

func TestFastGenByArgsFreezeHackedStringArg(t *testing.T) {
Expand All @@ -399,6 +391,8 @@ func TestFastGenByArgsFreezeHackedStringArg(t *testing.T) {
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
wrapped := errTest.Wrap(err).FastGenWithCause()
require.Equal(t, err.Error(), wrapped.(*withStack).error.(*Error).GetMsg())
}

func TestGenWithStackFreezeHackedStringArg(t *testing.T) {
Expand Down Expand Up @@ -430,33 +424,3 @@ func TestFastGenFreezeHackedStringArg(t *testing.T) {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
}

func TestGenWithStackByCauseFreezeHackedStringArg(t *testing.T) {
errTest := Normalize("Incorrect time value: '%s'", RFCCodeText("Internal:Test"))

origin := []byte("120120519090607")
arg := hackedStringArg{raw: origin}
err := errTest.GenWithStackByCause(arg)

copy(origin, "1 1:1:1.0000027")
got := err.(*withStack).error.(*Error).GetMsg()
want := "Incorrect time value: '120120519090607'"
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
}

func TestFastGenWithCauseFreezeHackedStringArg(t *testing.T) {
errTest := Normalize("Incorrect time value: '%s'", RFCCodeText("Internal:Test"))

origin := []byte("120120519090607")
arg := hackedStringArg{raw: origin}
err := errTest.FastGenWithCause(arg)

copy(origin, "1 1:1:1.0000027")
got := err.(*withStack).error.(*Error).GetMsg()
want := "Incorrect time value: '120120519090607'"
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
}
49 changes: 49 additions & 0 deletions tools/check/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Linting format arguments passed to `*Cause` methods

Passing arguments to `GenWithStackByCause` or `FastGenWithCause` is deprecated. Previously, wrapped error strings were treated as `printf` format templates, and will behave wrongly if the message contained format directives (e.g. `%s`).

Keep cause text literal and pass format arguments to the template methods instead:
* **Formatting a template:** `errCode.GenWithStackByArgs(args...)` or `errCode.FastGenByArgs(args...)`
* **Wrapping a literal cause:** `errCode.Wrap(err).GenWithStackByCause()` or `errCode.Wrap(err).FastGenWithCause()`

In the future versions we will remove support for passing format arguments directly to `*Cause` methods, and only the template methods will accept formatting arguments.

Currently, you can enforce this in downstream repositories using the [Ruleguard rules](ruleguard/pingcap-errors.go).

## Setup with golangci-lint

Add `ruleguard` to your `.golangci.yml`:

```yaml
version: "2"
linters:
enable:
- gocritic

settings:
gocritic:
disable-all: true
enabled-checks:
- ruleguard
settings:
ruleguard:
failOn: all
rules: '${config-path}/tools/check/ruleguard/pingcap-errors.go'

```

(Note: `${config-path}` resolves to the directory where `.golangci.yml` lives. If you already have `gocritic` enabled, just add `ruleguard` to your existing `enabled-checks` list instead of disabling everything else.)

Next, pull the rule file from your `pingcap/errors` dependency into your repo (or run this as a CI step before linting):

```sh
go mod download github.com/pingcap/errors
errors_dir=$(go list -m -f '{{.Dir}}' github.com/pingcap/errors)
mkdir -p tools/check/ruleguard
cp "$errors_dir/tools/check/ruleguard/pingcap-errors.go" tools/check/ruleguard/pingcap-errors.go
golangci-lint run
```

## Troubleshooting:

* **Missing DSL package:** Ruleguard requires `github.com/quasilyte/go-ruleguard/dsl` at runtime. If your linter fails to resolve it, add the DSL module to `go.mod`.
31 changes: 31 additions & 0 deletions tools/check/ruleguard/pingcap-errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//go:build ignore

package rules

import (
"github.com/quasilyte/go-ruleguard/dsl"
"github.com/quasilyte/go-ruleguard/dsl/types"
)

func isPingcapError(ctx *dsl.VarFilterContext) bool {
want := ctx.GetType("github.com/pingcap/errors.Error")
return types.Identical(ctx.Type, want) || types.Identical(ctx.Type, types.NewPointer(want))
}

func genWithStackByCauseArgs(m dsl.Matcher) {
m.Match(
`$recv.GenWithStackByCause($_, $*_)`,
`$recv.GenWithStackByCause($_...)`,
).
Where(m["recv"].Filter(isPingcapError)).
Report("Use GenWithStackByArgs for template arguments. Call GenWithStackByCause() with no arguments to render a wrapped cause.")
}

func fastGenWithCauseArgs(m dsl.Matcher) {
m.Match(
`$recv.FastGenWithCause($_, $*_)`,
`$recv.FastGenWithCause($_...)`,
).
Where(m["recv"].Filter(isPingcapError)).
Report("Use FastGenByArgs for template arguments. Call FastGenWithCause() with no arguments to render a wrapped cause.")
}
15 changes: 15 additions & 0 deletions tools/check/ruleguard_test/.golang-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
version: "2"
linters:
default: none
enable:
- gocritic

settings:
gocritic:
disable-all: true
enabled-checks:
- ruleguard
settings:
ruleguard:
failOn: all
rules: '${config-path}/../ruleguard/pingcap-errors.go'
Loading