Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
14 Oct 2026 · 28 min read ·Article 66 / 208
Go

Automated Golang Security Audit in CI/CD: gosec, Dependency Scan, AI Analysis

Set up an automated security audit for Go in CI/CD. A combination of gosec, govulncheck, dependency scanning, and AI-powered vulnerability analysis for a production Go service.

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Automated Security Audit: AI Scanning Vulnerabilities for Golang

Automated security audit for Golang is often skipped from the CI pipeline because it’s considered complex and full of false positives. This article shows a pragmatic approach: combining deterministic tools (gosec, govulncheck, gitleaks) with AI analysis to provide comprehensive security coverage without overwhelming developers. The result is a layered pipeline that catches secrets, anti-patterns, dependency CVEs, all the way to semantic issues like authorization bypass.


06.1 Threat Landscape for a Go Service

Before choosing tools, we need to know what we’re up against. The list below maps the most common vulnerability types in a production Go service, ordered by severity.

text
 1The most common vulnerability types in production Go services:
 2
 3LEVEL CRITICAL (directly exploitable):
 4  - SQL injection via string concatenation
 5  - Hardcoded credentials (API key, DB password)
 6  - Path traversal vulnerability
 7  - Insecure deserialization
 8  - JWT secret weak or hardcoded
 9
10LEVEL HIGH (needs an exploit chain):
11  - Dependency with a known CVE
12  - Integer overflow in financial calculations
13  - Race condition in concurrent code
14  - Missing rate limiting on public endpoints
15  - Insufficient input validation
16
17LEVEL MEDIUM (context-dependent):
18  - Missing TLS verification
19  - Weak cryptography (MD5, SHA1 for security)
20  - Information disclosure via error messages
21  - Missing CSRF protection
22  - Predictable random generation
23
24LEVEL LOW (defense in depth):
25  - Missing security headers
26  - Verbose error messages
27  - Missing audit logging

This level mapping determines the enforcement strategy: CRITICAL issues must block the build, while LOW issues are just notes for gradual improvement. Each tool we choose targets a different level.


06.2 Security Stack: The Tools We’ll Use

No single tool catches every issue, so we combine four that complement each other. The summary below compares the coverage, false positive rate, and cost of each.

text
 1TOOL 1: gosec (go security checker)
 2  Type: Static analysis, deterministic
 3  Coverage: ~80 rules for Go-specific security issues
 4  False positive: Medium (needs tuning)
 5  Cost: Zero
 6
 7TOOL 2: govulncheck
 8  Type: Dependency vulnerability scan
 9  Coverage: Go vulnerability database (vuln.go.dev)
10  False positive: Very low (CVE-based)
11  Cost: Zero
12
13TOOL 3: gitleaks
14  Type: Secret detection
15  Coverage: 100+ secret patterns (API keys, tokens, passwords)
16  False positive: Low with proper config
17  Cost: Zero
18
19TOOL 4: Claude AI Security Review
20  Type: Semantic analysis
21  Coverage: Context-aware issues that static tools miss
22  False positive: Medium (needs a good prompt)
23  Cost: Low ($0.001-0.003 per review)
24
25OPTIMAL COMBINATION:
26  gosec + govulncheck + gitleaks = baseline (zero cost)
27  AI review = semantic coverage for issues that deterministic tools miss

The principle behind this stack is defense in depth: three free tools form a baseline that catches the majority of issues, and the AI is only called for the semantic layer that pattern matching can’t reach. Total cost stays low because the paid tool is used most sparingly.


06.3 Optimal gosec Setup

gosec is the first line for Go anti-patterns, but its default produces many false positives. The configuration below installs gosec and tunes the rules so only relevant issues are reported.

bash
 1# Install
 2go install github.com/securego/gosec/v2/cmd/gosec@latest
 3
 4# .gosec.yml — configuration for Santekno Shop
 5cat > .gosec.yml << 'GOSEC'
 6global:
 7  audit: false
 8  nosec: false
 9  show-ignored: false
10
11rules:
12  exclude:
13    # G104: Errors unhandled — already covered by golangci-lint errcheck
14    - G104
15
16    # G304: File path provided as taint input — false positive in test utils
17    # Keep enabled but suppress in test files
18
19  include:
20    # G101: Hardcoded credentials
21    - G101
22    # G102: Bind to all interfaces
23    - G102
24    # G107: URL injection via taint input
25    - G107
26    # G201-G202: SQL injection
27    - G201
28    - G202
29    # G401-G402: Weak crypto
30    - G401
31    - G402
32    # G501: Import blocklist (crypto/md5, etc.)
33    - G501
34    # G601: Implicit memory aliasing in for range
35    - G601
36
37severity: medium
38GOSEC
39
40# Run gosec:
41gosec -conf .gosec.yml ./...
42
43# Run with JSON output for CI processing:
44gosec -conf .gosec.yml -fmt json -out /tmp/gosec-result.json ./...

Notice the exclude for G104 that’s already handled by errcheck in golangci-lint — avoiding a duplicate report. A one-to-two-hour investment in tuning .gosec.yml once will save hours of filtering false positives in the future.


06.4 govulncheck: Dependency Vulnerability Scan

After code anti-patterns, we check dependencies for known CVEs. govulncheck excels because it only reports vulnerabilities that are actually reachable from our code. The commands below run the scan and parse the result.

bash
 1# Install
 2go install golang.org/x/vuln/cmd/govulncheck@latest
 3
 4# Run a basic scan:
 5govulncheck ./...
 6
 7# Run with JSON output:
 8govulncheck -json ./... > /tmp/vuln-result.json
 9
10# Parse the result:
11cat /tmp/vuln-result.json | jq '
12  .findings[] | select(.trace != null) |
13  {
14    id: .osv.id,
15    summary: .osv.summary,
16    severity: .osv.database_specific.severity,
17    fixed_in: .osv.affected[0].ranges[0].events[-1].fixed
18  }
19'
20
21# Sample output:
22# {
23#   "id": "GO-2024-1234",
24#   "summary": "Denial of service in golang.org/x/net",
25#   "severity": "HIGH",
26#   "fixed_in": "0.17.0"
27# }

The select(.trace != null) filter is the key: it keeps only vulnerabilities that have a call trace from our code, dramatically reducing noise compared to merely listing all outdated packages. This is what makes govulncheck safe to use as a build gate.


06.5 Gitleaks Configuration

A leaked secret is the most critical issue, so gitleaks needs to be configured with the right patterns. The TOML file below defines detection rules for API keys, connection strings, and JWT secrets, plus an allowlist for test fixtures.

toml
 1# .gitleaks.toml
 2title = "Santekno Shop Secret Rules"
 3
 4[[rules]]
 5id = "anthropic-api-key"
 6description = "Anthropic API Key"
 7regex = '''sk-ant-[a-zA-Z0-9_-]{20,}'''
 8keywords = ["sk-ant-"]
 9severity = "CRITICAL"
10
11[[rules]]
12id = "generic-api-key"
13description = "Generic API Key pattern"
14regex = '''(?i)(api[_-]?key|apikey)['":\s]+['""]?([a-zA-Z0-9_\-]{20,})['""]?'''
15severity = "HIGH"
16
17[[rules]]
18id = "database-url"
19description = "Database connection string with password"
20regex = '''(postgres|postgresql|mysql|mongodb):\/\/[^:]+:[^@]+@'''
21severity = "CRITICAL"
22
23[[rules]]
24id = "jwt-secret"
25description = "JWT secret that looks hardcoded"
26regex = '''(?i)(jwt[_-]?secret|jwt[_-]?key)['":\s]+['""]?[a-zA-Z0-9_\-\.]{16,}['""]?'''
27severity = "HIGH"
28
29[[allowlist]]
30description = "Allow test fixtures and example configs"
31paths = [
32    '''testdata/.*''',
33    '''.*\.example\..*''',
34    '''.*_test\.go''',
35]
36regexes = [
37    '''REDACTED''',
38    '''YOUR_.*_HERE''',
39    '''sk-ant-REDACTED''',
40]

The allowlist section is as important as the detection rules: without it, placeholders in test fixtures and example files will trigger tiresome false positives. This balanced configuration is what makes the secret scan trustworthy as a mandatory gate.


06.6 AI Security Review for Context-Aware Issues

Deterministic tools only find what they’re programmed to find. For issues that require understanding context — authorization bypass, information disclosure — we use AI. The script below builds a structured security review prompt and fails the build if there’s a CRITICAL issue.

bash
 1#!/bin/bash
 2# scripts/ai-security-review.sh
 3# AI review specifically for security issues that static tools miss
 4
 5set -euo pipefail
 6
 7DIFF_FILE="${1}"
 8DIFF=$(cat "$DIFF_FILE")
 9
10# Load app context for better analysis
11APP_CONTEXT=""
12if [ -f "CLAUDE.md" ]; then
13  APP_CONTEXT=$(head -50 CLAUDE.md)
14fi
15
16PROMPT="Security review for a production Go e-commerce service.
17
18APP CONTEXT:
19$APP_CONTEXT
20
21Review the diff for security vulnerabilities:
22
231. SQL INJECTION
24   Is there string concatenation in a SQL query?
25   WRONG: fmt.Sprintf('SELECT * FROM orders WHERE id = ' + id)
26   RIGHT: pool.QueryRow(ctx, 'SELECT ... WHERE id = \$1', id)
27
282. INPUT VALIDATION
29   Is user input validated before use?
30   Check: UUID format, string length, allowed characters
31
323. AUTHORIZATION BYPASS
33   Is there an endpoint that skips the auth check?
34   Is there a hard-coded user ID or role?
35
364. INFORMATION DISCLOSURE
37   Does an error message expose internal details (DB schema, stack trace)?
38   WRONG: return c.JSON(500, map[string]string{'error': err.Error()})
39   RIGHT: return c.JSON(500, map[string]string{'error': 'INTERNAL_ERROR'})
40
415. CRYPTOGRAPHIC ISSUES
42   Is MD5/SHA1 used for security-critical operations?
43   Does random generation use crypto/rand (not math/rand)?
44
456. RACE CONDITION
46   Is shared state accessed from multiple goroutines without sync?
47
487. FINANCIAL CALCULATION SAFETY
49   Is there an integer overflow risk for large transaction amounts?
50   (int64 max = 9.2 * 10^18 cents — safe for normal use)
51
52DIFF:
53$DIFF
54
55Output format:
56CRITICAL:[description] at [file:line]
57  Risk: [potential impact]
58  Fix: [specific code fix]
59
60HIGH:[description] at [file:line]
61  Risk: [potential impact]
62  Fix: [specific code fix]
63
64MEDIUM:[description]
65INFO:[observation]
66
67SECURITY_SCORE: [0-100]
68(100=no issues, 80=minor issues, 60=some risks, <60=critical issues)"
69
70# Call Claude
71RESULT=$(./scripts/claude-call.sh "$PROMPT" 800)
72echo "$RESULT"
73
74# Fail if there's a CRITICAL
75if echo "$RESULT" | grep -q "^CRITICAL:"; then
76  echo ""
77  echo "::error::Critical security issues found"
78  exit 1
79fi
80
81# Warning for HIGH
82if echo "$RESULT" | grep -q "^HIGH:"; then
83  echo ""
84  echo "::warning::High severity security issues found"
85fi

The seven categories in this prompt deliberately target issues that gosec and govulncheck can’t see — for example, whether an endpoint checks order ownership, not merely its existence. This is the AI’s added value on top of the deterministic baseline.


06.7 GitHub Actions Workflow: Full Security Pipeline

Now the four tools are wired into a single security pipeline. The workflow below runs secret detection first, then static analysis, dependency scan, AI review, and a nightly comprehensive scan.

yaml
  1# .github/workflows/security.yml
  2name: Security Audit
  3
  4on:
  5  push:
  6    branches: [main, develop]
  7  pull_request:
  8    branches: [main, develop]
  9    types: [opened, synchronize]
 10  schedule:
 11    # Nightly vulnerability scan
 12    - cron: '0 1 * * *'  # 01:00 UTC = 08:00 WIB
 13
 14env:
 15  GO_VERSION: '1.22'
 16  ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
 17
 18jobs:
 19  # Job 1: Secret Detection (most important, runs first)
 20  secret-scan:
 21    name: Secret Detection
 22    runs-on: ubuntu-latest
 23    steps:
 24      - uses: actions/checkout@v4
 25        with:
 26          fetch-depth: 0  # need full history for gitleaks
 27
 28      - name: Gitleaks Scan
 29        uses: gitleaks/gitleaks-action@v2
 30        env:
 31          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
 32          GITLEAKS_CONFIG: .gitleaks.toml
 33
 34      - name: TruffleHog Deep Scan
 35        uses: trufflesecurity/trufflehog@main
 36        with:
 37          path: ./
 38          base: ${{ github.event.before || github.event.repository.default_branch }}
 39          head: HEAD
 40          extra_args: --only-verified
 41
 42  # Job 2: Static Security Analysis
 43  static-security:
 44    name: Static Security Analysis
 45    runs-on: ubuntu-latest
 46    steps:
 47      - uses: actions/checkout@v4
 48      - uses: actions/setup-go@v5
 49        with:
 50          go-version: '${{ env.GO_VERSION }}'
 51          cache: true
 52
 53      - name: Install gosec
 54        run: go install github.com/securego/gosec/v2/cmd/gosec@latest
 55
 56      - name: Run gosec
 57        id: gosec
 58        continue-on-error: true
 59        run: |
 60          gosec -conf .gosec.yml -fmt json -out /tmp/gosec.json ./... || true
 61
 62          # Parse results
 63          CRITICAL=$(jq '[.Issues[] | select(.severity == "HIGH")] | length' /tmp/gosec.json)
 64          MEDIUM=$(jq '[.Issues[] | select(.severity == "MEDIUM")] | length' /tmp/gosec.json)
 65          LOW=$(jq '[.Issues[] | select(.severity == "LOW")] | length' /tmp/gosec.json)
 66
 67          echo "critical=$CRITICAL" >> $GITHUB_OUTPUT
 68          echo "medium=$MEDIUM" >> $GITHUB_OUTPUT
 69          echo "low=$LOW" >> $GITHUB_OUTPUT
 70
 71          echo "gosec results: CRITICAL=$CRITICAL, MEDIUM=$MEDIUM, LOW=$LOW"
 72
 73      - name: Upload gosec report
 74        uses: actions/upload-artifact@v4
 75        with:
 76          name: gosec-report
 77          path: /tmp/gosec.json
 78          retention-days: 30
 79
 80      - name: Check critical issues
 81        run: |
 82          CRITICAL=${{ steps.gosec.outputs.critical }}
 83          if [ "$CRITICAL" -gt 0 ]; then
 84            echo "::error::gosec found $CRITICAL HIGH severity issues"
 85            jq '.Issues[] | select(.severity == "HIGH") | "\(.file):\(.line) — \(.details)"' /tmp/gosec.json
 86            exit 1
 87          fi
 88          echo "✅ No HIGH severity issues found"
 89
 90  # Job 3: Dependency Vulnerability Scan
 91  dependency-scan:
 92    name: Dependency Vulnerability Scan
 93    runs-on: ubuntu-latest
 94    steps:
 95      - uses: actions/checkout@v4
 96      - uses: actions/setup-go@v5
 97        with:
 98          go-version: '${{ env.GO_VERSION }}'
 99          cache: true
100
101      - name: Install govulncheck
102        run: go install golang.org/x/vuln/cmd/govulncheck@latest
103
104      - name: Run govulncheck
105        id: vulncheck
106        run: |
107          govulncheck -json ./... > /tmp/vuln.json 2>&1 || true
108
109          # Count vulnerabilities
110          VULN_COUNT=$(jq '[.findings[] | select(.trace != null)] | length' /tmp/vuln.json 2>/dev/null || echo "0")
111          echo "vuln_count=$VULN_COUNT" >> $GITHUB_OUTPUT
112
113          if [ "$VULN_COUNT" -gt 0 ]; then
114            echo "⚠️ Found $VULN_COUNT vulnerability findings:"
115            jq -r '.findings[] | select(.trace != null) |
116              "  \(.osv.id): \(.osv.summary) (fixed: \(.osv.affected[0].ranges[0].events[-1].fixed // "no fix"))"' \
117              /tmp/vuln.json 2>/dev/null || true
118          fi
119
120      - name: Post vulnerability report to PR
121        if: github.event_name == 'pull_request' && steps.vulncheck.outputs.vuln_count != '0'
122        uses: actions/github-script@v7
123        with:
124          script: |
125            const fs = require('fs');
126            const vuln = JSON.parse(fs.readFileSync('/tmp/vuln.json', 'utf8'));
127            const count = '${{ steps.vulncheck.outputs.vuln_count }}';
128
129            const findings = vuln.findings?.filter(f => f.trace) || [];
130            const lines = [
131              `## 🔒 Dependency Vulnerability Report`,
132              ``,
133              `**Found:** ${count} vulnerability(ies)`,
134              ``,
135            ];
136
137            for (const f of findings.slice(0, 10)) {
138              lines.push(`### ${f.osv.id}`);
139              lines.push(`**${f.osv.summary}**`);
140              lines.push(`- Severity: ${f.osv.database_specific?.severity || 'Unknown'}`);
141              lines.push(`- Fixed in: ${f.osv.affected?.[0]?.ranges?.[0]?.events?.slice(-1)?.[0]?.fixed || 'No fix available'}`);
142              lines.push('');
143            }
144
145            await github.rest.issues.createComment({
146              owner: context.repo.owner,
147              repo: context.repo.repo,
148              issue_number: context.issue.number,
149              body: lines.join('\n')
150            });
151
152      - name: Fail on critical CVEs
153        run: |
154          # Fail if there's a vulnerability with severity CRITICAL
155          CRITICAL_VULN=$(jq '[.findings[] |
156            select(.trace != null) |
157            select(.osv.database_specific.severity == "CRITICAL")] | length' \
158            /tmp/vuln.json 2>/dev/null || echo "0")
159
160          if [ "$CRITICAL_VULN" -gt 0 ]; then
161            echo "::error::Found $CRITICAL_VULN CRITICAL vulnerabilities in dependencies"
162            echo "Run: govulncheck ./... for details"
163            echo "Fix: update affected dependencies to fixed versions"
164            exit 1
165          fi
166
167          echo "✅ No CRITICAL vulnerabilities in dependencies"
168
169  # Job 4: AI Security Review (PR only)
170  ai-security:
171    name: AI Security Review
172    runs-on: ubuntu-latest
173    needs: [secret-scan]  # only runs if secret scan passes
174    if: github.event_name == 'pull_request'
175    permissions:
176      pull-requests: write
177      contents: read
178    steps:
179      - uses: actions/checkout@v4
180        with:
181          fetch-depth: 0
182
183      - name: Get diff for review
184        run: |
185          git diff origin/${{ github.base_ref }}...HEAD -- '*.go' \
186            | sed 's/sk-ant-[a-zA-Z0-9_-]*/REDACTED/g' \
187            | head -500 > /tmp/security-diff.txt
188
189      - name: AI Security Analysis
190        id: ai_security
191        continue-on-error: true
192        run: |
193          chmod +x scripts/ai-security-review.sh
194          RESULT=$(./scripts/ai-security-review.sh /tmp/security-diff.txt 2>&1) || FAILED=true
195
196          echo "result<<EOF" >> $GITHUB_OUTPUT
197          echo "$RESULT" >> $GITHUB_OUTPUT
198          echo "EOF" >> $GITHUB_OUTPUT
199
200          SCORE=$(echo "$RESULT" | grep "SECURITY_SCORE:" | grep -oP '\d+' || echo "85")
201          echo "score=$SCORE" >> $GITHUB_OUTPUT
202          echo "failed=${FAILED:-false}" >> $GITHUB_OUTPUT
203
204      - name: Post security review
205        uses: actions/github-script@v7
206        with:
207          script: |
208            const result = `${{ steps.ai_security.outputs.result }}`;
209            const score = parseInt('${{ steps.ai_security.outputs.score }}') || 85;
210
211            const scoreEmoji = score >= 80 ? '🟢' : score >= 60 ? '🟡' : '🔴';
212
213            const body = [
214              `## 🔐 AI Security Review`,
215              ``,
216              `**Security Score:** ${scoreEmoji} ${score}/100`,
217              ``,
218              result,
219              ``,
220              `---`,
221              `*AI Security Review — False positives? Comment \`/ignore-security\`*`
222            ].join('\n');
223
224            await github.rest.issues.createComment({
225              owner: context.repo.owner,
226              repo: context.repo.repo,
227              issue_number: context.issue.number,
228              body
229            });
230
231  # Job 5: Nightly Comprehensive Scan
232  nightly-scan:
233    name: Comprehensive Nightly Security Scan
234    runs-on: ubuntu-latest
235    if: github.event_name == 'schedule'
236    steps:
237      - uses: actions/checkout@v4
238      - uses: actions/setup-go@v5
239        with:
240          go-version: '${{ env.GO_VERSION }}'
241          cache: true
242
243      - name: Full dependency audit
244        run: |
245          go install golang.org/x/vuln/cmd/govulncheck@latest
246          govulncheck ./... > /tmp/nightly-vuln.txt 2>&1 || true
247
248      - name: Check for outdated dependencies
249        run: |
250          go list -m -u -json all 2>/dev/null | \
251            jq -r 'select(.Update != null) |
252            "\(.Path): \(.Version) → \(.Update.Version)"' | \
253            head -20 > /tmp/outdated-deps.txt
254
255          echo "Outdated dependencies:"
256          cat /tmp/outdated-deps.txt
257
258      - name: Notify Slack on vulnerabilities
259        if: always()
260        run: |
261          VULN_COUNT=$(grep -c "Vulnerability #" /tmp/nightly-vuln.txt || echo "0")
262
263          if [ "$VULN_COUNT" -gt 0 ]; then
264            curl -X POST "${{ secrets.SLACK_WEBHOOK }}" \
265              -H "Content-Type: application/json" \
266              -d "{\"text\": \":warning: Nightly security scan: $VULN_COUNT vulnerabilities found in dependencies. Check GitHub Actions for details.\"}"
267          fi

Notice the deliberate order: secret-scan runs first and ai-security depends on it (needs: [secret-scan]). There’s no point reviewing code style while a credential is leaking — a secret is the most critical issue and must stop everything.


06.8 Go Security Best Practices to Enforce

For the AI security review to have concrete targets, we need to know what a wrong versus right pattern looks like. The Go examples below pair five common anti-patterns with their safe versions.

go
 1// Example code patterns the AI security review needs to detect:
 2
 3// ❌ WRONG PATTERN: SQL injection via format string
 4func (r *orderRepo) GetByStatus(ctx context.Context, status string) ([]*domain.Order, error) {
 5    // VULNERABLE: status could contain SQL injection
 6    query := fmt.Sprintf("SELECT * FROM orders WHERE status = '%s'", status)
 7    rows, err := r.db.Query(ctx, query)
 8    // ...
 9}
10
11// ✅ RIGHT PATTERN: Parameterized query
12func (r *orderRepo) GetByStatus(ctx context.Context, status string) ([]*domain.Order, error) {
13    query := "SELECT * FROM orders WHERE status = $1"
14    rows, err := r.db.Query(ctx, query, status)
15    // ...
16}
17
18// ❌ WRONG PATTERN: Error detail exposure
19func (h *OrderHandler) GetOrder(c echo.Context) error {
20    order, err := h.usecase.GetOrder(ctx, id)
21    if err != nil {
22        // VULNERABLE: expose internal error detail to the client
23        return c.JSON(500, map[string]string{"error": err.Error()})
24    }
25    // ...
26}
27
28// ✅ RIGHT PATTERN: Generic error for the client
29func (h *OrderHandler) GetOrder(c echo.Context) error {
30    order, err := h.usecase.GetOrder(ctx, id)
31    if err != nil {
32        // Log detail internally, generic for the client
33        h.logger.Error().Err(err).Msg("get order failed")
34        return c.JSON(500, map[string]string{"error": "INTERNAL_ERROR"})
35    }
36    // ...
37}
38
39// ❌ WRONG PATTERN: Weak random for security
40import "math/rand"
41
42func generateToken() string {
43    // WRONG: math/rand is not cryptographically secure
44    return fmt.Sprintf("%d", rand.Int63())
45}
46
47// ✅ RIGHT PATTERN: Crypto random
48import "crypto/rand"
49import "encoding/hex"
50
51func generateToken() (string, error) {
52    bytes := make([]byte, 32)
53    if _, err := rand.Read(bytes); err != nil {
54        return "", fmt.Errorf("generateToken: %w", err)
55    }
56    return hex.EncodeToString(bytes), nil
57}
58
59// ❌ WRONG PATTERN: Integer overflow for financial
60func calculateTotal(price int64, quantity int) int64 {
61    // RISK: price * quantity can overflow if price is very large
62    return price * int64(quantity)
63}
64
65// ✅ RIGHT PATTERN: Overflow check
66func calculateTotal(price int64, quantity int) (int64, error) {
67    if quantity <= 0 {
68        return 0, errors.New("quantity must be positive")
69    }
70    result := price * int64(quantity)
71    // Check overflow: if the sign changes, there's an overflow
72    if price != 0 && result/price != int64(quantity) {
73        return 0, errors.New("total amount overflow")
74    }
75    return result, nil
76}

These five pattern pairs are a reference dictionary for the team and the AI reviewer alike: parameterized query, generic error, crypto/rand, and overflow check. Writing them explicitly makes review objective — not a matter of taste, but a matter of patterns that are clearly right or wrong.


06.9 Security Rules for CLAUDE.md

For the AI to consistently apply security standards in every review, these rules need to be written in CLAUDE.md. The block below is a Security section you can add directly, covering query safety, error exposure, cryptography, and financial arithmetic.

markdown
 1# Add to CLAUDE.md — Security section
 2
 3## Security Requirements (CRITICAL)
 4
 5### SQL Query Safety
 6ALWAYS use parameterized queries. NEVER string concatenation:
 7```go
 8// WRONG:
 9fmt.Sprintf("SELECT ... WHERE id = '%s'", userInput)
10
11// RIGHT:
12pool.QueryRow(ctx, "SELECT ... WHERE id = $1", userInput)
13```
14
15Use parameterized queries so user input is never concatenated directly into the SQL string.
16
17### Error Exposure
18NEVER return raw errors to HTTP clients:
19```go
20// WRONG:
21return c.JSON(500, map[string]string{"error": err.Error()})
22
23// RIGHT:
24h.logger.Error().Err(err).Msg("...")
25return c.JSON(500, map[string]string{"error": "INTERNAL_ERROR"})
26```
27
28Log the error details internally and return a generic message to the client so sensitive information never leaks.
29
30### Cryptography
31ALWAYS use crypto/rand for security-sensitive random values.
32NEVER use math/rand for tokens, nonces, or IDs.
33
34### Input Validation
35ALL user input MUST be validated:
36- UUID format: use uuid.Parse(), not direct string use
37- String length: define and enforce max length
38- Allowed characters: whitelist, not blacklist
39
40### Integer Arithmetic (Financial)
41Be aware of overflow in financial calculations.
42Use overflow-safe arithmetic for large transaction amounts.

Because CLAUDE.md is read automatically in every AI session, these rules become a persistent guardrail — code that’s generated or reviewed is always measured against the same security standard without needing to be repeated each time.


06.10 SAST Integration: SonarQube Alternative

For teams that need a dedicated SAST platform, GitHub CodeQL provides a powerful free alternative. The workflow below runs CodeQL security-extended queries on push, PR, and a weekly schedule.

yaml
 1# For teams that need a dedicated SAST platform:
 2# Free alternative: CodeQL from GitHub
 3
 4# .github/workflows/codeql.yml
 5name: CodeQL Analysis
 6
 7on:
 8  push:
 9    branches: [main]
10  pull_request:
11    branches: [main]
12  schedule:
13    - cron: '0 2 * * 1'  # Weekly on Monday
14
15jobs:
16  analyze:
17    name: CodeQL Security Analysis
18    runs-on: ubuntu-latest
19    permissions:
20      actions: read
21      contents: read
22      security-events: write
23    steps:
24      - uses: actions/checkout@v4
25
26      - name: Initialize CodeQL
27        uses: github/codeql-action/init@v3
28        with:
29          languages: go
30          queries: security-extended
31
32      - name: Build
33        run: go build ./...
34
35      - name: Perform CodeQL Analysis
36        uses: github/codeql-action/analyze@v3
37        with:
38          category: "/language:go"

CodeQL results appear in GitHub’s Security tab, separate from PR checks and accessible to the security team. This complements gosec: CodeQL is deeper for data-flow analysis, while gosec is faster for pattern checks on every PR.


06.11 Handling False Positives

Every static tool produces false positives, and how you handle them determines whether the team keeps trusting the pipeline. The example below shows how to suppress a legitimate gosec finding and the ignore mechanism for AI review.

bash
 1# gosec false positive — suppress with a comment:
 2// #nosec G107 -- URL is from config, not user input
 3resp, err := http.Get(cfg.WebhookURL)
 4
 5# Or in .gosec.yml:
 6[[rules.overrides]]
 7rule = "G107"
 8paths = ["internal/webhook/client.go"]
 9reason = "URL from validated config, not user input"
10
11# For AI review false positive:
12# A developer can comment on the PR: "/ignore-security [reason]"
13# The pipeline can detect this and skip strict enforcement
14
15# Detect the ignore command:
16- name: Check for security ignore
17  id: ignore_check
18  run: |
19    PR_BODY="${{ github.event.pull_request.body }}"
20    if echo "$PR_BODY" | grep -q "/ignore-security"; then
21      echo "ignored=true" >> $GITHUB_OUTPUT
22      echo "::notice::Security review ignored by developer"
23    else
24      echo "ignored=false" >> $GITHUB_OUTPUT
25    fi
26
27- name: AI Security Review
28  if: steps.ignore_check.outputs.ignored != 'true'
29  # ... run review

Notice that every suppression requires a reason — this prevents careless dismissal and leaves an audit trail. Track the false positive rate monthly; if it exceeds 10%, that’s a signal the rules need tuning, not ignoring.


06.12 Dependency Update Automation

Finding a vulnerability isn’t enough — we also need to fix it automatically. The workflow below runs a weekly scan and creates an automated PR to update vulnerable dependencies.

yaml
 1# Combine the security scan with an automatic update PR
 2
 3# .github/workflows/dependency-update.yml
 4name: Auto Dependency Update
 5
 6on:
 7  schedule:
 8    - cron: '0 3 * * 1'  # Monday 03:00 UTC
 9
10jobs:
11  update:
12    runs-on: ubuntu-latest
13    permissions:
14      contents: write
15      pull-requests: write
16    steps:
17      - uses: actions/checkout@v4
18      - uses: actions/setup-go@v5
19        with:
20          go-version: '1.22'
21
22      - name: Check for vulnerable dependencies
23        id: vuln
24        run: |
25          go install golang.org/x/vuln/cmd/govulncheck@latest
26          VULN_COUNT=$(govulncheck ./... 2>&1 | grep "Vulnerability #" | wc -l || echo "0")
27          echo "count=$VULN_COUNT" >> $GITHUB_OUTPUT
28
29      - name: Update vulnerable dependencies
30        if: steps.vuln.outputs.count != '0'
31        run: |
32          # Get list of modules with vulns
33          go get -u $(govulncheck -json ./... | \
34            jq -r '.findings[].trace[0].module' | \
35            sort -u | tr '\n' ' ')
36          go mod tidy
37
38      - name: Create PR for updates
39        if: steps.vuln.outputs.count != '0'
40        uses: peter-evans/create-pull-request@v6
41        with:
42          token: ${{ secrets.GITHUB_TOKEN }}
43          commit-message: "chore(deps): update vulnerable dependencies"
44          title: "Security: Update vulnerable dependencies"
45          body: |
46            ## Automated Security Dependency Update
47
48            **Vulnerabilities found:** ${{ steps.vuln.outputs.count }}
49
50            This PR updates dependencies to fix known security vulnerabilities.
51
52            Run `govulncheck ./...` locally for details.
53          branch: security/auto-update-deps
54          labels: security, dependencies

This automation closes the gap between detection and remediation: instead of vulnerabilities piling up while waiting for someone to have time, an update PR is created on its own every Monday. Developers just review and merge, rather than starting from scratch.


06.13 Security Score Dashboard

Different tools produce findings in different formats; we need a single composite score for the gate decision. The script below combines findings from gosec, govulncheck, and gitleaks into one security score with a weight per issue type.

bash
 1#!/bin/bash
 2# scripts/security-score.sh
 3# Calculate composite security score
 4
 5# Weights:
 6# gosec HIGH issues: -20 each
 7# govulncheck CRITICAL: -30 each
 8# govulncheck HIGH: -15 each
 9# gitleaks findings: -50 each (immediate block)
10# AI CRITICAL: -25 each
11
12SCORE=100
13ISSUES=()
14
15# gosec
16GOSEC_HIGH=$(jq '[.Issues[] | select(.severity == "HIGH")] | length' /tmp/gosec.json 2>/dev/null || echo "0")
17SCORE=$((SCORE - GOSEC_HIGH * 20))
18[ "$GOSEC_HIGH" -gt 0 ] && ISSUES+=("gosec: $GOSEC_HIGH HIGH issues")
19
20# govulncheck
21VULN_CRITICAL=$(jq '[.findings[] | select(.trace != null) |
22  select(.osv.database_specific.severity == "CRITICAL")] | length' \
23  /tmp/vuln.json 2>/dev/null || echo "0")
24SCORE=$((SCORE - VULN_CRITICAL * 30))
25[ "$VULN_CRITICAL" -gt 0 ] && ISSUES+=("vulnerabilities: $VULN_CRITICAL CRITICAL CVEs")
26
27# Ensure score doesn't go below 0
28[ "$SCORE" -lt 0 ] && SCORE=0
29
30echo "Security Score: $SCORE/100"
31if [ "${#ISSUES[@]}" -gt 0 ]; then
32  echo "Issues:"
33  for issue in "${ISSUES[@]}"; do
34    echo "  - $issue"
35  done
36fi
37
38# Verdict
39if [ "$SCORE" -lt 60 ]; then
40  echo "VERDICT: BLOCK"
41  exit 1
42elif [ "$SCORE" -lt 80 ]; then
43  echo "VERDICT: WARNING"
44  exit 0
45else
46  echo "VERDICT: PASS"
47  exit 0
48fi

The different weights reflect the level of risk: a gitleaks finding immediately drops the score to zero because a leaked secret is non-negotiable, while a gosec HIGH only subtracts 20 points. This single score makes the gate decision easy without having to interpret three separate reports.


06.14 Audit Log for Compliance

For security-sensitive actions, we need a traceable audit trail. The Go code below defines a structured audit logger that records the action, user, resource, and result.

go
 1// internal/audit/logger.go
 2// Audit logging for security-sensitive actions
 3
 4package audit
 5
 6import (
 7    "context"
 8    "time"
 9    "github.com/rs/zerolog"
10)
11
12type Event struct {
13    Action    string      `json:"action"`
14    UserID    string      `json:"user_id"`
15    Resource  string      `json:"resource"`
16    Result    string      `json:"result"` // SUCCESS | FAILURE | DENIED
17    Timestamp time.Time   `json:"timestamp"`
18    Details   interface{} `json:"details,omitempty"`
19}
20
21type AuditLogger struct {
22    log zerolog.Logger
23}
24
25func (a *AuditLogger) Log(ctx context.Context, event Event) {
26    event.Timestamp = time.Now()
27
28    a.log.Info().
29        Str("audit.action", event.Action).
30        Str("audit.user_id", event.UserID).
31        Str("audit.resource", event.Resource).
32        Str("audit.result", event.Result).
33        Interface("audit.details", event.Details).
34        Msg("AUDIT")
35}
36
37// Usage in a handler:
38func (h *OrderHandler) CancelOrder(c echo.Context) error {
39    // ... business logic ...
40
41    h.audit.Log(c.Request().Context(), audit.Event{
42        Action:   "order.cancel",
43        UserID:   userID.String(),
44        Resource: "order/" + orderID.String(),
45        Result:   "SUCCESS",
46    })
47
48    return c.NoContent(http.StatusNoContent)
49}

A structured audit log like this isn’t just a debugging aid — for regulated industries it’s a compliance obligation. The explicit Result field (SUCCESS/FAILURE/DENIED) enables analysis of suspicious access patterns without having to parse free-form logs.


06.15 Tips & Gotchas for Security Audit

💡 Tip 1: gosec before AI. Run gosec and govulncheck first (zero cost) before AI review. If there’s a deterministic issue, just fix it — no need to spend AI tokens.

💡 Tip 2: Tune .gosec.yml. The gosec default has many false positives. Investing 1-2 hours to tune the config per project will save a lot of time in the future.

💡 Tip 3: Nightly vuln scan. New vulnerabilities are discovered every day. Schedule a nightly scan to catch new CVEs before they become an incident.

💡 Tip 4: Separate security from regular CI. Security scans (especially the slower TruffleHog) are best kept in a separate workflow so they don’t slow down regular PR feedback.

⚠️ Gotcha 1: gitleaks + git history. Gitleaks scans the entire git history by default. Make sure fetch-depth: 0 in checkout for a full history scan, but this makes the checkout slower.

⚠️ Gotcha 2: govulncheck vs go list -m. govulncheck only reports vulnerabilities that are actually reachable from your code. go list -m -u reports all outdated packages. Both are useful but different.

⚠️ Gotcha 3: AI security review false positive. The AI sometimes flags things that aren’t actually vulnerabilities. Implement a /ignore-security mechanism and track the false positive rate.


06.16 Security Testing: Go Standard Approach

Automated scanning doesn’t replace explicit security tests. The Go tests below verify safe behavior directly: rejecting SQL injection, enforcing authorization, and not leaking internal errors.

go
 1// Add security-focused tests in Go:
 2
 3// internal/delivery/http/handler/order_handler_security_test.go
 4
 5package handler_test
 6
 7import (
 8    "net/http"
 9    "net/http/httptest"
10    "strings"
11    "testing"
12
13    "github.com/stretchr/testify/assert"
14)
15
16func TestCancelOrder_SQLInjectionAttempt(t *testing.T) {
17    // Test that SQL injection does not succeed
18    injectionAttempt := "'; DROP TABLE orders; --"
19
20    req := httptest.NewRequest(http.MethodDelete,
21        "/orders/"+injectionAttempt, nil)
22    rec := httptest.NewRecorder()
23
24    // Handler must return 400 (bad UUID format), not 500 (SQL error)
25    h.CancelOrder(echo.New().NewContext(req, rec))
26
27    assert.Equal(t, http.StatusBadRequest, rec.Code)
28    assert.NotContains(t, rec.Body.String(), "DROP TABLE")
29}
30
31func TestCancelOrder_AuthorizationCheck(t *testing.T) {
32    // Test that a user cannot cancel another user's order
33    orderID := uuid.New()
34    attackerUserID := uuid.New()
35
36    // Order belongs to another user
37    rec := httptest.NewRecorder()
38    req := httptest.NewRequest(http.MethodDelete, "/orders/"+orderID.String(), nil)
39    // Set the attacker's JWT
40    req.Header.Set("Authorization", "Bearer "+generateJWT(attackerUserID))
41
42    h.CancelOrder(echo.New().NewContext(req, rec))
43
44    // Must be 404, not 403 (security through obscurity: don't reveal it exists)
45    assert.Equal(t, http.StatusNotFound, rec.Code)
46}
47
48func TestCancelOrder_ErrorNotExposed(t *testing.T) {
49    // Test that an internal error is not exposed to the client
50    // Simulate a DB error
51    mockUC.EXPECT().CancelOrder(gomock.Any(), gomock.Any()).
52        Return(errors.New("pq: relation 'orders' does not exist"))
53
54    rec := httptest.NewRecorder()
55    h.CancelOrder(echo.New().NewContext(req, rec))
56
57    assert.Equal(t, http.StatusInternalServerError, rec.Code)
58    // The internal DB error must not appear in the response
59    assert.NotContains(t, rec.Body.String(), "pq:")
60    assert.NotContains(t, rec.Body.String(), "relation")
61    // Only INTERNAL_ERROR should appear
62    assert.Contains(t, rec.Body.String(), "INTERNAL_ERROR")
63}

These three tests turn security assumptions into automatically verified guarantees. Notice the authorization test that expects 404, not 403 — even revealing the existence of someone else’s resource is a form of information disclosure.


06.17 Summary

This article built a comprehensive security pipeline with four layers. The summary below recaps the role of each layer and the total cost.

text
 1Layer 1 (gitleaks/TruffleHog): Secret detection
 2  most critical, must pass first before the others.
 3
 4Layer 2 (gosec): Static analysis for Go-specific security issues
 5  SQL injection, weak crypto, hardcoded credentials.
 6
 7Layer 3 (govulncheck): Dependency vulnerability scan
 8  based on the Go vulnerability database, reachability-aware.
 9
10Layer 4 (AI): Context-aware security review
11  authorization bypass, information disclosure patterns, etc.
12
13Total cost: ~$0.002 per PR for the AI layer + $0 for the static tools.

The main principle is defense in depth: if one layer misses something, the next one catches it. The cost is under five dollars a month for the AI layer, free for the static tools, and its value is the incident prevented.


06.18 Security in the Context of Indonesian Compliance

For companies operating in Indonesia with sensitive data, these security tools also satisfy regulatory obligations. The mapping below links OJK, BI, and Kemenkes regulations to the relevant tool.

text
 1For companies operating in Indonesia with sensitive data:
 2
 3OJK (Fintech/Payment):
 4  POJK 77/POJK.01/2016: fintech lending
 5  Obligations: encrypt customer data, audit log, annual penetration testing
 6
 7  Relevance to Go security:
 8  - gosec to detect weak crypto (MD5, SHA1) → MUST replace
 9  - gitleaks to ensure secrets aren't committed
10  - govulncheck for dependencies that have a CVE
11
12BI (Bank/Payment System):
13  PBI 23/6/PBI/2021: payment systems
14  Obligations: security assessment, incident reporting
15
16  Relevance:
17  - SQL injection detection → parameterized query required
18  - Audit log for all financial transactions
19  - JWT with proper expiry and rotation
20
21Healthcare:
22  Permenkes 24/2022: medical records
23  Medical data: end-to-end encryption
24  Relevance:
25  - gosec G401: no MD5/SHA1 for medical data
26  - govulncheck: dependencies that handle medical data

This mapping makes compliance audits much easier: instead of proving compliance manually, you can show that every regulatory obligation is already enforced automatically in the pipeline with a specific tool.


06.19 Security Incident Response Runbook

When a security issue is detected, the team needs clear guidance for action per severity level. The runbook below defines the action, notification, and timeline for CRITICAL, HIGH, and MEDIUM severity.

text
 1When a security issue is detected in CI:
 2
 3SEVERITY CRITICAL (immediate action):
 4  - Hardcoded credential detected
 5  - Critical CVE in a deployed dependency
 6  → IMMEDIATE: Rotate credentials, patch ASAP
 7  → Notify: security lead, engineering manager
 8  → Timeline: < 4 hours to patch to production
 9
10SEVERITY HIGH (urgent):
11  - gosec HIGH issue in a production path
12  - High CVE in an active dependency
13  → Fix in the same sprint
14  → Notify: tech lead
15  → Timeline: < 24 hours for the PR, < 1 week for deploy
16
17SEVERITY MEDIUM (planned):
18  - gosec MEDIUM issues
19  - Outdated dependency without an active CVE
20  → Fix in the next sprint
21  → Track as a tech debt ticket

A runbook that sets explicit timelines — 4 hours for CRITICAL, 24 hours for HIGH — removes confusion when an incident happens. The team knows exactly what to do without having to debate priorities under pressure.


06.20 Monthly Security Metrics Review

Security isn’t a one-time checklist, but an ongoing process that needs monitoring. The script below generates a monthly security posture report: gosec trend, vulnerability count, secret scan status, and security test coverage.

bash
 1#!/bin/bash
 2# scripts/monthly-security-report.sh
 3# Generate monthly security posture report
 4
 5echo "=== MONTHLY SECURITY REPORT: $(date +%Y-%m) ==="
 6echo ""
 7
 8# 1. gosec trend
 9echo "## gosec Issues"
10echo "Current: $(gosec -conf .gosec.yml -fmt text ./... 2>&1 | grep -c 'HIGH\|MEDIUM' || echo 0) issues"
11
12# 2. Vulnerability count
13echo ""
14echo "## Dependency Vulnerabilities"
15echo "Current: $(govulncheck ./... 2>&1 | grep -c 'Vulnerability' || echo 0) vulnerabilities"
16
17# 3. Secret scan status
18echo ""
19echo "## Secret Scanning"
20echo "gitleaks: $(git log --since='30 days ago' --oneline | wc -l) commits scanned"
21
22# 4. Security test coverage
23echo ""
24echo "## Security Test Coverage"
25grep -r "TestSecurity\|_Security_\|security_test" internal/ --include="*.go" | wc -l
26echo "security-focused test functions"

This monthly report turns security from a reactive activity into a measurable discipline — you can see whether the number of issues is decreasing month over month, and raise the alarm if the trend worsens. All the tools are already configured and running automatically in CI.

Related Articles

💬 Comments