Analyzing your code with AI, Part 2: CI/CD Integration

In short
  • Reminder: Oasis analyzes code using Ollama models, accelerated by GPU.
  • Creating the Kubernetes objects necessary for the scan.
  • Configuring a Jenkins pipeline triggered with each code submission to the Git repository.
  • Testing on an example and reviewing the generated reports.

Introduction

In the previous article, the Oasis tool (Ollama Automated Security Intelligence Scanner) was containerized and associated with the Ollama pod to enable scanning code for security vulnerabilities.

As a reminder, Oasis uses LLM models available on Ollama to automatically identify potential security issues within the application code provided in a folder.

The tool is operated using the oasis command with arguments to produce comprehensive reports on the code's security status. The AI-based analysis is accelerated by the use of a GPU available on the Kubernetes node where Ollama runs.

For more details, I invite you to read the previous article.

The goal now is to integrate this scan into an initial CI chain so that it automatically triggers code analysis when code is submitted to a Git repository.

To achieve this, we will build on what was discussed here, namely the possible interactions between GitLab and Jenkins.

I also invite you to review the dedicated article on the subject, as we will be starting from that point, assuming that the necessary prerequisites have been set up between Jenkins and Gitlab for proper communication.

Here is the target diagram again, detailing the elements to be implemented and the desired logic.

Diagram of the target

Click the image to enlarge.

Creating Kubernetes objects

The storage

First, you need to create a persistent volume (PV) and a PersistentVolumeClaim (PVC) so that the Jenkins agent can deposit the code retrieved from the Git repository in order to submit it to Oasis.

This volume must therefore point to the same location as the one mounted in the Oasis container within the Ollama pod, since it will need to be read by the latter.

If you are not comfortable with the concept of persistent storage in Kubernetes, feel free to check here and there.

As a reminder, we used an NFS share and also created a pv/pvc, but for the Ollama pod within the namespace dedicated to it.

We will reuse the same configuration and link it to the Jenkins namespace (except for the persistent volume, which does not have a namespace concept).

First, we define the pv in the file 01-pv-jenkins-pip-security-code-check.yml:

---
apiVersion: v1
kind: PersistentVolume
metadata:
  annotations:
    pv.kubernetes.io/provisioned-by: nfs.csi.k8s.io
  name: pv-jenkins-pip-security-code-check
  labels:
      environment: prd
      network: lan
      application: jenkins
      pipeline: security-code-check
spec:
  capacity:
    storage: 30Gi
  accessModes:
    - ReadWriteMany
  persistentVolumeReclaimPolicy: Retain
  csi:
    driver: nfs.csi.k8s.io
    volumeHandle: /Volume1/nfsshare/rubikub.coolcorp.priv/namespaces/prd-jenkins-lan/pipelines/security-code-check
    volumeAttributes:
      server: 192.168.10.152
      share: /Volume1/nfsshare/rubikub.coolcorp.priv/namespaces/prd-jenkins-lan/pipelines/security-code-check
    

We reference exactly the same NFS export as for Ollama/Oasis, which, in my example, is /Volume1/nfsshare/rubikub.coolcorp.priv/namespaces/prd-jenkins-lan/pipelines/security-code-check.

This corresponds to a space on my NAS.

Also, be careful about the permissions set on this volume. This depends on the storage solution used, but you need to consider the permissions set in the next step for defining the pod associated with the Jenkins agent.

For example, in my case, I use a group called "rubikube" with a group ID of 2 on my NAS. My pod associated with the Jenkins agent must take this into account. We will come back to this point later.

Permissions on the NFS volume

Click the image to enlarge.

ID of the group on the NAS

Click the image to enlarge.

In the Namespace prd-jenkins-lan, which corresponds to the Namespace where I deployed Jenkins, we define the pvc via the file 02-pvc-jenkins-pip-security-code-check.yml.

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-jenkins-pip-security-code-check
  namespace: prd-jenkins-lan
  labels:
      environment: prd
      network: lan
      application: jenkins
      pipeline: security-code-check
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 30Gi
  volumeName: pv-jenkins-pip-security-code-check
  storageClassName: ""
    

This pvc points directly to the previous pv.

We apply both objects with the command kubectl apply -f nom_du_fichier.yml

The secret

Retrieving SSH connection components

For the Jenkins agent to retrieve the code from the Git repository, it will need to present a known SSH key associated with an account that has the necessary permissions on the repository.

Therefore, we generate a private/public key pair (using puttygen), and then we add the obtained public key to the settings of the GitLab account we want to use.

Retrieval of reports

Click the image to enlarge.

In the article about the interaction between Jenkins and GitLab, we created a service account svc-jenkins-togitlab in the Active Directory directory for this type of need. Therefore, we will add the public key to the settings of this account in GitLab.

Connection to GitLab with the service account

Click the image to enlarge.

Adding the key to the service account in GitLab

Click the image to enlarge.

Adding the key to the service account in GitLab

Click the image to enlarge.

For the private key, we will keep it aside for later. For now, it is necessary to retrieve the public key presented on the GitLab interface. The Jenkins agent must trust GitLab, and the certificate presented by GitLab must be known to the Jenkins agent.

Preserving the private key

Click the image to enlarge.

GitLab was also deployed under Kubernetes as detailed here.

Its "gitlab shell" component, which is responsible for listening for Git instructions via SSH, is exposed within the cluster through the Service gitlab-gitlab-shell in the Namespace prd-gitlab-lan.

Service responsible for redirecting SSH traffic

Click the image to enlarge.

To ensure we have the correct SSH signature, we can start a temporary pod with a basic container that executes the ssh-keyscan command to retrieve the host's fingerprint into a file named known_hosts.

We launch an alpine Pod, which is a Pod that runs the base image of the lightweight Alpine operating system, to connect to it immediately in interactive mode: kubectl run -it sshscan --rm --restart=Never --image=alpine -- sh

From there, we install ssh-keyscan.

apk add openssh

Then, we capture the desired fingerprint.

ssh-keyscan -H gitlab-gitlab-shell.prd-gitlab-lan.svc.cluster.local > known_hosts
Retrieval of the SSH fingerprint from GitLab

Click the image to enlarge.

Note the syntax gitlab-gitlab-shell.prd-gitlab-lan.svc.cluster.local to reach the "gitlab shell".

Indeed, the service associated with it is in the namespace prd-gitlab-lan, and our temporary pod is in the default namespace. Therefore, I need to use the full DNS name of the service to move between namespaces.

Once the file is retrieved, we can read its contents to save it and use it later.

Creating the secret

In fact, we are now going to create the secret sec-jenkinstogitlab-ssh, which will contain both:

  • The private key saved previously and corresponding to the service account, svc-jenkins-togitlab, which we will associate with the id_rsa parameter of the secret
  • The contents of the known_hosts file, retrieved just now, in the parameter of the same name at the secret level.

That is, the following command:

kubectl create secret generic sec-jenkinstogitlab-ssh --from-file=id_rsa=X:\gitlab\gitlab.coolcorp.priv\sa-jenkins-agent --from-file=known_hosts=X:\gitlab\gitlab.coolcorp.priv\known_hosts -n prd-jenkins-lan

(Here, I have placed the private key and the known_hosts file on my client machine in X:\gitlab\gitlab.coolcorp.priv).

Configuring Jenkins

We now have everything we need to tackle Jenkins.

To fully understand what follows, you need a basic understanding of it. Feel free to read my article on its installation under Kubernetes; this may already help you feel more comfortable.

The parameters

First, we will use parameters in our pipeline, specifically hidden parameters, to avoid hardcoding too many elements in our pipeline's code that we might need to change later.

You must ensure that you have the associated plugin installed. To do this, go to the administration of Jenkins, then plugins, and make sure to install Hidden Parameter.

Installation of the Jenkins Hidden Parameter plugin

Click the image to enlarge.

We can now create the pipeline. In my case, I name it security-code-check.

We give it a brief description, and then we check the box This build has parameters.

We create a hidden parameter for each variable that we want to use in our pipeline.

Creation of the pipeline

Click the image to enlarge.

To start, the following parameters:

Name Value Role
NFS_CLONE_PATH /nfs/repo Path within the Jenkins agent container where the code should be copied (corresponds to the persistent volume pointing to the NFS share).
POD_NAMESPACE prd-mygptgpu-lan Namespace in which the pod containing the Oasis application is running
CONTAINER_NAME oasis Name of the Oasis container within the Ollama pod
GITLAB_REPO [email protected]:apps/demo-check-code.git URL of the repository containing the code to be copied for analysis. Since Jenkins runs on the same Kubernetes cluster as GitLab, we can use internal services
OASIS_ARGS -sm gemma3:4b -m llama3:8b --clear-cache-scan --vulns all Argument that will be passed to Oasis within the container (an argument that we previously passed manually in the first article).
JENKINS_AGENT_IMAGE registry.gitlab.com/apps.coolcorp.priv/jenkins-custom:agent-2.492.2-lts-v2 Image of the Jenkins agent to be executed (see article on installing Jenkins under Kubernetes).
SSH_SECRET_NAME sec-jenkinstogitlab-ssh Name of the secret containing the private key to be used to connect to GitLab and the SSH fingerprint of the GitLab host. This is the secret created previously.
PVC_NAME pvc-jenkins-pip-security-code-check Name of the PVC to be used for the Jenkins agent. This is the PVC created at the beginning of the article, which allows us to point to the persistent volume that itself points to the NFS export shared by the Jenkins agent and Oasis
PV_NAME pv-jenkins-pip-security-code-check Name of the PV to be used for the Jenkins agent. This is only to use its name as a volume name in the agent's pod

These parameters and their values are examples adapted to my article. Of course, they can evolve depending on your usage and your own deployment.

Each of them must be entered as a Hidden Parameter

Creation of a parameter for the pipeline

Click the image to enlarge.

All parameters for the pipeline

Click the image to enlarge.

We can now write the pipeline code.

The pipeline

As I explained in my article about the possible interactions between GitLab and Jenkins, I use retrieving the jenkinsfile directly from a Git repository.

This simplifies writing and sharing the code because Jenkins can automatically retrieve the latest version of the pipeline during execution.

Feel free to review the associated tutorial to fully understand this point.

Here is the content of the Jenkins file security-code-check.jenkinsfile:


pipeline {

    agent none

    environment {
        CLONE_PATH          = "${env.NFS_CLONE_PATH}"
        POD_NAMESPACE       = "${env.POD_NAMESPACE}"
        CONTAINER_NAME      = "${env.CONTAINER_NAME}"
        GITLAB_REPO         = "${env.GITLAB_REPO}"
        OASIS_ARGS          = "${env.OASIS_ARGS}"
        JENKINS_AGENT_IMAGE = "${env.JENKINS_AGENT_IMAGE}"
        SSH_SECRET_NAME     = "${env.SSH_SECRET_NAME}"
        PVC_NAME            = "${env.PVC_NAME}"
        PV_NAME             = "${env.PV_NAME}"
     
    }

    stages {
        stage('Run with dynamic pod') {
            steps {
                script {
                    def podYaml = """
apiVersion: v1
kind: Pod
metadata:
  namespace: prd-jenkins-lan
  labels:
    purpose: pip-security-code-check
spec:
  serviceAccountName: sa-jenkins-agent
  securityContext:
    fsGroup: 4
  containers:
  - name: jnlp
    image: ${JENKINS_AGENT_IMAGE}
    securityContext:
      runAsUser: 2
    resources:
      limits:
        memory: "512Mi"
        cpu: "500m"
    volumeMounts:
    - name: ${PV_NAME}
      mountPath: /nfs
    - name: ssh-key-volume
      mountPath: /bin/.ssh/
      readOnly: true
  imagePullSecrets:
    - name: sec-jenkins-registry
  volumes:
  - name: ssh-key-volume
    secret:
      secretName: ${SSH_SECRET_NAME}
      defaultMode: 0400
  - name: ${PV_NAME}
    persistentVolumeClaim:
      claimName: ${PVC_NAME}
"""

                    podTemplate(yaml: podYaml, serviceAccount: "sa-jenkins-agent") {
                        node(POD_LABEL) {

                            stage('Clone repo into NFS') {
                                sh "rm -rf ${CLONE_PATH} && mkdir -p ${CLONE_PATH}"
                                sh '''
                                    ssh -vT [email protected] || echo "SSH FAILED"
                                '''
                                git branch: 'main',
                                    url: "${GITLAB_REPO}",
                                    changelog: false,
                                    poll: false
                                sh "cp -r . ${CLONE_PATH}/"
                            }

                            stage('Find oasis pod') {
                                script {
                                    def podName = sh(
                                        script: """
                                        kubectl get pods -n ${POD_NAMESPACE} --field-selector=status.phase=Running \\
                                          -o custom-columns=NAME:.metadata.name --no-headers \\
                                          | grep '^deploy-ollama-default-' | head -n 1
                                        """,
                                        returnStdout: true
                                    ).trim()

                                    if (!podName) {
                                        error "Pod 'deploy-ollama-default-*' en statut Running introuvable."
                                    }

                                    env.OASIS_POD = podName
                                }
                            }

                            stage('Run analysis in oasis container') {
                                script {
                                    def cmd = "oasis -i ${CLONE_PATH} ${OASIS_ARGS}"
                                    sh "kubectl exec -n ${POD_NAMESPACE} ${env.OASIS_POD} -c ${CONTAINER_NAME} -- ${cmd}"
                                }
                            }

                        }
                    }
                }
            }
        }
    }
}
    

At the beginning of this file, we retrieve the values of the various parameters that we previously specified as hidden parameters.

Then, using some of these parameters, we construct the code for the Pod that will be executed to launch the Jenkins agent. This agent is responsible for carrying out the various instructions.

These instructions will be as follows:

  1. The agent clones the source code from the repository specified in the parameters. The code is copied to the NFS volume attached to the persistent volume (PV)
  2. The agent identifies the Oasis pod by querying the cluster using the name of the associated Deployment
  3. The agent connects to the container context within the identified pod and executes the scan command as indicated by the hidden parameter OASIS_ARGS.

Please note that, for the pod definition, I refer to the securityContext: runAsUser: 2 option

This corresponds to the ID of my user associated with my NFS volume, as I mentioned previously. This allows the Pod to operate with the correct permissions and to be able to write to the NFS volume on my NAS, which is used as the target for the PV.

I place my file in the Git repository reserved for my Jenkins files and I identify it in the Jenkins user interface.

Automatic retrieval of the code for the pipeline

Click the image to enlarge.

Regarding the automatic execution of the pipeline via a push operation of the source code to GitLab, I will simply repeat what I have already said in my article about the relationship between Jenkins and GitLab.

You only need to set up a webhook: I invite you to read the associated tutorial if needed.

Now, it's time to test.

Testing and example

For this example, we will use some fictitious code associated with a Flask application, which is the same framework used for my website.

It contains a typical Flask structure with Python and HTML. Thanks to AI, I requested code that intentionally contained security vulnerabilities.

Here is the content of the app.py file:

from flask import Flask, request, render_template_string, redirect, session, make_response
import sqlite3
import os
import config  # ← import de secrets en dur

app = Flask(__name__)
app.secret_key = config.SECRET_KEY  # ❌ Clé secrète non sécurisée

# ❌ Pas d'authentification DB
def get_db():
    return sqlite3.connect("users.db")

# ❌ Création non protégée
@app.route("/init")
def init():
    db = get_db()
    db.execute("CREATE TABLE IF NOT EXISTS users (username TEXT, password TEXT)")
    db.execute("INSERT INTO users VALUES ('admin', 'admin')")
    db.commit()
    return "Database initialized"

# ❌ Login vulnérable à l'injection SQL
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        user = request.form["username"]
        pw = request.form["password"]
        db = get_db()
        # 🔥 SQL injection possible
        query = f"SELECT * FROM users WHERE username='{user}' AND password='{pw}'"
        result = db.execute(query).fetchone()
        if result:
            session["user"] = user
            return redirect("/dashboard")
        else:
            return "Invalid credentials", 403
    return render_template_string(open("templates/login.html").read())

# ❌ XSS via GET param
@app.route("/dashboard")
def dashboard():
    user = session.get("user", "guest")
    msg = request.args.get("msg", "")
   

# ❌ Téléchargement de fichiers sans contrôle (path traversal possible)
@app.route("/download")
def download():
    filename = request.args.get("file")
    try:
        with open(f"files/{filename}", "rb") as f:
            response = make_response(f.read())
            response.headers["Content-Disposition"] = f"attachment; filename={filename}"
            return response
    except FileNotFoundError:
        return "File not found", 404

# ❌ Exposition de l'API avec une clé codée en dur
@app.route("/api/data")
def api():
    key = request.args.get("key")
    if key != config.API_KEY:
        return "Forbidden", 403
    return {"secret_data": "This is internal"}

if __name__ == "__main__":
    app.run(debug=True)
    

We push the code to the repository (the demo app's repository).

A few seconds later, thanks to the Jenkins webhook called by GitLab, the Jenkins pipeline is triggered.

Triggering the pipeline

Click the image to enlarge.

You can follow its progress in the Jenkins interface.

Monitoring the progress of the pipeline

Click the image to enlarge.

As expected, the Jenkins agent is started in a Pod, and it runs the expected instructions to launch the scan of the code previously retrieved into the NFS volume.

This process will take several minutes and will utilize the GPU of the Kubernetes node on which Ollama is running.

GPU load on the node

Click the image to enlarge.

At the end of the pipeline, you can access the reports generated by Oasis, either through the web interface or directly in the NFS volume selected in the first article where we deployed Oasis.

As with the first time, there are several report formats available: PDF, HTML, or Markdown.

Collection of PDF reports

Click the image to enlarge.

If you browse the PDF reports, you will find all the security vulnerabilities in the code, along with the various recommendations for correcting them.

Summary of vulnerabilities found

Click the image to enlarge.

Example of a vulnerability

Click the image to enlarge.

Example of a vulnerability

Click the image to enlarge.

Recommendation following a vulnerability

Click the image to enlarge.

Conclusion

Through these two articles, I wanted to demonstrate the benefits of combining CI/CD and AI, not just through marketing rhetoric, but through a concrete example.

Thanks to open-source tools, it is possible to integrate advanced cybersecurity analysis features using AI, all integrated into a CI/CD pipeline to automate the process.

For example, you could invalidate deployments if vulnerabilities are detected to prevent running risky code.

At a time when everyone talks about cyber risk at every opportunity, this kind of combination can make perfect sense. Note that the process can be done locally without having to share any data externally.

This can be interesting when the code being analyzed is sensitive or if the company is subject to specific constraints in this area.

Of course, the demonstration still needs to be refined and improved for implementation in a production environment within a professional context.

However, it becomes clear that by putting aside flashy presentations and focusing on engineering, we can really take advantage of all these technological advancements.

AI is not a threat to IT professions, but an accelerator, a way to be more efficient and performant... provided we forget about marketing a little and are not afraid to experiment!