Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

golangci-lint: enable more linters and address linting issues #191

Merged
merged 12 commits into from
Oct 17, 2022
4 changes: 2 additions & 2 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
go-version: 1.19.x
- uses: golangci/golangci-lint-action@v3
with:
version: v1.49
version: v1.50

cross:
runs-on: ubuntu-20.04
Expand All @@ -54,7 +54,7 @@ jobs:
go-version: 1.19.x
- uses: golangci/golangci-lint-action@v3
with:
version: v1.49
version: v1.50
- name: test-stubs
run: make test

Expand Down
34 changes: 30 additions & 4 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,33 @@ run:
deadline: 5m
linters:
enable:
- whitespace
- gocritic
- errorlint
- gofumpt
- dupword # Detects duplicate words.
- errorlint # Detects code that may cause problems with Go 1.13 error wrapping.
- exportloopref # Detects pointers to enclosing loop variables.
- gocritic # Metalinter; detects bugs, performance, and styling issues.
- gofumpt # Detects whether code was gofumpt-ed.
- gosec # Detects security problems.
- misspell # Detects commonly misspelled English words in comments.
- nilerr # Detects code that returns nil even if it checks that the error is not nil.
- nolintlint # Detects ill-formed or insufficient nolint directives.
- prealloc # Detects slice declarations that could potentially be pre-allocated.
- predeclared # Detects code that shadows one of Go's predeclared identifiers
- revive # Metalinter; drop-in replacement for golint.
- tenv # Detects using os.Setenv instead of t.Setenv.
- thelper # Detects test helpers without t.Helper().
- tparallel # Detects inappropriate usage of t.Parallel().
- unconvert # Detects unnecessary type conversions.
linters-settings:
govet:
check-shadowing: true
enable-all: true
settings:
shadow:
strict: true
issues:
max-issues-per-linter: 0
max-same-issues: 0
exclude-rules:
- text: '^shadow: declaration of "err" shadows declaration'
linters:
- govet
13 changes: 9 additions & 4 deletions go-selinux/selinux.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@ var (
// ErrEmptyPath is returned when an empty path has been specified.
ErrEmptyPath = errors.New("empty path")

// ErrInvalidLabel is returned when an invalid label is specified.
ErrInvalidLabel = errors.New("invalid Label")

// InvalidLabel is returned when an invalid label is specified.
InvalidLabel = errors.New("Invalid Label")
//
// Deprecated: use [ErrInvalidLabel].
InvalidLabel = ErrInvalidLabel

// ErrIncomparable is returned two levels are not comparable
ErrIncomparable = errors.New("incomparable levels")
Expand Down Expand Up @@ -158,7 +163,7 @@ func SetTaskLabel(label string) error {
// SetSocketLabel takes a process label and tells the kernel to assign the
// label to the next socket that gets created. Calls to SetSocketLabel
// should be wrapped in runtime.LockOSThread()/runtime.UnlockOSThread() until
// the the socket is created to guarantee another goroutine does not migrate
// the socket is created to guarantee another goroutine does not migrate
// to the current thread before execution is complete.
func SetSocketLabel(label string) error {
return writeCon(attrPath("sockcreate"), label)
Expand Down Expand Up @@ -220,7 +225,7 @@ func SetEnforceMode(mode int) error {
}

// DefaultEnforceMode returns the systems default SELinux mode Enforcing,
// Permissive or Disabled. Note this is is just the default at boot time.
// Permissive or Disabled. Note this is just the default at boot time.
// EnforceMode tells you the systems current mode.
func DefaultEnforceMode() int {
return defaultEnforceMode()
Expand Down Expand Up @@ -266,7 +271,7 @@ func CopyLevel(src, dest string) (string, error) {
return copyLevel(src, dest)
}

// Chcon changes the fpath file object to the SELinux label label.
// Chcon changes the fpath file object to the SELinux label.
// If fpath is a directory and recurse is true, then Chcon walks the
// directory tree setting the label.
//
Expand Down
46 changes: 24 additions & 22 deletions go-selinux/selinux_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,17 @@ const (
)

type selinuxState struct {
mcsList map[string]bool
selinuxfs string
selinuxfsOnce sync.Once
enabledSet bool
enabled bool
selinuxfsOnce sync.Once
selinuxfs string
mcsList map[string]bool
sync.Mutex
}

type level struct {
sens uint
cats *big.Int
sens uint
}

type mlsRange struct {
Expand All @@ -54,10 +54,10 @@ type mlsRange struct {
}

type defaultSECtx struct {
user, level, scon string
userRdr, defaultRdr io.Reader

verifier func(string) error
userRdr io.Reader
verifier func(string) error
defaultRdr io.Reader
user, level, scon string
}

type levelItem byte
Expand Down Expand Up @@ -607,17 +607,17 @@ func bitsetToStr(c *big.Int) string {
return str
}

func (l1 *level) equal(l2 *level) bool {
if l2 == nil || l1 == nil {
return l1 == l2
func (l *level) equal(l2 *level) bool {
if l2 == nil || l == nil {
return l == l2
}
if l1.sens != l2.sens {
if l2.sens != l.sens {
return false
}
if l2.cats == nil || l1.cats == nil {
return l2.cats == l1.cats
if l2.cats == nil || l.cats == nil {
return l2.cats == l.cats
}
return l1.cats.Cmp(l2.cats) == 0
return l.cats.Cmp(l2.cats) == 0
}

// String returns an mlsRange as a string.
Expand Down Expand Up @@ -748,7 +748,7 @@ func newContext(label string) (Context, error) {
if len(label) != 0 {
con := strings.SplitN(label, ":", 4)
if len(con) < 3 {
return c, InvalidLabel
return c, ErrInvalidLabel
}
c["user"] = con[0]
c["role"] = con[1]
Expand Down Expand Up @@ -799,11 +799,12 @@ func enforceMode() int {
// setEnforceMode sets the current SELinux mode Enforcing, Permissive.
// Disabled is not valid, since this needs to be set at boot time.
func setEnforceMode(mode int) error {
//nolint:gosec // ignore G306: permissions to be 0600 or less.
return os.WriteFile(selinuxEnforcePath(), []byte(strconv.Itoa(mode)), 0o644)
}

// defaultEnforceMode returns the systems default SELinux mode Enforcing,
// Permissive or Disabled. Note this is is just the default at boot time.
// Permissive or Disabled. Note this is just the default at boot time.
// EnforceMode tells you the systems current mode.
func defaultEnforceMode() int {
switch readConfig(selinuxTag) {
Expand Down Expand Up @@ -1006,6 +1007,7 @@ func addMcs(processLabel, fileLabel string) (string, string) {

// securityCheckContext validates that the SELinux label is understood by the kernel
func securityCheckContext(val string) error {
//nolint:gosec // ignore G306: permissions to be 0600 or less.
return os.WriteFile(filepath.Join(getSelinuxMountPoint(), "context"), []byte(val), 0o644)
}

Expand Down Expand Up @@ -1035,7 +1037,7 @@ func copyLevel(src, dest string) (string, error) {
return tcon.Get(), nil
}

// chcon changes the fpath file object to the SELinux label label.
// chcon changes the fpath file object to the SELinux label.
// If fpath is a directory and recurse is true, then chcon walks the
// directory tree setting the label.
func chcon(fpath string, label string, recurse bool) error {
Expand All @@ -1046,7 +1048,7 @@ func chcon(fpath string, label string, recurse bool) error {
return nil
}

exclude_paths := map[string]bool{
excludePaths := map[string]bool{
"/": true,
"/bin": true,
"/boot": true,
Expand Down Expand Up @@ -1074,19 +1076,19 @@ func chcon(fpath string, label string, recurse bool) error {
}

if home := os.Getenv("HOME"); home != "" {
exclude_paths[home] = true
excludePaths[home] = true
}

if sudoUser := os.Getenv("SUDO_USER"); sudoUser != "" {
if usr, err := user.Lookup(sudoUser); err == nil {
exclude_paths[usr.HomeDir] = true
excludePaths[usr.HomeDir] = true
}
}

if fpath != "/" {
fpath = strings.TrimSuffix(fpath, "/")
}
if exclude_paths[fpath] {
if excludePaths[fpath] {
return fmt.Errorf("SELinux relabeling of %s is not allowed", fpath)
}

Expand Down
3 changes: 2 additions & 1 deletion go-selinux/selinux_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ func TestCanonicalizeContext(t *testing.T) {
}

func TestFindSELinuxfsInMountinfo(t *testing.T) {
//nolint:dupword // ignore duplicate words (sysfs sysfs)
const mountinfo = `18 62 0:17 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw,seclabel
19 62 0:3 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw
20 62 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,seclabel,size=3995472k,nr_inodes=998868,mode=755
Expand Down Expand Up @@ -307,10 +308,10 @@ func TestComputeCreateContext(t *testing.T) {

func TestGlbLub(t *testing.T) {
tests := []struct {
expectedErr error
sourceRange string
targetRange string
expectedRange string
expectedErr error
}{
{
sourceRange: "s0:c0.c100-s10:c0.c150",
Expand Down
2 changes: 1 addition & 1 deletion pkg/pwalk/pwalk.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,6 @@ func WalkN(root string, walkFn WalkFunc, num int) error {
// walkArgs holds the arguments that were passed to the Walk or WalkN
// functions.
type walkArgs struct {
path string
info *os.FileInfo
path string
}
47 changes: 23 additions & 24 deletions pkg/pwalk/pwalk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,12 @@ func makeManyDirs(prefix string, levels, dirs, files int) (count int, err error)
}
count++
for f := 0; f < files; f++ {
fi, err := os.CreateTemp(dir, "f-")
var fi *os.File
fi, err = os.CreateTemp(dir, "f-")
if err != nil {
return count, err
}
fi.Close()
_ = fi.Close()
count++
}
if levels == 0 {
Expand Down Expand Up @@ -133,31 +134,31 @@ func BenchmarkWalk(b *testing.B) {
)

benchmarks := []struct {
name string
walk filepath.WalkFunc
name string
}{
{"Empty", cbEmpty},
{"ReadFile", cbReadFile},
{"ChownChmod", cbChownChmod},
{"RandomSleep", cbRandomSleep},
{name: "Empty", walk: cbEmpty},
{name: "ReadFile", walk: cbReadFile},
{name: "ChownChmod", walk: cbChownChmod},
{name: "RandomSleep", walk: cbRandomSleep},
}

walkers := []struct {
name string
walker walkerFunc
name string
}{
{"filepath.Walk", filepath.Walk},
{"pwalk.Walk", Walk},
{name: "filepath.Walk", walker: filepath.Walk},
{name: "pwalk.Walk", walker: Walk},
// test WalkN with various values of N
{"pwalk.Walk1", genWalkN(1)},
{"pwalk.Walk2", genWalkN(2)},
{"pwalk.Walk4", genWalkN(4)},
{"pwalk.Walk8", genWalkN(8)},
{"pwalk.Walk16", genWalkN(16)},
{"pwalk.Walk32", genWalkN(32)},
{"pwalk.Walk64", genWalkN(64)},
{"pwalk.Walk128", genWalkN(128)},
{"pwalk.Walk256", genWalkN(256)},
{name: "pwalk.Walk1", walker: genWalkN(1)},
{name: "pwalk.Walk2", walker: genWalkN(2)},
{name: "pwalk.Walk4", walker: genWalkN(4)},
{name: "pwalk.Walk8", walker: genWalkN(8)},
{name: "pwalk.Walk16", walker: genWalkN(16)},
{name: "pwalk.Walk32", walker: genWalkN(32)},
{name: "pwalk.Walk64", walker: genWalkN(64)},
{name: "pwalk.Walk128", walker: genWalkN(128)},
{name: "pwalk.Walk256", walker: genWalkN(256)},
}

dir, total, err := prepareTestSet(levels, dirs, files)
Expand All @@ -172,15 +173,13 @@ func BenchmarkWalk(b *testing.B) {
walker := w.walker
walkFn := bm.walk
// preheat
err := w.walker(dir, bm.walk)
if err != nil {
if err := w.walker(dir, bm.walk); err != nil {
b.Errorf("walk failed: %v", err)
}
// benchmark
b.Run(bm.name+"/"+w.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
err := walker(dir, walkFn)
if err != nil {
if err := walker(dir, walkFn); err != nil {
b.Errorf("walk failed: %v", err)
}
}
Expand Down Expand Up @@ -213,6 +212,6 @@ func cbReadFile(path string, info os.FileInfo, _ error) error {
}

func cbRandomSleep(_ string, _ os.FileInfo, _ error) error {
time.Sleep(time.Duration(rand.Intn(500)) * time.Microsecond)
time.Sleep(time.Duration(rand.Intn(500)) * time.Microsecond) //nolint:gosec // ignore G404: Use of weak random number generator
return nil
}
2 changes: 1 addition & 1 deletion pkg/pwalkdir/pwalkdir.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,6 @@ func WalkN(root string, walkFn fs.WalkDirFunc, num int) error {
// walkArgs holds the arguments that were passed to the Walk or WalkN
// functions.
type walkArgs struct {
path string
entry fs.DirEntry
path string
}
Loading