SiamCafe.net Blog
Cybersecurity

Snyk Code Security Performance Tuning เพิ่มความเร็ว เร่ง Security Scan ใน CI/CD

snyk code security performance tuning เพมความเรว
Snyk Code Security Performance Tuning เพิ่มความเร็ว | SiamCafe Blog
2025-12-23· อ. บอม — SiamCafe.net· 1,299 คำ

Snyk Code Security ?????????????????????

Snyk ???????????? developer security platform ?????????????????????????????????????????????????????????????????? (vulnerabilities) ?????? source code, open source dependencies, container images ????????? infrastructure as code ???????????????????????? shift-left security ?????????????????????????????????????????????????????????????????????????????? development ????????????????????????????????? production

Snyk ?????? 4 products ???????????? Snyk Code ??????????????????????????????????????????????????? source code (SAST), Snyk Open Source ??????????????????????????????????????????????????? dependencies (SCA), Snyk Container ??????????????????????????????????????????????????? Docker images, Snyk IaC ????????????????????? misconfigurations ?????? Terraform, Kubernetes, CloudFormation

Performance Tuning ?????????????????????????????? Snyk scan ????????????????????????????????????????????????????????? large codebases ??????????????? CI/CD pipeline ????????? developer experience ??????????????? ?????????????????????????????????????????????????????????????????????????????????????????????????????? Snyk scan ?????????????????? pipeline ?????????????????????????????????????????? security scanning

??????????????????????????????????????????????????? Snyk

Setup Snyk ?????????????????? development workflow

# === Snyk Installation & Setup ===

# 1. Install Snyk CLI
npm install -g snyk

# Or via standalone binary
curl -sL https://static.snyk.io/cli/latest/snyk-linux -o /usr/local/bin/snyk
chmod +x /usr/local/bin/snyk

# 2. Authenticate
snyk auth  # Opens browser for authentication

# Or use API token (CI/CD)
export SNYK_TOKEN="your-snyk-api-token"

# 3. Basic Scans
# Scan open source dependencies
snyk test

# Scan source code (SAST)
snyk code test

# Scan Docker image
snyk container test nginx:latest

# Scan IaC files
snyk iac test terraform/

# 4. Configuration File
cat > .snyk << 'EOF'
version: v1.5.0
ignore:
  SNYK-JS-LODASH-590103:
    - '*':
        reason: 'Low severity, no direct impact'
        expires: '2024-12-31T00:00:00.000Z'
        
patch:
  SNYK-JS-LODASH-567746:
    - lodash:
        patched: '2024-01-15T00:00:00.000Z'
EOF

# 5. IDE Integration
cat > .vscode/settings.json << 'EOF'
{
  "snyk.features.openSourceSecurity": true,
  "snyk.features.codeSecurity": true,
  "snyk.features.iacSecurity": true,
  "snyk.severity": {
    "critical": true,
    "high": true,
    "medium": true,
    "low": false
  },
  "snyk.scanOnSave": true
}
EOF

# 6. Pre-commit Hook
cat > .pre-commit-config.yaml << 'EOF'
repos:
  - repo: local
    hooks:
      - id: snyk-test
        name: Snyk Security Test
        entry: snyk test --severity-threshold=high
        language: system
        pass_filenames: false
        stages: [commit]
EOF

echo "Snyk setup complete"

Performance Tuning ?????????????????? Snyk Scan

??????????????????????????????????????? Snyk scan

#!/usr/bin/env python3
# snyk_performance.py ??? Snyk Performance Tuning Guide
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("snyk_perf")

class SnykPerformanceTuner:
    def __init__(self):
        self.optimizations = {}
    
    def scan_optimization_strategies(self):
        return {
            "parallel_scanning": {
                "description": "????????? scan ?????????????????????????????????????????????",
                "before": "snyk test && snyk code test && snyk container test",
                "after": """
# Run scans in parallel
snyk test &
snyk code test &
snyk container test myapp:latest &
wait
echo "All scans complete"
                """,
                "improvement": "2-3x faster",
            },
            "selective_scanning": {
                "description": "Scan ?????????????????????????????????????????????????????????",
                "commands": {
                    "changed_files_only": "git diff --name-only HEAD~1 | snyk code test --file=-",
                    "specific_path": "snyk code test --path=src/auth/",
                    "exclude_tests": "snyk code test --exclude=test/, spec/,__tests__/",
                },
                "improvement": "50-80% faster for incremental scans",
            },
            "severity_filtering": {
                "description": "Filter ??????????????? severity ????????????????????????",
                "commands": {
                    "high_only": "snyk test --severity-threshold=high",
                    "critical_only": "snyk test --severity-threshold=critical",
                },
                "improvement": "????????????????????? findings ?????? processing time",
            },
            "caching": {
                "description": "Cache scan results",
                "ci_cache": {
                    "github_actions": """
- uses: actions/cache@v4
  with:
    path: ~/.snyk
    key: snyk-}
                    """,
                },
                "improvement": "Skip unchanged dependencies",
            },
            "exclude_patterns": {
                "description": "Exclude ?????????????????????????????????????????? scan",
                "snykignore": """
# .snyk file exclusions
*.test.js
*.spec.ts
**/node_modules/**
**/dist/**
**/build/**
**/coverage/**
**/__mocks__/**
                """,
                "improvement": "30-50% faster by reducing scan scope",
            },
            "delta_scanning": {
                "description": "Scan ??????????????? diff ????????? main branch",
                "command": "snyk code test --org=myorg --target-reference=main",
                "improvement": "70-90% faster for PR checks",
            },
        }
    
    def benchmark_results(self):
        return {
            "project_size": "100,000 lines of code, 500 dependencies",
            "results": {
                "full_scan_no_optimization": {"time": "180 seconds", "findings": 45},
                "severity_high_only": {"time": "120 seconds", "findings": 12},
                "delta_scan_pr": {"time": "25 seconds", "findings": 3},
                "parallel_all_scans": {"time": "90 seconds", "findings": 45},
                "cached_incremental": {"time": "15 seconds", "findings": 2},
            },
        }

tuner = SnykPerformanceTuner()
strategies = tuner.scan_optimization_strategies()
print("Snyk Performance Optimizations:")
for name, info in strategies.items():
    print(f"  {name}: {info['improvement']}")

bench = tuner.benchmark_results()
print(f"\nBenchmarks ({bench['project_size']}):")
for scan_type, result in bench["results"].items():
    print(f"  {scan_type}: {result['time']} ({result['findings']} findings)")

CI/CD Integration ????????? Snyk

Integrate Snyk ????????????????????? CI/CD pipeline

# === Snyk CI/CD Integration ===

# 1. GitHub Actions ??? Optimized
cat > .github/workflows/security.yml << 'EOF'
name: Security Scan
on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

jobs:
  snyk-scan:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        scan: [code, deps, container]
      fail-fast: false  # Run all scans even if one fails
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Cache Snyk
        uses: actions/cache@v4
        with:
          path: |
            ~/.snyk
            node_modules
          key: snyk-}-}
      
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      
      - name: Install Dependencies
        run: npm ci --ignore-scripts
      
      - name: Snyk Code (SAST)
        if: matrix.scan == 'code'
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: }
        with:
          command: code test
          args: --severity-threshold=high --sarif-file-output=snyk-code.sarif
      
      - name: Snyk Dependencies (SCA)
        if: matrix.scan == 'deps'
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: }
        with:
          args: --severity-threshold=high --sarif-file-output=snyk-deps.sarif
      
      - name: Snyk Container
        if: matrix.scan == 'container'
        uses: snyk/actions/docker@master
        env:
          SNYK_TOKEN: }
        with:
          image: myapp:}
          args: --severity-threshold=high
      
      - name: Upload SARIF
        if: always()
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: snyk-}.sarif
EOF

# 2. GitLab CI
cat > .gitlab-ci-snyk.yml << 'EOF'
snyk-security:
  stage: test
  image: snyk/snyk:node
  variables:
    SNYK_TOKEN: $SNYK_TOKEN
  script:
    - snyk test --severity-threshold=high --json > snyk-report.json || true
    - snyk code test --severity-threshold=high || true
  artifacts:
    reports:
      sast: snyk-report.json
  rules:
    - if: $CI_MERGE_REQUEST_IID
    - if: $CI_COMMIT_BRANCH == "main"
EOF

echo "CI/CD integration configured"

Custom Security Policies

??????????????? security policies ????????????????????????????????????

#!/usr/bin/env python3
# security_policies.py ??? Custom Snyk Security Policies
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("policies")

class SecurityPolicyManager:
    def __init__(self):
        self.policies = {}
    
    def define_policies(self):
        return {
            "vulnerability_thresholds": {
                "block_pipeline": {
                    "critical": 0,
                    "high": 0,
                    "medium": 10,
                    "low": "unlimited",
                },
                "description": "Block deployment ??????????????? critical/high vulnerabilities",
            },
            "sla_targets": {
                "critical": {"fix_within": "24 hours", "escalate_after": "4 hours"},
                "high": {"fix_within": "7 days", "escalate_after": "3 days"},
                "medium": {"fix_within": "30 days", "escalate_after": "14 days"},
                "low": {"fix_within": "90 days", "escalate_after": "60 days"},
            },
            "auto_fix": {
                "enabled": True,
                "auto_pr": True,
                "description": "Snyk ??????????????? PR ????????????????????????????????????????????? dependency updates",
                "config": {
                    "upgrade_policy": "major",
                    "patch_policy": "always",
                    "pr_limit": 5,
                },
            },
            "license_policy": {
                "allowed": ["MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC"],
                "restricted": ["GPL-2.0", "GPL-3.0", "AGPL-3.0"],
                "action_on_restricted": "block_and_notify",
            },
            "container_policy": {
                "base_images": {
                    "allowed": ["alpine", "distroless", "ubuntu-minimal"],
                    "blocked": ["latest tag", "root user"],
                },
                "max_age_days": 30,
                "max_critical": 0,
                "max_high": 5,
            },
        }
    
    def compliance_report(self):
        return {
            "scan_coverage": {
                "repos_scanned": 45,
                "repos_total": 50,
                "coverage_pct": 90.0,
                "unscanned_repos": ["legacy-app-1", "internal-tool-2"],
            },
            "vulnerability_summary": {
                "critical": 2,
                "high": 15,
                "medium": 45,
                "low": 120,
                "total": 182,
                "fixed_this_month": 35,
                "new_this_month": 12,
                "avg_fix_time_days": 5.2,
            },
            "sla_compliance": {
                "critical": {"target": "24h", "actual": "18h", "met": True},
                "high": {"target": "7d", "actual": "5.2d", "met": True},
                "medium": {"target": "30d", "actual": "22d", "met": True},
            },
        }

manager = SecurityPolicyManager()
policies = manager.define_policies()
print("Security Policies:")
print(f"  Block thresholds: Critical={policies['vulnerability_thresholds']['block_pipeline']['critical']}, High={policies['vulnerability_thresholds']['block_pipeline']['high']}")
print(f"  Auto-fix: {policies['auto_fix']['enabled']}")
print(f"  License: {len(policies['license_policy']['allowed'])} allowed, {len(policies['license_policy']['restricted'])} restricted")

report = manager.compliance_report()
print(f"\nCompliance: {report['scan_coverage']['coverage_pct']}% repos scanned")
print(f"Vulnerabilities: {report['vulnerability_summary']['total']} total, {report['vulnerability_summary']['fixed_this_month']} fixed this month")

Monitoring ????????? Reporting

?????????????????? security posture

#!/usr/bin/env python3
# snyk_monitoring.py ??? Snyk Monitoring Dashboard
import json
import logging
from typing import Dict

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("monitor")

class SnykDashboard:
    def __init__(self):
        self.data = {}
    
    def dashboard(self):
        return {
            "overview": {
                "projects_monitored": 50,
                "total_vulnerabilities": 182,
                "critical_open": 2,
                "high_open": 15,
                "auto_fix_prs": 8,
                "scan_frequency": "Every push + Daily full scan",
            },
            "performance_metrics": {
                "avg_scan_time_code": "25 seconds",
                "avg_scan_time_deps": "15 seconds",
                "avg_scan_time_container": "45 seconds",
                "pipeline_overhead": "< 2 minutes (parallel)",
                "cache_hit_rate": "78%",
            },
            "trends_30d": {
                "new_vulnerabilities": 12,
                "fixed_vulnerabilities": 35,
                "trend": "improving (net -23)",
                "mttr_critical": "18 hours",
                "mttr_high": "5.2 days",
            },
            "top_issues": [
                {"vuln": "SNYK-JS-EXPRESS-6474509", "severity": "high", "projects": 8, "fix": "Upgrade express to 4.19.2"},
                {"vuln": "SNYK-PYTHON-REQUESTS-6928761", "severity": "high", "projects": 5, "fix": "Upgrade requests to 2.32.0"},
                {"vuln": "CVE-2024-21626", "severity": "critical", "projects": 2, "fix": "Upgrade runc in container base image"},
            ],
        }

dashboard = SnykDashboard()
data = dashboard.dashboard()
print(f"Projects: {data['overview']['projects_monitored']}")
print(f"Critical: {data['overview']['critical_open']}, High: {data['overview']['high_open']}")
print(f"Scan time: Code {data['performance_metrics']['avg_scan_time_code']}, Deps {data['performance_metrics']['avg_scan_time_deps']}")
print(f"Trend: {data['trends_30d']['trend']}")
print(f"\nTop Issues:")
for issue in data["top_issues"]:
    print(f"  [{issue['severity']}] {issue['vuln']}: {issue['fix']}")

FAQ ??????????????????????????????????????????

Q: Snyk ????????? SonarQube ???????????????????????????????????????????

A: Snyk ???????????? security ???????????????????????? ???????????? vulnerabilities ?????? code, dependencies, containers, IaC ?????? vulnerability database ??????????????????????????????????????? ?????? auto-fix PR Developer-friendly ????????????????????? SonarQube ???????????? code quality ??????????????????????????? ???????????? bugs, code smells, security hotspots, technical debt, coverage ?????? community edition ????????? ??????????????? code review ????????????????????????????????????????????? Snyk ?????????????????? security, SonarQube ?????????????????? code quality ???????????????????????????????????????????????? ?????????????????? security ??????????????? Snyk ?????????????????? overall quality ??????????????? SonarQube

Q: Snyk scan ?????????????????? ????????????????????????????

A: ??????????????????????????????????????????????????? ????????? delta scanning scan ??????????????? diff ????????? main (???????????????????????? 70-90%), ????????? scans ????????? parallel (code, deps, container ????????????????????????), Cache dependencies ?????? CI ????????????????????????????????????????????????????????????????????????, Exclude ???????????????????????????????????????????????? (tests, build, node_modules), ????????? severity-threshold=high skip findings ????????????????????????, ????????? Snyk CLI --all-projects ?????????????????? monorepo (scan ??????????????????????????????), ????????? Snyk API ????????? CLI ?????????????????? automation (????????????????????????) ???????????????????????? project 100K LOC ????????? 180 ?????????????????? ????????????????????? 15-25 ?????????????????? ???????????? delta scan + cache

Q: Snyk Free Plan ??????????????????????????????????????????????

A: Snyk Free Plan ????????? 200 open source tests/???????????????, 100 container tests/???????????????, 300 IaC tests/???????????????, Snyk Code (SAST) limited, 1 user ??????????????????????????????????????? developer ????????????????????? ???????????? open source project ??????????????? Team Plan ($25/user/???????????????) ??????????????? unlimited tests, team collaboration, Jira integration, priority support Business Plan ????????????????????? enterprise ??????????????? custom policies, SSO, compliance reports ?????????????????????????????????????????? Free Plan ????????????????????? ?????????????????????????????? 3+ ?????? ????????? upgrade ???????????? Team

Q: SAST ????????? SCA ???????????????????????????????????????????

A: SAST (Static Application Security Testing) ??????????????????????????? source code ?????????????????????????????????????????? ?????????????????? SQL injection, XSS, hardcoded secrets, insecure crypto ?????? Snyk ????????? "Snyk Code" SCA (Software Composition Analysis) ??????????????????????????? open source dependencies (libraries, packages) ?????????????????? known vulnerabilities (CVEs) ?????? dependencies ?????? Snyk ????????? "Snyk Open Source" ?????????????????????????????????????????? SAST ???????????? code ?????????????????????????????????, SCA ???????????? code ?????????????????? import ??????????????? 80%+ ????????? code ?????????????????????????????????????????????????????? open source ????????????????????? SCA ????????????????????????

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

Qwik Resumability Performance Tuning เพิ่มความเร็วอ่านบทความ → Tailwind CSS v4 Performance Tuning เพิ่มความเร็วอ่านบทความ → GCP BigQuery ML Performance Tuning เพิ่มความเร็วอ่านบทความ → Cloudflare D1 Low Code No Codeอ่านบทความ → DALL-E API Performance Tuning เพิ่มความเร็วอ่านบทความ →

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