Skip to content
ImagineWorld

AI Security with MLSecOps

node_idnode-book_adversarial-ai-defense-strategies_chapter-18-ai-security-with-mlsecops
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num18
chapter_titleAI Security with MLSecOps
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the previous chapter, we discussed our secure-by-design AI methodology that can help us identify threats relevant to our solution and apply appropriate mitigations and controls. We highlighted the need for MLSecOps to be a fundamental enabler of AI security. In this chapter, we will discuss in more detail, with practical demonstrations, why MLSecOps are so essential and provide a practical exploration of the concepts.

We will cover the following topics:

  • How modern AI trends are accelerating the imperative of MLSecOps
  • MLSecOps workflows to evolve from DevSecOps and MLOps to MLSecOps
  • Building a simple MLSecOPs platform with Jenkins and MLFlow
  • MLSecOps in action with Jenkins, MLFlow, and our sample solution
  • Integrating MLSecOps with notebook-based interactive workflows
  • The MLSecOps aspects of LLMs and the role of LLMOps
  • Advanced use of MLSecOps with ML SBOMs

Let’s start with a refresher on the critical concepts in light of the recent changes in AI.

In Chapters 3, 5, and 6, our discussions about securing AI-driven systems explored the roles of DevSecOps and MLOps. DevSecOps emphasizes integrating security practices within software’s development and operations life cycle, advocating a security as code philosophy. This approach ensures that security measures are not afterthoughts but are ingrained throughout the development process.

MLOps, conversely, plays a critical role in managing the life cycle of machine learning models, from data preparation and model training to deployment and monitoring, emphasizing automation and continuous improvement. MLOps provides an invaluable platform for good governance, which aids security but – reflecting the emerging nature of threats – has not had the maturity emphasis on security that DevSecOps brought to DevOps.

Early MLSecOps approaches consisted of tentative but encouraging steps in bringing security tooling and practices into MLOps pipelines, but more is needed.

As we pivot toward the concept of MLSecOps, it becomes increasingly clear that the convergence of these two domains is not just beneficial but also essential.

In the earlier stages of AI and ML adoption, especially in predictive AI, software development and ML development were kept in parallel and often separated streams. ML was more of an activity with fewer restrictions and much emphasis on model development. This is no longer tenable for a few reasons:

  • The complexity and dynamism of AI systems, with their blend of software code, live data, and machine learning models, demand a holistic approach to security that transcends traditional boundaries. As we discussed in Chapters 3 and 6, by not having integration with traditional DevSecOps pipelines, AI development and scientific environments could be exploited by rogue packages. We discussed the example of the 2022 dependency confusion attack on PyPI nightly builds of PyTorch, allowing malware to be installed in data science environments. With access to live data, these environments become a security backdoor that could be exploited, and the UK’s National Cyber Security Centre (NCSC) has highlighted the changing role in its principles of ML security and its guidelines for secure AI system development. You can read these extensive principles and guidelines at https://www.ncsc.gov.uk/collection/machine-learning and https://www.ncsc.gov.uk/collection/guidelines-secure-ai-system-development.
  • The democratization of AI with an explosion of pre-trained models has reduced the emphasis on heavy science and model development. This trend is changing the nature of AI development life cycles and increasing the use of models and AI artifacts, in a manner similar to software packages. As a result, the science time is reduced and the software development time is increased, bringing the two flows closer together but bringing new and more severe supply-chain threats. Unlike open source packages, ML models are black boxes with no code to inspect and detect vulnerabilities. The JFrog 2024 report on Hugging Face demonstrated a staggering amount of malware disguised as models in this immensely popular model repository. This represents a critical juncture where models become an easily reused utility without the safeguards that a utility should have. We discussed the JFrog report in Chapter 6; here is the link to it: https://jfrog.com/blog/data-scientists-targeted-by-malicious-hugging-face-ml-models-with-silent-backdoor/.
  • The rise of LLMs has propelled AI to new heights but, paradoxically, reduced the emphasis on model development and engineering activities, shifting the focus to API-driven prompts. This is an example of where MLOps almost disappears, but MLSecOps is a critical necessity more than ever. The emergence of open-access LLMs is changing some dynamics, but the complexity transitions model development to a specialized platform-like activity. Instead, solution developers focus on the use and fine-tuning of models, bringing the supply-chain challenges of the previous point to LLMs.
  • Aided by LLMs’ advanced capabilities and non-determinism, a challenge exists to a different degree in foundation models operated by AI vendors. Given the vast generalist scope of LLM functionality, benchmarking red teaming and dynamic testing emerge as activities that should be repeated as we build an application that require continuous monitoring. This is akin to the practices DevSecOps introduced for components and applications with DAST (Dynamic Application Security Testing) and requires automation to scale. In the next section, we will discuss an MLSecOps framework that focuses on the unified orchestration of AI activities, viewed as value chains, irrespective of the process’s individual swim lanes (ML, software, and the platform).
  • More sophisticated attacks, due to advanced capabilities and adversarial AI in the hands of adversaries, are hard to detect, requiring automated and fast defenses and responses across the AI solution. AI-generated adversarial perturbations for prompt injections, for instance, require automated and joint defenses across the three elements of an AI solution – ML, software, and the platform.

These changes pivot MLSecOps beyond adding security tooling to MLOps pipelines. MLSecOps represents a synthesis, marrying the principles and process of DevSecOps with the specialized needs of MLOps. It requires a unified view and orchestration of AI security and safety across a solution, not just specialized activities.

MLSecOps underscores the imperative to recognize AI’s changing life cycles, increase adversary capabilities, and shift our defensive strategies leftward. Captured by the term shift-left, MLSecOps requires integrating security considerations early and throughout the AI life cycle in a combined process view.

In essence, this is the passage from the ML to the AI Era and heralds v2. of MLSecOps. The following section will discuss tooling, responsibilities, and patterns of the emergent MLSecOps 2.0 approach.

Shifting MLSecOps to be intentionally integrated into AI solutions’ life cycle requires understanding and mapping its stages. AI life cycles will vary, depending on the model and data source (own or external), model hosting (own or third-party), the solution packaging (backend API, web application, or mobile app), and the type of AI (predictive or generative). Nevertheless, we can identify distinct steps commonly used in these variations. We can use them to create reusable patterns of MLSecOps orchestration. The patterns highlight the applicable security controls and the role of CI pipelines, MLOps, and SCM.

A crucial element is the orchestrator of flows across the AI solution spectrum, offering a single control pane ideally.

Let’s explore the options for this crucial role.

CI pipelines are an ideal candidate to act as the orchestrator of MLSecOps flows, and there are good reasons for that:

  • CI pipelines are the ubiquitous fabric of solution development
  • They are well-understood platforms with readily available expertise within teams
  • They have mature integration with tools and APIs, including those of MLOps platforms
  • They are the backbone of continuous delivery and production deployments
  • CI pipelines combine traditional applications, platforms, and ML development, which is the essence of MLSecOps 2.0

However, CI tools are general in nature, and they will need MLOps and other integrations and plugins to perform ML, such as ZenML, MLRun, Metaflow, Kendor, and Netflix Genie. Also, Spotify’s Luigi offers a rich set of reusable ML-specific features and integrations with data processing platforms (e.g., Spark and Hadoop).

Depending on expertise, environment, and requirements, these tools can accelerate MLSecOps orchestration. Still, you will need to ensure they integrate or intersect consistently with your CI pipeline platform, instead of creating two separate difficult-to-integrate silos.

Top-end MLOps platforms, such as Amazon SageMaker and Azure Machine Learning pipelines, offer a good combination of ML orchestration and integration with CI pipelines and DevOps.

More general workflow engines can offer more scalable, manageable performance, with a better feature match for more complex computational environments with heavy data engineering components. They use DAGs (Directed Acyclic Graphs) – an approach to specifying and executing workflows – to define, execute, and track a flow with its steps and dependencies. Apache Airflow is the leading open source choice in this space, with the more recent Perfect being a popular contender.

Finally, containerization and Kubernetes are popular approaches to managing ML and application workloads, making Kuberflow pipelines and Argo popular choices.

The following table offers a non-exhaustive list of MLSecOps orchestration options:

OrchestratorDescriptionURL
Apache AirflowAn open source platform to schedule, coordinate, and manage complex computational workflows. Widely used for ML orchestration due to its flexibility and extensive plugin system.https://airflow.apache.org/
Argo WorkflowsA Kubernetes-native workflow engine that orchestrates parallel jobs on Kubernetes, designed for microservices and capable of running complex job dependencies.https://argoproj.github.io/argo-workflows/
KedroAn open source Python framework that provides a standard way to create data and ML pipelines, promoting modular and maintainable code.https://github.com/kedro-org/kedro
Kubeflow PipelinesDesigned for machine learning workflows on Kubernetes, it provides a platform for building and deploying scalable ML workflows.https://www.kubeflow.org/
LuigiDeveloped by Spotify, Luigi helps you build complex pipelines of batch jobs, handling dependency resolution, workflow management, and so on.https://github.com/spotify/luigi
MetaflowMetaflow is a human-centric framework created by Netflix that easily builds and manages real-life data science projects.https://metaflow.org/
MLRunAn open source MLOps framework to manage and automate machine learning pipelines, designed to work in diverse environments.https://github.com/mlrun/mlrun
Netflix GenieA platform to run big data jobs and manage data processing tasks that are part of ML pipelines, including job scheduling and execution.https://netflix.github.io/genie/
PrefectA Python-based workflow management system offers a modern approach to defining and executing workflows, focusing on simplicity.https://prefect.io/
ZenMLAn extensible MLOps framework to create reproducible ML pipelines, focusing on the entire life cycle of ML projects.https://github.com/zenml-io/zenml

Table 18.1 – The MLSecOps Orchestration platforms

The choice of tool will depend on specific project needs, existing infrastructure, and the complexity of workflows. You should ensure that it allows you to build a unified view and control plane of how your AI solutions are developed and apply MLSecOps in an integrated and consistent manner.

This section assumes CI pipelines as the baseline of MLSecOps orchestration patterns. We will discuss these patterns in the next subsection, and the mapping is straightforward enough to be applied to more specialized tools.

By identifying commonly used steps and flows in the AI life cycle, we can build MLSecOp patterns of security orchestration. These patterns help us create, share, and reuse recipes with standardized terminology, thus increasing effectiveness and maturity. Here are the common flows and their MLSecOps orchestration pattern:

  • Model sourcing: Acquiring preexisting models from various repositories or sources to reuse as a fine-tuning starting point or benchmark for new projects:
    • CI pipelines: Automates the fetching and validation process of models from repositories and updates the MLOps platform via plugins and API calls. Applies the security controls we define ahead.
      • MLOps: Registers and versions sourced models, captures metadata – including hashing identifiers, model cards, and generated SBOMs – and ensures their integrity and reproducibility with a stored copy. Tags a model appropriately so that it can be used for future experiments.
      • Security controls: Baseline malware and serialization vulnerabilities, model integrity verification and hashing, additional vulnerability scanning, and the creation and storage of a signed SBOM.
  • Data sourcing: The process of gathering and validating the data needed to train and evaluate the ML model:
    • CI pipeline: Provisions data storage, if needed, and executes automated scripts to manage data encryption, permissions, and any automated validation scripts, updating the MLOps platform with data artifacts and references.
      • MLOps: Logs data versions and metadata, enhancing traceability and reproducibility. Data is tagged appropriately so that it can be used for future work.
      • Security Controls: Encryption in transit and at rest, strict access controls, malware checks, and validation scripts, including anomaly and drift detection, adversarial tests, etc. Data scientists will typically perform validation interactively in Jupyter Notebooks or Python scripts. Once automated, these can be reused in CI pipelines.
  • Model evaluation: Assessing the performance and safety of a machine learning model against a set of metrics, ensuring that it meets the desired criteria and is safe before deployment. This stage will follow both model acquisition when using a pre-trained model and model training, either base model development or fine-tuning. This is where adversarial robustness and other tests will be performed, most likely interactively, using Jupyter notebooks and the automated pipelines:
    • CI pipeline: Triggers the flow and updates MLOps to create a new experiment. This will execute relevant validation tests that have already been automated. For manual and exploratory validation (e.g., a Jupyter notebook), it will apply DevSecOps to the source code check-in, including SAST, vulnerability scanning for third-party components, and sensitive data leaks in the notebook or code, including secrets. If a new version of the model is checked in, integrity checks using the original hash are compared before updating the MLOps Model Registry. The CI will update and sign the model SBOM with any vulnerabilities or other findings. A copy or reference is also added as model metadata to the model in the Model Registry. An auxiliary pipeline will also promote manual tests after refactoring and testing as automated tests for future reuse. This will apply the usual DevSecOps checks (SAST, vulnerability scanning of packages, and secrets scanning).
      • MLOps: Logs experiments and model metadata. For automated tests and operations, the CI pipeline does this via a plugin to the MLOps API. The data scientist may update MLOps directly via their APIs for all manual work.
      • Security controls: Malware checks, integrity checks, validation, and adversarial tests. Access controls to models that have passed previous scans. This can be done easily when models are checked out via the pipeline with automated checks. For interactive and manual work, the data scientists, developers, and ML engineers will need to use the Model Registry via the MLOPs API and filter approved models. This will be enforced by custom libraries supporting the workflow, code reviews to ensure these have been followed, and policies to require compliance.
  • Data evaluation: This involves analyzing the quality and relevance of the data used to train models to ensure they are suitable for a task. This can follow data sourcing or be part of subsequent evaluations. It assumes data is already approved and stored in a secure location. Like model evaluation, data evaluation will initially be manual evaluations with automation to provide monitoring. The pipeline may run regularly (e.g., overnight to perform anomaly detection and support monitoring):
    • CI pipeline: Ensures only approved datasets are checked out. It runs any automated validation scripts and updates MLOps records, including stages and tags, to enforce access controls and workflows.
      • MLOps: Logs data versions and metadata, enhancing traceability and reproducibility. Data is tagged appropriately so that it can be used for future work.
      • Security controls: Encryption in transit and at rest, strict access controls, malware checks, and validation scripts, including anomaly and drift detection, adversarial tests, and so on. Data scientists will typically perform validation interactively in Jupyter notebooks or Python scripts. Once automated, these can be reused in CI pipelines. The earlier observations on how to enforce workflow for model evaluation apply to data, too.
  • Data exploration and preprocessing: This involves analyzing data initially to understand its characteristics, performing feature selection and engineering, cleaning the data, and transforming it into a format suitable for model training. This will predominantly involve manual work by data scientists and engineers. Complex transformation and data treatment may already be coded and applied to data retrieval. Some of this work may be codified into the automated generation, retrieval, and preprocessing of derivative data for future use. In the MLSecOps 2.0 model, only registered and evaluated data can be used. Data treatment for sensitive data is also an essential element of data access. The CI pipeline and MLOps tracking enforces appropriate checks, using tags and workflow stages:
    • CI pipeline: This step uses MLOps tags to ensure only approved datasets are checked out and runs any automated validation and sanitization scripts on checkouts. Scripts to retrieve data after applying scrubbing, anonymization, and other data treatment will be executed in this step. Once the task is completed, CI pipelines will run automated checks on check-in. If applicable, apply DevSecOps to code and dependencies, and update MLOps records, including stages and tags, to enforce access controls and workflows.
      • MLOps: Logs data versions and metadata, enhancing traceability and reproducibility. Data is tagged appropriately so that it can be used for future work.
      • Security controls: Data anonymization and treatment, validation scripts, anomaly and drift detection, adversarial tests, and so on. DevSecOps controls code and dependencies, as described earlier. Use of MLOps tracking metadata and stages and access control policies to apply additional access control. The earlier observations on how to enforce workflow for model evaluation apply to data, too.
  • Direct model development, including fine-tuning: This is the process of directly creating or modifying machine learning models, often including adjusting model parameters to improve performance. Only approved models can be used. The model evaluation follows this step to perform automated performance, adversarial, and other tests:
    • CI pipeline: Manages secure development environments and access control, integrating code security scans we have described earlier. Implements hooks to trigger the model evaluation step to support detection and model monitoring.
      • MLOps: Tracks model versions, parameters, and training metrics directly from Jupyter notebooks and code.
      • Security controls: Secure sharing of pre-trained models by enforcing access to approved modes only. The DevSecOps controls we discussed earlier are applied at check-in. Version control for models and triggering the model evaluation step provide additional assurances.
  • API-driven model development (fine-tuning): This involves using APIs to iteratively finetune models based on specific performance metrics or feedback loops:
    • CI pipeline: Manages the deployment and scaling of secure API interfaces, incorporating security tests
      • MLOps: Versions and tracks model performance metrics to facilitate API-driven iterations
      • Security controls: API security measures such as authentication and rate limiting
  • Prompt engineering: Designing and optimizing the inputs (prompts) used to interact with models, especially in natural language processing and generative tasks, to produce desired outputs:
    • CI pipeline: Manages secure prompt management systems, validating and storing prompts.
      • MLOps: Versions and manages different sets of prompts, enabling systematic experimentation. MLOps may not offer support for tracking prompts.
      • Security controls: Prompt validation, regression tests, and secure storage.
  • Retrieval-Augmented Generation (RAG): Enhancing model outputs by integrating external knowledge or data at runtime, typically used in NLP for generating richer responses:
    • CI pipeline: Automates secure information retrieval, incorporating content validation steps
      • MLOps: Tracks experiments and outcomes to optimize retrieval sources and algorithms
      • Security controls: Secure access to external knowledge, data, and content validation
  • Platform model deployment: The process of deploying trained models to a production environment where they can serve predictions or inferences:
    • CI pipeline: Facilitates secure automated deployments with integrated security monitoring
      • MLOps: Manages model packaging, versioning, and deployment, ensuring consistent deployment practices
      • Security controls: Automated deployment to ensure deployment only takes place in compliant platforms with secure platform integrations
  • AI software development (service apps): The broader process of developing software solutions that incorporate ML models, including integrating AI into existing systems:
    • CI pipeline: Orchestrates CI/CD processes, integrating tools for dependency scanning and automated security testing
      • MLOps: Manages AI feature integrations and tracks dependencies and versions
      • Security controls: Dependency scanning, secret management, and secure coding practices
  • Model edge development: Adapting and deploying ML models to edge devices for local inference, often requiring optimization for performance and resource constraints:
    • CI pipeline: Manages the secure development and deployment of edge models, ensuring encrypted communications
      • MLOps: Employed for edge model versioning and tracking deployment activities
      • Security controls: Secure firmware/software updates encryption on edge devices
  • Monitoring and alerting: Establishing systems to continuously monitor the performance and health of deployed models and setting up alerts for anomalies or significant changes in performance:
    • CI pipeline: Integrates real-time monitoring tools, providing alerts and insights for quick response
      • MLOps: Tracks model performance in production, aiding in monitoring
      • Security controls: Real-time application and model monitoring, and automated alerting systems

The steps and patterns we discussed emphasize the role of CI pipelines and ML operations tools in managing and securing the ML life cycle, from initial model sourcing to monitoring deployed models in production.

Development and deployment workflows may vary, depending on requirements, the nature of the solution, and the environment. Still, these variations will be present in the steps and MLSecOps patterns we covered.

The following section will walk through a practical application of some of these patterns, using Jenkins, MLFlow, and the sample Enhanced Foodie AI solution we used in the previous chapter.

Before we walk through MLSecOps flows, let’s explain how to build a basic dockerized MLSecOPs platform.

We will apply our MLSecOps patterns using Jenkins and MLFlow, which are the core of our MLSecOps. The book’s repository contains all the necessary files, and in this section, we will walk through how to build a basic MLSecOPs platform and use it for our Foodie AI solution.

The following diagram illustrates the basic architecture of our simple MLSecOps platform:

Figure 18.1 – MLSecOps architecture

Figure 18.1 – MLSecOps architecture

This is a sample architecture to demonstrate the concepts and help understand the technical challenges. It combines Jenkins pipelines, supporting MLSecOps scripts, and MLFlow:

  • Jenkins pipelines are called with parameters via the Jenkins API in invoker scripts, securely invoking them from the CLI, Jupyter notebooks, Git hooks, and cron -like schedules. The pipelines use stages and steps to orchestrate these scripts and fail if specific compliance baselines are violated.
  • Automation scripts implement the flow and MLSecOps controls in Python. The scripts invoke other services and utilities, implement validation or adversarial tests, and call the MLFlow API to track experiments, register and retrieve models, update and read metadata, and maintain state and status, which are used to enforce the workflow.
  • MLFlow runs as a server, exposing its UI and API.

We host Jenkins and MLFlow as Docker containers and provide a Docker file for each:

  • Jenkins will install the tools we need, such as ClamAV, bandit and trivy, and the Python packages, and it will copy and set up the pipelines and scripts we will use. We discussed bandit and trivy in Chapter 3. A quick reminder – bandit is a security code scanner for Python, offering SAST (Static Application Security Testing), whereas Trivy offers vulnerability scanning for third-party packages and Docker images, and recently, it has added secret scanning to prevent passwords and tokens leaking via code. ClamAV is an open source antivirus scanner that scans files, directories, and emails for malware. We will use it in our practical demonstration to scan files. You may have a different malware scanner in place, but the approach will be similar, and ClamAV allows us to see MLSecOps in action easily. You can find more about ClamAV on the project’s website at https://www.clamav.net/.
  • MLFlow uses out-of-the-box configuration to use the filesystem as its backing storage. You may want to change this to use a database or cloud storage (an S3 bucket or Azure Blob storage) for artifacts.

We also provide a docker-compose file to create the stack, configure the MLFlow tracking URL for Jenkins, and access the mounted volume that acts as the staging environment for untrusted artifacts.

Here is what docker-compose looks like for our simple MLSecOps stack:

version: '3.8'
services:
jenkins-mlsecops:
build:
context: ./jenkins
ports:
- "8080:8080"
- "50000:50000"
volumes:
- jenkins_home:/var/jenkins_home
- models:/downloads/models
- scripts/:/scripts
environment:
- MLFLOW_TRACKING_URI=http://mlflow-server:5000
mlflow-server:
build:
context: ./mlflow
ports:
- "5000:5000"
volumes:
jenkins_home:

The stack relies on two images (jenkins-mlsecops and mlfow-server). It mounts the volumes we need. These are for the Jenkins container and include the following:

  • /var/jenkins_home mapped to a named volume (jenkins_home). The base Jenkins image uses the volume and offers persistent storage to maintain Jenkins installations across image deployments and container runs. As a result, you don’t have to reconfigure Jenkins every time you run the container.
  • /download/models mapped to a host folder ($(HOME)/models), an untrusted staging area where we put any external untrusted models before registering them.
  • /scripts is a utility volume mapped to our source code, allowing us to develop our scripts without redeploying every time we want to test changes.

Note

For production systems, you will need to remove volumes and use the immutability of the container to avoid malicious tampering with your scripts outside the CI deployment.

We will also add the volumes we need to mount for Jenkins to work:

volumes:
- jenkins_home:/var/jenkins_home
- $(HOME)/models:/downloads/models
- scripts/:/scripts

We create the named jenkins-home volume using the following statement in docker-compose:

volumes:
jenkins_home:

This creates or uses an existing volume that Docker manages and prevents accidental changes or tampering that a localhost path mapping could entail.

To access the volume contents from the host, you will need to use Docker commands such as docker volume inspect jenkins_home and docker cp.

For more information, see https://docs.docker.com/storage/volumes/.

docker-compose passes the URL for MLFlow to Jenkins via the environment variable:

environment:
- MLFLOW_TRACKING_URI=http://mlflow-server:5000

Let’s dive into the two images and understand how they work.

We use a customized Docker file, extending the official base Jenkins Docker image to update all packages and install our tools. We use the root user to gain admin access:

FROM jenkins/jenkins:lts
USER root
# Update and install necessary packages
RUN apt-get update && apt-get install -y \
python3-venv \
wget \
apt-transport-https \
gnupg \
lsb-release \
clamav \
clamav-daemon

Because trivy is not part of the OS package repository, we need to install it by adding the official trivy repository and its PGP key (essential to avoid tampering and impersonation attacks). We then install it as usual:

# Install Trivy
RUN apt-get install -y wget apt-transport-https gnupg lsb-release
RUN wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | apt-key add -
RUN echo deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main | tee -a /etc/apt/sources.list.d/trivy.list
RUN apt-get update && apt-get install -y trivy

We will create a Python virtual environment to install Python-based packages and use it at runtime to execute our MLSecOps scripts. We will use mainly ART, but you can add any additional dependencies here. You can optimize this part with a requirements.txt file that you maintain, copy, and then install instead of the individual files we have in this example. This allows you to highlight critical dependencies, but it is harder to scale:

# Create a virtual environment
RUN python3 -m venv /app/venv
# Activate the virtual environment and install your Python packages
RUN . /app/venv/bin/activate && pip install modelscan mlflow adversarial-robustness-toolbox bandit
# Setting up the environment for Python and security tools
RUN python3 -m venv /app/venv \
&& . /app/venv/bin/activate \
&& pip install --upgrade pip \
&& pip install modelscan h5py tensorflow torch dill joblib mlflow adversarial-robustness-toolbox bandit

The Docker file installs the plugin we need to install pipelines:

# Install Jenkins plugins
COPY plugins.txt /usr/share/jenkins/plugins.txt
RUN /usr/local/bin/install-plugins.sh < /usr/share/jenkins/plugins.txt

We then copy job creation scripts and pipeline files, ensuring the Jenkins user owns them. This is the user under which Jenkins will run, and they will need to be able to access the files:

# Copy the job creation Groovy script and Jenkinsfile
COPY create_pipeline_job.groovy /usr/share/jenkins/ref/init.groovy.d/create_pipeline_job.groovy
COPY pipelines/ /usr/share/jenkins/ref/jobs/ModelPipelineJob/
# Ensure Jenkins owns all copied files
RUN chown -R jenkins:jenkins /usr/share/jenkins/ref

We repeat the same for our MLSecOps scripts:

# Copy your Python scripts into the image
COPY scripts /app/scripts
# Ensure the script directory and its contents are owned by the correct user
RUN chown -R jenkins:jenkins /app/scripts
# Ensure the script directory and its contents are owned by the correct user
RUN chown -R jenkins:jenkins /app/scripts

Finally, we update the antivirus database and revert to the jenkins user that the base image has created. This is crucial in applying least-privilege access and avoiding attacks that abuse the root super user:

# Freshen ClamAV's database
RUN freshclam
USER jenkins

We don’t specify an entry point because we use the one from the base image that runs the Jenkins server.

The MLFlow image is much simpler but could be more complex if we configured options to use other technologies for persistence and storing artifacts.

The image uses a base official Python image, adds a new user (we leave it as an exercise for you to fine-tune the user permissions), and uses pip to install MLFlow. Finally, we run MLFlow as a server using the server command-line option:

# Use an official Python runtime as a parent image
FROM python:3.10-slim-bullseye
# Create a new user "mlflow"
RUN useradd -m mlflow
# Set the working directory in the container
# Add /home/mlflow/.local/bin to PATH
ENV PATH="/home/mlflow/.local/bin:${PATH}"
WORKDIR /home/mlflow
# Change to the new user
USER mlflow
# Upgrade pip
RUN pip install --upgrade pip --user
# Install MLflow
RUN pip install --no-cache mlflow --user
# Expose the port the app runs on
EXPOSE 5000
# Define environment variable
ENV MLFLOW_HOME /home/mlflow
# Run MLflow server
CMD ["mlflow," "server", "--host", "0.0.0.0"]

Now that we have explained how to build the stack, let’s see how we can use this sample architecture for some essential AI flows.

In this section, we will use the MLSecOps platform we built to secure our sample Enhanced Foodie AI solution, which we used for our secure-by-design AI exploration in the previous chapter. The following diagram is a quick reminder of the sample application:

Figure 18.2 – Enhanced Foodie AI architecture

Figure 18.2 – Enhanced Foodie AI architecture

We will start using MLSecOps by sourcing and validating a model to protect us from supply-chain threats.

The example assumes that the team fine-tuned the official TensorFlow ResNet50 CNN model from the TensorFlow Hub, leading to Kaggle. We will start implementing our pattern by automating basic security checks.

We want to automate the model sourcing MLSecOps pattern we described in the previous section and apply the following controls:

  • Baseline malware and serialization vulnerabilities
  • Model integrity verification with hashing and hash registration

Note

We will cover more advanced steps in a later section to keep this walkthrough simple. These include analyzing the model’s dependencies, checking for vulnerabilities, and creating and storing an ML SBOM alongside the model’s card.

Our workflow relies on downloading and placing the ResNet50 model in a staging area. This will be the $(HOME)/models folder, which we mounted in the /downloads/models folder in the Jenkins container.

We then trigger the AI-Validate-New-Model pipeline, defined in the register-external-model-pipeline.groovy file. Jenkins pipelines use stages and steps, in which you can invoke scripts.

The following diagram illustrates our pipeline:

Figure 18.3 – The AI-Validate-New-Model pipeline

Figure 18.3 – The AI-Validate-New-Model pipeline

Note

Creating good Jenkins pipelines is beyond the scope of this book, and we will use them simply to demonstrate the concepts of MLSecOPs. You can find more details on Jenkins pipelines at https://www.jenkins.io/doc/book/pipeline/.

Creating our Jenkins pipeline requires defining the pipeline in Jenkins and supplying a pipeline script.

You can create the pipeline in the Jenkins Dashboard by selecting New Item, supply the name, AI-Validate New Model, and select the type of item, Pipeline. This leads to the pipeline Configuration page.

Jenkins provides a lot of configuration options. In this example we will not set any, other than defining custom input parameters that supply the pipeline script. You can add the configuration parameters by checking This project is parameterized and create the parameters you plan to pass to your pipeline when you run it, as show in the next figure:

Figure 18.4 – Configuring a Jenkins pipeline

Figure 18.4 – Configuring a Jenkins pipeline

In our case, we want to pass the location of the model, the source, a model card, and additional metadata. These will be handled by the pipeline script, which is also supplied in a memo field on this configuration page.

A pile script is written in Groovy, which is easy to use for simple orchestration tasks. Let’s use our pipeline script to see how it brings things together following the Jenkins Pipeline syntax:

  1. The first part of the pipeline script defines the input parameters, which include the model filename and an optional mode
    pipeline {
    agent any
    parameters {
    string(name: 'MODEL_FILE_PATH', defaultValue: '', description: 'Path to the model file'),
    string(name: 'MODEL_REF_CARD', defaultValue: ''
    .......
    }
    environment {
    // Use the environment variable from the Jenkins agent
    MLFLOW_TRACKING_URI = "${env.MLFLOW_TRACKING_URI}"
    }
  2. The first two stages
    stages {
    stage('AV Scan') {
    steps {
    echo "AV scanning for file at ${params.MODEL_FILE_PATH}"
    sh 'clamscan --infected --remove --recursive /downloads/models/${MODEL_FILE_PATH}'
    }
    }
    stage('Model Scan') {
    steps {
    script {
    echo "Scanning model ${params.MODEL_FILE_PATH} with ModelScan"
    sh '. /app/venv/bin/activate && modelscan -p /downloads/models/${MODEL_FILE_PATH}'
  3. The first stage (AV Scan) invokes the ClamAV to scan for viruses and fail the pipeline if any are found. It does so by invoking ClamAV, using an inline
    sh 'clamscan --infected --remove --recursive /downloads/models/${MODEL_FILE_PATH}
    You can test the pipeline using a file with the EICAR synthetic malware. This harmless file triggers malware scanners that classify it as malware. For more information on EICAR, see https://www.eicar.org/download-anti-malware-testfile/.
  4. The second stage (Model Scan) uses the ModelScan utility we used in Chapter 3 to automate scanning the model for serialization vulnerabilities. ModelScan was installed via Pip. As a result, we need to adjust our inline shell script to first activate our Python virtual environment and then run modelscan:
    sh '. /app/venv/bin/activate && modelscan -p /downloads/models/${MODEL_FILE_PATH}
  5. If any of these stages fail, the pipeline will fail, too. If they succeed, the pipeline will execute the next stage (Register Model). This is a more complex step implemented as a Python MLSecOPs script (register_external_model.py), which is invoked by our pipeline using a Python call in an inline script:
    stage('Register Model') {
    steps {
    script {
    sh '. /app/venv/bin/activate && python /app/scripts/register_model.py \
    --tracking-uri ${MLFLOW_TRACKING_URI} \
    --model-file ${MODEL_FILE_PATH} \
    --model-name ${MODEL_NAME}' \
    --model-name ${MODEL_CARD' }\
    --model-name ${MODEL_CARD' \
    }
    }
    }
    The code for the Python script is shown here:
    def register_model(tracking_uri, model_file, model_name, description="", source="", dataset_name="", dataset_version="", run="Jenkins Pipeline"):
    mlflow.set_tracking_uri(tracking_uri)
    if model_name == "":
    model_name = model_file.split("/")[-1].split(".")[0]
    hash = create_sha256(model_file)
    pipeline = timestamped_string(run)
    with mlflow.start_run() as run:
    reg = ModelRegistry()
    # Log tags relevant to both the model and the experiment
    reg.registration_tags["av scanned"] = True
    reg.registration_tags["model Scanned"] = True
    reg.registration_tags["mlflow.runName"] = pipeline
    for key in reg.registration_tags:
    mlflow.set_tag(key, reg.registration_tags[key])
    print(f"Tag '{key}' set to '{reg.registration_tags[key]}'.")
    # tags only relevant to the model
    reg.registration_tags["hash"] = hash
    reg.registration_tags["stage"] = "evaluation"
    reg.registration_tags["registered by"] =pipeline
    del reg.registration_tags["mlflow.runName"]
    reg.log_model_dynamically(model_file,model_name, alias="scanned", description=description)
    print(f"Model '{model_name}' registered in MLflow Model Registry.")
    print(args)
    register_model( args.tracking_uri, args.model_file, args.model_name,run=args.run)

The script’s main function is to use the MLFlow API to load and check the model, create a copy, and register it with the model registered in MLFlow.

This also creates a sha-256 hash and stores it alongside the model as a tag. This will allow us to perform integrity checks and confirm the model can be traced back to the original one, and also that it has not been tampered with and replaced manually in MLFlow’s artifacts backend (the filesystem, S3 bucket, and Azure Blob storage).

Because the model registration APIs in MLFlow are framework-specific, the book repository extensive code to handle different formats, including multifile archives such as older TensorFlow and PyTorch models with separate weights files. Similarly, the hashing code ensures that all associated files are hashed, too, and all the hashes are stored with the filenames in the model’s registry record.

In addition to registering the mode, we log an MLFlow experiment with relevant details. This ensures auditability and allows us to track the work. The following code uses a wrapper class we created for the MLFlow calls (ModelRegistry) and coordinates the experiment logging and model registration.

We log tags that help us track our work and a stage tag. This stage tag is at the core of our workflow, and we update it as we move through the model’s life cycle. MLFlow has built-in stages, but they are being deprecated in favor of the tags that we use here to support our MLSecOps workflow with reg.registration_tags["stage"] = " evaluation".

Now that we have defined the scripts and pipelines, let’s run our pipeline. For now, we will use the Jenkins UI, as shown in the following screenshot. Note the pb extension of the model. This indicates an older TensorFlow model, a sub-directory with multiple files, including architecture and weights:

Figure 18.5 – Invoking the pipeline for external model validation

Figure 18.5 – Invoking the pipeline for external model validation

We can see the pipeline building in real time and performing the steps in the Jenkins UI, as shown in the following figure:

Figure 18.6 – Running the external model validation pipeline

Figure 18.6 – Running the external model validation pipeline

Our model has no virus or other malware hidden in the serialization format, and we have logged both the model and the experiment.

Note

Use the Console Output of a build in Jenkins to troubleshoot failures and errors.

The following screenshot shows the experiment record created by the pipeline, capturing the tags and related models. This is our audit record of doing the minimum security checks for an external model:

Figure 18.7 – A pipeline-register experiment

Figure 18.7 – A pipeline-register experiment

We can navigate to the Model Registry and see the model details we have registered, as shown in the following figure. MLFlow has built-in versioning and has registered our model as Version 1:

Figure 18.8 – A model registered by the Jenkins pipeline

Figure 18.8 – A model registered by the Jenkins pipeline

Because the model contains multiple files, the hash tag is a JSON array of all files and their hashes. In addition to the tags we added in the experiment, note the workflow-related tag, evaluation.

This indicates that the model has been scanned and is ready for further evaluation. Similarly, we have created a version alias, scanned.

As we can see, this allows data scientists and engineers to filter models that can be used for further work and avoid working with insecure models. This may also require additional support from policies and conditional access control.

Note

These steps can be done manually, but the pipeline helps automate the process and ensure that steps do not become optional and missed at the expense of security.

The following section will show how to integrate this pipeline into team member workflows.

Integrating pipelines with development and data science workflows

Section titled “Integrating pipelines with development and data science workflows”

We invoked the pipeline using the Jenkins UI. Using Jenkins support to trigger pipeline builds via an API is a different approach. Jenkins offers a variety of ways to invoke a pipeline build. In this example, the pipeline is configured to enable calls via a URL:

Figure 18.9 – Configuring a pipeline trigger

Figure 18.9 – Configuring a pipeline trigger

By doing this, you enable scientists and engineers to trigger the pipeline with a simple curl command from the command line:

curl --location --request POST http://localhost:8080/job/test/buildWithParameters --data token=AISIC --data MODEL_FILE_PATH=simple-cifar10.h5 --user jsotiro:11096b874b1f4eb067c70fa2d57b57e4ec

Note the difference between our example and the URL in the trigger configuration. The example would work with anonymous users enabled, but that can be insecure, so we use a user token and basic authentication (<user name>:<user token>) as an additional safeguard. You can create a user token from the Jenkins UI by logging into it, clicking on the user profile, and then clicking Configure. We use a user token to demonstrate the security levels that are available to you. Based on your security and auditing requirements, you will need to balance security with usability, deciding whether to use anonymous triggers that skip the need to log in and get a user token as well as the API token.

We can take this further and provide a Python wrapper, allowing data scientists and engineers to integrate this step into their workflows from either the command line or Jupyter notebooks.

Now that we have applied some basic security to the external model, let’s see how a data scientist integrates their model evaluation work with our MLSecOps pipelines.

This stage will be primarily interactive for a new model, with data scientists evaluating the model in their notebooks. We can support this mode of work by using the MLFlow API directly in evaluation code and providing helper functions to support our workflow.

These functions can help scientists manage their workload by only working with models. The book repository contains a Python library with two functions – demonstrating listing models in the evaluation stage and getting a model by its version alias (e.g., scanned).

A data scientist will use these functions to access MLFlow in alignment with our process. This will typically involve these steps:

  1. Retrieve the model from the Model Registry, setting a tag (used_by) to indicate that they are using it.
  2. Evaluate and visualize performance and log metrics and parameters.
  3. Update the status, stage, and used_by tags to let others know the model is now available to work with if it is rejected or needs further evaluations.

Let’s walk through these steps in more detail.

We can retrieve a registered model with its MLFlow wrapper using the mlflow.pyfunc.load_model method, which uses MLFLOW model URIs to access the models. We can simplify this with a simple wrapper function:

import mlflow.pyfunc
client = mlflow.tracking.MlflowClient()
def get_model_from_registry(model_name, version_alias):
model = mlflow.pyfunc.load_model(f"models:/{model_name}@{ version_alias }")
client.set_model_version_tag(model_name, version_alias, "used_by",get_user_name())
return model

We can use our model as usual. However, we must also log the evaluation for auditing and reproducibility. MLFlow has an autolog() function that allows scientists to log and trace their evaluations without any other code. The function can be used for pre-trained models and ones developed from scratch. autolog() supports most popular frameworks, and for Keras, it will monitor the model’s fit, evaluate, and predict methods, logging key metrics for either training or inference. We are only interested in inference and how well the model performs at this stage.

All you have to do is include the following statements in your notebook or code before you start training or testing a model:

import mlflow
mlflow.keras.autolog()
X_train, X_test, y_train, y_test = train_test_split(data, labels)
loss, accuracy = model.evaluate(X_test, y_test)

This is a seamless way to integrate experiment tracking and MLOps into our work. It can be customized to log more metadata, including the data we used. This will use the mlflow.start_run method before the model’s evaluation, for example:

with mlflow.start_run():
# log artifacts
mlflow.log_artifacts(images, "images")

In our case, we want to reset the used_by tag when we complete and set the status and stage tags, depending on the outcomes of our evaluations:

client.set_model_version_tag(model_name, version_alias, "used_by","")
client.set_model_version_tag(model_name, version_alias, "status","approved")
client.set_model_version_tag(model_name, version_alias, "stage","available")

Executing the code in the evaluation Notebook will make the model available to others to use.

This is pure MLOps. Where does MLSecOps fit in? In the evaluation process, the scientist will need to create an adversarial robustness test and log the results as part of the experiment.

These tests will become part of the pipeline to check out the model and further evaluate, fine-tune, or deploy it as it is. Alternatively, we can make them part of the new built-in model and data evaluation functionality of MLFlow and trigger it from our pipeline. We will explore this functionality later when we talk about integrating MLSecOps with LLMOPs (LLM Operations).

Note

When evaluating models, we will use Python libraries. We have not covered this in our example, but we will need to be scan them for vulnerabilities as part of checking in code and its associated requirements.txt, or similar dependencies file. This should be automated as part of setting up the development environment and for pull requests to the source-code repository with the evaluation notebook or code. We can use a privately hosted repository with its own scans for enhanced security and protect our development environment, as discussed in Chapter 6.

This completes our detailed example of creating an MLSecOps pipeline. Let’s briefly discuss extending this to cover other MLSecOps patterns.

The example we walked through demonstrates all the critical concepts to implement MLSecOps. Jenkins is the control plane to use with the support of MLFlow. However, unlike traditional software development, many of these will be interactive in Jupyter notebooks and require hooks with our MLSecOps.

A pipeline like the model evaluation and the pattern we described will apply here, too.

The repository contains a sample of registering and evaluating a dataset for our ingredient recognition model. There are some differences between model and data sourcing and evaluation.

For data, we can do additional checks for the file for completeness, such as the file format and internal validity (for instance, valid JSON or CSV files).

Your ML Ops platform may not support data registration and tracking. MLFlow, for instance, allows for dataset tracking and artifacts but only as part of experiments and without a registry, such as the Model Registry. This should be sufficient to get you starting for most use cases, but if data versioning is essential to your requirements and your use case is data-intensive, requiring a data processing pipeline, then you can expand your MLSecOps platform by integrating with other tools specializing in data versioning and pipelines. DVC (Data Version Control) is an open source tool designed for data versioning and control, integrating with git repositories and offering its own experiment tacking, but with a focus on data transformation. When it comes to data tracking, DVC stands out for several reasons:

  • Version control for data: DVC extends Git’s capabilities to not only source code but also to large data files. It allows you to track the history of your data changes alongside your code changes, using familiar Git commands.
  • Integration with cloud storage: DVC seamlessly integrates with various cloud storage providers (such as Amazon S3, Google Cloud Storage, and Azure Blob Storage) to store large data files while keeping the metadata in Git. This approach keeps the repository size small while enabling the sharing of large datasets.
  • Data pipelines: DVC allows you to define and version your data processing pipelines, making your ML experiments reproducible. You can easily rerun pipelines from any point, saving time and computational resources.
  • Experiment tracking: DVC provides tools to track, compare, and share ML experiments. You can track experiment history and navigate through past experiments without reruns.
  • Compatibility: DVC works alongside Git, so it does not interfere with existing repositories or require a significant change in workflow. It is compatible with various ML frameworks and languages. You can find out more about DVC at https://dvc.org/.

You may need to pull data from batch and transformation jobs such as Spark for complex use cases. You can accommodate limited cases by triggering data source scripts from your Jenkins pipeline. An example would be a step before an AV scan that triggers a remote job on Spark that pulls and computes a large amount of data, before dumping it on our staging area.

Finally, for all tools, support may be limited to standard data formats such as pandas, and you may need to write some adaptation code.

Regardless of these differences, the workflow will be similar. Once we have scanned and registered the dataset, we will evaluate and visualize the data with tests, including data quality (e.g., blurring, resolution, and label accuracy), data distribution, duplications, and anomalies. This may include running adversarial tests against the data using an approved baseline image.

From an MLSecOps point of view, it is vital that we enforce evaluations as part of the life cycle with experiment tracking to record and audit them, as well as automate them in subsequent pipelines. Initial evaluations are likely to be manual, but once we have done them once, we can automate them for subsequent data dumps, making them part of a secure life cycle.

The model development workflow is similar to that of evaluation, with some differences:

  • We retrieve models that are approved
  • We track experiments for the model.fit, and method.evaluate methods
  • We log new versions of the model to the Model Registry
  • We tag the model with appropriate status and stage tags
  • It runs automated tests – including adversarial robustness tests – and automates new ones
  • It supports approvals for promotions to higher environments

The book’s code repository contains an example of integrating notebook fine-tuning and our MLSec pipelines.

Deploying models to production in an MLSecOps world requires automation with Jenkins, MLFlow, Git, Docker, and Platform engineering, with a few separate pipelines covering the following:

  • Environment provisioning, which includes the appropriate security controls, as we discussed in Chapter 3 (e.g., private container registry, encryption, network segregation, and rate limiting). This is a typical DevOps platform function but an essential prerequisite for MSecOps to achieve its objective of secure AI.
  • The life cycle of the code that serves the model and exposes it as an API. This will include traditional DevSecOps and GitFlow workflows taking place before deployment, namely code scanning, secret scanning, and vulnerability scanning for dependencies and the Docker container used.
  • A model deployment pipeline that runs our automated model validation tests, including adversarial robustness tests. Once approval is given, the mode is promoted to the right stage. It may update the service configuration to point to the correct version, running automated and smokescreen tests against an inference API.

Note

Integrating Jenkins deployment pipelines and the MLFlow registry prevents file copying steps that are prone to misconfiguration, increasing the attack surface of a model.

This completes our walkthrough of using MLSecOps for the predictive AI flows of Foodie A sample. In the next section, we will discuss the integration of MLSecOps and our patterns with a new emerging field, LLMOps.

As discussed in Chapter 12, LLMs have significantly changed the scope of our security concerns by introducing the following:

  • Non-deterministic outputs and the importance of input as a critical attack vector for prompt injections
  • RAG, which expands the scope of input data significantly and introduces embeddings to model input preprocessing
  • Large models cover generalist domains and have advanced capabilities and understanding. They require evaluation and benchmarking beyond the relatively simple tests against predictive AI models
  • Predominantly external models and third-party hosting, which has shifted the operational focus to supply-chain validation and the previous three aspects

These differences have given rise to LLM Operations (LLMOps) to ensure that LLMs (owned or a third party) are robustly integrated into applications, providing reliable and efficient LLM services. LLMOps provide the backbone to operationalize LLM applications.

In this context, they complement MLSecOps in the same way MLOps do. We could use the LLMSecOps term here, but there are enough terms already, and MLSecOps adequately covers our concerns, with some differences and shifting of emphasis:

  • Model registration and evaluation: A third party may own and operate models, and the sourcing and evaluation will differ. Some MLOP platforms, such as MLFlow, offer placeholders to unify access and the API experience under its model deployment services. These are in addition to MLFlow’s traditional Model Registry and are part of the Registry’s functionality to manage all models, including those not physically stored in the Registry. The functionality provides the same experience across models, including both traditional models as well as OpenAI ChatGPT, Anthropic Claude, and the Hugging Face API, but brings an additional layer to learn and operate. For more information, see https://mlflow.org/docs/latest/llms/index.html. One of the benefits of using the MLOps/MLFlow layer is that the same constructs are in place, and your workflows and pipelines will work with some changes. Since the interfaces to LLMs are more or less the same prompt-based interfaces, we can correct and reuse evaluation and benchmarking test suites that automate the evaluation process, by adding tests to our pipeline. MLFlow offers its simple model.evaluate() function, with basic tests and an evaluator interface that can be used to add domain-specific evaluation benchmarks and maintain our own dashboards. A well-known AI security vendor has created a plugin that allows you to run the comprehensive Giskard LLM evaluation, which uses ChatGPT in the background against models. Giskard has a tutorial on using the feature to test LLMs, using the ICC report on climate change. This can be found at https://docs.giskard.ai/en/latest/integrations/mlflow/mlflow-llm-example.html.
  • Data sourcing and evaluation: This remains the same for the pipelines we had for predictive AI. It uses its own tests, which may contain model evaluation or new datasets, instead of the adversarial robustness tests we run against data used in predictive AI. Our data sourcing and evaluation pipelines will be critical to safeguard data used for RAG and fine-tuning. The latter will be less direct than predictive AI, since fine-tuning will be done via APIs, either the model hosting provider or the model repos (i.e., Hugging Face). In all cases, tracking experiments will be essential, and this is where investing in universal tracking in MLOps may pay higher dividends.
  • Embeddings and vector operations: A provisioning pipeline creates infrastructure to store and access embeddings generated by the LLM securely, ensuring that the vector data store is protected against unauthorized access or data leaks.
  • Prompt templates and system prompts: These are new artifacts that LLM brings, and their integrity, confidentiality, and availability are crucial with elevated security access requirements. Our pipelines will treat them as sensitive data, perform hashing and integrity checks, and deploy them. Another necessary step, similar to other data, is to automate tests to evaluate the model based on changes, and then log the results and metrics.
  • Deployment: The workflows we described for predictive AI will apply to fine-tuned models or own-hosted open-access models. They will need to be adapted to use some of the APIs of the ecosystem you use (e.g., a transformer or the vLLM deployment platform).

However, the primary area for LLMs will be the application and data life cycle and running the evaluations, DevSecOps scans for code, secrets, third-party packages, and containers, and running automated red-teaming tests against new versions.

Note

LLMOps is a new and evolving field, and its tools’ capabilities will often be incomplete. Make sure you evaluate and prototype tools before you commit to any investment.

In the next section, we will conclude our DevSecOps chapter by combining MLSecOps automation with a more advanced vulnerability management approach and SBOMs.

We have integrated model evaluation in our MLSecOps pipeline, but it is still nowhere near the thorough vulnerability testing we use for software packages. This is because vulnerability reporting and scanning are still in their infancy in AI. Databases such as airisk.io, now owned by MITRE, and standards such as the OWASP Cyclone DX ML SBOM (Signed Bill of Materials) are initiatives that will transform the MLSecOps space, allowing us to apply similar diligence to AI artifacts, including data and models.

The following diagram summarizes the vision of a robust MLSecOps pipeline to secure models:

Figure 18.10 – A reference MLSecOps pipeline

Figure 18.10 – A reference MLSecOps pipeline

It uses safety benchmarks, such as Decoding Trust to evaluate against Trustworthy AI metrics such as toxicity, bias, and so on. We use this to create an SBOM using the Cyclone DX format and signed attestations, as we discussed in Chapter 6.

Note

You may not want to run all our benchmarks all the time to avoid running high costs. This will depend on whether you evaluate a self-hosted or public image via its API. The latter will incur high costs. Running the full Decoding Trust against OpenGPT, for instance, could cost you up to $9K. You may choose to have regular runs of benchmarks that add value. The Decoding Trust we have there as an example is already run by Hugging Face and you may simply grab the results from there to feed to your pipeline when sourcing a model from it.

This section will explore an experimental pipeline to generate and use an SBOM as a model.

Our first challenge is the absence of a mature AI vulnerabilities database. airisk.io, at the time of writing, has no API to invoke. Until MITRE or Robust Intelligence provides an API, this will remain a semi-automated approach, at best using automated screen scraping or, at worse, manual creation of an airisk.io vulnerabilities manifest.

Things are easier on the vulnerabilities of model dependencies. This only applies to the models we host for predictive or generative AI. Models often declare their frameworks, which we can use to create a requirements.txt file and feed it into our SBOM. Additional metadata can be useful for governance and search purposes.

First, let’s install the required dependencies:

pip install pandas cyclonedx-python-lib

Let’s assume we run our tests against the simple-ciffar10.h5 model and use the runtime dependencies for inference; we will create a basic SBOM for this model by doing the following:

  1. Hash the model and store the hash model file and store the sha256 hex digest as a model property in
    def generate_sha256_hash(file_path):
    hash_sha256 = hashlib.sha256()
    with open(file_path, 'rb') as f:
    while chunk := f.read(8192):
    hash_sha256.update(chunk)
    return hash_sha256.hexdigest()
    # Read and hash the model file
    model_file_path = 'simple-cifar10.h5'
    model_hash = generate_sha256_hash(model_file_path)
  2. Read the model_evaluations.json file that’s produced by a benchmark like Decoding Trust and which stores the results as
    # Function to read model evaluations from model_evaluation.json
    def read_model_evaluation(file_path):
    with open(file_path, 'r') as file:
    return json.load(file)
    # Read model evaluations
    evaluation_file_path = 'model_evaluation.json'
    model_evaluations = read_model_evaluation(evaluation_file_path)
  3. Read the requirements.txt file and store the entries as
    # Function to read dependencies from requirements.txt
    def read_requirements(file_path):
    components = []
    with open(file_path, 'r') as file:
    for line in file:
    parts = line.split('>=') if '>=' in line else [line.strip(), '']
    name = parts[0].strip()
    version = parts[1].strip() if len(parts) > 1 else None
    components.append((name, version))
    return components
    # Read components from requirements.txt
    requirements_file_path = 'requirements.txt'
    components = read_requirements(requirements_file_path)
  4. Use the cyclone DX API to declare the root component as MACHINE_LEARNING_MODEL and create a BOM containing the properties
    from cyclonedx.model.bom import Bom
    from cyclonedx.model.component import Component, ComponentType
    from cyclonedx.model import Property
    bom = Bom()
    # Create root component
    model_file_name = Path(model_file_path).name
    root_component = Component(
    name=model_file_name,
    type=ComponentType.MACHINE_LEARNING_MODEL,
    bom_ref='myModel',
    properties=[Property(name='hash', value=model_hash)]
    )
    # Add model evaluation properties to root component
    for key, value in model_evaluations.items():
    root_component.properties.add(Property(name=key, value=str(value)))
    bom.metadata.component = root_component
    # Add components from requirements.txt to the BOM
    for name, version in components:
    component = Component(
    name=name,
    version=version,
    type=ComponentType.LIBRARY,
    purl=PackageURL(type='pypi', namespace=None, name=name, version=version if version else None)
    )
    bom.components.add(component)
    bom.register_dependency(root_component, [component])
  5. Serialize it to JSON and store it
    from cyclonedx.output.json import JsonV1Dot5
    # Serialize BOM to JSON using the CycloneDX library
    output_file_path = 'sbom.json'
    my_json_outputter = JsonV1Dot5(bom)
    serialized_json = my_json_outputter.output_as_string(indent=2)
    # Save the serialized JSON to a file
    with open(output_file_path, 'w') as f:
    f.write(serialized_json)
    print(f"SBOM generated and saved to {output_file_path}")

The code will create an experimental ML SBOM that is intended to demonstrate how we can use relevant information and create an artifact which we can sign digitally. We can hash the SBOM file and store the hash somewhere securely so that we know it has not been tampered with.

We now have an attestation for our model, with critical facts that are resistant to tampering and offer non-repudiation assurances.

We can also feed the SBOM file to a tool such as trivy or grype to check for dependency vulnerabilities related to our model. As technology and tooling evolve, more attributes will be captured in SBOMs, providing better assurance than self-governed model cards. They can be generated by a pipeline and its validation by SBOM-capable tools can also be integrated to a CI.

However, SBOMs are mostly designed for tool consumption and there is a value in model cards in their readability. A more advanced approach would be to create a readable version of the information in the SBOM and append it optionally with the results of vulnerability scanning to a model card and create an enhanced version of the model card, a security model card. This is a concept pioneered by Ron F. Del Rosario, Chief Security Architect at SAP ISBN. You can find out more about his work at https://github.com/guerilla7/SecurityModelCards.

This is a rapidly evolving area and vendors will provide tools. For now, ensure that you have some basic SBOMs with related information and explore how to evolve and enrich it.

In this chapter, we discussed in great depth the need for and the role of MLSecOps to integrate with traditional DevSecOps and MLOPs security, delivering a robust automated AI development and deployment platform.

We will conclude our journey into adversarial AI by discussing mature AI security and connecting it with your organization’s enterprise cybersecurity programs.