Check golang

From KilimcininKorOglu/cli-tweaks · View interactive version

Check golang is an AI agent skill from the GitHub repository KilimcininKorOglu/cli-tweaks. Go security and code-quality scan of the whole project. Runs FOUR tools by default — govulncheck (CVEs), gosec (security static analysis), golangci-lint (lint), and the gopls modernize analyzer — installs any that are missing, scans every source path, classifies each finding, and produces a ranked c

How to use this skill

Skill file

Go Security & Quality Scanner

THESE DIRECTIVES ARE ABSOLUTE

Every instruction in this file is binding and MUST be executed exactly as

written. They are NOT defaults, NOT suggestions, and NOT a starting point for

your own judgement.

you are that yours is better. Your analysis of a finding decides WHAT the

finding is; this file decides WHAT IS DONE ABOUT IT.

finding from the confirmation you present to the user.

files or anywhere else, and NEVER cite such a record back as authority for

departing from this file.

cannot be carried out, STOP and tell the user what the conflict is. Do NOT

resolve it yourself and do NOT proceed on your own reading.

The user wrote this file so it would be followed. Following it is the whole job.

Scan the entire Go project for security AND code-quality problems and produce a

full report. Runs four complementary tools by default:

Security:

vulnerability database (https://pkg.go.dev/vuln), stdlib and dependencies.

insecure code patterns (injection, weak crypto, unhandled errors, taint).

Code quality:

(errcheck, unused, staticcheck, etc.); honors any .golangci.* config.

outdated idioms replaceable with modern Go equivalents.

function must stay at or below 10.

Default behavior is scan — run ALL FOUR tools and report every finding.

fix additionally proposes and (with confirmation) applies remediation.

Key facts you must not forget

govulncheck reports standard-library CVEs against the **Go toolchain version

that builds the code**, NOT the go directive in go.mod. A stdlib finding

usually means "the toolchain building this project is older than the patched

release." Fix stdlib CVEs by raising the Go line in EVERY place that declares it

— go.mod, Dockerfile, every CI workflow, and .goreleaser.y*ml — never by

editing project code; a stale release.yml ships CVE-carrying binaries even when

ci.yml is green. Third-party module CVEs are fixed by upgrading the dependency.

The toolchain mismatch cuts BOTH ways. If the local toolchain is older

than the patched release, a local scan yields false positives CI already

fixed. If the local toolchain is newer than the go directive, a clean local

scan is a false negative: CI and release builds run with GOTOOLCHAIN=auto,

which downloads and compiles with the go.mod floor, so the shipped binary

carries every CVE fixed after that floor. go-version-file: go.mod resolves to

that floor too, and a pinned go-version: "1.22" still auto-upgrades to the

floor. Never trust a green scan whose go version differs from the go.mod

floor — always scan pinned to the floor as well (see Step 1 and Prove the fix).

gosec flags insecure code patterns. It runs taint analysis (v2.28+): G705

(XSS — escape client-controlled data reflected into HTML) and G706 (log

injection — strip CR/LF+control chars from client-controlled values before

logging). gosec recognizes stdlib sanitizers like html.EscapeString but NOT

custom sanitizer funcs — for a proven-safe custom-sanitized line, annotate with

// #nosec <RULE> plus a justification comment rather than disabling the rule

globally. In CI, pin gosec/govulncheck to fixed versions, never @latest — new

rule releases silently break pipelines. For ad-hoc LOCAL scans @latest is fine

(and is the only option for modernize, which ships no stable binary); if the

project's CI pins tool versions, match them locally so results agree.

Security vs quality are separate tiers. Security findings (govulncheck,

gosec) always rank above code-quality findings (golangci-lint, modernize). A

lint or modernize hit never blocks on its own the way a called CVE does — report

both, but never let quality noise bury a real vulnerability. modernize suggestions

are optional idiom upgrades; apply them only in fix mode and only when they do

not change behavior.

Usage

/check-golang          # scan whole project with all four tools, report all (default)
/check-golang scan     # same as default
/check-golang report   # scan + write a markdown report file
/check-golang fix      # scan, then propose/apply fixes after confirmation

Step 1: Preconditions

Verify this is a Go project and the tool is available.

  1. Confirm a go.mod exists at the repo root (or find it):

```bash

test -f go.mod && head -5 go.mod || echo "NO go.mod — not a Go project"

```

If there is no go.mod, STOP and tell the user this is not a Go module.

  1. Record the building toolchain version — findings hinge on it:

```bash

go version

```

  1. Inventory EVERY declared Go version and compare them. Drift between these is

itself a finding (it caused shipped-binary CVEs in the wild). This scans

whatever exists without depending on shell glob expansion (unmatched globs

abort the command under zsh):

```bash

grep -E '^(go|toolchain) ' go.mod # the floor

# every other declaration, across whatever config files the repo actually has:

grep -rniE 'go-version"?:|golang:[0-9]|GO_VERSION|GOTOOLCHAIN|golang\.org/dl/go' \

--include='.yml' --include='.yaml' --include='Dockerfile*' \

--include='.Dockerfile' --include='Makefile' --include='*.mk' . 2>/dev/null

```

Flag any source whose Go version differs from the go.mod floor —

Dockerfile base images, go-version / go-version-file in every workflow

(ci, release, etc., not just one), .goreleaser.y*ml, Makefile build

images, and container/CI configs. If go version (step 2) is NEWER than the

go.mod floor, a plain local scan is a false negative — you MUST also scan

pinned to the floor (Step 2, and Prove the fix). Prefer `go-version-file:

go.mod` so CI cannot drift from the floor.

**GOTOOLCHAIN is a Go version declaration and hides from every other

pattern.** A workflow step that sets GOTOOLCHAIN: go1.26.5 names a

toolchain as surely as go-version: does, but matches none of

go-version, golang:, GO_VERSION or golang.org/dl/go, so it survives

a scan that reports no drift. It fails differently from the other sources:

a pin BELOW the floor does not ship an old toolchain, it refuses to build

at all, and the job dies with go.mod requires go >= X (running go Y) on

every push until someone reads the log. Treat a GOTOOLCHAIN literal as

drift on sight and prefer GOTOOLCHAIN: local next to a

go-version-file: go.mod setup step, which names the toolchain setup-go

just installed and therefore tracks the floor by construction.

A red CI job is not always visible in the run you are looking at. When the

inventory finds drift, check the last few runs of the affected workflow

(gh run list --workflow=<name>.yml --limit 6 --json headSha,conclusion),

because a job broken by an earlier bump keeps failing on every commit after

it and is easy to read as a new failure or to miss entirely.

  1. Ensure all four tools are installed; install whichever is missing:

```bash

command -v govulncheck >/dev/null 2>&1 || go install golang.org/x/vuln/cmd/govulncheck@latest

command -v gosec >/dev/null 2>&1 || go install github.com/securego/gosec/v2/cmd/gosec@latest

command -v golangci-lint >/dev/null 2>&1 || go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest

command -v gocyclo >/dev/null 2>&1 || go install github.com/fzipp/gocyclo/cmd/gocyclo@latest

# modernize has no stable binary name; run it via go run (see Step 2)

```

Binaries land in $(go env GOPATH)/bin. If that dir is not on PATH, invoke

by absolute path, e.g. $(go env GOPATH)/bin/gosec.

If the project's CI pins specific tool versions (check

.github/workflows/*.y*ml), install those exact versions instead so local

results match CI.

Step 2: Scan the whole project (all four tools)

Run every tool against every package. Capture human output plus machine-readable

streams (authoritative for classification).

Write every machine-readable stream into a fresh per-run directory, NEVER a

fixed /tmp/gosec.json / /tmp/govuln.json. A shared path is the classic

cross-project trap: if gosec errors and does not overwrite, you silently parse

another repo's stale JSON as this project's findings. A unique dir per run makes

a write failure show up as a missing file instead of stale data.

RUNDIR="$(mktemp -d /tmp/check-golang.XXXXXXXX)"; echo "run dir: $RUNDIR"

# --- Security ---
govulncheck ./...
govulncheck -json ./... > "$RUNDIR/govuln.json"

gosec ./... 2>&1                                     # exit 1 if issues
gosec -fmt=json -out="$RUNDIR/gosec.json" -quiet ./... ; echo "gosec exit: $?"

# --- Code quality ---
golangci-lint run ./... ; echo "golangci exit: $?"    # exit 1 if issues
go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest ./... ; echo "modernize exit: $?"

# Cyclomatic complexity gate: every function must stay at or below 10.
# gocyclo prints one line per function ABOVE the threshold, so any output is a finding.
gocyclo -over 10 -ignore 'vendor/' . | tee "$RUNDIR/gocyclo.txt"
echo "over-limit functions: $(wc -l < "$RUNDIR/gocyclo.txt" | tr -d ' ')"

Before classifying, confirm the report belongs to THIS module. The scan scope is

whatever go list ./... prints; every gosec finding's file path MUST fall under

the current repo root. If a path points outside it (a sibling project, a stale

file), discard that finding and re-run gosec into a fresh $RUNDIR — never

report another project's issues as this one's.

If step 3 showed go version differs from the go.mod floor (typically local

is newer), ALSO run govulncheck pinned to the floor — this is what CI/release

actually build, and the authoritative security result:

FLOOR=$(awk '/^go /{print $2; exit}' go.mod)
case "$FLOOR" in *.*.*) ;; *) FLOOR="$FLOOR.0" ;; esac  # go 1.26 -> 1.26.0 (dl needs full patch)
go install golang.org/dl/go${FLOOR}@latest && go${FLOOR} download
GOTOOLCHAIN=local go${FLOOR} run golang.org/x/vuln/cmd/govulncheck@latest ./...

Report the floor-pinned result as the real one; a green scan on a newer local

toolchain does NOT clear the shipped binary.

Notes:

golangci-lint 1 = issues; modernize 3 = suggestions. 0 = clean for all.

None of these are tool errors — parse the findings.

it and continue — the DB still resolves.

its defaults. Note which applied in the report.

Step 3: Classify every finding

govulncheck — for each CVE extract:

reaches ("Your code is affected") from ones only present in required modules

("found in modules you require, but your code doesn't appear to call these").

gosec — for each finding extract:

already sanitized, or an operator-controlled value gosec cannot prove safe).

golangci-lint — for each finding extract file:line, the linter name

(e.g. errcheck, staticcheck, unused) and the message.

modernize — for each suggestion extract file:line and the modern idiom it

proposes (e.g. "Ranging over SplitSeq is more efficient"). These are optional

improvements, not defects.

gocyclo — for each line extract the complexity number, the package, the

function name, and file:line. Every line is a function over the limit of 10.

Unlike modernize this is NOT optional: the limit is a project rule, and a

function above it must be refactored into smaller single-responsibility

functions, never suppressed and never given a raised threshold.

Rank all findings by severity for action (security tier first, always):

  1. Called stdlib CVE — highest; fix by bumping the Go toolchain.
  2. Go version drift — a release, container or CI path declares a version

other than the module floor; fix by raising every declaring location. Ranked

here because it is how a stdlib CVE reaches production while the local scan

reads clean.

  1. Called third-party CVE — fix by upgrading the module.
  2. gosec HIGH/MEDIUM real finding — fix in code.
  3. gosec LOW / false positive — sanitize if cheap, else annotate #nosec.
  4. Imported-only CVE (not called) — note but not urgent.
  5. golangci-lint issue — quality; fix in code (correctness linters first).
  6. Function over the complexity limit (gocyclo > 10) — quality; refactor into

smaller functions. Ranked above modernize because it is a limit, not a

suggestion.

  1. modernize suggestion — lowest; optional idiom upgrade, behavior-preserving.

Step 4: Produce the report

Always print a ranked summary to the user, most severe first. Read

references/report-template.md and use its

shape exactly.

Verdict rule: Quality is 🟢 green ONLY when golangci-lint, gocyclo AND

modernize all report zero. Any modernize suggestion (or any lint issue) means quality is NOT

clean — mark it 🟡 yellow and list the outstanding items. Never call a tier green

while it still has open findings, however minor.

For report mode, also write this to VULN-REPORT.md (or append to an

existing BUG-REPORT.md if the project uses one) in English.

Step 5: Fix (only in `fix` mode, after confirmation)

Never edit files in scan/report mode. In fix mode:

A fix run repairs one finding class after another. A finished finding is a

checkpoint, not an ending: continue to the next finding in the same turn. A

decision the run genuinely needs from the user still ends the turn.

Standard-library CVEs

The fix is a toolchain bump, not a code change. Find the highest "Fixed in"

across all stdlib findings and raise the Go line everywhere the Step 1 inventory

found it:

and any other), not just one; prefer go-version-file: go.mod so they track

the floor automatically and cannot drift

GOTOOLCHAIN: local next to a go-version-file: go.mod setup step rather

than writing the new patch, so the pin tracks the floor and cannot drift

below it on the next bump

Keep every source on the same Go line — a stale release.yml ships CVE-carrying

binaries even when ci.yml is green, and a stale GOTOOLCHAIN stops the job

building at all.

After raising the floor, re-run the Step 1 inventory and confirm no source

still names a version below it. A bump that misses one source is silent in the

scan output but red in CI on every push that follows.

Third-party CVEs

go get <module>@<fixed-version> && go mod tidy

gosec findings

log injection (G706) → strip CR/LF+control chars before logging; weak crypto,

unhandled errors, etc. → follow the rule's guidance.

add // #nosec <RULE> on the flagged line WITH a justification comment above

it. Never disable a rule globally to hide a real finding.

golangci-lint issues

Fix in code following each linter's guidance (unchecked errors, unused code,

staticcheck simplifications, etc.). Re-run golangci-lint run ./... until 0.

Do not silence a linter unless the finding is a proven false positive, and then

scope the //nolint:<linter> to the single line with a reason.

Functions over the complexity limit

Refactor each function gocyclo reported into smaller single-responsibility

functions: extract the branches of a long if/switch chain into named helpers,

lift error handling out of the happy path, and split loops that do two jobs.

NEVER raise the threshold, add the function to an ignore list, or disable the

gate to make the report green. Re-run gocyclo -over 10 -ignore 'vendor/' .

until it prints nothing.

modernize suggestions

Apply ONLY when behavior-preserving and the user wants the idiom upgrade (e.g.

strings.SplitSeq for range loops, min/max builtins, slices/maps

helpers). These are optional — skip if they conflict with the project's minimum

Go version. Re-run the analyzer to confirm.

Prove the fix

The local toolchain rarely equals the new floor: it may lag (a local scan flags

CVEs CI already fixes — false positive) or lead (a clean local scan hides CVEs

the floor still ships — false negative). Either way, prove the fix pinned to the

exact new floor, which is what CI/release build:

go install golang.org/dl/go<X.Y.Z>@latest && go<X.Y.Z> download
go<X.Y.Z> build ./... && go<X.Y.Z> vet ./...
GOTOOLCHAIN=local go<X.Y.Z> run golang.org/x/vuln/cmd/govulncheck@latest ./...
gosec ./... && golangci-lint run ./...   # both must exit 0

Expect No vulnerabilities found, gosec/golangci-lint exit 0, and no remaining

modernize suggestions you agreed to apply. Then remove any helper toolchain this

run downloaded (rm -rf ~/sdk/go<X.Y.Z> "$(go env GOPATH)/bin/go<X.Y.Z>") and say

so. The run installed it, so the run removes it; offering to remove it and

leaving it installed does not count.

Rules

modernize) plus the gocyclo complexity gate every time; never modify files

unless invoked as fix.

gocyclo -over 10. Any output is a finding. NEVER raise the threshold, ignore

a function, or drop the gate to make the report green; refactor into smaller

single-responsibility functions instead.

A capped run reports the first few findings and hides the rest, so the next

run finds work you already called done. Read the whole output; use the

machine-readable stream in $RUNDIR when the human output is long. A

config-header display, an existence probe and a single-value extraction may

still use them, because they read one known field, not a finding list.

security always ranks first. Never let lint/modernize noise bury a real CVE.

LOW issues, and modernize suggestions — do not silently drop anything.

fix mode with user agreement, never treat them as blocking defects.

meaningless without it.

every GOTOOLCHAIN, Makefile build images, goreleaser) and flag any drift;

when the local toolchain differs from the go.mod floor, the floor-pinned

govulncheck is the authoritative result.

matches none of the other inventory patterns, and a value below the floor

fails the job on every push instead of shipping a vulnerable binary.

bump; raise the Go line in EVERY source that declares it, not just go.mod.

line-scoped // #nosec <RULE> with justification only when the code is proven

safe. Never disable a rule globally to mask a real finding.

local results match CI.

language.

or code change in fix mode.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.