# Getting an AI system through security review

> Build the pack a CISO expects for an AI system on SAP (data flow, threat model, DPIA screening, questionnaire, pen-test scope) and close its gaps first.

- Course: Orchestrate, Unit 11 · AI security and governance
- Page: https://erpfde.com/topics/getting-an-ai-system-through-security-review/
- Updated: 2026-11-25
- Reading time: Foundational 9 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

Before an AI system touches real company data, someone in information security has to agree to it. That person, often reporting to the chief information security officer (CISO), wants to know five things:

1. **Where does the data go?** Every system, every hop, every region.
2. **Who can use it, and how do they prove who they are?** People and machines.
3. **What is kept, and for how long?** Logs, prompts, answers, copies.
4. **What could go wrong, and what stops it?** A threat model.
5. **Has anyone tried to break it?** And what may they test?

Teams that fail security review rarely fail because the AI is unsafe. They fail because they can't answer those questions with evidence.

The fix is a **review pack**: a small set of documents built from one description of the system, so every answer points at the same facts. This topic shows what goes in it and how to find the gaps before the reviewer does.

### Why it matters to the business

Take Calder Pumpworks, the fictional pump maker this course follows. Its accounts payable (AP) team runs an invoice triage agent, `AGT_INV_TRIAGE`. It reads supplier invoices that are blocked for payment, explains why, and drafts a next step. An AP accountant decides. The agent never releases an invoice.

The pilot worked. Then Calder planned to switch it on for both company codes: `CP10` in the US, and `CP20` in Germany once it joins the same S/4HANA system. Calder's security team sent a questionnaire. The project team filled it in from memory in an afternoon. The review came back with six blocking findings:

- **The gateway's admin console used local passwords**, not the company's single sign-on (SSO).
- **Nobody knew where the fallback model ran.** The team had added a second model for outages; its region was never recorded.
- **Full prompts and answers were being kept in a cloud storage bucket** for troubleshooting, with no deletion rule. Those prompts hold supplier contact names and emails.
- **Three threats on that bucket had no control** at all.

None was hard to fix once someone owned it. Together they cost the go-live a month, surfacing one review cycle at a time.

The business case for doing this well is simple: **security review is on the critical path of every AI go-live.** A pack that is right the first time takes one review cycle instead of three.

### How SAP does it

When the AI runs on SAP's platform, part of each answer is SAP's, and part is yours. As of November 2026, these SAP pages are where the SAP side comes from:

- **Training and providers.** SAP's training material says external model providers reached through SAP services such as the generative AI hub are contractually restricted in how they use customer data ([SAP Learning](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/third-party-ai-providers-and-transparency)). In its section on SAP's EU AI Cloud it adds that SAP doesn't use customer data to train third-party models ([SAP Learning](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/data-residency-and-digital-sovereignty-for-ai)). Your contract is what binds; the training page tells you what to look for in it.
- **Residency.** SAP says data residency for generative AI depends on the architecture: processing may happen on SAP infrastructure or at an approved external provider, depending on the use case and configuration. Regional options are "subject to availability" ([SAP Learning](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/data-residency-and-digital-sovereignty-for-ai)). So you must record the region of each model you use, not of "SAP" as a whole.
- **Documents for the reviewer.** SAP's training points reviewers to the sub-processor lists and data transfer factsheets on the SAP Trust Center ([SAP Learning](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/third-party-ai-providers-and-transparency)); ask your SAP account team for the compliance documents that cover the services and regions you use.
- **Shared responsibility.** SAP's Trust Center says SAP tests its own services, including third-party penetration tests and red teaming, while customers manage user access inside their solution and detect threats in their own applications ([SAP Trust Center](https://www.sap.com/about/trust-center/security.html)).
- **SSO.** SAP Cloud Identity Services' Identity Authentication connects SAP cloud apps to your corporate identity provider over SAML 2.0 or OpenID Connect ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/introduction-to-identity-and-access-management-on-sap-btp-51c1677.md)).
- **Testing SAP's services.** Penetration testing SAP cloud services needs SAP's approval first; SAP's knowledge base article 3080379 describes how customers request it ([SAP KBA 3080379](https://userapps.support.sap.com/sap/support/knowledge/en/3080379), public preview; the steps need an SAP for Me login).

Everything you build around SAP's services stays yours to answer for.

### The review pack on one page

| Document | The reviewer's question | Who writes it | Who signs |
| --- | --- | --- | --- |
| **Data flow diagram** | Where does each kind of data go, and across which boundaries? | Solution architect | Security architect |
| **Threat model** | What could go wrong at each boundary, and what stops it? | Architect with security | Security architect |
| **DPIA screening** (and a full DPIA if needed) | Is this high-risk processing of personal data? | Process owner with the data protection officer | Data protection officer |
| **Questionnaire answers** | The security team's standard questions, each with evidence | Project lead | CISO's team |
| **Penetration test scope** | What may testers attack, and what needs a provider's approval? | Security lead | CISO's team |
| **Gap list and risk acceptance** | What is still open, and who accepted it? | Project lead | Business owner and CISO |

A **DPIA** (data protection impact assessment) is the privacy check European data protection law requires before high-risk processing of personal data. Calder needs to screen for one because the German company `CP20` is in scope.

Two rules make the pack work. First, every document is built from **one description of the system**, so the diagram, the threat model and the questionnaire never disagree. Second, every answer names its **evidence**: a configuration export, a test report, a contract clause. "Yes, encrypted" without evidence is a finding.

> **Note** **For functional consultants.** The pack needs you in three places. You describe the process and the personal data in it (the DPIA's "nature, scope, context and purpose"). The human approval step is listed as a security control, so it becomes UAT test cases: an accountant releases, the agent can't. And roles you design for the agent and the accountants are evidence the reviewer will ask to see.

### Questions to ask

Ask your project team:

- Can we draw every component and data flow on one page, with the region and owner of each?
- Which stores keep prompts, answers or logs? For how long, and what deletes them?
- Does every person sign in through SSO, including administrators of our own tools?
- Which machine identities call SAP, and what can each one change?
- Is there a list of threats per boundary, each with a control and an owner?

Ask your vendor or partner:

- Which models do you use, including fallbacks, and in which regions do they run?
- Do you or your model providers keep or train on our prompts? Show us the contract clause.
- Which questionnaire can you answer with evidence: CSA's AI-CAIQ, ISO/IEC 42001, your own?
- What may our testers attack, and whose approval do we need first?

### Common misconceptions

- **"It runs on SAP, so SAP's certificates cover it."** They cover SAP's services. Your app, gateway, logs and identities are yours to evidence.
- **"We don't store prompts."** Check every troubleshooting switch. Observability, debug logs and gateways often keep full payloads.
- **"Masking means no personal data leaves us."** Masking applies where you configure it. A copy taken before masking, or a log that keeps the original, is still personal data.
- **"A DPIA is always required for AI."** Using AI is one screening criterion. It usually takes two before a DPIA is indicated; record the screening either way.
- **"The pen-test firm can test everything we use."** Testing a provider's service without its approval can break your contract. Scope Calder-built endpoints; request approval for the rest.

### Key terms

- **Security review:** the check by an information security team before a system goes live or changes materially.
- **Review pack:** the set of documents that answers a security review with evidence.
- **Data flow diagram (DFD):** a picture of components, stores and the data that moves between them, with trust boundaries.
- **Trust boundary:** a line where data passes between parties or environments that trust each other differently.
- **Threat model:** a list of what could go wrong at each part of a system, with the control that addresses each threat.
- **STRIDE:** a checklist of six threat types: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege.
- **DPIA:** data protection impact assessment, required under GDPR before processing that is likely to be high risk for people.
- **AI-CAIQ:** the Cloud Security Alliance's questionnaire for AI services, aligned to its AI Controls Matrix.
- **Residual risk:** what is left after controls, which a named owner must accept.

### Check yourself

1. Why do AI projects most often stall in security review?
   - A. The models are found to be unsafe for most business processes
   - B. The team can't back its answers about data with evidence
   - C. Reviewers refuse every system that uses an external model provider
   - D. Security teams only review systems that SAP has certified for AI

   Answer: B. The questions are predictable: where data goes, who has access, what is kept, what could go wrong. Stalls come from answers given from memory without evidence, which return as findings one cycle at a time.

2. Calder's agent runs on SAP's AI platform. Which part of the review can SAP's own documents answer?
   - A. How long Calder's gateway keeps its audit records and who reads them
   - B. Whether the admin console of Calder's gateway uses single sign-on
   - C. How SAP's managed services and their providers handle Calder's data
   - D. Which Calder machine identities may read invoices in S/4HANA

   Answer: C. Responsibility is shared. SAP's Trust Center and contracts cover SAP's services and its providers, while Calder's own app, gateway, logs and identities need Calder's evidence.

3. A partner says "we don't store your prompts". Which follow-up matters most?
   - A. Ask which model they use for the main answer in production
   - B. Ask about every log and debug store, and its retention
   - C. Ask whether the prompts are written in English or German
   - D. Ask how many tokens a prompt uses on average each month

   Answer: B. Full prompts often end up in observability stores, debug logs or gateways switched on for troubleshooting. Calder's own finding was a bucket of full payloads with no deletion rule.

4. Calder's AI use counts as one DPIA screening criterion and no other criterion applies. What should happen?
   - A. A full DPIA is required, because any use of AI requires one
   - B. Nothing, because one criterion means no privacy work is needed
   - C. The regulator must be consulted before the system can go live
   - D. Record the screening; two criteria usually indicate one

   Answer: D. Using AI is one screening criterion, and it usually takes two before a DPIA is indicated. Either way the screening and its reasoning are recorded, so the decision can be shown later.

5. Your pen-test firm wants to test the generative AI hub and Identity Authentication too. What do you do?
   - A. Let them test, since your subscription covers security testing
   - B. Remove all SAP services and Calder's own endpoints from scope
   - C. Scope Calder's endpoints; request SAP's approval for SAP's
   - D. Ask SAP to run the test on your behalf and share the full report

   Answer: C. Testing SAP cloud services needs SAP's approval first, through the process in SAP's knowledge base. Calder-built endpoints such as the approval UI and the gateway can be tested under Calder's own authority.

6. Why should the data flow diagram, threat model and questionnaire be built from one description of the system?
   - A. Reviewers only accept documents produced by one tool
   - B. So the documents can't contradict each other
   - C. Because a single file is faster for the model to process
   - D. So the pack can skip the evidence column for each answer

   Answer: B. When each document is written separately, a region or store changes in one and not the others, and the reviewer finds the contradiction. One description keeps every answer consistent and makes gaps visible.

## Deep layer

### Mental model: the reviewer reads the data flow first

A security reviewer reads your system the way water flows: from where data enters to everywhere it ends up. Every question in a questionnaire is a question about some edge or box on that path. So build the pack the same way:

1. **Describe the system once**, as data: components, trust zones, data flows, stores, data classes, identities and controls.
2. **Generate the documents from that description**: the diagram, the threat list, the DPIA screening, the questionnaire answers and the test scope.
3. **Let the description fail loudly.** A store with no retention, a component with no region, a threat with no control, an admin login that isn't SSO: each is a gap you find before the reviewer does.

The review then becomes a conversation about decisions and residual risk, not a hunt for facts.

### How it works

```mermaid
flowchart LR
  D[System<br/>description] --> DFD[Data flow<br/>diagram]
  D --> TM[Threat model]
  D --> DP[DPIA<br/>screening]
  D --> Q[Questionnaire<br/>answers]
  D --> PT[Pen-test<br/>scope]
  TM --> G{Gaps?}
  DP --> G
  Q --> G
  G -->|yes| D
  G -->|no| R[Review and<br/>risk acceptance]
```

#### The data flow diagram and trust boundaries

A data flow diagram has four kinds of element: **external entities** (people or systems you don't control), **processes** (code you run), **data stores** and **data flows**. Group elements into **trust zones**: the users' devices, your platform account, SAP's AI service, the model provider, S/4HANA, the identity service. A flow that crosses from one zone to another crosses a **trust boundary**, and those are where most threats sit.

Label each flow with the data it carries. Calder uses three data classes: invoice and PO data (amounts, items, block reasons; not personal), supplier contact names and emails found in invoice texts (personal), and AP user IDs with their approvals (personal). The classes decide which flows matter for privacy.

#### The threat model: STRIDE per element

STRIDE gives six threat types to ask about. The classic way to apply it is **per element**: data flows face tampering, information disclosure and denial of service; processes face all six; stores face tampering, information disclosure and denial of service (and repudiation when they hold logs). This lab trims that table to keep the list short: flows that cross a boundary get T, I and D; your own processes get S, R and E; your stores get T and I. Add the rest where they fit.

| Letter | Threat | The property it attacks | A Calder example |
| --- | --- | --- | --- |
| S | Spoofing | Authentication | Someone calls the agent's endpoint as an AP accountant |
| T | Tampering | Integrity | A record in the gateway's audit log is changed after the fact |
| R | Repudiation | Non-repudiation | Nobody can show who approved a release draft |
| I | Information disclosure | Confidentiality | Supplier contacts sit readable in a storage bucket |
| D | Denial of service | Availability | A flood of calls exhausts the team's model budget |
| E | Elevation of privilege | Authorization | The agent releases an invoice it should only explain |

STRIDE predates language models, so add AI-specific questions for any process that calls a model. This course uses four, each taught earlier in Unit 11:

- **AI1** instructions hidden in business data steer the agent ([prompt injection](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/));
- **AI2** the agent calls a tool or changes data beyond its task ([agent permissions](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/));
- **AI3** personal data reaches the model or its logs unmasked ([data security and PII](https://erpfde.com/topics/data-security-and-pii/));
- **AI4** loops or abuse drive cost up ([AI gateways](https://erpfde.com/topics/ai-gateways-for-model-and-agent-traffic/)).

Each threat gets at least one **control** with an owner and **evidence**. A threat with no control is a gap. A threat you decide not to control is a residual risk, accepted by name.

#### Identity: people, machines and administrators

Reviewers ask three separate identity questions, and AI systems often answer only the first:

- **Users.** Do people sign in through the company's identity provider? On SAP BTP that is Identity Authentication acting as a proxy to the corporate identity provider over SAML 2.0 or OpenID Connect ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/introduction-to-identity-and-access-management-on-sap-btp-51c1677.md)). SAP recommends a Cloud Identity Services tenant over the default identity provider, and every BTP customer is entitled to at least two (test and production).
- **Machines.** Which non-human identities call SAP, and with what rights? Calder's agent reads S/4HANA with its own service identity and read-only APIs; releases happen only under the accountant's own user. [Roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/) showed why: an agent role that can release invoices is a high finding.
- **Administrators.** Who can change the gateway's policies, the agent's prompt or the observability settings, and how do they sign in? This is the question Calder's v1 pack missed: the gateway console had local accounts.

#### Residency: every hop, every model

"Where is our data processed?" has one answer per component, not one per vendor. SAP says generative AI processing may run on SAP's infrastructure or at an approved external provider, depending on the use case and configuration, with regional options subject to availability ([SAP Learning](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/data-residency-and-digital-sovereignty-for-ai)). So record the region of the orchestration service, of each model in the chain, including fallbacks from [model routing](https://erpfde.com/topics/model-routing-with-fallbacks-in-the-sap-cloud-sdk/), and of each store. A fallback that only runs during an outage still processes real data when it runs.

#### Retention: find every copy

List every place a prompt, answer or log can rest, and give each a period and a deletion method. The usual suspects:

- the gateway's audit log ([AI gateways](https://erpfde.com/topics/ai-gateways-for-model-and-agent-traffic/));
- the agent's memory or checkpoints, if it has them;
- **inference observability** in generative AI hub, which records a call only when the request headers ask for it, and in full mode keeps the request and response payloads in an S3 object store you provide ([SAP Developers](https://developers.sap.com/tutorials/ai-core-genaihub-inference-observability.html)).

The last one is a common trap. SAP's tutorial says deleting observability records removes the metadata, while the request, response and feedback in your object store stay. As [batch and observability in the generative AI hub](https://erpfde.com/topics/batch-and-observability-in-the-generative-ai-hub/) explains, those payloads are stored as sent, so treat them as holding everything the call held. The deletion method is a lifecycle rule on your bucket, not SAP's delete call.

#### The DPIA screening

GDPR Article 35 requires a DPIA before processing that is likely to be high risk to people. The UK regulator's guidance sets out nine European screening criteria (from the WP248 guidelines) and says that, in most cases, two of them together indicate a DPIA; its own list names innovative technology, including AI ([ICO](https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/accountability-and-governance/data-protection-impact-assessments-dpias/when-do-we-need-to-do-a-dpia)). Supervisory authorities publish their own lists, so your data protection officer decides which applies; for `CP20` that is a German authority.

If a DPIA is needed, the ICO describes seven steps: identify the need, describe the processing (nature, scope, context and purposes), consider consultation, assess necessity and proportionality, identify and assess risks, identify measures, and sign off with the residual risk recorded ([ICO](https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/accountability-and-governance/data-protection-impact-assessments-dpias/how-do-we-do-a-dpia)). The review pack's job is the input: the description, the data classes, the flows and the controls. The DPO owns the assessment.

> **Note** The DPIA is a privacy check, not the EU AI Act's risk classification. Calder's invoice agent explains supplier invoices; it isn't an Annex III use. See [the EU AI Act for SAP customers](https://erpfde.com/topics/eu-ai-act-for-sap-customers/), and for US processing [US state AI laws](https://erpfde.com/topics/us-state-ai-laws-for-sap-deployments/).

#### The questionnaire

Most security teams send a questionnaire, either their own or a standard one. For AI services the Cloud Security Alliance published the AI Controls Matrix (AICM) v1.1 in July 2026: 247 control objectives in 18 domains, built as a superset of its Cloud Controls Matrix, with a 320-question AI-CAIQ for self-assessment or vendor assessment, and mappings to ISO/IEC 42001, the EU AI Act and the NIST AI RMF ([CSA](https://cloudsecurityalliance.org/blog/2026/07/14/ai-controls-matrix-v1-1-strengthening-the-foundation-for-trustworthy-ai)). You don't need to answer 320 questions to get through an internal review. You need answers that come from your system description and point at evidence, so a standard questionnaire becomes a mapping exercise rather than a writing one.

#### The pen-test scope

A penetration test scope lists what testers may attack and under whose authority. For an AI system on SAP:

- **In scope under your authority:** the endpoints you built and run (the approval UI, the agent's API, the gateway), plus AI tests such as injection through invoice texts. [Red-teaming your AI system](https://erpfde.com/topics/red-teaming-your-ai-system/) covers how to run those.
- **SAP services:** only after SAP approves; SAP's knowledge base article 3080379 explains how to request it ([SAP KBA](https://userapps.support.sap.com/sap/support/knowledge/en/3080379)).
- **Model providers reached through SAP:** out of scope; you test through your own endpoints instead.

### Build it yourself: a review pack for the invoice triage agent

> **Before you start** Complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 11](https://erpfde.com/topics/set-up-for-unit-11/). This lab needs only Python's built-in modules.

You will describe Calder's invoice triage agent once, as a JSON file, and let a script build the whole review pack from it: a data flow diagram, a threat model, a DPIA screening, answers to sixteen review questions and a pen-test scope. The first version is the one Calder's team submitted, and the script finds the same six gaps the reviewers found. Then you load the corrected version and watch the pack come out clean.

```mermaid
flowchart LR
  J[invoice_triage_v1.json<br/>one description] --> S[review_pack.py build]
  S --> P[pack_v1/<br/>dataflow, threats, DPIA,<br/>questionnaire, scope, gaps]
  S -->|exit code 1| X[NOT READY]
  J2[invoice_triage_v2.json<br/>gaps fixed] --> S2[review_pack.py build]
  S2 -->|exit code 0| OK[READY]
```

> **Note** **New words.** **JSON** is a text format for structured data, with `{ }` for objects and `[ ]` for lists. **CSV** is a table saved as text, one row per line, which any spreadsheet opens. An **exit code** is the number a program returns when it ends: 0 means success, anything else means "stop". **Mermaid** is a text format for diagrams that GitHub and VS Code (with an extension) draw as pictures.

#### What you need

- Your course folder `orchestrate-course` with its `.venv`. Python 3.10 or newer.
- No account, no internet, no new libraries. Cost: free.
- About 30 minutes.

> **Note** Calder, its agent, regions, endpoints, users, controls and volumes are fictional course values. The STRIDE types, the nine DPIA screening criteria and the review questions' themes come from the sources in this topic; the sixteen questions themselves are written for this course, not copied from any standard questionnaire.

#### Step 1: Open your course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

Run every command in this topic from the course folder, not from inside `unit11`.

#### Step 2: Save the script

1. In VS Code's Explorer, right-click the `unit11` folder and choose **New File**. Name it `review_pack.py`.
2. Paste this code and save (**Ctrl+S** on Windows, **Cmd+S** on macOS).

```python
"""Build a security review pack for an AI system from one JSON description.

Usage (from the course folder):
  python unit11/review_pack.py sample            # write the system as first submitted (v1)
  python unit11/review_pack.py sample --fixed    # write the corrected system (v2)
  python unit11/review_pack.py build unit11/review/invoice_triage_v1.json

Built-in modules only. No randomness: the same input gives the same pack.
All Calder names, regions and values are fictional course values.
"""
import argparse
import csv
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
REVIEW = HERE / "review"

# STRIDE per element, trimmed from the classic per-element table (which gives
# processes all six and stores T, I, D): which threat types to ask about here.
STRIDE_NAMES = {
    "S": "Spoofing", "T": "Tampering", "R": "Repudiation",
    "I": "Information disclosure", "D": "Denial of service",
    "E": "Elevation of privilege",
}
PER_ELEMENT = {"flow": "TID", "process": "SRE", "store": "TI"}
# Extra questions for a process that calls a language model (course list).
AI_THREATS = {
    "AI1": "Instructions hidden in business data steer the agent (prompt injection)",
    "AI2": "The agent calls a tool or changes SAP data beyond its task (excessive agency)",
    "AI3": "Personal or confidential data reaches the model or its logs unmasked",
    "AI4": "Runaway loops or abuse drive model cost up (unbounded consumption)",
}
# The nine screening criteria (WP248, as listed in the ICO's DPIA guidance).
DPIA_CRITERIA = [
    ("evaluation_or_scoring", "Evaluation or scoring of people"),
    ("automated_decision_significant_effect", "Automated decisions with legal or similar significant effect"),
    ("systematic_monitoring", "Systematic monitoring"),
    ("sensitive_data", "Sensitive or highly personal data"),
    ("large_scale", "Data processed on a large scale"),
    ("matching_datasets", "Matching or combining datasets"),
    ("vulnerable_people", "Data about vulnerable people"),
    ("innovative_technology", "Innovative use of technology (including AI)"),
    ("prevents_rights_or_service", "Prevents people using a right, service or contract"),
]


def sample_system(fixed: bool) -> dict:
    """Calder's invoice-triage agent as the team first submitted it (v1) or after fixes (v2)."""
    system = {
        "system": {
            "id": "AGT_INV_TRIAGE",
            "name": "Calder invoice triage agent",
            "version": "v2" if fixed else "v1",
            "purpose": "Explain why a supplier invoice is blocked for payment and draft a next step "
                       "for an AP accountant, who decides. The agent never releases an invoice.",
            "owner": "AP process owner, Calder Pumpworks Inc.",
            "company_codes": ["CP10", "CP20"],
            "allowed_regions": ["us", "eu"],
            "submitted": "2026-11-23",
        },
        "data_classes": {
            "invoice": {"label": "Supplier invoice and PO data (amounts, items, block reasons)", "personal": False},
            "contact": {"label": "Supplier contact names and emails in invoice texts", "personal": True},
            "user_id": {"label": "AP user IDs and their approvals", "personal": True},
        },
        "components": [
            {"id": "E1", "name": "AP accountant", "kind": "person", "zone": "users", "operator": "Calder"},
            {"id": "P1", "name": "Approval UI", "kind": "process", "zone": "calder-btp", "operator": "Calder",
             "region": "us", "auth": "sso", "endpoint": "https://ap-triage.calder.example"},
            {"id": "P2", "name": "Invoice triage agent", "kind": "process", "ai": True, "zone": "calder-btp",
             "operator": "Calder", "region": "us", "auth": "service-identity AGT_INV_TRIAGE",
             "endpoint": "https://ap-triage.calder.example/agent"},
            {"id": "P3", "name": "AI gateway", "kind": "process", "zone": "calder-btp", "operator": "Calder",
             "region": "us", "auth": "agent keys", "admin_auth": "sso" if fixed else "local accounts",
             "endpoint": "https://ai-gw.calder.example"},
            {"id": "X1", "name": "Generative AI hub orchestration", "kind": "external", "zone": "sap-ai",
             "operator": "SAP", "region": "us"},
            {"id": "X2", "name": "Primary model (alias fast)", "kind": "external", "zone": "provider",
             "operator": "Model provider via SAP", "region": "us", "trains_on_data": False},
            {"id": "X3", "name": "Fallback model", "kind": "external", "zone": "provider",
             "operator": "Model provider via SAP", "region": "us" if fixed else None, "trains_on_data": False},
            {"id": "X4", "name": "S/4HANA (CP10, CP20 after rollout)", "kind": "external", "zone": "sap-erp",
             "operator": "SAP (RISE)", "region": "us"},
            {"id": "X5", "name": "Identity Authentication with Calder's corporate IdP", "kind": "external",
             "zone": "identity", "operator": "SAP and Calder", "region": "us"},
            {"id": "S1", "name": "Gateway audit log", "kind": "store", "zone": "calder-btp", "operator": "Calder",
             "region": "us", "retention_days": 400, "deletion": "nightly purge job"},
            {"id": "S2", "name": "Inference observability payloads (object store)", "kind": "store",
             "zone": "calder-btp", "operator": "Calder", "region": "us",
             "retention_days": 30 if fixed else None, "deletion": "bucket lifecycle rule" if fixed else None},
        ],
        "flows": [
            {"id": "F01", "from": "E1", "to": "X5", "what": "Sign-in", "data": ["user_id"], "protocol": "OIDC"},
            {"id": "F02", "from": "E1", "to": "P1", "what": "Open worklist, approve drafts", "data": ["user_id", "invoice"], "protocol": "HTTPS"},
            {"id": "F03", "from": "P1", "to": "P2", "what": "Triage request with user token", "data": ["user_id", "invoice"], "protocol": "HTTPS"},
            {"id": "F04", "from": "P2", "to": "X4", "what": "Read invoice, PO, history", "data": ["invoice", "contact"], "protocol": "HTTPS OData, OAuth client credentials"},
            {"id": "F05", "from": "P2", "to": "P3", "what": "Model call", "data": ["invoice", "contact"], "protocol": "HTTPS"},
            {"id": "F06", "from": "P3", "to": "S1", "what": "Audit record per call", "data": ["user_id"], "protocol": "internal"},
            {"id": "F07", "from": "P3", "to": "X1", "what": "Orchestration call with masking", "data": ["invoice", "contact"], "protocol": "HTTPS, OAuth"},
            {"id": "F08", "from": "X1", "to": "X2", "what": "Masked prompt", "data": ["invoice"], "protocol": "HTTPS (SAP-managed)"},
            {"id": "F09", "from": "X1", "to": "X3", "what": "Masked prompt on fallback", "data": ["invoice"], "protocol": "HTTPS (SAP-managed)"},
            {"id": "F10", "from": "X1", "to": "S2", "what": "Full request and response payloads", "data": ["invoice", "contact"], "protocol": "HTTPS (S3 API)"},
            {"id": "F11", "from": "P1", "to": "X4", "what": "Release by the accountant, as the accountant", "data": ["invoice", "user_id"], "protocol": "HTTPS OData, principal propagation"},
        ],
        "processing": {
            "nature": "Reads blocked supplier invoices and related purchase orders; a model explains the block; a person decides.",
            "scope": "About 2,500 invoices a month in CP10 and CP20; supplier contacts and about 12 AP users.",
            "context": "Employees of Calder in the US and Germany; supplier staff named in invoice texts.",
            "purpose": "Faster, more consistent handling of blocked invoices.",
            "criteria": {
                "innovative_technology": "Uses a language model to explain blocks and draft next steps.",
            },
        },
        "controls": [
            {"id": "C01", "name": "TLS 1.2 or higher on every network flow", "covers": ["F*:T", "F*:I"],
             "owner": "Platform team", "evidence": "TLS scan report; SAP Learning data protection page for SAP services"},
            {"id": "C02", "name": "SSO through Identity Authentication and the corporate IdP", "covers": ["P1:S", "F01:*", "F02:*"],
             "owner": "Identity team", "evidence": "IAS application config export"},
            {"id": "C03", "name": "Agent has its own service identity with read-only APIs", "covers": ["P2:S", "P2:E", "F04:*"],
             "owner": "SAP security", "evidence": "Communication arrangement and role export for AGT_INV_TRIAGE"},
            {"id": "C04", "name": "Gateway: per-agent keys, tool allow-list, rate limit, team budget", "covers": ["P3:S", "P3:E", "F05:*", "AI2", "AI4"],
             "owner": "AI platform team", "evidence": "Gateway policy file and test run"},
            {"id": "C05", "name": "Hash-chained audit log of every model and tool call", "covers": ["P1:R", "P2:R", "P3:R", "F06:*", "S1:T"],
             "owner": "AI platform team", "evidence": "Audit log sample and chain verification output"},
            {"id": "C06", "name": "Orchestration masking and input and output filters", "covers": ["F07:*", "AI1", "AI3"],
             "owner": "AI platform team", "evidence": "Orchestration config; red-team report"},
            {"id": "C07", "name": "Human approval: release only by the accountant's own user", "covers": ["P1:E", "F03:*", "F11:*", "AI1", "AI2"],
             "owner": "AP process owner", "evidence": "Role design; UAT test cases"},
            {"id": "C08", "name": "SAP-managed provider calls under SAP's contracts", "covers": ["F08:*", "F09:*"],
             "owner": "SAP (shared responsibility)", "evidence": "SAP Trust Center sub-processor list and data transfer factsheet"},
            {"id": "C09", "name": "Audit log readable only by AI platform admins and audit", "covers": ["S1:I"],
             "owner": "AI platform team", "evidence": "Access list export"},
        ],
    }
    if fixed:
        system["controls"].append(
            {"id": "C10", "name": "Payload store: private bucket, 30-day lifecycle rule, access by two admins", "covers": ["S2:I", "S2:T", "F10:*"],
             "owner": "AI platform team", "evidence": "Bucket policy and lifecycle rule export"})
    return system


def load(path: Path) -> dict:
    with path.open(encoding="utf-8") as f:
        system = json.load(f)
    for key in ("system", "data_classes", "components", "flows", "processing", "controls"):
        if key not in system:
            sys.exit(f"ERROR: {path} has no '{key}' section")
    return system


def threats(system: dict) -> list:
    """List threats per element: crossing flows (T, I, D), Calder processes (S, R, E),
    Calder stores (T, I), plus the AI questions for a process that calls a model."""
    comps = {c["id"]: c for c in system["components"]}
    rows = []
    for f in system["flows"]:
        src, dst = comps[f["from"]], comps[f["to"]]
        if src["zone"] == dst["zone"]:
            continue  # STRIDE focuses on flows that cross a trust boundary
        for letter in PER_ELEMENT["flow"]:
            rows.append({"id": f"{f['id']}:{letter}", "element": f"{f['id']} {src['name']} -> {dst['name']}",
                         "threat": STRIDE_NAMES[letter]})
    for c in system["components"]:
        if c["operator"] != "Calder" or c["kind"] not in ("process", "store"):
            continue
        for letter in PER_ELEMENT[c["kind"]]:
            rows.append({"id": f"{c['id']}:{letter}", "element": f"{c['id']} {c['name']}",
                         "threat": STRIDE_NAMES[letter]})
        if c.get("ai"):
            for tid, text in AI_THREATS.items():
                rows.append({"id": tid, "element": f"{c['id']} {c['name']}", "threat": text})
    return rows


def covers(pattern: str, threat_id: str) -> bool:
    if ":" not in pattern or ":" not in threat_id:
        return pattern == threat_id  # AI1 to AI4 match by exact id
    p_el, p_letter = pattern.split(":")
    t_el, t_letter = threat_id.split(":")
    element_ok = p_el in ("*", t_el) or (p_el.endswith("*") and t_el.startswith(p_el[:-1]))
    return element_ok and p_letter in ("*", t_letter)


def threat_model(system: dict) -> list:
    rows = threats(system)
    for row in rows:
        ids = [c["id"] for c in system["controls"] if any(covers(p, row["id"]) for p in c["covers"])]
        row["controls"] = " ".join(ids) if ids else "GAP"
    return rows


def checks(system: dict) -> list:
    """Return (area, finding) for each blocking gap outside the threat table."""
    gaps = []
    allowed = set(system["system"]["allowed_regions"])
    handled = {d for f in system["flows"] for d in f["data"]}
    for c in system["components"]:
        if c["kind"] == "person":
            continue
        region = c.get("region")
        if region is None:
            gaps.append(("Residency", f"{c['id']} {c['name']}: processing region not recorded"))
        elif region not in allowed:
            gaps.append(("Residency", f"{c['id']} {c['name']}: region '{region}' is outside policy"))
        if c["kind"] == "process" and c["operator"] == "Calder":
            if c.get("auth") in (None, "shared user"):
                gaps.append(("Identity", f"{c['id']} {c['name']}: no named or service identity"))
            if "admin_auth" in c and c["admin_auth"] != "sso":
                gaps.append(("Identity", f"{c['id']} {c['name']}: admin access uses {c['admin_auth']}, not SSO"))
        if c["kind"] == "store" and (c.get("retention_days") is None or not c.get("deletion")):
            gaps.append(("Retention", f"{c['id']} {c['name']}: no retention period or deletion method"))
        if "trains_on_data" in c and c["trains_on_data"] is not False:
            gaps.append(("Model use", f"{c['id']} {c['name']}: training on customer data not excluded"))
    for d in sorted(handled - set(system["data_classes"])):
        gaps.append(("Data", f"data class '{d}' is used in a flow but not described"))
    return gaps


def dpia(system: dict) -> tuple:
    met = system["processing"].get("criteria", {})
    unknown = sorted(set(met) - {k for k, _ in DPIA_CRITERIA})
    if unknown:
        sys.exit(f"ERROR: unknown DPIA criteria {unknown}")
    count = len(met)
    if count >= 2:
        verdict = "DPIA required: two or more screening criteria are met."
    elif count == 1:
        verdict = ("DPIA not indicated by the two-criteria rule of thumb. Record this screening; "
                   "the controller may still decide one criterion is enough.")
    else:
        verdict = "No screening criteria met. Record this screening."
    return met, verdict


QUESTIONS = [
    ("Q01", "Architecture", "Provide a data flow diagram of the system."),
    ("Q02", "Identity", "How do users authenticate? Is SSO with our identity provider used?"),
    ("Q03", "Identity", "Which non-human identities call our systems, and with what access?"),
    ("Q04", "Identity", "How is administrative access to each component authenticated?"),
    ("Q05", "Data", "Which personal data does the system process?"),
    ("Q06", "Residency", "In which regions is data processed and stored, per component?"),
    ("Q07", "Model use", "Is our data used to train any model?"),
    ("Q08", "Retention", "What does each store keep, for how long, and how is it deleted?"),
    ("Q09", "Encryption", "How is data protected in transit and at rest?"),
    ("Q10", "AI risk", "How are prompt injection and harmful output handled?"),
    ("Q11", "AI risk", "Can the AI change business data or approve transactions on its own?"),
    ("Q12", "Logging", "What is logged, and can logs show who did what?"),
    ("Q13", "Third parties", "Which third parties process our data, and under which terms?"),
    ("Q14", "Privacy", "Has a DPIA screening been done, and what was the outcome?"),
    ("Q15", "Testing", "What security testing has been done or is planned, and what is in scope?"),
    ("Q16", "Risk", "Which threats remain open, and who accepted them?"),
]


def answers(system: dict, tm: list, gaps: list, dpia_verdict: str) -> list:
    comps = system["components"]
    gap_areas = {a for a, _ in gaps}
    out = []

    def add(qid, text, evidence, ok=True):
        out.append({"id": qid, "answer": text, "evidence": evidence, "status": "answered" if ok else "GAP"})

    add("Q01", f"{len(comps)} elements, {len(system['flows'])} flows; see dataflow.md.", "dataflow.md")
    add("Q02", "Users sign in through Identity Authentication, which proxies Calder's corporate IdP (OIDC).", "C02")
    add("Q03", "; ".join(f"{c['name']}: {c['auth']}" for c in comps if c.get("auth", "").startswith(("service", "agent"))), "C03, C04")
    admin = [f"{c['name']}: {c['admin_auth']}" for c in comps if "admin_auth" in c]
    add("Q04", "; ".join(admin) or "Not described.", "component list", ok="Identity" not in gap_areas)
    personal = [v["label"] for v in system["data_classes"].values() if v["personal"]]
    add("Q05", "; ".join(personal), "data_classes")
    regions = "; ".join(f"{c['id']} {c.get('region') or 'NOT RECORDED'}" for c in comps if c["kind"] != "person")
    add("Q06", regions, "component list", ok="Residency" not in gap_areas)
    models = [c for c in comps if "trains_on_data" in c]
    add("Q07", "No: " + ", ".join(c["name"] for c in models) + " are used without training on Calder data.",
        "C08", ok="Model use" not in gap_areas)
    stores = "; ".join(f"{c['name']}: {c.get('retention_days') or 'NOT SET'} days, {c.get('deletion') or 'NO DELETION'}"
                       for c in comps if c["kind"] == "store")
    add("Q08", stores, "store list", ok="Retention" not in gap_areas)
    add("Q09", "TLS 1.2 or higher in transit; at rest per platform (record per store).", "C01")
    ai_rows = [r for r in tm if r["id"] in ("AI1", "AI3")]
    add("Q10", "Masking and input and output filters in orchestration; human approval of every draft.",
        "C06, C07", ok=all(r["controls"] != "GAP" for r in ai_rows))
    add("Q11", "No. The agent reads and drafts; only the accountant's own user releases.", "C03, C07")
    add("Q12", "Every model and tool call: user, agent, target, decision, hash chain.", "C05")
    third = sorted({c["operator"] for c in comps if "Calder" not in c["operator"]})
    add("Q13", "; ".join(third) + ". Terms: SAP contracts and Trust Center documents.", "C08")
    add("Q14", dpia_verdict, "dpia_screening.md")
    add("Q15", "Calder-built endpoints in scope; SAP services only with SAP's approval; see pentest_scope.md.", "pentest_scope.md")
    open_threats = [r["id"] for r in tm if r["controls"] == "GAP"]
    add("Q16", "None open." if not open_threats else "Open: " + ", ".join(open_threats), "threat_model.csv",
        ok=not open_threats)
    return out


def mermaid(system: dict) -> str:
    comps = system["components"]
    zones = []
    for c in comps:
        if c["zone"] not in zones:
            zones.append(c["zone"])
    lines = ["```mermaid", "flowchart LR"]
    for z in zones:
        lines.append(f"  subgraph {z.replace('-', '_')}[{z}]")
        for c in comps:
            if c["zone"] == z:
                shape = {"person": ("([", "])"), "store": ("[(", ")]")}.get(c["kind"], ("[", "]"))
                label = f"{c['id']} {c['name']}".replace('"', "'")
                lines.append(f'    {c["id"]}{shape[0]}"{label}"{shape[1]}')
        lines.append("  end")
    for f in system["flows"]:
        lines.append(f"  {f['from']} -->|{f['id']}| {f['to']}")
    lines.append("```")
    return "\n".join(lines)


def build(path: Path) -> int:
    system = load(path)
    meta = system["system"]
    out = REVIEW / f"pack_{meta['version']}"
    out.mkdir(parents=True, exist_ok=True)

    tm = threat_model(system)
    gaps = checks(system)
    gaps += [("Threat", f"{r['id']} {r['element']}: {r['threat']} has no control") for r in tm if r["controls"] == "GAP"]
    met, verdict = dpia(system)
    if len(met) >= 2 and not system["processing"].get("dpia_reference"):
        gaps.append(("Privacy", "DPIA required but no dpia_reference recorded"))
    qa = answers(system, tm, gaps, verdict)

    (out / "dataflow.md").write_text(
        f"# Data flow: {meta['name']} ({meta['version']})\n\n{mermaid(system)}\n\n"
        + "| Flow | From | To | What | Data | Protocol |\n| --- | --- | --- | --- | --- | --- |\n"
        + "".join(f"| {f['id']} | {f['from']} | {f['to']} | {f['what']} | {', '.join(f['data'])} | {f['protocol']} |\n"
                  for f in system["flows"]), encoding="utf-8")
    with (out / "threat_model.csv").open("w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=["id", "element", "threat", "controls"])
        w.writeheader()
        w.writerows(tm)
    p = system["processing"]
    (out / "dpia_screening.md").write_text(
        f"# DPIA screening: {meta['name']} ({meta['version']})\n\n"
        f"- Nature: {p['nature']}\n- Scope: {p['scope']}\n- Context: {p['context']}\n- Purpose: {p['purpose']}\n\n"
        + "| Criterion | Met | Why |\n| --- | --- | --- |\n"
        + "".join(f"| {label} | {'yes' if key in met else 'no'} | {met.get(key, '')} |\n" for key, label in DPIA_CRITERIA)
        + f"\n**Result:** {verdict}\n", encoding="utf-8")
    with (out / "questionnaire.csv").open("w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=["id", "area", "question", "answer", "evidence", "status"])
        w.writeheader()
        for (qid, area, question), a in zip(QUESTIONS, qa):
            w.writerow({"id": qid, "area": area, "question": question, "answer": a["answer"],
                        "evidence": a["evidence"], "status": a["status"]})
    comps = system["components"]
    scope_lines = []
    for c in comps:
        if c["kind"] in ("person", "store"):
            continue
        if c["operator"] == "Calder":
            rule = f"IN SCOPE: {c.get('endpoint', 'no endpoint recorded')}"
        elif c["operator"].startswith("SAP"):
            rule = "SAP service: test only with SAP's written approval"
        else:
            rule = "OUT OF SCOPE: reached only through SAP"
        scope_lines.append(f"| {c['id']} | {c['name']} | {rule} |")
    (out / "pentest_scope.md").write_text(
        f"# Penetration test scope: {meta['name']} ({meta['version']})\n\n| Id | Component | Rule |\n| --- | --- | --- |\n"
        + "\n".join(scope_lines) + "\n\nInclude the AI tests: prompt injection through invoice texts (AI1), "
        "tool misuse (AI2), data leakage (AI3) and cost abuse (AI4).\n", encoding="utf-8")
    (out / "gaps.md").write_text(
        f"# Blocking gaps: {meta['name']} ({meta['version']})\n\n"
        + ("".join(f"- **{a}:** {t}\n" for a, t in gaps) if gaps else "None.\n"), encoding="utf-8")

    covered = sum(1 for r in tm if r["controls"] != "GAP")
    answered = sum(1 for a in qa if a["status"] == "answered")
    print(f"Review pack for {meta['id']} {meta['version']} -> {out.relative_to(HERE.parent)}")
    print(f"  Threats: {len(tm)} listed, {covered} with a control, {len(tm) - covered} open")
    print(f"  Questionnaire: {answered} of {len(qa)} answered")
    print(f"  DPIA screening: {len(met)} of {len(DPIA_CRITERIA)} criteria met. {verdict}")
    if gaps:
        print(f"  BLOCKING GAPS ({len(gaps)}):")
        for area, text in gaps:
            print(f"    {area:<10} {text}")
        print("Result: NOT READY for review")
        return 1
    print("Result: READY for review")
    return 0


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest="command", required=True)
    s = sub.add_parser("sample", help="write Calder's sample system description")
    s.add_argument("--fixed", action="store_true", help="write the corrected version (v2)")
    b = sub.add_parser("build", help="build the review pack from a system description")
    b.add_argument("path", type=Path)
    args = parser.parse_args()
    if args.command == "sample":
        REVIEW.mkdir(parents=True, exist_ok=True)
        name = "invoice_triage_v2.json" if args.fixed else "invoice_triage_v1.json"
        target = REVIEW / name
        target.write_text(json.dumps(sample_system(args.fixed), indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {target.relative_to(HERE.parent)}")
        return
    if not args.path.exists():
        sys.exit(f"ERROR: {args.path} not found. Run: python unit11/review_pack.py sample")
    sys.exit(build(args.path))


if __name__ == "__main__":
    main()
```

#### Step 3: Write the system as Calder first submitted it

```bash
python unit11/review_pack.py sample
```

```text
Wrote unit11/review/invoice_triage_v1.json
```

Open `unit11/review/invoice_triage_v1.json` in VS Code and skim it. It has six sections:

| Section | What it holds |
| --- | --- |
| `system` | Name, purpose, owner, company codes and the regions policy allows (`us`, `eu`) |
| `data_classes` | The three kinds of data and whether each is personal |
| `components` | People, processes, external services and stores, each in a trust zone with an operator and region |
| `flows` | Who sends what to whom, over which protocol |
| `processing` | The DPIA description (nature, scope, context, purpose) and the screening criteria met |
| `controls` | Each control, the threats it covers, its owner and its evidence |

A control's `covers` list uses short codes: `F04:*` means every threat on flow `F04`, `P2:E` means elevation of privilege on process `P2`, `F*:T` means tampering on every flow, and `AI1` names an AI threat.

#### Step 4: Build the pack and read the gaps

```bash
python unit11/review_pack.py build unit11/review/invoice_triage_v1.json
```

```text
Review pack for AGT_INV_TRIAGE v1 -> unit11/review/pack_v1
  Threats: 41 listed, 38 with a control, 3 open
  Questionnaire: 12 of 16 answered
  DPIA screening: 1 of 9 criteria met. DPIA not indicated by the two-criteria rule of thumb. Record this screening; the controller may still decide one criterion is enough.
  BLOCKING GAPS (6):
    Identity   P3 AI gateway: admin access uses local accounts, not SSO
    Residency  X3 Fallback model: processing region not recorded
    Retention  S2 Inference observability payloads (object store): no retention period or deletion method
    Threat     F10:D F10 Generative AI hub orchestration -> Inference observability payloads (object store): Denial of service has no control
    Threat     S2:T S2 Inference observability payloads (object store): Tampering has no control
    Threat     S2:I S2 Inference observability payloads (object store): Information disclosure has no control
Result: NOT READY for review
```

On Windows the path in the first line shows backslashes. The exit code is 1, so a pipeline would stop here.

Read the gaps as a reviewer would. Four of six come from one forgotten component: the observability bucket someone switched on while debugging. It holds full requests and answers, including supplier contacts, with no owner, no retention and no control. That is the most common shape of an AI review finding: not the model, but a copy.

#### Step 5: Look inside the pack

Open the folder `unit11/review/pack_v1`. It holds six files:

| File | What to look at |
| --- | --- |
| `dataflow.md` | The diagram, one box per component grouped by trust zone, and a table of flows. In VS Code, open it and press **Ctrl+Shift+V** (**Cmd+Shift+V** on macOS) for the preview; diagrams render with a Mermaid extension, or paste the block into the Mermaid Live Editor at mermaid.live |
| `threat_model.csv` | 41 rows: threat id, element, threat type, and the controls that cover it or `GAP` |
| `dpia_screening.md` | The processing description and the nine criteria with yes or no |
| `questionnaire.csv` | Sixteen questions with the answer, its evidence and `answered` or `GAP` |
| `pentest_scope.md` | Each component marked in scope, SAP approval needed, or out of scope |
| `gaps.md` | The blocking list from Step 4 |

Open `questionnaire.csv` in a spreadsheet. Row `Q06` shows why a team answering from memory gets residency wrong:

```text
Q06,Residency,"In which regions is data processed and stored, per component?",P1 us; P2 us; P3 us; X1 us; X2 us; X3 NOT RECORDED; X4 us; X5 us; S1 us; S2 us,component list,GAP
```

#### Step 6: Load the corrected version and compare

Calder's team fixed the gaps: the gateway console moved behind SSO, the fallback model's region was confirmed, and the payload bucket got an owner, a 30-day lifecycle rule and a control. Write that version:

```bash
python unit11/review_pack.py sample --fixed
```

See exactly what changed with Git, which compares any two files:

```bash
git diff --no-index unit11/review/invoice_triage_v1.json unit11/review/invoice_triage_v2.json
```

You should see four changes: `admin_auth` from `local accounts` to `sso`, the fallback model's `region` from `null` to `us`, the bucket's `retention_days` and `deletion`, and a new control `C10`. Press **q** to leave the diff if it opens in a pager.

#### Step 7: Build the corrected pack

```bash
python unit11/review_pack.py build unit11/review/invoice_triage_v2.json
```

```text
Review pack for AGT_INV_TRIAGE v2 -> unit11/review/pack_v2
  Threats: 41 listed, 41 with a control, 0 open
  Questionnaire: 16 of 16 answered
  DPIA screening: 1 of 9 criteria met. DPIA not indicated by the two-criteria rule of thumb. Record this screening; the controller may still decide one criterion is enough.
Result: READY for review
```

The exit code is 0. "READY" means the pack is complete and consistent, not that the system is approved. The reviewer still judges whether each control is good enough, and someone still signs the residual risk.

#### Step 8: Save your work in Git

```bash
git add unit11/review_pack.py unit11/review
git commit -m "Unit 11: security review pack for the invoice triage agent"
```

This pack holds only made-up data. A pack for a real system describes your defenses and, after a pen test, your weaknesses: keep it in an access-controlled store, not a public repository.

#### How the code works

| Part | What it does |
| --- | --- |
| `STRIDE_NAMES`, `PER_ELEMENT` | The six threat types and which ones to ask about for flows, processes and stores |
| `AI_THREATS` | The four AI questions added for any process that calls a model |
| `DPIA_CRITERIA` | The nine screening criteria with their labels |
| `sample_system` | Calder's agent as JSON; `--fixed` writes the corrected version |
| `threats` | Lists threats per element: only flows that cross a trust zone, only components Calder operates |
| `covers`, `threat_model` | Match each threat to the controls whose codes cover it; no match is `GAP` |
| `checks` | The rules outside STRIDE: region recorded and allowed, SSO for admins, an identity per process, retention and deletion per store, no training on customer data |
| `dpia` | Counts criteria met and gives the verdict; two or more without a `dpia_reference` is a gap |
| `QUESTIONS`, `answers` | Sixteen questions answered from the same data, each marked answered or `GAP` |
| `mermaid` | Draws the data flow diagram with one subgraph per trust zone |
| `build` | Writes the six files, prints the summary and returns exit code 1 if any gap is open |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your path, or the virtual environment is off | Turn on `.venv` (Step 1); on macOS or Linux try `python3` |
| `can't open file ... review_pack.py` | You're not in the course folder, or the file has another name | `cd` to `orchestrate-course`; check the file is `unit11/review_pack.py` |
| `ERROR: ... not found. Run: python unit11/review_pack.py sample` | The JSON file doesn't exist yet | Run Step 3 (or Step 6 for v2) first |
| `json.decoder.JSONDecodeError` | You edited the JSON and broke it, often a missing comma or quote | Undo the edit, or rerun `sample` to start fresh; VS Code underlines the error in red |
| `KeyError: 'region'` or similar | A component or flow lacks a field the script needs | Compare your entry with a working one in the sample |
| `ERROR: unknown DPIA criteria` | A criterion key is misspelt | Use the keys in `DPIA_CRITERIA`, such as `systematic_monitoring` |
| The diagram shows as text | VS Code has no Mermaid preview | Install a Mermaid preview extension, or paste the block into mermaid.live |
| A network or proxy error | Not from this script: it uses no network | Check you ran the right command |

### The SAP way

SAP doesn't generate a review pack for you. What it gives you are the facts and evidence for its part of each answer, and services whose configuration becomes your evidence. As of November 2026:

#### Evidence SAP publishes

- **SAP Trust Center.** SAP's training points reviewers to its sub-processor lists and data transfer factsheets ([SAP Learning](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/third-party-ai-providers-and-transparency)), and its security page describes SAP's own testing and the split of responsibilities ([SAP Trust Center](https://www.sap.com/about/trust-center/security.html)). Ask your account team which certificates and reports cover the exact services and regions you use.
- **Data handling in AI scenarios.** SAP's training describes TLS 1.2 or higher in transit, AES-256 at rest for SAP HANA Cloud and AI Core-managed environments, OAuth-based service-to-service authentication and audit logging ([SAP Learning](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/data-protection-in-ai-scenarios)). It doesn't state retention periods, which is why your pack has a row per store.
- **Model providers.** SAP's training says external providers reached through SAP services are contractually restricted, and, for its EU AI Cloud, that SAP doesn't use customer data to train third-party models. Training pages explain; contracts bind. Cite the contract in your evidence column.

#### Configuration that becomes evidence

| Control in Calder's pack | SAP service and what to export |
| --- | --- |
| C02 SSO for users | Identity Authentication application settings and the corporate identity provider trust |
| C03 Agent's own identity | The communication arrangement and roles for `AGT_INV_TRIAGE` in S/4HANA |
| C06 Masking and filters | The orchestration configuration in generative AI hub ([orchestration](https://erpfde.com/topics/sap-generative-ai-hub-and-orchestration/), [guardrails](https://erpfde.com/topics/guardrails-and-content-filtering/)) |
| C10 Payload store | Whether observability runs in `full` or metadata mode, the object store secret it uses, and your bucket's lifecycle rule |

#### Testing SAP's services

SAP's knowledge base article 3080379 covers how customers request approval for penetration tests and vulnerability assessments on SAP cloud products. As of November 2026 its public preview lists SAP BTP, Identity Authentication and SAP S/4HANA Cloud Public Edition among the products, and SAP AI Core with generative AI hub in its environment ([SAP KBA](https://userapps.support.sap.com/sap/support/knowledge/en/3080379)). The request steps, with any notice periods and limits, need an SAP for Me login; for SAP's own penetration attestations, the preview points you to your account executive. Plan the request into the test schedule; don't assume approval.

#### Licensing

The SAP services here have their own licences: inference observability needs an extended SAP AI Core plan ([SAP Developers](https://developers.sap.com/tutorials/ai-core-genaihub-inference-observability.html)), and its storage is in your own object store, on your bill. The review pack itself costs nothing but time.

### Build vs. SAP

| Need | Build it yourself | Use SAP | Choose |
| --- | --- | --- | --- |
| One system description and generated pack | A JSON file and a script like this lab's, in your repository | No SAP tool generates it | Build; it's small and stays next to the code |
| Evidence for SAP's services | Not possible | Trust Center, contracts, your account team | SAP |
| SSO and user lifecycle | Your own login: a finding waiting to happen | Identity Authentication with your corporate identity provider | SAP |
| Masking and content filtering | Your own detector, as in [data security and PII](https://erpfde.com/topics/data-security-and-pii/) | Orchestration masking and filters | SAP in production; your own tests to prove it works |
| A standard questionnaire | Your security team's own | CSA's AI-CAIQ or an ISO/IEC 42001 mapping (not SAP) | Map your answers to whichever your reviewer uses |
| Pen test of SAP services | Not allowed without approval | SAP's approval process | Request it early |

### Architecture view

#### Where it sits

The review pack describes the landscape rather than adding to it. Calder's invoice triage agent spans six trust zones: AP users, Calder's BTP account (approval UI, agent, gateway, audit log, payload bucket), SAP's AI service, the model providers, S/4HANA (`CP10`, and `CP20` after the July 2027 rollout) and the identity service. The diagram from Step 5 is the architecture picture a review board reads; keep it in the repository so it changes with the code.

#### Non-functional requirements

| Requirement | Typical target | What breaks if it's missed |
| --- | --- | --- |
| Residency | Every component's region recorded and inside policy | A fallback or log quietly moves data out of region |
| Retention | Every store has a period and an automatic deletion | Copies of prompts outlive their purpose and widen any breach |
| Identity | SSO for users and admins; one identity per machine caller | Shared or local accounts make actions untraceable |
| Auditability | Every model and tool call traceable to a user and agent | Nobody can show who approved what |
| Review lead time | One review cycle | Each missed fact costs a cycle, often weeks |

#### Integration and identity

Users sign in through Identity Authentication, which delegates to Calder's corporate identity provider. The approval UI passes the user's token to the agent; the agent reads S/4HANA under its own service identity through released APIs; the gateway calls the orchestration service with OAuth; releases happen in S/4HANA under the accountant's own user. Each of those is a row in the threat model with its own evidence.

#### The decision to record

In the short form from [writing a solution design doc](https://erpfde.com/topics/writing-a-solution-design-doc/):

- **Context:** Calder's AI agents each go through security review, and answers drifted between the diagram, the questionnaire and the code.
- **Options:** (A) write each document by hand per review; (B) keep one machine-readable system description in the repository and generate the pack; (C) adopt a commercial threat-modeling tool.
- **Decision:** B for every AI system, with the generated pack attached to each review; revisit C if more than a handful of systems need continuous modeling.
- **Consequences:** a pack rebuilds in seconds when the system changes, and a build that finds gaps stops the release. The description must be kept current, so changing it becomes part of the definition of done for any architectural change.

#### What a design review will ask

1. Which components keep a copy of prompts or answers, and what deletes each copy?
2. Where does each model in the chain run, including fallbacks?
3. Which identity performs each write to SAP, and could the agent perform it alone?
4. Which threats are accepted rather than controlled, and who signed?
5. Who updates the system description when the design changes?

### Production concerns

- **Keep the description in the repository and build it in CI.** A pull request that adds a store or a flow without its controls fails the build, the same way a test would. That is how the pack stays true after go-live.
- **Evidence goes stale.** Configuration exports, test reports and certificates have dates. Record the date in the evidence column and re-collect on a schedule, or when the component changes.
- **Changes trigger re-review.** Agree with the security team which changes need a new review: a new model or region, a new store, a new write tool, a new company code. Calder's `CP20` rollout is one.
- **Protect the pack.** After a pen test it lists your weaknesses. Store it with access control and share it with vendors under NDA.
- **Residual risk needs an owner.** "Accepted" with no name is not accepted. Record who, when and until when, and review it at the next change.
- **Connect it to governance.** The pack is the security evidence your AI register and approval process point to; see [AI governance for SAP programs](https://erpfde.com/topics/ai-governance-for-sap-programs/).

### Pitfalls

- **Answering the questionnaire before drawing the data flow.** The answers drift from the system, and the reviewer finds it.
- **Forgetting troubleshooting copies.** Observability in full mode, debug logging and gateway request logs all keep payloads.
- **Recording "SAP" as the region.** Record the region of each service and model you actually use.
- **Treating the fallback as hypothetical.** It runs on real data during every outage.
- **Testing a provider's service without approval.** Scope your endpoints; request approval for theirs.
- **Calling one DPIA criterion "no privacy work".** Record the screening and its reasoning; the DPO may still decide a DPIA is wise.
- **Letting "READY" mean "approved".** The script checks completeness. People judge adequacy.

### Exercise: add a feature that changes the privacy answer

Calder's AP manager asks for a daily report of each accountant's approvals and overrides, built from the gateway's audit records. Add it to the pack and see what it changes.

1. Copy the corrected file to a new version:

   - **Windows (PowerShell):**

     ```powershell
     Copy-Item unit11\review\invoice_triage_v2.json unit11\review\invoice_triage_v3.json
     ```

   - **macOS / Linux:**

     ```bash
     cp unit11/review/invoice_triage_v2.json unit11/review/invoice_triage_v3.json
     ```

2. In `invoice_triage_v3.json`, change `"version": "v2"` to `"version": "v3"`.
3. Add a component to the end of `components` (mind the comma after the previous entry): `{"id": "S3", "name": "Per-user productivity report", "kind": "store", "zone": "calder-btp", "operator": "Calder", "region": "us", "retention_days": null, "deletion": null}`.
4. Add a flow to the end of `flows`: `{"id": "F12", "from": "P3", "to": "S3", "what": "Daily counts per AP user", "data": ["user_id"], "protocol": "internal"}`.
5. Under `processing`, `criteria`, add `"systematic_monitoring": "Daily counts of each AP user's approvals and overrides."`.
6. Build: `python unit11/review_pack.py build unit11/review/invoice_triage_v3.json`. You should see `2 of 9 criteria met. DPIA required` and four gaps: the report's retention, two threats on `S3` and `DPIA required but no dpia_reference recorded`.
7. Close the gaps: give `S3` a retention period and a deletion method, add a control `C11` that covers `S3:T` and `S3:I` with an owner and evidence, and add `"dpia_reference": "DPIA-2026-007 (draft with the DPO)"` under `processing`. Build again.
8. In `unit11/review/decision_v3.md`, write three sentences for the AP manager: what the report changes for privacy, what you need from the DPO, and whether a per-team report without names would avoid the DPIA.
9. Add the evidence you built in earlier Unit 10 and 11 exercises to the evidence columns where it applies: your containment profile from [sandboxing agents](https://erpfde.com/topics/sandboxing-agents-authorization-vs-containment/), the routing decision from [model routing](https://erpfde.com/topics/model-routing-with-fallbacks-in-the-sap-cloud-sdk/) and the supply-chain findings from [AI supply-chain controls](https://erpfde.com/topics/ai-supply-chain-controls/).

**Done when** the v3 build prints `DPIA required` and `Result: READY for review`, `pack_v3/dpia_screening.md` shows `Systematic monitoring` as `yes`, and `decision_v3.md` answers the three questions. The pack feeds [UAT and sign-off for AI in SAP programs](https://erpfde.com/topics/uat-and-sign-off-for-ai-in-sap-programs/).

### Check yourself

1. Why does the threat model ask about tampering, disclosure and denial of service only on flows that cross a trust zone?
   - A. STRIDE forbids listing threats on flows inside one zone
   - B. Most threats sit where parties with different trust meet
   - C. Flows inside a zone are always encrypted by the platform
   - D. The script would list too many threats to fit in a spreadsheet

   Answer: B. Per-element STRIDE focuses on flows between zones because that is where an attacker or another party can reach the data. Flows inside a zone still matter, but the element's own process and store threats cover most of them.

2. In Calder's v1 pack, four of six gaps trace back to one component. What was it, and why is it typical?
   - A. The fallback model, because fallbacks are always in another region
   - B. The approval UI, because user interfaces skip single sign-on
   - C. The observability bucket, as debug copies are easy to forget
   - D. The audit log, because hash chains can't be retained for long

   Answer: C. Full-mode observability keeps request and response payloads in the customer's object store, and nobody had given it an owner, retention or control. Forgotten copies of prompts are a common review finding.

3. You delete observability records through SAP's API. What happens to the payloads in your S3 bucket?
   - A. They stay, so your bucket needs its own lifecycle rule
   - B. They are deleted together with the metadata by SAP
   - C. They are moved to SAP's archive for one more year
   - D. They are masked automatically once the records are gone

   Answer: A. SAP's tutorial says deleting records removes the metadata while the request, response and feedback in the object store remain. The deletion method in the pack is therefore a lifecycle rule on Calder's bucket.

4. How does `threat_model` decide that a threat is covered?
   - A. It asks the model whether any control sounds relevant to the threat
   - B. It counts a threat as covered when any control exists for that zone
   - C. It matches the threat's code to each control's `covers` list
   - D. It covers a threat when the component has a region and an owner

   Answer: C. Each threat has a code such as `S2:I` or `AI1`, and `covers` checks it against patterns like `F*:T` or `F04:*`. No matching control means `GAP`, which blocks the build.

5. The AP manager's per-user report adds systematic monitoring. Why does the build now block?
   - A. Monitoring of employees is never allowed under GDPR
   - B. Two criteria indicate a DPIA, and none is referenced yet
   - C. The report's region is outside Calder's allowed regions
   - D. Systematic monitoring requires a second model to review it

   Answer: B. With innovative technology and systematic monitoring, two of the nine criteria are met, which usually indicates a DPIA. The script blocks until a `dpia_reference` shows the DPO has one in hand.

6. Your pen-test firm plans to fire injection attacks at the generative AI hub's endpoint directly. What do you change in the plan?
   - A. Nothing, since the hub is part of Calder's subscription and scope
   - B. Attack through Calder's endpoints; ask SAP to approve the rest
   - C. Drop all AI tests, because model behavior can't be pen-tested
   - D. Move the tests to production so the results reflect real traffic

   Answer: B. SAP services need SAP's approval before testing, through the process in KBA 3080379. Injection through invoice texts can be tested end to end via Calder's approval UI and agent, which are in Calder's own scope.

7. The v2 build prints `READY for review`. What does that tell the CISO's team?
   - A. The system has passed review and can go live tomorrow
   - B. SAP has confirmed every control listed in the pack
   - C. Every fact and threat is filled in, ready for judgment
   - D. The DPO has signed the DPIA and accepted all residual risk

   Answer: C. The script checks completeness and consistency, not whether a control is good enough. Reviewers still judge adequacy, and named owners still accept residual risk.

## Sources

- [When do we need to do a DPIA? (UK Information Commissioner's Office)](https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/accountability-and-governance/data-protection-impact-assessments-dpias/when-do-we-need-to-do-a-dpia): read 2026-11-22, re-read 2026-11-25; under review for the Data (Use and Access) Act; Article 35(1) high-risk test; the ICO's list names innovative technology including AI; nine European screening criteria (WP248); in most cases two criteria indicate a DPIA
- [How do we do a DPIA? (UK Information Commissioner's Office)](https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/accountability-and-governance/data-protection-impact-assessments-dpias/how-do-we-do-a-dpia): read 2026-11-22, re-read 2026-11-25; under review for the Data (Use and Access) Act; seven steps from identifying the need to sign-off; describe nature, scope, context and purposes; record residual risk; accepting a remaining high risk requires prior consultation with the regulator; seek the DPO's advice
- [AI Controls Matrix v1.1: strengthening the foundation for trustworthy AI (Cloud Security Alliance, 14 July 2026)](https://cloudsecurityalliance.org/blog/2026/07/14/ai-controls-matrix-v1-1-strengthening-the-foundation-for-trustworthy-ai): read 2026-11-22; AICM v1.1 has 247 control objectives in 18 domains, a superset of CCM v4.1; AI-CAIQ v1.1 has 320 questions for self- and third-party assessment; mappings to ISO/IEC 42001, the EU AI Act and NIST AI RMF; STAR Level 1 self-assessment, Level 2 third-party audit
- [Data residency and digital sovereignty for AI (SAP Learning)](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/data-residency-and-digital-sovereignty-for-ai): read 2026-11-22; residency depends on architecture; generative AI processing on SAP-managed infrastructure or approved external providers depending on configuration; in its EU AI Cloud section, SAP does not use customer data to train third-party models; regional options subject to availability; locally hosted AI and SAP Sovereign Cloud
- [Third-party AI providers and transparency (SAP Learning)](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/third-party-ai-providers-and-transparency): read 2026-11-22; third-party models reached through SAP-managed services such as generative AI hub; providers contractually restricted; data processed only for the customer's purpose; masking and filtering in some scenarios; sub-processor lists and data transfer factsheets on the SAP Trust Center
- [Data protection in AI scenarios (SAP Learning)](https://learning.sap.com/courses/building-confidence-in-ai-with-sap/data-protection-in-ai-scenarios): read 2026-11-22; TLS 1.2 or higher in transit; AES-256 at rest for SAP HANA Cloud and AI Core-managed environments; OAuth-based service authentication; audit logging; no retention periods stated
- [Introduction to identity and access management on SAP BTP (SAP BTP documentation, SAP-docs on GitHub)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/introduction-to-identity-and-access-management-on-sap-btp-51c1677.md): read 2026-11-25 (replaces an SAP Learning lesson that now returns 404); Identity Authentication for authentication and SSO, delegating to corporate identity providers; federation over SAML 2.0 and OpenID Connect; at least two Cloud Identity Services tenants per BTP customer (test and production); SAP recommends them over the default identity provider
- [Security (SAP Trust Center)](https://www.sap.com/about/trust-center/security.html): read 2026-11-22; SAP runs its own scans, third-party penetration tests and red teaming; customers manage user access in the solution administration layer and application threat detection; encryption in transit and at rest
- [3080379 - Customer Penetration Vulnerability Testing Request Process (SAP Knowledge Base Article)](https://userapps.support.sap.com/sap/support/knowledge/en/3080379): re-read 2026-11-25 as a public preview; how customers request approval of penetration testing and vulnerability assessment on SAP cloud products; penetration attestations through the account executive; environment lists SAP AI Core and generative AI hub, product list SAP BTP, Identity Authentication and SAP S/4HANA Cloud Public Edition; the preview no longer names pentest@sap.com; request steps need an SAP for Me login
- [Inference observability in generative AI hub (SAP Developers tutorial)](https://developers.sap.com/tutorials/ai-core-genaihub-inference-observability.html): read 2026-11-22, re-read 2026-11-25; recorded only when observability headers ask; full mode keeps request and response payloads in an S3 object store; deleting records removes metadata, payloads in the object store stay; extended AI Core plan
