# Netflix Jenkins Pipeline

Here's a detailed **stage-by-stage breakdown** of your Jenkins pipeline, explaining **why** each stage is used in **real-world DevSecOps pipelines** and how it helps with **security, quality, and automation**.

---

This is the root of a **Declarative Jenkinsfile**. It defines all the **stages, environment variables, post-actions**, etc.

---

```bash
pipeline {
    agent any

    environment {
        SCANNER_HOME = tool 'sonar-scanner'
    }
```

### ✅ Stage: **Clean Workspace**

```bash
stage('Clean Workspace') {
    steps {
        cleanWs()
    }
}
```

#### 🔹 Purpose:

* Ensures a **clean working directory** before starting the build.
    
* Removes leftover files from previous runs.
    

#### 🛡️ Real-World Security/Quality Reason:

* Prevents **cache poisoning**, file conflict issues, or using old binaries.
    
* Ensures the pipeline is **idempotent** (same input = same output).
    

---

### ✅ Stage: **Git Checkout**

```bash
stage('Git Checkout') {
    steps {
        git branch: 'main', 
        url: 'https://github.com/AungAung-Drlinuxer/nextflix.git'
    }
}
```

#### 🔹 Purpose:

* Fetches the source code from GitHub (`main` branch).
    

#### 🛡️ Real-World Usage:

* In real projects, you **automate CI/CD** based on commits to Git (push or PR triggers).
    
* Always use **verified repositories** and **SSH or tokens** instead of open HTTPS for production.
    

---

### ✅ Stage: **SonarQube Analysis**

```bash
stage('SonarQube Analysis') {
    steps {
        withSonarQubeEnv('sonar-server') {
            sh '''$SCANNER_HOME/bin/sonar-scanner \
                -Dsonar.projectName=Netflix \
                -Dsonar.projectKey=Netflix'''
        }
    }
}
```

We have used the SonarQube static code analysis process on our source code repository. It automatically scans the code to find issues related to quality, security, and maintainability. Nowadays, SonarQube is widely used in DevOps pipelines to ensure code quality before merging or deploying.

Scanning the source code for bugs, code smells, duplications, security hotspots, and OWASP Top 10 issues.

### 🔍 **1\. Bugs**

These are **potential errors in the code** that could cause the application to behave incorrectly or even crash.

* ❗ Example: Null pointer dereference, logic errors, unreachable code.
    
* ✅ Goal: Prevent runtime failures and incorrect application behavior.
    
* 🧠 SonarQube uses rules to detect patterns that indicate incorrect logic or operations.
    

---

### 💨 **2\. Code Smells**

Code smells are **indicators of poor design or coding practices** that make the code harder to understand or maintain.

* ❗ Example: Long methods, duplicated logic, unused variables, magic numbers, deeply nested code.
    
* ✅ Goal: Improve **readability, maintainability**, and reduce **technical debt**.
    
* 🧠 Code smells usually won’t break your code but will make it harder to modify or scale.
    

---

### 📄 **3\. Duplications**

SonarQube identifies **duplicated blocks of code** across files and modules.

* ❗ Example: Copy-pasted logic in different files or functions.
    
* ✅ Goal: Encourage **DRY (Don’t Repeat Yourself)** principle and easier maintenance.
    
* 🔁 Helps in reducing bugs caused by updating one copy but missing others.
    

---

### 🔐 **4\. Security Hotspots**

These are **sensitive parts of the code** that require **manual review** to ensure they are secure.

* ❗ Example: Custom authentication mechanisms, use of eval(), insecure deserialization.
    
* ✅ Goal: Alert developers to places where a **security vulnerability might exist**.
    
* 🛡️ Not always a vulnerability, but **a place where misuse could lead to security issues**.
    

---

### 🛑 **5\. OWASP Top 10 Issues in Source**

SonarQube can detect code that might be vulnerable to issues listed in the **OWASP Top 10** — the most critical web application security risks.

Examples from OWASP Top 10 include:

* A01: Broken Access Control
    
* A02: Cryptographic Failures
    
* A03: Injection (e.g., SQL, OS, LDAP)
    
* A05: Security Misconfiguration
    
* A07: Identification and Authentication Failures
    

SonarQube rules map to these risks and try to flag:

* Unsafe use of user inputs
    
* Improper validation
    
* Misconfigurations in security headers or auth flows
    
* Use of outdated or insecure libraries
    

### 🛠️ How It Works Technically:

1. **Scanner runs** on our codebase (locally or in CI/CD).
    
2. Source code is **parsed and tokenized**.
    
3. Static analysis engines apply rules from **quality profiles**.
    
4. Results are pushed to the SonarQube server (or SonarCloud).
    
5. Developers get a **dashboard** view with metrics, hotspots, and suggestions.
    

---

### ✅ Stage: **Quality Gate**

```bash
stage('Quality Gate') {
    steps {
        script {
            waitForQualityGate abortPipeline: false, credentialsId: 'SonarQube-Token'
        }
    }
}
```

#### A **Quality Gate** in SonarQube is a set of **conditions or thresholds** that your code must meet to be considered **"healthy" or acceptable**.

Think of it like a **checkpoint** or **go/no-go decision** in your CI/CD pipeline. If your code passes the gate, it's good to proceed (merge, deploy, etc). If it fails, the build/pipeline should stop — just like a red traffic light.

---

### 🔧 **What it does (in CI/CD):**

> 💬 *"Waits for SonarQube’s Quality Gate result. Can pass or fail the build based on predefined rules."*

This means that after SonarQube scans the code:

* It **calculates metrics** (bugs, code smells, coverage, vulnerabilities, etc.).
    
* It **evaluates those metrics** against the rules you set in the **Quality Gate**.
    
* The pipeline **waits** for that evaluation result.
    
* The build **passes or fails** depending on whether the gate is passed or failed.
    

---

### ✅ Stage: **OWASP Dependency Check**

```bash
stage('OWASP Dependency Check') {
    steps {
        dependencyCheck additionalArguments: '--scan ./ --disableYarnAudit --disableNodeAudit', odcInstallation: 'DP-Check'
        dependencyCheckPublisher pattern: '**/dependency-check-report.xml'
    }
}
```

OWASP Dependency-Check is an open-source software composition analysis (SCA) tool that scans your project’s third-party dependencies (like libraries from npm, Maven, pip, etc.) for known security vulnerabilities — specifically, CVEs (Common Vulnerabilities and Exposures).

It's part of the OWASP Project, aiming to help developers and DevOps teams identify risky libraries early.

---

### 💬 Explanation of this line:

> **"Scans project dependencies (e.g., npm, pip, Maven) for known CVEs (Common Vulnerabilities and Exposures)."**

This means:

* It **analyzes your dependency list** (from `package.json`, `requirements.txt`, `pom.xml`, etc.).
    
* Then it **checks those libraries against public vulnerability databases** like:
    
    * NVD (National Vulnerability Da[tabase)](https://nvd.nist.gov/)
        
    * GitHub Advisory Database
        
    * OSS Index (optional integrations)
        
* If a dependency has a known CVE, it **flags it**, showing:
    
    * CVE ID (like CVE-2023-12345)
        
    * Severity (CVSS score)
        
    * Affected version
        
    * Fix recommendation (if available)
        

---

### 📦 Supported Package [Managers:](https://nvd.nist.gov/)

OWASP Dependency-Check supports many ecosystems, including:

| Ecosystem | Example Files |
| --- | --- |
| **Ja**[**va (Maven, Gradle)**](https://nvd.nist.gov/) | [`pom.xml`, `build.gradle`](https://nvd.nist.gov/) |
| [**JavaScript (npm)**](https://nvd.nist.gov/) | `package.json`, `package-lock.json` |
| **Python (pip)** | `requirements.txt`, [`setup.py`](http://setup.py) |
| [**.NET (NuGet)**](https://nvd.nist.gov/) | [`.csproj`, `.sln`](https://nvd.nist.gov/) |
| [**Ruby**](https://nvd.nist.gov/) | `Gemfile.lock` |
| **PHP (Composer)** | `composer.lock` |

---

### ✅ Stage: **Trivy File Scan**

```bash
stage('Trivy File Scan') {
    steps {
        script {
            try {
                sh "trivy fs . > trivyfs.txt"
            } catch(Exception e) {
                input(message: "Are you sure to proceed?", ok: "Proceed")
            }
        }
    }
}
```

#### Absolutely! Let's break it down 👇

---

## 🔍 **What is Trivy File Scan?**

**Trivy** (by Aqua Security) is an open-source **security scanner**. One of its features is **file system scanning**, also known as **Trivy File Scan**, where it scans a directory or a file on your system for **secrets**, **vulnerabilities**, and **misconfigurations** — without needing to run a container.

---

### 💬 Explaining This Line:

> **"Performs file system scanning for secrets, vulnerabilities, misconfigs, etc."**

That means Trivy will:

### ✅ **1\. Detect Secrets**

* Scans files (like `.env`, config files, code) for hardcoded secrets such as:
    
    * AWS keys
        
    * API tokens
        
    * Private keys
        
    * Passwords
        
* Example:
    
    ```bash
    AWS_SECRET_ACCESS_KEY=abcd1234...
    ```
    

---

### ✅ **2\. Detect Vulnerabilities**

* Scans for known **vulnerable OS packages or libraries** in the scanned directory.
    
* For example, if it finds an old version of `openssl`, it will check for CVEs (like CVE-2023-0286).
    
* Useful when scanning unpacked Docker images or a directory with dependencies.
    

---

### ✅ **3\. Detect Misconfigurations**

* Scans IaC (Infrastructure-as-Code) files:
    
    * Dockerfiles
        
    * Kubernetes YAML
        
    * Terraform (`.tf`)
        
    * Helm charts
        
* Example findings:
    
    * `containers running as root`
        
    * `no resource limits set`
        
    * `insecure file permissions`
        

---

### 🧪 **How to Use Trivy File Scan**

Simple CLI command:

```bash
trivy fs ./my-app
```

That tells Trivy to scan everything under the `my-app` directory.

---

### 📂 Example Output:

```txt
Secrets:
  [AWS Secret] found in config/.env

Misconfigurations:
  [HIGH] Dockerfile - Container runs as root

Vulnerabilities:
  [CVE-2023-4567] openssl-1.0.2 (HIGH)
```

---

### 🧠 Use Cases:

* ✅ Local development: check for secrets or misconfigs before committing.
    
* ✅ CI/CD pipelines: block insecure code from being deployed.
    
* ✅ Security audits: scan codebases or extracted Docker images.
    
* ✅ SAST + IaC scanning in one tool.
    

---

### 📌 Summary Table

| Scan Type | What It Checks |
| --- | --- |
| 🔐 Secrets | Hardcoded secrets (AWS keys, tokens, passwords) |
| 🛡️ Vulnerabilities | OS packages & libs for known CVEs |
| ⚙️ Misconfigurations | IaC, Dockerfiles, K8s, Terraform issues |
| 📁 Scope | Any folder, file, or directory on your filesystem |

---

---

### ✅ Stage: **Docker Build Image**

```bash
stage('Docker Build Image') {
    steps {
        withCredentials([string(credentialsId: 'NETFLIX_API_KEY', variable: 'API_KEY')]) {
            sh "docker build --build-arg API_KEY=$API_KEY -t netflix ."
        }
    }
}
```

#### 🔹 Purpose:

* Builds the application Docker image using the Dockerfile.
    

#### 🛡️ Real-World Practice:

* You may **inject secrets securely** (e.g., via `Vault`, not hardcoded).
    
* Use **multi-stage builds** to reduce image size and **attack surface**.
    
* Ensure Dockerfile is **linted** and has no `latest` tags in `FROM`.
    

---

### ✅ Stage: **Trivy Image Scan**

```bash
stage('Trivy Image Scan') {
    steps {
        sh "trivy image netflix > trivyimage.txt"
        script {
            input(message: "Review Trivy Image scan. Proceed to Push?", ok: "Proceed")
        }
    }
}
```

#### 🔹 Purpose:

* Scans the built Docker image for known vulnerabilities.
    

#### 🛡️ DevSecOps Usage:

* **Container image scanning** is vital.
    
* Prevents publishing images with **critical CVEs** to public or private registries.
    

---

### ✅ Stage: **Docker Push**

```bash
stage('Docker Push') {
    steps {
        script {
            withDockerRegistry(credentialsId: 'docker') {
                sh "docker tag netflix aungaungmyomyint/netflix:latest"
                sh "docker push aungaungmyomyint/netflix:latest"
            }
        }
    }
}
```

#### 🔹 Purpose:

* Pushes Docker image to Docker Hub (or private registry).
    

#### 🛡️ Real-World Practice:

* Only **signed** and **scanned** images should be pushed.
    
* Ensure image registry access is restricted and uses **personal access tokens or service accounts**.
    

---

### ✅ Stage: **Docker Scout Analysis**

```bash
stage('Docker Scout Analysis') {
    steps {
        script {
            withDockerRegistry(credentialsId: 'docker', toolName: 'docker') {
                sh 'docker-scout quickview aungaungmyomyint/netflix:latest'
                sh 'docker-scout cves aungaungmyomyint/netflix:latest'
                sh 'docker-scout recommendations aungaungmyomyint/netflix:latest'
            }
        }
    }
}
```

#### Great! Let's break down what **Docker Scout Analysis** is, especially in the context of modern container and supply chain security 👇

---

## 🐳 What is **Docker Scout Analysis**?

**Docker Scout** is a **container image analysis tool** built by Docker. It helps you:

* Analyze your **Docker images**
    
* Identify **known CVEs (Common Vulnerabilities and Exposures)**
    
* Get **remediation suggestions**
    
* Understand **dependency chains**
    
* Improve your overall **supply chain security posture**
    

Think of it like an intelligent assistant that continuously evaluates your container images for **security**, **trust**, and **compliance**.

---

### 💬 Explanation of this line:

> **"Advanced container analysis: suggestions, CVE reports, and recommendations. Scout gives runtime CVE analysis and upgrade recommendations. Useful for supply chain security and zero-trust environments."**

Let's break it down:

---

### ✅ **1\. Advanced Container Analysis**

Docker Scout deeply analyzes your Docker image to:

* **Inspect all software layers** inside (OS packages, language libraries)
    
* Map out the **software bill of materials (SBOM)**
    
* Identify **outdated packages or vulnerable versions**
    

It’s more than just a CVE scanner — it gives **contextual insight** into what needs to be fixed and why.

---

### ✅ **2\. CVE Reports**

It generates **detailed CVE reports** for:

* OS-level packages (e.g., Alpine, Ubuntu, Debian)
    
* Application-level dependencies (e.g., pip, npm, Java, Go)
    

Each CVE entry includes:

* CVE ID (e.g., CVE-2024-12345)
    
* Severity (Low/Medium/High/Critical)
    
* Affected package & version
    
* Links to patches or CVE info
    

---

### ✅ **3\. Recommendations & Upgrade Guidance**

Scout doesn’t just say “you have a problem” — it also tells you:

* **What to upgrade**
    
* **Which base image to switch to** (e.g., `node:18` → `node:20`)
    
* If a **newer image with fewer vulnerabilities** is available
    

So you get **actionable insights**, not just alerts.

---

### ✅ **4\. Runtime CVE Analysis**

Docker Scout can **monitor running containers**, not just static images. This allows:

* Real-time CVE monitoring as containers run
    
* Early detection if a CVE affects a live service
    

---

### ✅ **5\. Supply Chain Security & Zero Trust**

Docker Scout aligns with **modern security models** like:

* 🔐 **Supply Chain Security**: You see every piece of software that went into building your image — reducing the risk of hidden dependencies or malicious packages.
    
* 🛡️ **Zero Trust**: No component is blindly trusted. Scout verifies image provenance, trust policies, and more.
    

---

### 🧠 Use Case Example

1. You build a Docker image.
    
2. Docker Scout scans it and shows:
    
    * 5 critical vulnerabilities
        
    * 2 medium-level misconfigurations
        
3. It suggests:
    
    * Use `python:3.12.2-slim` instead of `python:3.9`
        
    * Upgrade `openssl` to a secure version
        
4. You take action, rebuild, and re-scan — fewer/no CVEs 🎉
    

---

### 🚀 How to Use It

You can use it from:

* **Docker Desktop** (integrated UI)
    
* **Docker CLI**:
    
    ```bash
    docker scout quickview my-image:tag
    ```
    
* **CI/CD** (GitHub Actions, GitLab CI, etc.)
    

---

### 📌 Summary

| Feature | Description |
| --- | --- |
| CVE Detection | Identifies vulnerabilities in container images |
| Upgrade Suggestions | Recommends safer versions and base images |
| Runtime Insights | Monitors live containers for CVEs |
| SBOM Support | Tracks what software is in your image |
| Supply Chain Security | Verifies image origin and trust |
| CI/CD Integration | Automates security checks in pipelines |

---

### ✅ Stage: **Deploy to Container**

```bash
stage('Deploy to Container') {
    steps {
        sh 'docker run -d --name netflix -p 3000:3000 aungaungmyomyint/netflix:latest'
    }
}
```

#### 🔹 Purpose:

* Runs the container locally or on a test host.
    

#### 🛡️ DevOps Usage:

* Can be extended to **Kubernetes, ECS, or Helm deployments**.
    
* Add health checks, monitoring (Prometheus), and rollbacks here.
    

---

### ✅ `post { always { ... } }`

```bash
post {
    always {
        emailext( ... )
    }
}
```

#### 🔹 Purpose:

* Always sends a **build notification** email (pass or fail).
    
* Includes logs and scan reports (`trivyfs.txt`, `trivyimage.txt`).
    

#### 🛡️ Real-World Practice:

* Keeps teams aware of pipeline results.
    
* Logs can be parsed for **audit and compliance**.
    

---

### 💼 Summary You Can Say in Interview

> "I designed a secure and automated Jenkins CI/CD pipeline using SonarQube for static analysis, OWASP Dependency Check for vulnerable packages, and Trivy for both filesystem and container scanning. I enforced quality gates, performed Docker Scout analysis for runtime CVEs, and managed secure image builds and registry pushes. Every stage had a purpose — from ensuring clean workspaces, securing build artifacts, to deploying only verified containers. These practices are based on DevSecOps principles that shift security left and build trust into the delivery pipeline."

---
