SiamCafe.net Blog
Cybersecurity

Snyk Code Security

snyk code security คมอฉบบสมบรณ 2026
Snyk Code Security | SiamCafe Blog
2026-02-04· อ. บอม — SiamCafe.net· 9,877 คำ

Snyk Developer Security Platform

Snyk เป็น Developer Security Platform ที่ตรวจสอบ Vulnerabilities ตั้งแต่ Code, Dependencies, Containers ไปจนถึง Infrastructure as Code ทำงานร่วมกับ Developer Workflow ตรวจจับปัญหาตั้งแต่เขียน Code ใน IDE

Snyk มี 4 Products หลัก ได้แก่ Snyk Code (SAST), Snyk Open Source (SCA), Snyk Container และ Snyk IaC ใช้ร่วมกันได้ครอบคลุม Security ทั้ง Software Development Lifecycle

Snyk CLI และ Configuration

# === Snyk Installation และ Configuration ===

# 1. ติดตั้ง Snyk CLI
npm install -g snyk
# หรือ
brew install snyk
# หรือ
pip install snyk

# 2. Authentication
snyk auth
# หรือใช้ Token
export SNYK_TOKEN="your-api-token"

# 3. Snyk Open Source (SCA) — ตรวจ Dependencies
# ตรวจ Vulnerabilities
snyk test

# ตรวจพร้อม Fix Suggestions
snyk test --severity-threshold=high

# Monitor (ส่งผลไป Snyk Dashboard)
snyk monitor

# ตรวจ Specific Package Manager
snyk test --file=requirements.txt    # Python
snyk test --file=package.json        # Node.js
snyk test --file=pom.xml             # Java
snyk test --file=go.mod              # Go
snyk test --file=Gemfile.lock        # Ruby

# 4. Snyk Code (SAST) — ตรวจ Source Code
snyk code test

# ตรวจเฉพาะ Directory
snyk code test --path=./src

# Output เป็น JSON
snyk code test --json > snyk-code-report.json

# 5. Snyk Container — ตรวจ Docker Image
snyk container test node:18-alpine
snyk container test myapp:latest --file=Dockerfile

# Monitor Container
snyk container monitor myapp:latest

# 6. Snyk IaC — ตรวจ Infrastructure as Code
snyk iac test
snyk iac test terraform/
snyk iac test kubernetes/deployment.yaml
snyk iac test --severity-threshold=high

# 7. ดู Report
snyk test --json | snyk-to-html -o report.html

echo "Snyk configured"
echo "  Open Source: snyk test"
echo "  Code (SAST): snyk code test"
echo "  Container: snyk container test"
echo "  IaC: snyk iac test"

CI/CD Integration

# === GitHub Actions — Snyk Security Pipeline ===
# .github/workflows/snyk-security.yml

name: Snyk Security
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 6 * * 1'  # ทุกวันจันทร์ 06:00

env:
  SNYK_TOKEN: }

jobs:
  snyk-open-source:
    name: Dependency Scan (SCA)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - run: npm ci

      - name: Snyk Open Source Test
        uses: snyk/actions/node@master
        continue-on-error: true
        with:
          command: test
          args: --severity-threshold=high

      - name: Snyk Open Source Monitor
        uses: snyk/actions/node@master
        if: github.ref == 'refs/heads/main'
        with:
          command: monitor

  snyk-code:
    name: Code Analysis (SAST)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Snyk Code Test
        uses: snyk/actions/node@master
        continue-on-error: true
        with:
          command: code test
          args: --severity-threshold=high

  snyk-container:
    name: Container Scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build Docker Image
        run: docker build -t myapp:test .

      - name: Snyk Container Test
        uses: snyk/actions/docker@master
        continue-on-error: true
        with:
          image: myapp:test
          args: --severity-threshold=high

  snyk-iac:
    name: IaC Security
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Snyk IaC Test
        uses: snyk/actions/iac@master
        continue-on-error: true
        with:
          args: --severity-threshold=medium

  security-gate:
    name: Security Gate
    needs: [snyk-open-source, snyk-code, snyk-container, snyk-iac]
    runs-on: ubuntu-latest
    steps:
      - name: Check Results
        run: |
          echo "All security scans completed"
          echo "Check Snyk Dashboard for details"

Snyk Policy และ Automation

# snyk_automation.py — Snyk Automation Script
import subprocess
import json
from dataclasses import dataclass
from typing import List, Dict
from datetime import datetime

@dataclass
class Vulnerability:
    id: str
    title: str
    severity: str
    package_name: str
    version: str
    fixed_in: str
    cvss_score: float
    exploit_maturity: str

class SnykAutomation:
    """Snyk Automation สำหรับ Security Management"""

    def __init__(self):
        self.results: List[Vulnerability] = []

    def scan_dependencies(self, path="."):
        """Scan Dependencies"""
        result = subprocess.run(
            ["snyk", "test", "--json", f"--file={path}"],
            capture_output=True, text=True,
        )

        try:
            data = json.loads(result.stdout)
            vulns = data.get("vulnerabilities", [])

            for v in vulns:
                self.results.append(Vulnerability(
                    id=v.get("id", ""),
                    title=v.get("title", ""),
                    severity=v.get("severity", ""),
                    package_name=v.get("packageName", ""),
                    version=v.get("version", ""),
                    fixed_in=", ".join(v.get("fixedIn", [])),
                    cvss_score=v.get("cvssScore", 0),
                    exploit_maturity=v.get("exploit", "No Known Exploit"),
                ))

            return len(vulns)
        except json.JSONDecodeError:
            print("Error parsing Snyk output")
            return 0

    def generate_report(self):
        """สร้าง Security Report"""
        print(f"\n{'='*60}")
        print(f"Snyk Security Report — {datetime.now().strftime('%Y-%m-%d')}")
        print(f"{'='*60}")
        print(f"  Total Vulnerabilities: {len(self.results)}")

        # By Severity
        severity_count = {}
        for v in self.results:
            severity_count[v.severity] = severity_count.get(v.severity, 0) + 1

        print(f"\n  By Severity:")
        for sev in ["critical", "high", "medium", "low"]:
            count = severity_count.get(sev, 0)
            if count > 0:
                print(f"    {sev:>10}: {count}")

        # Fixable
        fixable = [v for v in self.results if v.fixed_in]
        print(f"\n  Fixable: {len(fixable)}/{len(self.results)}")

        # Top Critical/High
        critical = [v for v in self.results if v.severity in ["critical", "high"]]
        if critical:
            print(f"\n  Critical/High Issues:")
            for v in critical[:10]:
                print(f"    [{v.severity:>8}] {v.package_name}@{v.version}")
                print(f"      {v.title}")
                if v.fixed_in:
                    print(f"      Fix: upgrade to {v.fixed_in}")

    def policy_check(self, max_critical=0, max_high=5):
        """ตรวจสอบ Security Policy"""
        critical = sum(1 for v in self.results if v.severity == "critical")
        high = sum(1 for v in self.results if v.severity == "high")

        passed = critical <= max_critical and high <= max_high

        print(f"\n  Policy Check:")
        print(f"    Critical: {critical}/{max_critical} "
              f"{'PASS' if critical <= max_critical else 'FAIL'}")
        print(f"    High: {high}/{max_high} "
              f"{'PASS' if high <= max_high else 'FAIL'}")
        print(f"    Overall: {'PASS' if passed else 'FAIL'}")

        return passed

# snyk = SnykAutomation()
# snyk.scan_dependencies("package.json")
# snyk.generate_report()
# snyk.policy_check(max_critical=0, max_high=3)

Best Practices

Snyk คืออะไร

Developer Security Platform ตรวจ Vulnerabilities ใน Code (SAST) Dependencies (SCA) Containers IaC รองรับหลายภาษา CLI IDE Plugin CI/CD Integration ฟรีสำหรับ Open Source

SAST กับ SCA ต่างกันอย่างไร

SAST วิเคราะห์ Source Code ที่เขียนเอง หา SQL Injection XSS Path Traversal SCA วิเคราะห์ Open Source Dependencies หา Known Vulnerabilities (CVE) License Issues

Snyk ใช้ฟรีได้หรือไม่

ได้ Free Plan 200 tests/month Open Source 100 tests/month Container Snyk Code ฟรีสำหรับ Individual IDE Plugin ฟรี CLI ฟรี

วิธี Fix Vulnerabilities ที่ Snyk พบทำอย่างไร

Snyk แนะนำวิธีแก้ Upgrade Version Apply Patch Alternative Package แนะนำ Code ปลอดภัย สร้าง Fix PR อัตโนมัติ GitHub Priority ตาม CVSS Score

สรุป

Snyk เป็น Developer Security Platform ที่ครอบคลุมทั้ง Code Dependencies Containers IaC ใช้ Shift Left ตรวจจับตั้งแต่ IDE CI/CD Gate Block Deploy ถ้ามี Critical Auto Fix PRs อัพเดท Dependencies Weekly Scan ตรวจ Vulnerabilities ใหม่ Policy as Code กำหนด Security Standards

📖 บทความที่เกี่ยวข้อง

Elasticsearch OpenSearch อ่านบทความ → AWS Glue ETL อ่านบทความ → Snyk Code Security Hexagonal Architectureอ่านบทความ → Snyk Code Security Pub Sub Architectureอ่านบทความ → Snyk Code Security Security Hardening ป้องกันแฮกอ่านบทความ →

📚 ดูบทความทั้งหมด →