Skip to content
Santekno.com | Level Up Your Engineering Skills
ID
📖 0%
14 Oct 2026 · 27 mnt baca ·Artikel 66 / 208
Go

Security Audit Otomatis Golang di CI/CD: gosec, Dependency Scan, AI Analysis

Setup automated security audit untuk Go di CI/CD. Kombinasi gosec, govulncheck, dependency scanning, dan AI-powered vulnerability analysis untuk production Go service.

IH
Ihsan Arif
Penulis di Santekno · Backend Engineer

Security Audit Otomatis: AI Scan Vulnerability untuk Golang

Security audit otomatis untuk Golang sering di-skip dari pipeline CI karena dianggap kompleks dan banyak false positive. Artikel ini menunjukkan pendekatan yang pragmatic: kombinasi tools deterministik (gosec, govulncheck, gitleaks) dengan AI analysis untuk memberikan security coverage yang comprehensive tanpa membuat developer kewalahan. Hasilnya adalah pipeline berlapis yang menangkap secret, anti-pattern, CVE dependency, sampai isu semantik seperti authorization bypass.


06.1 Threat Landscape untuk Go Service

Sebelum memilih tools, kita perlu tahu apa yang sedang kita lawan. Daftar berikut memetakan tipe vulnerability yang paling umum di production Go service, diurutkan berdasarkan tingkat keparahan.

text
 1Vulnerability types yang paling umum di production Go services:
 2
 3LEVEL CRITICAL (exploitable langsung):
 4  - SQL injection via string concatenation
 5  - Hardcoded credentials (API key, DB password)
 6  - Path traversal vulnerability
 7  - Insecure deserialization
 8  - JWT secret weak atau hardcoded
 9
10LEVEL HIGH (perlu exploit chain):
11  - Dependency dengan known CVE
12  - Integer overflow untuk financial calculation
13  - Race condition di concurrent code
14  - Missing rate limiting di public endpoints
15  - Insufficient input validation
16
17LEVEL MEDIUM (context-dependent):
18  - Missing TLS verification
19  - Weak cryptography (MD5, SHA1 untuk 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

Pemetaan level ini menentukan strategi enforcement: isu CRITICAL harus mem-block build, sedangkan isu LOW cukup jadi catatan untuk perbaikan bertahap. Setiap tool yang kita pilih menargetkan level yang berbeda.


06.2 Security Stack: Tools yang Akan Kita Pakai

Tidak ada satu tool yang menangkap semua isu, jadi kita gabungkan empat yang saling melengkapi. Ringkasan berikut membandingkan cakupan, tingkat false positive, dan biaya masing-masing.

text
 1TOOL 1: gosec (go security checker)
 2  Type: Static analysis, deterministic
 3  Coverage: ~80 rules untuk Go-specific security issues
 4  False positive: Medium (perlu 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 dengan proper config
17  Cost: Zero
18
19TOOL 4: Claude AI Security Review
20  Type: Semantic analysis
21  Coverage: Context-aware issues yang tools statis miss
22  False positive: Medium (perlu good prompt)
23  Cost: Low ($0.001-0.003 per review)
24
25KOMBINASI OPTIMAL:
26  gosec + govulncheck + gitleaks = baseline (zero cost)
27  AI review = semantic coverage untuk issues yang deterministic miss

Prinsip di balik stack ini adalah defense in depth: tiga tool gratis membentuk baseline yang menangkap mayoritas isu, dan AI hanya dipanggil untuk lapisan semantik yang tidak bisa dijangkau pattern matching. Total biaya tetap rendah karena tool berbayar dipakai paling hemat.


06.3 Setup gosec yang Optimal

gosec adalah lini pertama untuk anti-pattern Go, tapi default-nya menghasilkan banyak false positive. Konfigurasi berikut memasang gosec dan men-tune rules agar hanya isu yang relevan yang dilaporkan.

bash
 1# Install
 2go install github.com/securego/gosec/v2/cmd/gosec@latest
 3
 4# .gosec.yml — konfigurasi untuk 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 — sudah cover di golangci-lint errcheck
14    - G104
15
16    # G304: File path provided as taint input — false positive di test utils
17    # Tetap enable tapi suppress di 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 dengan output JSON untuk CI processing:
44gosec -conf .gosec.yml -fmt json -out /tmp/gosec-result.json ./...

Perhatikan exclude untuk G104 yang sudah ditangani errcheck di golangci-lint — menghindari laporan ganda. Investasi satu-dua jam untuk men-tune .gosec.yml sekali akan menghemat berjam-jam menyaring false positive di masa depan.


06.4 govulncheck: Dependency Vulnerability Scan

Setelah anti-pattern kode, kita periksa dependency untuk CVE yang diketahui. govulncheck unggul karena hanya melaporkan vulnerability yang benar-benar reachable dari kode kita. Perintah berikut menjalankan scan dan mem-parse hasilnya.

bash
 1# Install
 2go install golang.org/x/vuln/cmd/govulncheck@latest
 3
 4# Run basic scan:
 5govulncheck ./...
 6
 7# Run dengan output JSON:
 8govulncheck -json ./... > /tmp/vuln-result.json
 9
10# Parse hasil:
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# }

Filter select(.trace != null) adalah kunci: ia menyaring hanya vulnerability yang punya jejak pemanggilan dari kode kita, secara dramatis mengurangi noise dibanding sekadar mendaftar semua package usang. Ini yang membuat govulncheck aman dipakai sebagai gate build.


06.5 Gitleaks Configuration

Secret yang bocor adalah isu paling kritis, jadi gitleaks perlu dikonfigurasi dengan pattern yang tepat. File TOML berikut mendefinisikan aturan deteksi untuk API key, connection string, dan JWT secret, plus allowlist untuk 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]

Bagian allowlist sama pentingnya dengan rules deteksi: tanpa itu, placeholder di test fixture dan file example akan memicu false positive yang melelahkan. Konfigurasi yang seimbang inilah yang membuat secret scan bisa dipercaya sebagai gate wajib.


06.6 AI Security Review untuk Context-Aware Issues

Tools deterministik hanya menemukan apa yang diprogram untuk ditemukan. Untuk isu yang butuh pemahaman konteks — authorization bypass, information disclosure — kita gunakan AI. Script berikut membangun prompt security review yang terstruktur dan mem-fail build jika ada isu CRITICAL.

bash
 1#!/bin/bash
 2# scripts/ai-security-review.sh
 3# AI review khusus untuk security issues yang static tools miss
 4
 5set -euo pipefail
 6
 7DIFF_FILE="${1}"
 8DIFF=$(cat "$DIFF_FILE")
 9
10# Load app context untuk better analysis
11APP_CONTEXT=""
12if [ -f "CLAUDE.md" ]; then
13  APP_CONTEXT=$(head -50 CLAUDE.md)
14fi
15
16PROMPT="Security review for production Go e-commerce service.
17
18APP CONTEXT:
19$APP_CONTEXT
20
21Review diff untuk security vulnerabilities:
22
231. SQL INJECTION
24   Apakah ada string concatenation dalam 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   Apakah user input di-validate sebelum dipakai?
30   Check: UUID format, string length, allowed characters
31
323. AUTHORIZATION BYPASS
33   Apakah ada endpoint yang skip auth check?
34   Apakah ada hard-coded user ID atau role?
35
364. INFORMATION DISCLOSURE
37   Apakah 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   Apakah ada MD5/SHA1 untuk security-critical operations?
43   Apakah random generation pakai crypto/rand (bukan math/rand)?
44
456. RACE CONDITION
46   Apakah shared state di-access dari multiple goroutines tanpa sync?
47
487. FINANCIAL CALCULATION SAFETY
49   Apakah ada integer overflow risk untuk large transaction amounts?
50   (int64 max = 9.2 * 10^18 cents — aman untuk 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 jika ada CRITICAL
75if echo "$RESULT" | grep -q "^CRITICAL:"; then
76  echo ""
77  echo "::error::Critical security issues found"
78  exit 1
79fi
80
81# Warning untuk HIGH
82if echo "$RESULT" | grep -q "^HIGH:"; then
83  echo ""
84  echo "::warning::High severity security issues found"
85fi

Ketujuh kategori dalam prompt ini secara sengaja menargetkan isu yang gosec dan govulncheck tidak bisa lihat — misalnya apakah sebuah endpoint memeriksa kepemilikan order, bukan sekadar keberadaannya. Inilah nilai tambah AI di atas baseline deterministik.


06.7 Workflow GitHub Actions: Full Security Pipeline

Sekarang keempat tool dirangkai menjadi satu pipeline security. Workflow berikut menjalankan secret detection lebih dulu, lalu static analysis, dependency scan, AI review, dan 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 (paling penting, run pertama)
 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  # butuh full history untuk 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 jika ada vulnerability dengan 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]  # hanya jalan kalau secret scan pass
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

Perhatikan urutan yang disengaja: secret-scan berjalan pertama dan ai-security bergantung padanya (needs: [secret-scan]). Tidak ada gunanya mereview gaya kode ketika ada credential yang bocor — secret adalah isu paling kritis dan harus menghentikan segalanya.


06.8 Go Security Best Practices yang Perlu Di-enforce

Agar AI security review punya target konkret, kita perlu tahu seperti apa pattern yang salah versus benar. Contoh Go berikut menyandingkan lima anti-pattern umum dengan versi amannya.

go
 1// Contoh code patterns yang AI security review perlu detect:
 2
 3// ❌ PATTERN SALAH: SQL injection via format string
 4func (r *orderRepo) GetByStatus(ctx context.Context, status string) ([]*domain.Order, error) {
 5    // VULNERABLE: status bisa 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// ✅ PATTERN BENAR: 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// ❌ PATTERN SALAH: 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 ke client
23        return c.JSON(500, map[string]string{"error": err.Error()})
24    }
25    // ...
26}
27
28// ✅ PATTERN BENAR: Generic error untuk client
29func (h *OrderHandler) GetOrder(c echo.Context) error {
30    order, err := h.usecase.GetOrder(ctx, id)
31    if err != nil {
32        // Log detail untuk internal, generic untuk 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// ❌ PATTERN SALAH: Weak random untuk security
40import "math/rand"
41
42func generateToken() string {
43    // WRONG: math/rand tidak cryptographically secure
44    return fmt.Sprintf("%d", rand.Int63())
45}
46
47// ✅ PATTERN BENAR: 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// ❌ PATTERN SALAH: Integer overflow untuk financial
60func calculateTotal(price int64, quantity int) int64 {
61    // RISK: price * quantity bisa overflow jika price sangat besar
62    return price * int64(quantity)
63}
64
65// ✅ PATTERN BENAR: 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: jika tanda berubah, ada overflow
72    if price != 0 && result/price != int64(quantity) {
73        return 0, errors.New("total amount overflow")
74    }
75    return result, nil
76}

Kelima pasangan pattern ini adalah kamus rujukan bagi tim maupun AI reviewer: parameterized query, generic error, crypto/rand, dan overflow check. Menuliskannya eksplisit membuat review objektif — bukan soal selera, tapi soal pola yang jelas benar atau salah.


06.9 Security Rules untuk CLAUDE.md

Agar AI konsisten menerapkan standar keamanan di setiap review, aturan ini perlu ditulis di CLAUDE.md. Blok berikut adalah section Security yang bisa langsung ditambahkan, mencakup query safety, error exposure, kriptografi, dan aritmetika finansial.

markdown
 1# Tambahkan ke 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
15Gunakan query berparameter agar input pengguna tidak pernah digabung langsung ke dalam string SQL.
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
28Catat detail error di log internal dan kembalikan pesan generik ke klien agar informasi sensitif tidak bocor.
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.

Karena CLAUDE.md dibaca otomatis di setiap sesi AI, aturan ini menjadi persistent guardrail — kode yang di-generate maupun di-review selalu diukur terhadap standar keamanan yang sama tanpa perlu diulang tiap kali.


06.10 SAST Integration: SonarQube Alternative

Untuk tim yang butuh SAST platform terdedikasi, GitHub CodeQL menyediakan alternatif gratis yang kuat. Workflow berikut menjalankan CodeQL security-extended queries pada push, PR, dan jadwal mingguan.

yaml
 1# Untuk tim yang butuh dedicated SAST platform:
 2# Alternatif gratis: CodeQL dari 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"

Hasil CodeQL muncul di tab Security GitHub, terpisah dari PR checks dan dapat diakses tim security. Ini melengkapi gosec: CodeQL lebih mendalam untuk data-flow analysis, sedangkan gosec lebih cepat untuk pattern check di setiap PR.


06.11 Penanganan False Positive

Semua tool static menghasilkan false positive, dan cara menanganinya menentukan apakah tim tetap mempercayai pipeline. Contoh berikut menunjukkan cara men-suppress temuan gosec yang sah dan mekanisme ignore untuk AI review.

bash
 1# gosec false positive — suppress dengan comment:
 2// #nosec G107 -- URL is from config, not user input
 3resp, err := http.Get(cfg.WebhookURL)
 4
 5# Atau di .gosec.yml:
 6[[rules.overrides]]
 7rule = "G107"
 8paths = ["internal/webhook/client.go"]
 9reason = "URL from validated config, not user input"
10
11# Untuk AI review false positive:
12# Developer bisa comment di PR: "/ignore-security [reason]"
13# Pipeline bisa detect ini dan skip strict enforcement
14
15# Deteksi 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

Perhatikan bahwa setiap suppression mewajibkan reason — ini mencegah pengabaian sembarangan dan meninggalkan jejak audit. Lacak tingkat false positive secara bulanan; jika melebihi 10%, itu sinyal rules perlu di-tune, bukan diabaikan.


06.12 Dependency Update Automation

Menemukan vulnerability saja tidak cukup — kita juga perlu memperbaikinya secara otomatis. Workflow berikut menjalankan scan mingguan dan membuat PR otomatis untuk meng-update dependency yang rentan.

yaml
 1# Kombinasikan security scan dengan 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

Otomasi ini menutup gap antara deteksi dan remediasi: alih-alih vulnerability menumpuk menunggu ada yang sempat, PR update dibuat sendiri setiap Senin. Developer tinggal me-review dan merge, bukan memulai dari nol.


06.13 Security Score Dashboard

Berbagai tool menghasilkan temuan dalam format berbeda; kita perlu satu skor komposit untuk keputusan gate. Script berikut menggabungkan temuan gosec, govulncheck, dan gitleaks menjadi satu security score dengan bobot per tipe isu.

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

Bobot yang berbeda mencerminkan tingkat risiko: gitleaks finding langsung menjatuhkan skor ke nol karena secret bocor tidak bisa ditawar, sedangkan gosec HIGH hanya mengurangi 20 poin. Skor tunggal ini memudahkan keputusan gate tanpa perlu menafsirkan tiga laporan terpisah.


06.14 Audit Log untuk Compliance

Untuk aksi yang sensitif secara keamanan, kita butuh jejak audit yang bisa ditelusuri. Kode Go berikut mendefinisikan audit logger terstruktur yang mencatat aksi, user, resource, dan hasilnya.

go
 1// internal/audit/logger.go
 2// Audit logging untuk 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 di 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}

Audit log terstruktur seperti ini bukan sekadar debugging aid — untuk industri teregulasi ia adalah kewajiban compliance. Field Result yang eksplisit (SUCCESS/FAILURE/DENIED) memungkinkan analisis pola akses mencurigakan tanpa perlu mem-parse log bebas.


06.15 Tips & Gotchas Security Audit

💡 Tip 1: gosec sebelum AI. Jalankan gosec dan govulncheck dulu (zero cost) sebelum AI review. Jika ada issue deterministik, cukup fix itu — tidak perlu spend AI token.

💡 Tip 2: Tune .gosec.yml. Default gosec punya banyak false positive. Invest 1-2 jam untuk tune config per project akan save banyak waktu di masa depan.

💡 Tip 3: Nightly vuln scan. Vulnerability baru ditemukan setiap hari. Schedule scan nightly untuk catch CVE baru sebelum menjadi incident.

💡 Tip 4: Separate security dari regular CI. Security scan (terutama TruffleHog yang lebih slow) sebaiknya di workflow terpisah agar tidak memperlambat regular PR feedback.

⚠️ Gotcha 1: gitleaks + git history. Gitleaks scan seluruh git history by default. Pastikan fetch-depth: 0 di checkout untuk full history scan, tapi ini membuat checkout lebih lambat.

⚠️ Gotcha 2: govulncheck vs go list -m. govulncheck hanya report vulnerabilities yang actually reachable dari kode kamu. go list -m -u report semua outdated packages. Keduanya berguna tapi berbeda.

⚠️ Gotcha 3: AI security review false positive. AI kadang flag hal yang tidak actually vulnerability. Implementasikan mekanisme /ignore-security dan track false positive rate.


06.16 Security Testing: Go Standard Approach

Automated scanning tidak menggantikan test keamanan yang eksplisit. Test Go berikut memverifikasi perilaku aman secara langsung: menolak SQL injection, menegakkan authorization, dan tidak membocorkan error internal.

go
 1// Tambahkan security-focused tests di 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 bahwa SQL injection tidak berhasil
18    injectionAttempt := "'; DROP TABLE orders; --"
19
20    req := httptest.NewRequest(http.MethodDelete,
21        "/orders/"+injectionAttempt, nil)
22    rec := httptest.NewRecorder()
23
24    // Handler harus return 400 (bad UUID format), bukan 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 bahwa user tidak bisa cancel order milik user lain
33    orderID := uuid.New()
34    attackerUserID := uuid.New()
35
36    // Order milik user lain
37    rec := httptest.NewRecorder()
38    req := httptest.NewRequest(http.MethodDelete, "/orders/"+orderID.String(), nil)
39    // Set attacker's JWT
40    req.Header.Set("Authorization", "Bearer "+generateJWT(attackerUserID))
41
42    h.CancelOrder(echo.New().NewContext(req, rec))
43
44    // Harus 404, bukan 403 (security through obscurity: jangan reveal it exists)
45    assert.Equal(t, http.StatusNotFound, rec.Code)
46}
47
48func TestCancelOrder_ErrorNotExposed(t *testing.T) {
49    // Test bahwa internal error tidak di-expose ke client
50    // Simulate 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    // Internal DB error tidak boleh muncul di response
59    assert.NotContains(t, rec.Body.String(), "pq:")
60    assert.NotContains(t, rec.Body.String(), "relation")
61    // Hanya INTERNAL_ERROR yang muncul
62    assert.Contains(t, rec.Body.String(), "INTERNAL_ERROR")
63}

Ketiga test ini mengubah asumsi keamanan menjadi jaminan yang terverifikasi otomatis. Perhatikan test authorization yang mengharapkan 404 bukan 403 — mengungkap keberadaan resource milik orang lain pun sudah termasuk information disclosure.


06.17 Ringkasan

Artikel ini membangun security pipeline yang komprehensif dengan empat layer. Ringkasan berikut merangkum peran tiap layer dan total biayanya.

text
 1Layer 1 (gitleaks/TruffleHog): Secret detection
 2  paling critical, harus pass dulu sebelum yang lain.
 3
 4Layer 2 (gosec): Static analysis untuk Go-specific security issues
 5  SQL injection, weak crypto, hardcoded credentials.
 6
 7Layer 3 (govulncheck): Dependency vulnerability scan
 8  berdasarkan Go vulnerability database, reachability-aware.
 9
10Layer 4 (AI): Context-aware security review
11  authorization bypass, information disclosure pattern, dll.
12
13Total cost: ~$0.002 per PR untuk AI layer + $0 untuk static tools.

Prinsip utamanya adalah defense in depth: jika satu layer melewatkan sesuatu, layer berikutnya menangkapnya. Biaya di bawah lima dolar per bulan untuk layer AI, gratis untuk tools statis, dan nilainya adalah insiden yang tercegah.


06.18 Security dalam Konteks Compliance Indonesia

Untuk perusahaan yang beroperasi di Indonesia dengan data sensitif, security tools ini juga memenuhi kewajiban regulasi. Pemetaan berikut menghubungkan regulasi OJK, BI, dan Kemenkes dengan tool yang relevan.

text
 1Untuk perusahaan yang beroperasi di Indonesia dengan data sensitif:
 2
 3OJK (Fintech/Payment):
 4  POJK 77/POJK.01/2016: fintech lending
 5  Kewajiban: enkripsi data nasabah, audit log, penetration testing tahunan
 6
 7  Relevansi ke Go security:
 8  - gosec untuk detect weak crypto (MD5, SHA1) → WAJIB replace
 9  - gitleaks untuk ensure secrets tidak di-commit
10  - govulncheck untuk dependency yang punya CVE
11
12BI (Bank/Payment System):
13  PBI 23/6/PBI/2021: sistem pembayaran
14  Kewajiban: security assessment, incident reporting
15
16  Relevansi:
17  - SQL injection detection → wajib parameterized query
18  - Log audit untuk semua transaksi finansial
19  - JWT dengan proper expiry dan rotation
20
21Healthcare:
22  Permenkes 24/2022: rekam medis
23  Data medis: enkripsi end-to-end
24  Relevansi:
25  - gosec G401: no MD5/SHA1 untuk medical data
26  - govulncheck: dependency yang handle medical data

Pemetaan ini membuat audit compliance jauh lebih mudah: alih-alih membuktikan kepatuhan secara manual, kamu bisa menunjukkan bahwa setiap kewajiban regulasi sudah ditegakkan otomatis di pipeline dengan tool yang spesifik.


06.19 Security Incident Response Runbook

Ketika security issue terdeteksi, tim butuh panduan tindakan yang jelas per tingkat keparahan. Runbook berikut menetapkan aksi, notifikasi, dan timeline untuk severity CRITICAL, HIGH, dan MEDIUM.

text
 1Ketika ada security issue yang terdeteksi di CI:
 2
 3SEVERITY CRITICAL (immediate action):
 4  - Hardcoded credential terdeteksi
 5  - CVE critical di dependency yang di-deploy
 6  → IMMEDIATE: Rotate credentials, patch ASAP
 7  → Notify: security lead, engineering manager
 8  → Timeline: < 4 jam untuk patch ke production
 9
10SEVERITY HIGH (urgent):
11  - gosec HIGH issue di production path
12  - CVE high di active dependency
13  → Fix dalam sprint yang sama
14  → Notify: tech lead
15  → Timeline: < 24 jam untuk PR, < 1 minggu untuk deploy
16
17SEVERITY MEDIUM (planned):
18  - gosec MEDIUM issues
19  - Outdated dependency tanpa active CVE
20  → Fix di sprint berikutnya
21  → Track sebagai tech debt ticket

Runbook yang menetapkan timeline eksplisit — 4 jam untuk CRITICAL, 24 jam untuk HIGH — menghilangkan kebingungan saat insiden terjadi. Tim tahu persis apa yang harus dilakukan tanpa harus berdebat prioritas di tengah tekanan.


06.20 Security Metrics Monthly Review

Security bukan checklist satu kali, tapi proses berkelanjutan yang perlu dipantau. Script berikut menghasilkan laporan security posture bulanan: tren gosec, jumlah vulnerability, status secret scan, dan coverage test keamanan.

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"

Laporan bulanan ini mengubah keamanan dari kegiatan reaktif menjadi disiplin yang terukur — kamu bisa melihat apakah jumlah isu menurun dari bulan ke bulan, dan menaikkan alarm bila trennya memburuk. Semua tool sudah terkonfigurasi dan berjalan otomatis di CI.

Artikel Terkait

💬 Komentar