TutorialsLast Updated Nov 16, 20266 min read

Adding application and image scans to your CI/CD pipeline

Angel Rivera

Developer Advocate, CircleCI

Security is a shared responsibility. DevSecOps integrates security into the software development lifecycle (SDLC) to detect and resolve vulnerabilities early. Traditional security checks at the end of the development cycle often result in delays, rework, and inefficiencies. Embedding security into CI/CD pipelines mitigates these issues by automating scans and alerts, ensuring vulnerabilities are addressed promptly.

Adding security to CI/CD with Snyk

Snyk helps developers identify and fix vulnerabilities in applications and containers. CircleCI integrates with Snyk via the Snyk Orb, enabling seamless security scanning within CI/CD.

Setting up the project

To demonstrate the DevSecOps practices, we will create a simple Python (Flask) project with basic functionality, write unit tests using pytest, and integrate security scanning with Snyk.

Prerequisites

Ensure you have:

  • CircleCI account
  • Snyk account. The free tier is sufficient for this tutorial.
  • Docker Hub account
  • Python 3.12 or 3.13 and pip installed on your local machine. The deliberately outdated Flask release used in the first part of this tutorial doesn’t run on Python 3.14 or later.

Creating the Flask project

Create a new directory and set up a basic Flask application:

mkdir circleci-flask-app && cd circleci-flask-app
python3.12 -m venv venv
source venv/bin/activate
pip install flask==0.12.4 Jinja2==2.11.3 MarkupSafe==2.0.1 itsdangerous==2.0.1 pytest

This initializes a new project, creates a virtual environment, and installs Flask along with other required dependencies. With Python 3.13, run python3.13 -m venv venv instead.

These versions are intentionally outdated and have known vulnerabilities, so Snyk has something to find later in the tutorial. MarkupSafe and itsdangerous are pinned because newer releases removed features these old versions of Flask and Jinja2 depend on.

Next, create app.py with a simple route:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Secure World!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

This is a minimal Flask application that serves a simple message when accessed via a browser.

Now create requirements.txt with the dependencies:

Flask==0.12.4
Jinja2==2.11.3
MarkupSafe==2.0.1
itsdangerous==2.0.1
pytest

This defines the dependencies required for the application to run.

Deploying the project to CircleCI (without security)

To automate the build process and streamline deployments, we will integrate our Flask application with CircleCI. This initial setup focuses on ensuring that our application builds successfully without introducing any security checks. Later, we will enhance the pipeline with security scanning to detect vulnerabilities.

Create .circleci/config.yml and paste the following in it:

version: 2.1
jobs:
  build:
    docker:
      - image: cimg/python:3.12
    steps:
      - checkout
      - run:
          name: Install Dependencies
          command: pip install --no-cache-dir -r requirements.txt
workflows:
  build_test_deploy:
    jobs:
      - build

At this stage, the pipeline will execute without running security checks, allowing the application to build successfully but leaving vulnerabilities undetected.

Commit and push your local changes to GitHub.

Next, log in to CircleCI and click Create project. Name the project and click Next. Keep the suggested pipeline name or enter a new one, and select the circleci-flask-app repository. If the repository isn’t listed, click Update access on GitHub to give the CircleCI GitHub App access to it, then refresh the list. Keep the All pushes trigger and click Next. On the Config step, CircleCI detects the .circleci/config.yml file we pushed. Click Next, review the setup, and click Go to project.

In the CircleCI Create a project wizard, the circleci-flask-app repository is selected with the All pushes trigger, and the Config step shows that CircleCI detected the config file.

For organizations that use the GitHub OAuth integration instead, go to Projects, click Set Up Project next to circleci-flask-app, select Fastest to use the existing config, and click Set Up Project. This triggers the first pipeline run.

In the Create project flow, the pipeline runs on the next push. Push a new commit to start the first run:

git commit --allow-empty -m "Trigger first CircleCI pipeline"
git push

The pipeline runs and builds successfully.

The CircleCI build job for circleci-flask-app shows Success, with the Spin up environment, Preparing environment variables, Checkout code, and Install Dependencies steps all passing.

Again, nothing much to check here as the pipeline is running without security checks. Before we add security scanning, let’s add a Snyk token to CircleCI as an environment variable. On the project’s page, open the Project menu and select Project settings. Go to Environment Variables and click Add. Enter SNYK_TOKEN as the name and a Snyk personal access token as the value, then click Add environment variable.

The CircleCI Add environment variable dialog in project settings, with SNYK_TOKEN entered in the Name field.

To create the token, open your Snyk account settings, go to Personal Access Tokens, enter a name, choose an Expiry, and click Generate new token. Copy the token right away, because Snyk shows it only once. Personal access tokens expire after 90 days at most, so generate a new one and update SNYK_TOKEN in CircleCI before it expires.

The Snyk Personal Access Tokens page in account settings, with a token name and an expiry date entered and the Generate new token button enabled.

Adding Snyk security scan

The Snyk Orb is a partner orb, which CircleCI classifies as uncertified. Organizations must opt in before their pipelines can use uncertified orbs, or the pipeline fails with an Orb snyk/snyk@2.3.0 not loaded error. In CircleCI, click Org in the sidebar, go to Security, and turn on Allow uncertified public orbs under Orb Security Settings. Only an organization admin can change this setting.

The CircleCI organization Security settings page with Allow uncertified public orbs turned on under Orb Security Settings.

Now modify the .circleci/config.yml file to include the Snyk Orb for security scanning:

version: 2.1
orbs:
  snyk: snyk/snyk@2.3.0
jobs:
  build_test:
    docker:
      - image: cimg/python:3.12
    steps:
      - checkout
      - run:
          name: Install Dependencies
          command: pip install --no-cache-dir -r requirements.txt
      - snyk/scan
workflows:
  build_test_deploy:
    jobs:
      - build_test

This introduces Snyk scanning to the pipeline. Since the project still uses outdated dependencies, the scan will fail. This is expected behavior as the goal is to identify and fix vulnerabilities. Push the changes to GitHub to trigger the pipeline.

The Run Snyk step fails in the build_test job, listing high-severity Werkzeug vulnerabilities introduced through flask 0.12.4 and a test summary with 17 open security issues.

Fixing vulnerabilities and adding unit tests

At this stage, we will update our dependencies and introduce unit tests to verify that our application behaves as expected. Updating dependencies ensures that we mitigate security risks, while unit tests provide a layer of validation.

Update the requirements.txt file to fix the vulnerabilities:

Flask
Jinja2
pytest

Now create test_app.py to verify the endpoint:

import pytest
from app import app

def test_home():
    client = app.test_client()
    response = client.get('/')
    assert response.status_code == 200
    assert response.data == b"Hello, Secure World!"

This test ensures that the home route is working correctly.

Modify .circleci/config.yml to re-run Snyk with updated dependencies and unit tests:

version: 2.1
orbs:
  snyk: snyk/snyk@2.3.0
jobs:
  build_test:
    docker:
      - image: cimg/python:3.12
    steps:
      - checkout
      - run:
          name: Install Fixed Dependencies
          command: pip install --no-cache-dir -r requirements.txt
      - snyk/scan
      - run:
          name: Run Unit Tests
          command: pytest
workflows:
  build_test_deploy:
    jobs:
      - build_test

This configuration now includes unit tests and ensures vulnerabilities are mitigated before deployment. Push the changes to GitHub to trigger the pipeline.

The Run Snyk step passes in the build_test job after Snyk tests 12 dependencies and finds 0 issues, followed by a passing Snyk monitor step.

Similarly, you can check the Snyk dashboard to confirm the vulnerabilities have been resolved.

The Snyk project page for the circleci-flask-app repository shows 0 issues and 12 dependencies.

Security enabled pipeline - the Snyk Docker image scan

After discussing Snyk’s application scanning capabilities, we now move on to Docker image scanning, which is seamlessly integrated into CI/CD pipelines. This step ensures that vulnerabilities within containerized applications are detected early, preventing insecure images from being deployed.

We will use the same Flask application and extend our pipeline by adding a Docker image build and scan step. If vulnerabilities are found, the image will not be pushed to Docker Hub, ensuring only secure images are deployed.

Create a Dockerfile in the root of the project:

FROM python:3.12
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir Flask==0.12.4 Jinja2==2.11.3 MarkupSafe==2.0.1 itsdangerous==2.0.1 pytest
EXPOSE 5000
CMD ["python", "app.py"]

Next, update the .circleci/config.yml file to include the Docker image build and scan job:

version: 2.1
orbs:
  snyk: snyk/snyk@2.3.0
jobs:
  build_test:
    docker:
      - image: cimg/python:3.12
    steps:
      - checkout
      - run:
          name: Install Fixed Dependencies
          command: pip install --no-cache-dir -r requirements.txt
      - snyk/scan
      - run:
          name: Run Unit Tests
          command: pytest
  build_push_image:
    docker:
      - image: cimg/python:3.12
    steps:
      - checkout
      - setup_remote_docker
      - run:
          name: Build Docker Image
          command: |
            docker build -t $DOCKERHUB_USERNAME/app:latest .
      - snyk/scan:
          docker-image-name: "$DOCKERHUB_USERNAME/app:latest"
          monitor-on-build: true
      - run:
          name: Push Docker Image
          command: |
            echo $DOCKERHUB_PASS | docker login -u $DOCKERHUB_USERNAME --password-stdin
            docker push $DOCKERHUB_USERNAME/app:latest
workflows:
  build_test_deploy:
    jobs:
      - build_test
      - build_push_image:
          requires:
            - build_test

Before you push the changes to GitHub, go back to CircleCI and add the following environment variables:

  • DOCKERHUB_USERNAME (Docker Hub username)
  • DOCKERHUB_PASS (a Docker Hub personal access token with Read & Write access, which the pipeline needs to push the image)

Now commit your changes and push to GitHub to trigger the pipeline.

As expected, the pipeline will fail. The Snyk Docker image scan detects known vulnerabilities in the base image’s operating system packages and in the outdated Python packages installed in the image, and fails the pipeline.

The Run Snyk step fails in the build_push_image job: Snyk reports high-severity Werkzeug vulnerabilities in the image and finds that 2 of the 3 projects it tested contain vulnerable paths.

We can fix the vulnerabilities by switching the Dockerfile to a slimmer base image with fewer vulnerable packages and installing current versions of the Python dependencies.

FROM python:3.12-alpine
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir Flask Jinja2 pytest
EXPOSE 5000
CMD ["python", "app.py"]

Once you push the changes to GitHub, the pipeline will run successfully and the Docker image will be pushed to the Docker Hub.

Conclusion

By integrating security scans into the CI/CD pipeline, teams can proactively identify vulnerabilities in both application dependencies and Docker images. Using the Snyk Orb simplifies security integration, ensuring your applications and infrastructure remain protected.

The complete code for this tutorial is available on GitHub.