Module 8: Capstone Project — Secured AI System

1. Introduction: Capstone Project — Secured AI System

Overview

You have built seven modules of defenses: threat model, OWASP mapping, injection defense, sanitization pipeline, secrets management, PII protection, and security audit report. Each piece works individually. But a secure system is not a collection of pieces — it is an integrated architecture where each layer knows the others exist, where order matters, and where a failure in one layer triggers the next one's plan B. This module teaches you to connect everything.

The difference between "I have 7 defenses" and "I have a secure system" is integration. A firewall that blocks injection but lets PII through is an individual defense. A pipeline where the injection filter cleans the input, the PII scanner verifies there's no sensitive data, and the output validator confirms the response is safe — that is a system. You will build that system in this module.

This module is the guide's final project. There are no new concepts — there is new architecture. You will take each artifact you built in M1-M7, connect them in a coherent pipeline, resolve the conflicts between layers, configure the system for different environments, and produce a Secured AI System that is portfolio-worthy. At the end, you will have a system you can show in interviews, present to your team, or deploy as the basis for a real product.


The problem it solves

Building individual defenses is necessary but insufficient. The real problem appears when you try to make them work together. Think about what you've built so far:

  • M1: A threat model that identifies risks
  • M2: An OWASP mapping that categorizes vulnerabilities
  • M3: An injection defense pipeline that detects attacks
  • M4: A sanitization pipeline that cleans inputs/outputs
  • M5: A secrets manager that protects credentials
  • M6: A PII protection layer that redacts sensitive data
  • M7: A security audit report that validates everything

Seven artifacts. Seven folders. Zero integration. That is exactly what happens in the industry: teams that have security tools but not a security system. A 2024 Gartner study found that 65% of the organizations that suffered security breaches in their AI systems had individual defenses installed — the problem was that those defenses were not connected.

The integration challenges are specific and predictable:

Order conflicts. Does the injection detector go before or after the PII scanner? If it goes before, it may alert on redacted PII tokens like [REDACTED_EMAIL] thinking they are injection markers. If it goes after, it may not detect injections hidden in PII data. There is a correct order, and finding it requires understanding the dependencies between layers.

Interference between layers. Sanitization can modify the input in a way that the injection detector no longer recognizes patterns. The PII redactor can create placeholders that confuse the output validator. Each layer transforms the data, and the next layer receives data different from the original. Managing these transformations is the work of integration.

Error propagation. If the secrets manager fails to load an API key, what happens to the injection detector that needs to call an evaluator LLM? Does the whole pipeline stop? Does it continue without that layer? The error handling decisions between layers are critical and have no obvious answer — they depend on your risk tolerance.

Compound performance. Each layer adds latency. If the injection detector takes 200ms, the sanitizer 100ms, the PII scanner 150ms, and the output validator 200ms, you've already spent 650ms on security alone — not counting the LLM call. The performance budget needs active management.

To size the problem, look at the difference between a system with individual defenses and an integrated system:

from dataclasses import dataclass, field

@dataclass
class SecuritySystem:
    """Contrast between individual defenses and an integrated system."""
    name: str
    layers: list[str]
    has_defined_order: bool
    has_error_handling: bool
    has_layer_contracts: bool
    has_performance_budget: bool
    has_env_config: bool

    @property
    def integration_score(self) -> int:
        checks = [
            self.has_defined_order,
            self.has_error_handling,
            self.has_layer_contracts,
            self.has_performance_budget,
            self.has_env_config,
        ]
        return sum(checks)

    @property
    def assessment(self) -> str:
        score = self.integration_score
        if score == 0:
            return "FRAGMENTED — isolated defenses with no coordination"
        elif score <= 2:
            return "PARTIAL — some connections but significant gaps"
        elif score <= 4:
            return "SOLID — good integration with areas to improve"
        else:
            return "INTEGRATED — coordinated system with defense in depth"


before = SecuritySystem(
    name="Pre-integration (individual M1-M7)",
    layers=["injection", "sanitization", "pii", "secrets", "audit"],
    has_defined_order=False,
    has_error_handling=False,
    has_layer_contracts=False,
    has_performance_budget=False,
    has_env_config=False,
)

after = SecuritySystem(
    name="Post-integration (Secured AI System)",
    layers=["injection", "sanitization", "pii", "secrets", "audit"],
    has_defined_order=True,
    has_error_handling=True,
    has_layer_contracts=True,
    has_performance_budget=True,
    has_env_config=True,
)

for system in [before, after]:
    print(f"{system.name}:")
    print(f"  Score: {system.integration_score}/5")
    print(f"  State: {system.assessment}")
    print()

# Expected output:
# Pre-integration (individual M1-M7):
#   Score: 0/5
#   State: FRAGMENTED — isolated defenses with no coordination
#
# Post-integration (Secured AI System):
#   Score: 5/5
#   State: INTEGRATED — coordinated system with defense in depth

By the end of this module, your system will go from 0/5 to 5/5. That is the goal.


What will you learn in this module?

By the end of this module you will be able to:

  1. Integrate all the security layers (M1-M7) into a unified pipeline

    • You will connect injection detection, sanitization, PII protection, and output validation into a coherent sequence
    • You will resolve dependencies between layers with an explicit execution graph
    • You will produce a SecuredAIPipeline that encapsulates the whole flow
  2. Implement the complete flow of a secure request from end to end

    • You will trace a request from its entry to the final response, passing through each layer
    • You will instrument timing and logging at each step of the pipeline
    • You will verify that each transformation preserves the semantic integrity of the input
  3. Close the gaps identified in the Security Audit Report (M7)

    • You will review each audit finding and verify that the integrated system mitigates it
    • You will implement fixes for findings that the individual layers did not cover
    • You will generate a closure report that maps findings → mitigations
  4. Create a deployment checklist that covers pre-production security

    • You will define security gates for each stage: development → staging → production
    • You will include verifications for secrets, permissions, configuration, and active defenses
    • You will automate the critical verifications with executable scripts
  5. Document the security decisions with ADRs (Architecture Decision Records)

    • You will record each design decision with context, options, and justification
    • You will create a living document that explains the "why" behind each choice
    • You will ease the onboarding of new developers to the security system
  6. Create an incident response runbook for attack scenarios

    • You will define procedures for the 5 most likely incidents according to your threat model
    • You will include detection, containment, eradication, and recovery steps
    • You will create communication templates for stakeholders
  7. Update the OWASP mapping with the final state of the integrated system

    • You will review the 10 OWASP categories with the integrated defenses
    • You will document the final state: mitigated, partially mitigated, or not applicable
    • You will compare the security posture pre-integration vs post-integration
  8. Produce a portfolio-worthy Secured AI System with complete documentation

    • You will generate a security README that explains the architecture to any audience
    • You will include diagrams, metrics, and testing evidence
    • You will create a presentable repository for interviews or demos

Module roadmap

#CapsuleWhat you'll learn
01Introduction: Capstone ProjectWhy integrate, integration challenges, overview
02Integration ArchitectureComplete flow of a request, layer order, pipeline class
03Closing Audit GapsReview M7 findings, implement fixes, closure report
04Deployment ChecklistSecurity gates, pre-prod verifications, automation
05Security DocumentationADRs, security README, architecture diagrams
06Incident Response RunbookResponse procedures, communication templates
07OWASP Final AssessmentFinal mapping, pre/post comparison, coverage metrics
08Project: Secured AI SystemComplete integrated, documented, and tested system

Progression: context (01) → architecture (02) → validation (03-04) → documentation (05-06) → assessment (07) → delivery (08).


Context within the guide

Phase 1: Security Foundations (Modules 1-3)
├── Module 1: AI Security Landscape & Threat Model    ✅ Completed
├── Module 2: OWASP LLM Top 10 Deep Dive             ✅ Completed
└── Module 3: Prompt Injection — Attacks & Defenses   ✅ Completed

Phase 2: Defense Implementation (Modules 4-6)
├── Module 4: Input & Output Sanitization             ✅ Completed
├── Module 5: Secrets Management                      ✅ Completed
└── Module 6: Data Privacy & PII Protection           ✅ Completed

Phase 3: Production Security (Modules 7-8)
├── Module 7: Security Testing & Auditing             ✅ Completed
└── Module 8: Capstone Project — Secured AI System    ← YOU ARE HERE

This is the final module. Everything you built in M1-M7 converges here. There is no "Module 9" — what you produce in this module is the final result of the guide.


Prerequisites

For this module you need:

  • Modules 1-7 completed — you need all the artifacts built and validated
  • Python 3.10+ with an active virtual environment
  • Security Audit Report (M7) — especially the findings and their severity
  • Prior artifacts ready for integration

Necessary artifacts

from dataclasses import dataclass

@dataclass
class ModuleArtifact:
    """Artifact produced by a previous module, needed for integration."""
    module: str
    artifact_name: str
    artifact_type: str
    needed_for: str

artifacts = [
    ModuleArtifact("M1", "Threat Model Document", "document",
                   "Reference for risks, attackers, and critical assets"),
    ModuleArtifact("M2", "OWASP Mapping Audit", "spreadsheet",
                   "Categorization of vulnerabilities by OWASP Top 10"),
    ModuleArtifact("M3", "Injection Defense Pipeline", "code",
                   "Injection detection layer in the pipeline"),
    ModuleArtifact("M4", "Sanitization Pipeline", "code",
                   "Input/output cleaning layer in the pipeline"),
    ModuleArtifact("M5", "Secrets Management Setup", "configuration",
                   "Secure loading of API keys and system credentials"),
    ModuleArtifact("M6", "PII Protection Layer", "code",
                   "Sensitive data redaction layer in the pipeline"),
    ModuleArtifact("M7", "Security Audit Report", "document",
                   "Findings to close and a verified security baseline"),
]

print("Artifacts needed for the Capstone Project:")
print("=" * 60)
for a in artifacts:
    print(f"  [{a.module}] {a.artifact_name} ({a.artifact_type})")
    print(f"       → Use: {a.needed_for}")

# Expected output:
# Artifacts needed for the Capstone Project:
# ============================================================
#   [M1] Threat Model Document (document)
#        → Use: Reference for risks, attackers, and critical assets
#   [M2] OWASP Mapping Audit (spreadsheet)
#        → Use: Categorization of vulnerabilities by OWASP Top 10
#   [M3] Injection Defense Pipeline (code)
#        → Use: Injection detection layer in the pipeline
#   [M4] Sanitization Pipeline (code)
#        → Use: Input/output cleaning layer in the pipeline
#   [M5] Secrets Management Setup (configuration)
#        → Use: Secure loading of API keys and system credentials
#   [M6] PII Protection Layer (code)
#        → Use: Sensitive data redaction layer in the pipeline
#   [M7] Security Audit Report (document)
#        → Use: Findings to close and a verified security baseline

Technical setup

source security-guide-env/bin/activate

# All the accumulated dependencies of the guide
pip install openai pydantic python-dotenv cryptography presidio-analyzer \
  presidio-anonymizer pytest pytest-asyncio httpx

# Quick verification
python -c "
from pydantic import BaseModel
from openai import OpenAI
print('Capstone project dependencies: OK')
"

Connection with the project

This module is the final project. There is no separation between "learning" and "building" — each capsule produces a piece of the final system. Capsule 08 is the assembly and delivery.

╔═══════════════════════════════════════════════════════════════════════╗
║           CONVERGENCE OF ARTIFACTS → SECURED AI SYSTEM              ║
╠═══════════════════════════════════════════════════════════════════════╣
║                                                                       ║
║  M1: Threat Model ──────────────┐                                     ║
║  M2: OWASP Mapping ────────────┤                                     ║
║  M3: Injection Pipeline ───────┤                                     ║
║  M4: Sanitization Pipeline ────┼───→ Secured AI System (M8)          ║
║  M5: Secrets Management ───────┤    ┌─────────────────────────┐      ║
║  M6: PII Protection ──────────┤    │ ✅ Integrated pipeline   │      ║
║  M7: Audit Report ─────────────┘    │ ✅ Gaps closed           │      ║
║                                      │ ✅ Deployment checklist  │      ║
║                                      │ ✅ Documentation         │      ║
║                                      │ ✅ Incident runbook      │      ║
║                                      │ ✅ OWASP final           │      ║
║                                      │ ✅ Portfolio-ready       │      ║
║                                      └─────────────────────────┘      ║
║                                                                       ║
╚═══════════════════════════════════════════════════════════════════════╝

Each capsule of this module takes one or more previous artifacts and transforms them:

M8 CapsuleInput artifactsProduct
02M3 + M4 + M6Integrated pipeline with a defined order
03M7 findingsGaps closed with evidence
04M5 + pipelineVerified deployment checklist
05AllArchitecture documentation
06M1 (threat model)Incident response runbook
07M2 + integrated systemFinal OWASP assessment
08Everything aboveComplete Secured AI System

What this module does NOT cover

  • Cloud deployment (AWS/GCP/Azure) — the architecture is local/Docker. Cloud deployment is a separate topic with its own security guides.
  • Kubernetes and orchestration — the system runs in a single process. Horizontal scaling is outside the scope of this guide.
  • Compliance and certifications — you won't obtain SOC2 or ISO 27001 with this module. The foundations are there, but formal certification is an organizational process that involves external audits.
  • Security team management — this is an individual project. Coordinating a security team requires governance processes, role rotation, and communication frameworks that go beyond code.
  • Model training security — we don't cover model poisoning, backdoor attacks, or data poisoning of the training set. The focus is exclusively the application layer, where you as a developer have direct control.

The analogy: building a house

You've spent 7 modules building the components of a house: the walls (injection defense), the roof (secrets management), the plumbing (PII protection), the electrical wiring (sanitization), the foundations (threat model), the alarm system (OWASP mapping), and the safety inspection (audit report). Each component was built separately, tested separately, and works separately.

But a house is not a collection of components — it is an integrated system. The plumbing needs to pass through the walls without weakening them. The electricity needs to avoid the plumbing. The smoke detectors need to be connected to the electrical system. And everything needs to work when someone opens the faucet and turns on the light at the same time.

House BEFORE integration:            House AFTER integration:
┌──────────────────────┐            ┌──────────────────────┐
│ Walls ✅              │            │ ┌──── Roof ─────────┐│
│ Roof ✅               │            │ │ Electricity ←→    ││
│ Plumbing ✅           │            │ │ Plumbing   ←→     ││
│ Electricity ✅        │            │ │ Walls             ││
│ Foundations ✅        │            │ │ Foundations       ││
│ Alarm ✅              │            │ │ Alarm ←→ All      ││
│ Inspection ✅         │            │ │ Inspection        ││
│                      │            │ │ = Living system   ││
│ ❌ Nothing connected  │            │ └────────────────────┘│
└──────────────────────┘            └──────────────────────┘
  "I have pieces"                     "I have a house"

The place where houses fail is not in the individual components — it is in the connections. An electrician who doesn't coordinate with the plumber causes a short circuit. A roof that isn't sealed against the walls creates leaks. Integration failures are the most costly because they affect multiple systems simultaneously and are the hardest to diagnose.

Your Secured AI System has the same challenge. The injection detector that doesn't coordinate with the PII redactor generates false positives. The sanitizer that modifies the input before the injection detector analyzes it can mask attacks. The secrets manager that fails silently leaves the pipeline without access to the LLM. Each connection between layers is a potential failure point that needs explicit design.

The good news: unlike a real house, you can iterate quickly. If the connection between two layers doesn't work, you adjust the code, run the M7 tests, and verify in minutes. The feedback cycle is fast — take advantage of it to experiment with different configurations.

Another lesson from construction: the most resistant houses aren't the ones with the most expensive materials, but the ones with the best-designed joints. A reinforced concrete wall with poorly sealed joints is less safe than a brick wall with perfect joints. In your system, the quality of the integration (contracts between layers, error handling, logging) matters more than the sophistication of each individual layer.


Integration mindset

To integrate security defenses you need to think in systems, not in components. This is a shift in perspective from the previous modules, where each piece lived in isolation.

Think in flows, not in functions. When you built the injection detector in M3, you thought "does this function detect injection?". Now you need to think "what happens to a request that enters through the endpoint, passes through the injection detector, then the sanitizer, then the PII scanner, reaches the LLM, and comes back?". The focus moves from the individual function to the complete flow of the data through the system. Each intermediate transformation affects all the downstream layers.

Think in contracts between layers. Each layer has an implicit contract: it receives an input of a certain shape and produces an output of a certain shape. The injection detector receives plain text and produces a verdict + the text (possibly cleaned). The PII scanner receives text and produces text with redacted tokens. If a layer changes its contract (for example, the sanitizer starts returning an object instead of a string), all the downstream layers break. Defining explicit contracts between layers prevents this kind of failure.

from pydantic import BaseModel
from typing import Optional
from enum import Enum

class LayerStatus(str, Enum):
    PASSED = "passed"
    FLAGGED = "flagged"
    ERROR = "error"
    SKIPPED = "skipped"

class LayerResult(BaseModel):
    """Standard contract between layers of the security pipeline.
    Each layer receives text and returns a uniform LayerResult."""
    layer_name: str
    status: LayerStatus
    output_text: str
    metadata: dict = {}
    execution_time_ms: float = 0.0
    should_continue: bool = True

    def summary(self) -> str:
        return (f"[{self.layer_name}] {self.status.value} "
                f"({self.execution_time_ms:.0f}ms)")

# Each layer returns a LayerResult — the contract is uniform
example_result = LayerResult(
    layer_name="injection_detector",
    status=LayerStatus.PASSED,
    output_text="What are the business hours?",
    metadata={"risk_score": 0.05, "patterns_checked": 12},
    execution_time_ms=45.2,
    should_continue=True
)

print(example_result.summary())
print(f"  Continue pipeline: {example_result.should_continue}")
print(f"  Risk score: {example_result.metadata.get('risk_score')}")

# Expected output:
# [injection_detector] passed (45ms)
#   Continue pipeline: True
#   Risk score: 0.05

Think in graceful degradation. In a system of components, if one fails, it simply doesn't work. In an integrated system, if one fails, you need to decide what happens to the rest. Does the pipeline stop? Does it continue without that layer? Does it use a fallback? The answer depends on the criticality of the layer: if the secrets manager fails, you can't continue (you have no API key). If the output PII scanner fails, you could continue with a warning and extra logging because the input redaction already covered the first line of defense. These decisions must be encoded in the configuration, not improvised at the moment of failure.

Think in observability. When you have 7+ layers, debugging a problem requires knowing exactly what happened in each one. Did the injection detector let something through? Did the sanitizer modify it inadvertently? Did the PII scanner redact it incorrectly? Without structured logging in each layer, diagnosing problems in production becomes nearly impossible. Each layer must emit a LayerResult that tells the complete story of what it did with the data. The request_id that connects all the logs of a single request is your main debugging tool.


Pre-assessment

Before starting the module, evaluate your readiness. These questions cover the integration concepts you'll need:

Question 1

"Having each individual defense tested with unit tests guarantees that the integrated system is secure."

See answer

False. Unit tests verify each piece in isolation. Integration problems — order conflicts, interference between transformations, error propagation — only appear when the layers work together. You need specific integration tests that run the complete pipeline.

Question 2

"The order in which the security layers run doesn't affect the result."

See answer

False. The order is critical. If the PII redactor runs before the injection detector, the detector may interpret tokens like [REDACTED_EMAIL] as injection markers. If the sanitizer runs before the detector, it may remove evidence of an attack. The correct order derives from the dependencies between layers.

Question 3

"If a pipeline layer fails, the safest thing is always to stop the whole pipeline (fail-closed)."

See answer

It depends. Fail-closed is safer but sacrifices availability. For layers that are the only line of defense (injection detector, PII input redactor), fail-closed is mandatory. For layers that are defense in depth (PII output check, content filter), fail-open with logging can be acceptable because other layers already partially cover that function.

Question 4

"A security pipeline with 8 layers will inevitably be slow (>5 seconds)."

See answer

False. Most security layers (regex, keyword matching, sanitization) operate in <50ms. The most costly layer is the LLM call (~500-1000ms). With a well-managed performance budget, the complete pipeline can stay below 2 seconds. Also, some independent layers can run in parallel.

Question 5

"Documenting security decisions can be done at the end of the project."

See answer

False. Documenting at the end produces incomplete documentation because you forget the context and the alternatives you considered. The best architecture decisions are documented in the moment with ADRs (Architecture Decision Records) that capture the context, the evaluated options, and the justification for the choice.

Question 6

"A pipeline with 7 security layers is always safer than one with 3 layers."

See answer

Not necessarily. More layers don't mean more security if they aren't integrated correctly. A pipeline with 3 well-connected layers, with clear contracts, defined error handling, and integration tests is safer than one with 7 layers that interfere with each other, have inconsistent configuration, and silent failures. The quality of the integration matters more than the number of layers.

Question 7

"In an integrated system, each layer must work completely independently."

See answer

Partially true. Each layer must be testable independently (unit tests), but in the integrated pipeline the layers are interdependent: they share a data contract (LayerResult), respect an execution order, and their decisions affect the downstream layers. Independence is for testing; coordination is for production.


Quick glossary

TermDefinition
Security pipelineAn ordered sequence of defense layers that process a request from end to end.
LayerResultStandard contract between layers: includes status, processed text, metadata, and continuation decision.
Fail-closedStrategy where the pipeline stops if a layer fails. Maximizes security, reduces availability.
Fail-openStrategy where the pipeline continues if a non-critical layer fails. Maintains availability with logging.
Circuit breakerPattern that temporarily disables an unstable layer after repeated failures, avoiding cascades.
Performance budgetTime budget assigned to each pipeline layer. Overall target: < 2 seconds.
Defense in depthStrategy of multiple layers where each one covers gaps from the previous ones.
ADRArchitecture Decision Record — a document that captures the context, options, and justification of a design decision.
Graceful degradationThe system's ability to keep working with reduced functionality when a component fails.
Contract between layersAgreement on the input/output format between two consecutive pipeline layers.
Hot-reloadThe ability to change the pipeline configuration without restarting the service.
Correlation IDUnique identifier (request_id) that connects all the logs of a single request across the layers.
Integration testTest that verifies the behavior of the complete pipeline, not of individual layers.

How is this module structured?

Unlike the previous modules where each capsule taught a new concept, this module follows a progressive construction flow. Each capsule produces an artifact that integrates into the final system:

Day 1: Context and architecture (Capsules 01-02)
├── Understand the integration challenges
├── Design the complete flow of the request
├── Implement SecuredAIPipeline
└── Resolve order conflicts between layers

Day 2: Validation and preparation (Capsules 03-04)
├── Close gaps from the Security Audit Report (M7)
├── Verify each mitigation with evidence
├── Create the deployment checklist
└── Automate pre-production verifications

Day 3: Documentation and procedures (Capsules 05-06)
├── Write ADRs for the architecture decisions
├── Generate the security README
├── Create the incident response runbook
└── Define escalation procedures

Day 4: Assessment and delivery (Capsules 07-08)
├── Update the OWASP mapping with the final state
├── Compare the pre/post integration posture
├── Assemble the complete Secured AI System
└── Verify that the system is portfolio-ready

You don't need to follow this schedule exactly. What matters is that each capsule builds on the previous one: you can't close audit gaps (day 2) without the integrated pipeline (day 1), and you can't document decisions (day 3) without having made them (days 1-2).


Common mistakes

"I already have all the pieces, integration is trivial"

Integration is where the most subtle problems appear. Each piece works in isolation, but when you connect them you discover order conflicts, interference between transformations, and edge cases that no individual piece contemplated. Reserve the same time for integration as you dedicated to building the pieces — no less.

"I'm going to integrate everything at once"

Integrating 7 layers simultaneously makes it impossible to diagnose problems. If something fails, which of the 7 layers caused the failure? Integrate incrementally: start with 2 layers, verify they work, add a third, verify again. This approach gives you a working system at each step and makes problems easy to locate.

"The order of the layers doesn't matter"

The order matters enormously. A PII scanner that runs before the injection detector can redact tokens that the detector needed to see to identify an attack. A sanitizer that runs after the detector can clean evidence of a detected attack. The correct order derives from the dependencies between layers — capsule 02 teaches you exactly what it is and why.

"I don't need integration tests, I already tested each layer"

The unit tests of each layer verify that the layer works in isolation. The integration tests verify that the layers work together. A unit test of the injection detector verifies that it detects "ignore instructions". An integration test verifies that a malicious prompt is detected, sanitized, processed by the LLM, and the response is validated — all in sequence, with no leaked data or false positives.

"I'll do the documentation at the end"

Documenting at the end means documenting from memory, which produces incomplete and inaccurate documentation. Document each decision when you make it: why you chose that layer order, why one layer can fail gracefully and another can't, what alternatives you considered and discarded. Simultaneous documentation is more accurate and requires less total effort than reconstructing the reasoning weeks later.


Summary

  • 🔗 Integrating individual defenses into a coherent system is the final and most complex challenge of the guide
  • ⚡ Integration problems (order conflicts, interference between layers, error propagation) don't exist when the pieces are isolated — they only appear when you connect them
  • 📐 Each layer needs an explicit contract (expected input, produced output, behavior on errors) using a model like LayerResult
  • 🏗️ Integration must be incremental: 2 layers first, then 3, verifying at each step with integration tests
  • 🔄 Graceful degradation (what happens when a layer fails) must be designed and encoded, not improvised at the moment of failure
  • 📊 The pipeline's total performance budget should be < 2 seconds including all the security layers and the LLM call
  • 📝 This module takes the 7 previous artifacts (M1-M7) and transforms them into a portfolio-worthy Secured AI System
  • 🎯 At the end, you'll have a complete, documented, tested system ready to present in interviews or demos

Next capsule: In capsule 02 you'll design the Integration Architecture — the complete flow of a secure request, the layers' execution order, and the SecuredAIPipeline class that orchestrates it all.


Additional resources

  1. OWASP Application Security Verification Standard — Security verification standard for applications
  2. Building Secure AI Systems (Microsoft) — Microsoft's guide to building secure AI systems
  3. NIST AI Risk Management Framework — NIST's AI risk management framework
  4. Architecture Decision Records (ADR) — Reference for documenting architecture decisions
  5. Incident Response Planning (SANS) — SANS handbook for incident response
  6. Defense in Depth Strategy (CISA) — CISA's defense in depth strategy
  7. LLM Security Best Practices (OWASP) — Security best practices for LLMs
  8. Secure Software Development Framework (NIST) — Secure software development framework

Created: March 2026 Version: 1.0