forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrules.go
More file actions
268 lines (246 loc) · 8.47 KB
/
rules.go
File metadata and controls
268 lines (246 loc) · 8.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Package gorules defines custom lint rules for ruleguard.
//
// golangci-lint runs these rules via go-critic, which includes support
// for ruleguard. All Go files in this directory define lint rules
// in the Ruleguard DSL; see:
//
// - https://go-ruleguard.github.io/by-example/
// - https://pkg.go.dev/github.com/quasilyte/go-ruleguard/dsl
//
// You run one of the following commands to execute your go rules only:
//
// golangci-lint run
// golangci-lint run --disable-all --enable=gocritic
//
// Note: don't forget to run `golangci-lint cache clean`!
package gorules
import (
"github.com/quasilyte/go-ruleguard/dsl"
"github.com/quasilyte/go-ruleguard/dsl/types"
)
// Use xerrors everywhere! It provides additional stacktrace info!
//
//nolint:unused,deadcode,varnamelen
func xerrors(m dsl.Matcher) {
m.Import("errors")
m.Import("fmt")
m.Import("golang.org/x/xerrors")
m.Match("fmt.Errorf($*args)").
Suggest("xerrors.New($args)").
Report("Use xerrors to provide additional stacktrace information!")
m.Match("errors.$_($msg)").
Where(m["msg"].Type.Is("string")).
Suggest("xerrors.New($msg)").
Report("Use xerrors to provide additional stacktrace information!")
}
// databaseImport enforces not importing any database types into /codersdk.
//
//nolint:unused,deadcode,varnamelen
func databaseImport(m dsl.Matcher) {
m.Import("github.com/coder/coder/coderd/database")
m.Match("database.$_").
Report("Do not import any database types into codersdk").
Where(m.File().PkgPath.Matches("github.com/coder/coder/codersdk"))
}
// doNotCallTFailNowInsideGoroutine enforces not calling t.FailNow or
// functions that may themselves call t.FailNow in goroutines outside
// the main test goroutine. See testing.go:834 for why.
//
//nolint:unused,deadcode,varnamelen
func doNotCallTFailNowInsideGoroutine(m dsl.Matcher) {
m.Import("testing")
m.Match(`
go func($*_){
$*_
$require.$_($*_)
$*_
}($*_)`).
At(m["require"]).
Where(m["require"].Text == "require").
Report("Do not call functions that may call t.FailNow in a goroutine, as this can cause data races (see testing.go:834)")
// require.Eventually runs the function in a goroutine.
m.Match(`
require.Eventually(t, func() bool {
$*_
$require.$_($*_)
$*_
}, $*_)`).
At(m["require"]).
Where(m["require"].Text == "require").
Report("Do not call functions that may call t.FailNow in a goroutine, as this can cause data races (see testing.go:834)")
m.Match(`
go func($*_){
$*_
$t.$fail($*_)
$*_
}($*_)`).
At(m["fail"]).
Where(m["t"].Type.Implements("testing.TB") && m["fail"].Text.Matches("^(FailNow|Fatal|Fatalf)$")).
Report("Do not call functions that may call t.FailNow in a goroutine, as this can cause data races (see testing.go:834)")
}
// useStandardTimeoutsAndDelaysInTests ensures all tests use common
// constants for timeouts and delays in usual scenarios, this allows us
// to tweak them based on platform (important to avoid CI flakes).
//
//nolint:unused,deadcode,varnamelen
func useStandardTimeoutsAndDelaysInTests(m dsl.Matcher) {
m.Import("github.com/stretchr/testify/require")
m.Import("github.com/stretchr/testify/assert")
m.Import("github.com/coder/coder/testutil")
m.Match(`context.WithTimeout($ctx, $duration)`).
Where(m.File().Imports("testing") && !m.File().PkgPath.Matches("testutil$") && !m["duration"].Text.Matches("^testutil\\.")).
At(m["duration"]).
Report("Do not use magic numbers in test timeouts and delays. Use the standard testutil.Wait* or testutil.Interval* constants instead.")
m.Match(`
$testify.$Eventually($t, func() bool {
$*_
}, $timeout, $interval, $*_)
`).
Where((m["testify"].Text == "require" || m["testify"].Text == "assert") &&
(m["Eventually"].Text == "Eventually" || m["Eventually"].Text == "Eventuallyf") &&
!m["timeout"].Text.Matches("^testutil\\.")).
At(m["timeout"]).
Report("Do not use magic numbers in test timeouts and delays. Use the standard testutil.Wait* or testutil.Interval* constants instead.")
m.Match(`
$testify.$Eventually($t, func() bool {
$*_
}, $timeout, $interval, $*_)
`).
Where((m["testify"].Text == "require" || m["testify"].Text == "assert") &&
(m["Eventually"].Text == "Eventually" || m["Eventually"].Text == "Eventuallyf") &&
!m["interval"].Text.Matches("^testutil\\.")).
At(m["interval"]).
Report("Do not use magic numbers in test timeouts and delays. Use the standard testutil.Wait* or testutil.Interval* constants instead.")
}
// InTx checks to ensure the database used inside the transaction closure is the transaction
// database, and not the original database that creates the tx.
func InTx(m dsl.Matcher) {
// ':=' and '=' are 2 different matches :(
m.Match(`
$x.InTx(func($y) error {
$*_
$*_ = $x.$f($*_)
$*_
})
`, `
$x.InTx(func($y) error {
$*_
$*_ := $x.$f($*_)
$*_
})
`).Where(m["x"].Text != m["y"].Text).
At(m["f"]).
Report("Do not use the database directly within the InTx closure. Use '$y' instead of '$x'.")
// When using a tx closure, ensure that if you pass the db to another
// function inside the closure, it is the tx.
// This will miss more complex cases such as passing the db as apart
// of another struct.
m.Match(`
$x.InTx(func($y database.Store) error {
$*_
$*_ = $f($*_, $x, $*_)
$*_
})
`, `
$x.InTx(func($y database.Store) error {
$*_
$*_ := $f($*_, $x, $*_)
$*_
})
`, `
$x.InTx(func($y database.Store) error {
$*_
$f($*_, $x, $*_)
$*_
})
`).Where(m["x"].Text != m["y"].Text).
At(m["f"]).Report("Pass the tx database into the '$f' function inside the closure. Use '$y' over $x'")
}
// HttpAPIErrorMessage intends to enforce constructing proper sentences as
// error messages for the api. A proper sentence includes proper capitalization
// and ends with punctuation.
// There are ways around the linter, but this should work in the common cases.
func HttpAPIErrorMessage(m dsl.Matcher) {
m.Import("github.com/coder/coder/coderd/httpapi")
isNotProperError := func(v dsl.Var) bool {
return v.Type.Is("string") &&
// Either starts with a lowercase, or ends without punctuation.
// The reason I don't check for NOT ^[A-Z].*[.!?]$ is because there
// are some exceptions. Any string starting with a formatting
// directive (%s) for example is exempt.
(m["m"].Text.Matches(`^"[a-z].*`) ||
m["m"].Text.Matches(`.*[^.!?]"$`))
}
m.Match(`
httpapi.Write($_, $_, $s, httpapi.Response{
$*_,
Message: $m,
$*_,
})
`, `
httpapi.Write($_, $_, $s, httpapi.Response{
$*_,
Message: fmt.$f($m, $*_),
$*_,
})
`,
).Where(isNotProperError(m["m"])).
At(m["m"]).
Report("Field \"Message\" should be a proper sentence with a capitalized first letter and ending in punctuation. $m")
}
// HttpAPIReturn will report a linter violation if the http function is not
// returned after writing a response to the client.
func HttpAPIReturn(m dsl.Matcher) {
m.Import("github.com/coder/coder/coderd/httpapi")
// Manually enumerate the httpapi function rather then a 'Where' condition
// as this is a bit more efficient.
m.Match(`
if $*_ {
httpapi.Write($*a)
}
`, `
if $*_ {
httpapi.Forbidden($*a)
}
`, `
if $*_ {
httpapi.ResourceNotFound($*a)
}
`).At(m["a"]).
Report("Forgot to return early after writing to the http response writer.")
}
// ProperRBACReturn ensures we always write to the response writer after a
// call to Authorize. If we just do a return, the client will get a status code
// 200, which is incorrect.
func ProperRBACReturn(m dsl.Matcher) {
m.Match(`
if !$_.Authorize($*_) {
return
}
`).Report("Must write to 'ResponseWriter' before returning'")
}
// FullResponseWriter ensures that any overridden response writer has full
// functionality. Mainly is hijackable and flushable.
func FullResponseWriter(m dsl.Matcher) {
m.Match(`
type $w struct {
$*_
http.ResponseWriter
$*_
}
`).
At(m["w"]).
Where(m["w"].Filter(notImplementsFullResponseWriter)).
Report("ResponseWriter \"$w\" must implement http.Flusher and http.Hijacker")
}
// notImplementsFullResponseWriter returns false if the type does not implement
// http.Flusher, http.Hijacker, and http.ResponseWriter.
func notImplementsFullResponseWriter(ctx *dsl.VarFilterContext) bool {
flusher := ctx.GetInterface(`net/http.Flusher`)
hijacker := ctx.GetInterface(`net/http.Hijacker`)
writer := ctx.GetInterface(`net/http.ResponseWriter`)
p := types.NewPointer(ctx.Type)
return !(types.Implements(p, writer) || types.Implements(ctx.Type, writer)) ||
!(types.Implements(p, flusher) || types.Implements(ctx.Type, flusher)) ||
!(types.Implements(p, hijacker) || types.Implements(ctx.Type, hijacker))
}