# Set up for Unit 27: Calder's security sample pack and an optional Identity Services trial

> Build a week of Calder's sign-in, audit and read access logs on your laptop, read them against eight rules, and know what the free identity trial offers.

- Course: Orchestrate, Unit 27 · Security, identity and compliance
- Page: https://erpfde.com/topics/set-up-for-unit-27/
- Updated: 2026-11-30
- Reading time: Foundational 7 min, Deep 30 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

Unit 27 is about who can get into Calder Pumpworks' systems, what they may do there, and how anyone finds out afterwards. Calder is the course's fictional pump maker. The unit covers authorizations, identity and single sign-on, segregation of duties, logging, privacy, patching, networks and encryption. It is written for architects and the leaders who sign off on their designs.

Most of the unit is reading and design. You can't safely practise on a company's production security, and SAP's security products are not offered as free trials for a laptop. So this setup builds a **sample pack**: one week of Calder's users, sign-ins, audit log and read access log, generated on your laptop, with eight findings planted in it. A small script reads the pack against eight course rules. The unit's topics come back to the same week.

One SAP trial helps too: an **SAP Cloud Identity Services** tenant inside an SAP BTP trial, free for the trial's 90 days. It is optional. Setup takes 30 to 45 minutes and costs nothing.

### Why it matters to the business

Security failures at an SAP customer are rarely clever. A person leaves and their user stays open. A technical user's password ends up on a laptop. An emergency ID is used at night with nobody recording why. A log fills up and stops, and nobody notices until the auditor asks for that afternoon.

Each of those is in this week's sample. Each costs real money when it happens: an audit finding, a fraudulent payment run, a privacy breach that must be reported. The unit asks an architect to design the controls that catch them. Reading logs in a lab first makes the design concrete: you see what a rule finds and what it misses.

### How SAP does it

The tools the unit discusses sit in three places:

| Where | What records or controls access | Covered in |
| --- | --- | --- |
| ABAP systems such as S/4HANA and ECC | Roles and authorizations; the **security audit log**, which records security-related activity such as logons, transaction starts and changes to users ([SAP Help](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/41bf80aa601c86e10000000a42189b/content.htm)); **read access logging**, which records who read sensitive data ([SAP Help](https://help.sap.com/saphelp_nwpi711/helpdata/en/c8/747a52e97b9f11e10000000a441470/content.htm)) | The authorization, audit and privacy topics |
| SAP Cloud Identity Services | Sign-in and single sign-on, user provisioning and a shared user directory ([SAP Learning](https://learning.sap.com/courses/operating-sap-business-technology-platform/explaining-identity-and-access-management-on-sap-btp)) | The identity, single sign-on and principal propagation topics |
| Governance tools | Access risk rules, access requests, emergency access and reviews | The access control and identity access governance topics |

As of 30 November 2026, SAP Learning says an SAP BTP trial account is entitled to one Identity Services trial tenant ([SAP Learning](https://learning.sap.com/courses/operating-sap-business-technology-platform/explaining-identity-and-access-management-on-sap-btp)). An SAP blog post lists its limits: up to 50 users, no connection to a company's own user store, and it can't sign in BTP administrators ([SAP Community](https://community.sap.com/t5/technology-blog-posts-by-sap/sap-cloud-identity-services-offered-as-trial-version/ba-p/13552272)). The product pages for [SAP Cloud Identity Access Governance](https://www.sap.com/canada/products/financial-management/cloud-iam.html) and [SAP Enterprise Threat Detection](https://www.sap.com/india/products/financial-management/enterprise-threat-detection.html), read on 30 November 2026, list paid editions and a test edition for partners, not a free trial.

> **Note** **For functional consultants:** nothing in your configuration changes in this setup. Read the findings, though: a role assigned without a ticket, a leaver still signing in, a buyer reading suppliers' bank details. Each of those becomes a test case or a role question in the topics that follow.

### What this unit adds

| Item | What it is | Cost | Used in |
| --- | --- | --- | --- |
| `unit27/security_pack.py` | Writes the sample pack and reads it against rules `SL01` to `SL08` | Free | Authorization, access control, audit logging, threat detection and privacy topics |
| `unit27/pack/` | Five files: users, sign-ins, audit log, read access log, emergency sessions | Free | Same |
| `check_unit27.py` | Runs the pack's self-test and looks for tools from earlier units | Free | Before every Unit 27 topic |
| Identity Services trial tenant (optional) | SAP's identity admin console, in your BTP trial | Free, ends with the trial | Identity, single sign-on and principal propagation topics |

The unit also reuses two earlier tools when you have them: Calder's role matrix from [roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/), and the personal-data detector from [Set up for Unit 11](https://erpfde.com/topics/set-up-for-unit-11/). Nothing new to install: the pack script uses only what comes with Python.

### Time and money

- **Time:** 30 to 45 minutes for the pack and the check. The trial tenant adds about 20 minutes.
- **Money:** nothing. No Unit 27 exercise needs a paid SAP product.
- **Clocks:** the Identity Services trial tenant lives as long as the BTP trial, 90 days from registration ([sap.com](https://www.sap.com/products/technology-platform/trial.html)). If your BTP trial from Unit 21 is still running, create the tenant there.

### Questions to ask

Ask IT security or your SAP basis team before the unit's design work:

- Is the security audit log switched on in every production client, and who reads it, how often?
- What happens when the audit log's storage fills up: does anyone get an alert?
- Do we run read access logging, and for which data?
- When HR records a leaver, how long until their SAP and identity provider users are locked?
- Which technical users exist, and can any of them log on through the SAP GUI or the browser?
- Who approves the use of an emergency ID, and who reviews its log afterwards?

### Common misconceptions

- **"The audit log records everything."** It records what its configuration selects, and SAP's documentation says auditing stops when its storage limit is reached.
- **"Locking the user is enough when someone leaves."** The identity provider, the cloud apps and the SAP system each hold a user. All of them must be closed.
- **"Technical users are safe because nobody knows the password."** Somebody set it, and it works wherever that user type allows a logon.
- **"Emergency access is fine if it is rare."** It is fine when every use is requested, recorded and reviewed. Rare and unrecorded is the dangerous combination.
- **"The trial shows SAP's security products."** It shows Identity Services only, with limits. The governance and detection products have no free trial we could find.

### Key terms

- **Identity provider:** the service that checks who a person is and tells applications, such as SAP Cloud Identity Services or a company's own directory.
- **Security audit log:** an ABAP system's log of security-related activity, such as logons, transaction starts and user changes.
- **Read access logging:** an ABAP feature that records who read selected sensitive data, and through which channel.
- **Technical user:** a user that a system, not a person, signs in with, for example for an interface.
- **Emergency ID:** a powerful user borrowed for a short, recorded session to fix an urgent problem; also called a firefighter ID.
- **Leaver:** a person who has left the company or a job; their access must end on that date.

### Check yourself

1. Why does this unit's setup build a sample pack instead of giving you a security system to practise on?
   - A. SAP's security logs can't be read outside an SAP system
   - B. The unit's topics use real customer logs supplied later by SAP
   - C. Real systems are off limits and the products have no trials
   - D. A sample pack is required by SAP before using a trial

   Answer: C. You can't practise on a company's real security, and we found no free trials of SAP's governance and detection products. The pack gives a week of logs with known problems, so you can see what a rule finds.

2. A leader asks what the free Identity Services trial is good for. What is the honest answer?
   - A. Testing single sign-on against our company's user directory
   - B. Seeing SAP's identity admin console with a few test users
   - C. Signing in our BTP administrators during the pilot
   - D. Running identity governance reviews on our cloud apps

   Answer: B. The trial tenant has up to 50 users, no connection to a company user store and can't sign in platform administrators. It is good for seeing the console and trying trust and sign-in settings on test users.

3. In the sample week, a maintenance technician who left in October signed in on 24 November. Which question does that raise for the business?
   - A. Whether the technician's role was designed correctly
   - B. Whether the audit log is configured to record logons
   - C. How fast a leaver's users get locked everywhere
   - D. Whether the identity provider supports multi-factor sign-in

   Answer: C. The role is not the issue: the person should have no access at all. The question is the leaver process, covering the identity provider, the cloud apps and the SAP system.

4. The security audit log in the sample goes silent on Wednesday afternoon. What should an architect ask IT?
   - A. Whether staff went home early that day
   - B. Whether the read access log can replace it for audits
   - C. Whether the log needs a separate licence
   - D. What alerts anyone when the log stops recording

   Answer: D. SAP's documentation says auditing stops when the log's storage limit is reached. A silent log looks the same as a quiet afternoon unless something checks for it and alerts a person.

5. An emergency ID was used at 19:20 on Tuesday with no session recorded. What makes this a problem rather than a fix?
   - A. Emergency IDs may only be used during office hours
   - B. Nobody requested, recorded or can review that use
   - C. The emergency ID should have been locked after Monday
   - D. The user who borrowed it worked in a different team

   Answer: B. Emergency access is acceptable when every use is requested, recorded and reviewed. A logon with no session can't be tied to a reason or a person, so nobody can review it.

## Deep layer

### Mental model: the same week, read many ways

Security architecture is easier to learn on one fixed story than on scattered examples. This setup writes one week at Calder: Monday 23 to Friday 27 November 2026 in `S4P`, Calder's production S/4HANA system, client 100. Five files hold the week. Each later topic reads them with a different question: who could do this, who should have stopped it, what would have detected it, what the auditor sees.

```mermaid
flowchart LR
  HR[HR leaver dates] --> U[users.csv]
  IDP[Identity provider] --> S[signins.csv]
  SAL[Security audit log] --> A[audit_log.csv]
  RAL[Read access log] --> R[read_access.csv]
  FF[Emergency sessions] --> E[emergency_sessions.csv]
  U & S & A & R & E --> P[security_pack.py<br/>rules SL01-SL08]
  P --> F[Findings]
  P --> T[One user's week<br/>--user]
```

The pack's layouts are course formats, written to be easy to read in a spreadsheet. SAP's logs keep their own records; the left-hand boxes say which SAP feature each file stands in for.

### How it works

#### What the files stand in for

| File | Stands in for | What SAP's version records |
| --- | --- | --- |
| `users.csv` | The user list in `S4P`, joined with HR's leaver dates | In SAP, the user master; the leaver date comes from HR, as in the [hire-to-retire topic](https://erpfde.com/topics/hire-to-retire-touchpoints/) |
| `signins.csv` | Sign-ins at the identity provider in front of the launchpad | Identity Services keeps its own logs; the identity topics open them |
| `audit_log.csv` | The security audit log | A record per event with, among other fields, the user, client, terminal, transaction, program, audit class and message text ([SAP Help](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/41bf80aa601c86e10000000a42189b/content.htm)) |
| `read_access.csv` | Read access logging | Read access to sensitive data through RFC, Dynpro, Web Dynpro and web services ([SAP Help](https://help.sap.com/saphelp_nwpi711/helpdata/en/c8/747a52e97b9f11e10000000a441470/content.htm)) |
| `emergency_sessions.csv` | The request log of an emergency access tool | Who asked, when, why, and whether the reviewer read the session |

The audit log's `audit_class` column uses the eight audit classes SAP's design documentation lists: dialog logon, RFC/CPIC logon, RFC function call, transaction start, report start, user master change, system and other. The terminal names, the event wording and the `detail` column are course values. Transaction codes such as `ME21N` (create purchase order), `MIRO` (enter supplier invoice) and `F110` (payment run) are standard S/4HANA transactions; your own system's log shows which ones your users start.

#### Why the log can go silent

SAP's design documentation says the audit file's size is capped by the profile parameter `rsau/max_diskspace/local`, with a default of 1 MB in the release we read, and that auditing stops when the cap is reached ([SAP Help](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/41bf80aa601c86e10000000a42189b/content.htm)). It also says the files are not deleted automatically. That is why rule `SL08` looks for silent stretches: a log that stopped looks exactly like a quiet afternoon unless something checks. Sizing and retention are covered later in Unit 27, in the audit and read access logging topic.

#### The eight rules

| Rule | What it checks | Where the unit takes it |
| --- | --- | --- |
| `SL01` | Nobody signs in or logs on after their leaver date | Identity, identity governance |
| `SL02` | Every leaver's user is locked | Identity governance |
| `SL03` | Technical users never log on in dialog | Authorization concept, network security |
| `SL04` | Five failed logons within 15 minutes are flagged | Single sign-on, threat detection |
| `SL05` | Every user change by a person names a ticket | Access control |
| `SL06` | The emergency ID logs on only inside a recorded session | Access control |
| `SL07` | Supplier bank details are read only by the jobs that need them | Privacy controls, threat detection |
| `SL08` | The production audit log has a record at least every two hours on working days | Audit logging, secure operations |

All eight are **course rules**, not SAP defaults or a recommended baseline. SAP's own guidance on what to watch includes logons by standard and interesting dialog users, generic table access, downloads and changes to the audit configuration itself ([SAP user group deck, 2025](https://assets.dm.ux.sap.com/sap-user-groups/pdfs/250522_security_audit_log_past_present_and_future_01.pdf)). The unit's threat detection topic compares the two.

#### The trial tenant

As of 30 November 2026, SAP's material describes the route like this. In a BTP trial account, a subaccount offers **Cloud Identity Services** with plan **default**. Creating an instance creates a tenant, and the first administrator gets an activation email for the admin console ([SAP tutorial](https://developers.sap.com/tutorials/application-frontend-trial-setup.html)). The tutorial notes that this step is needed only in trial accounts; in paid accounts the tenant is provisioned when the account is created.

The SAP blog post on the trial lists its limits: one tenant per BTP global trial account, up to 50 users, no Connectivity plan (so no corporate user store or on-premise provisioning), usable only as an identity provider for applications, not for platform users, deployed in US East, and retired with the trial ([SAP Community](https://community.sap.com/t5/technology-blog-posts-by-sap/sap-cloud-identity-services-offered-as-trial-version/ba-p/13552272)). SAP Learning adds the distinction the unit keeps using: **platform users** are administrators, developers and operators; **business users** use the applications ([SAP Learning](https://learning.sap.com/courses/operating-sap-business-technology-platform/explaining-users-and-identity-providers)).

### Build it yourself: the security pack and the Unit 27 check

You will create the pack script, write the week, read it against the rules, follow one user through the week, run the unit check, and optionally create the trial tenant. Steps 1 to 6 need no account.

```mermaid
flowchart LR
  A[security_pack.py --init] --> B[security_pack.py]
  B --> C[--user 00100094]
  B --> D[check_unit27.py]
  D -.optional.-> E[Identity Services<br/>trial tenant]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/). [Set up for Unit 11](https://erpfde.com/topics/set-up-for-unit-11/) and [roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/) are useful but not required; the check marks them `LATER` if they are missing. This walkthrough doesn't repeat those steps.

> **Note** New words. A **CSV file** is a table saved as text, one row per line, values separated by commas; a spreadsheet opens it. A **log** is a file a system writes to record what happened, one line per event. A **rule** here is a check the script applies to the logs. A **self-test** is a run of the script that checks its own results against what it planted.

#### What you need

- Your course folder `orchestrate-course` with its `.venv` from the computer setup.
- About 30 to 45 minutes. Everything is free.
- Optional: an SAP BTP trial account for Step 7 (free, 90 days).

#### 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
     ```

4. Create the folder for this unit:

   ```bash
   mkdir unit27
   ```

Run every command from the course folder.

#### Step 2: Create the pack script

1. In VS Code, create `unit27/security_pack.py`, paste the code below and save:

```python
"""Calder's security sample pack for Unit 27: users and one week of logs, and a first reading of them.

Run from your course folder:
    python unit27/security_pack.py --init          # write the sample pack to unit27/pack/
    python unit27/security_pack.py                 # check the pack against the course rules SL01-SL08
    python unit27/security_pack.py --user 00100094 # one user's week across all logs, in time order
    python unit27/security_pack.py --selftest      # prove the checks find what was planted

Built-in Python only, no randomness, no account. Calder Pumpworks is fictional. The file layouts,
terminals, rules SL01-SL08 and every finding are course values, not SAP formats: SAP's security
audit log, Identity Authentication and read access logging each keep their own records.
Exit code 0 when the pack could be read (findings are expected), 2 when a file is missing or broken.
"""
import argparse
import csv
import datetime as dt
import pathlib
import shutil
import sys
import tempfile

HERE = pathlib.Path(__file__).resolve().parent
PACK = HERE / "pack"
AS_OF = dt.date(2026, 11, 30)                      # lab date: Monday after the logged week
WEEK = [dt.date(2026, 11, d) for d in (23, 24, 25, 26, 27)]
HOLIDAYS = {dt.date(2026, 11, 26)}                 # Calder's course calendar has 26 November off
SYSTEM, CLIENT = "S4P", "100"

# kind: person, technical, emergency. left_on comes from the HR feed (hire-to-retire topic).
USERS = [
    # user, kind, job, left_on, locked
    ("00100211", "person", "Buyer, Rockford", "", "no"),
    ("00100153", "person", "Maintenance planner, Rockford", "", "no"),
    ("00100094", "person", "Maintenance technician, Rockford", "2026-10-16", "no"),
    ("00100253", "person", "Purchasing manager, Rockford", "", "no"),
    ("00100247", "person", "Receiving clerk, Rockford DC", "", "no"),
    ("00100241", "person", "AP accountant, shared service", "", "no"),
    ("00100244", "person", "AP supervisor, shared service", "", "no"),
    ("00100250", "person", "Master data specialist", "", "no"),
    ("00100259", "person", "Buyer, Rockford, covers Augsburg AP", "", "no"),
    ("00100331", "person", "Security administrator", "", "no"),
    ("TU_MES_RFC", "technical", "MES Rockford reads production orders", "", "no"),
    ("FF_P2P_CP10", "emergency", "Emergency ID for procure-to-pay in CP10", "", "no"),
]
# Each person's usual work: terminal and the transactions they start on a normal day.
DAILY = {
    "00100211": ("RKPC-0211", ["ME21N", "ME23N", "ME21N"]),
    "00100153": ("RKPC-0153", ["IW38", "ME51N"]),
    "00100253": ("RKPC-0253", ["ME23N", "ME28"]),
    "00100247": ("RKDC-0247", ["MIGO", "MIGO"]),
    "00100241": ("RKPC-0241", ["MIRO", "MIRO", "MIR4"]),
    "00100244": ("RKPC-0244", ["MRBR", "MIR4"]),
    "00100250": ("RKPC-0250", ["BP", "BP"]),
    "00100259": ("RKPC-0259", ["ME21N", "MIRO"]),
    "00100331": ("RKPC-0331", ["SU01"]),
}
# Emergency ID sessions: who asked, when, why, and whether the reviewer has read the log.
SESSIONS = [("FF-0009", "00100250", "2026-11-23 09:30", "2026-11-23 09:55",
             "Correct Tamsfield's bank key after a failed payment", "reviewed")]
BANK_READERS = {"00100250", "00100244", "00100241"}  # course rule: jobs that need supplier bank data
AUDIT_FIELDS = ["time", "system", "client", "user", "terminal", "audit_class", "event", "tcode", "outcome", "detail"]


def stamp(day, hh, mm):
    return f"{day.isoformat()} {hh:02d}:{mm:02d}"


def build_rows():
    """Return the five files' rows: a normal week plus the planted cases."""
    audit, signins, reads = [], [], []

    def log(time, user, terminal, cls, event, tcode="", outcome="ok", detail=""):
        audit.append([time, SYSTEM, CLIENT, user, terminal, cls, event, tcode, outcome, detail])

    for day in WEEK:
        if day in HOLIDAYS:
            continue
        for n, (user, (terminal, tcodes)) in enumerate(DAILY.items()):
            if user == "00100241" and day == WEEK[0]:
                continue  # her Monday starts with the lockout below
            minute = 2 + 3 * n
            signins.append([stamp(day, 8, minute - 1), "S4P launchpad", user, "success", ""])
            log(stamp(day, 8, minute), user, terminal, "Dialog logon", "Logon successful")
            for k, tcode in enumerate(tcodes):
                log(stamp(day, 9 + 2 * k, minute), user, terminal, "Transaction start", "Transaction started", tcode)
        for hour in range(6, 19):  # the MES polls once an hour over RFC
            log(stamp(day, hour, 0), "TU_MES_RFC", "rkmes01", "RFC/CPIC logon", "RFC logon successful")
            log(stamp(day, hour, 0), "TU_MES_RFC", "rkmes01", "RFC function call", "Function module called",
                detail="Z_MES_GET_ORDERS")

    mon, tue, wed, fri = WEEK[0], WEEK[1], WEEK[2], WEEK[4]
    # SL04: five wrong passwords in a row, the user is locked, then unlocked with a ticket.
    for m in range(41, 46):
        signins.append([stamp(mon, 7, m), "S4P launchpad", "00100241", "failed", "wrong password"])
        log(stamp(mon, 7, m), "00100241", "unknown", "Dialog logon", "Logon failed", outcome="failed",
            detail="wrong password")
    log(stamp(mon, 7, 46), "00100241", "unknown", "User master change", "User locked", outcome="ok",
        detail="locked after failed logons")
    log(stamp(mon, 8, 20), "00100331", "RKPC-0331", "User master change", "User unlocked", "SU01",
        detail="user 00100241; ticket REQ-4471")
    signins.append([stamp(mon, 8, 24), "S4P launchpad", "00100241", "success", ""])
    log(stamp(mon, 8, 25), "00100241", "RKPC-0241", "Dialog logon", "Logon successful")
    # SL06: the emergency ID inside its recorded session, then once more with no session at all.
    log(stamp(mon, 9, 31), "FF_P2P_CP10", "RKPC-0250", "Dialog logon", "Logon successful", detail="session FF-0009")
    log(stamp(mon, 9, 40), "FF_P2P_CP10", "RKPC-0250", "Transaction start", "Transaction started", "BP")
    log(stamp(tue, 19, 20), "FF_P2P_CP10", "RKPC-0244", "Dialog logon", "Logon successful")
    log(stamp(tue, 19, 26), "FF_P2P_CP10", "RKPC-0244", "Transaction start", "Transaction started", "F110")
    # SL01 and SL02: a leaver's user is still open and is used.
    signins.append([stamp(tue, 10, 11), "S4P launchpad", "00100094", "success", ""])
    log(stamp(tue, 10, 12), "00100094", "RKSF-0012", "Dialog logon", "Logon successful")
    log(stamp(tue, 10, 15), "00100094", "RKSF-0012", "Transaction start", "Transaction started", "ME51N")
    # SL03: the MES's technical user signs on at a laptop, as a person would.
    log(stamp(tue, 16, 40), "TU_MES_RFC", "RKLT-0457", "Dialog logon", "Logon successful")
    log(stamp(tue, 16, 43), "TU_MES_RFC", "RKLT-0457", "Transaction start", "Transaction started", "SE16")
    # SL08: the audit file reaches its size limit and the log stops at 13:52 on Wednesday.
    audit = [r for r in audit if not (r[0] > stamp(wed, 13, 52) and r[0] < stamp(wed + dt.timedelta(1), 0, 0))]
    # SL07: a buyer reads fourteen suppliers' bank details after the log stopped; read access logging still records it.
    for k in range(14):
        reads.append([stamp(wed, 17, 30 + k), "Dynpro", "00100259", "Supplier bank details",
                      f"supplier {20000001 + k % 6}", "bank key; account number"])
    reads.append([stamp(mon, 9, 42), "Dynpro", "FF_P2P_CP10", "Supplier bank details", "supplier 20000002",
                  "bank key; account number"])
    reads.append([stamp(fri, 10, 5), "Dynpro", "00100250", "Supplier bank details", "supplier 20000003",
                  "bank key"])
    # SL05: a role is added without a ticket (and makes the AP accountant an approver too).
    log(stamp(fri, 11, 5), "00100331", "RKPC-0331", "User master change", "Role assigned", "PFCG",
        detail="user 00100241; role ZD_P2P_AP_SUPERVISOR_US")

    audit.sort(key=lambda r: (r[0], r[3]))
    signins.sort()
    reads.sort()
    return {
        "users.csv": (["user", "kind", "job", "left_on", "locked"], [list(u) for u in USERS]),
        "audit_log.csv": (AUDIT_FIELDS, audit),
        "signins.csv": (["time", "application", "user", "result", "reason"], signins),
        "read_access.csv": (["time", "channel", "user", "data", "record", "fields"], reads),
        "emergency_sessions.csv": (["session", "requested_by", "start", "end", "reason", "review"],
                                   [list(s) for s in SESSIONS]),
    }


def write_pack(folder):
    folder.mkdir(parents=True, exist_ok=True)
    for name, (header, rows) in build_rows().items():
        with open(folder / name, "w", newline="", encoding="utf-8") as handle:
            writer = csv.writer(handle)
            writer.writerow(header)
            writer.writerows(rows)


def read_pack(folder):
    data = {}
    for name in build_rows():
        path = folder / name
        if not path.exists():
            raise FileNotFoundError(f"{path} is missing; run: python unit27/security_pack.py --init")
        with open(path, newline="", encoding="utf-8") as handle:
            data[name] = list(csv.DictReader(handle))
    return data


def when(text):
    return dt.datetime.strptime(text, "%Y-%m-%d %H:%M")


def check(data):
    """Apply the course rules. Returns (rule, verdict, text) tuples in rule order."""
    users = {u["user"]: u for u in data["users.csv"]}
    audit, signins, reads = data["audit_log.csv"], data["signins.csv"], data["read_access.csv"]
    out = []

    # SL01: nobody who has left signs in or logs on afterwards.
    hits = []
    for row in audit + signins:
        left = users.get(row["user"], {}).get("left_on", "")
        good = row.get("outcome", row.get("result")) in ("ok", "success")
        if left and good and row["time"][:10] > left and ("logon" in row.get("audit_class", "").lower()
                                                          or "application" in row):
            hits.append((row["time"], row["user"]))
    first = {}
    for time, user in sorted(hits):
        first.setdefault(user, [time, 0])[1] += 1
    out.append(("SL01", "FAIL" if hits else "OK", "Sign-ins and logons after leaving: "
                + ("; ".join(f"{u} from {t} ({n} event(s))" for u, (t, n) in first.items()) or "none")))
    # SL02: a leaver's user is locked.
    open_ = [u["user"] for u in users.values() if u["left_on"] and u["locked"] != "yes"]
    out.append(("SL02", "FAIL" if open_ else "OK", "Leavers not locked: " + (", ".join(open_) or "none")))
    # SL03: technical users never log on in dialog.
    dialog = [f"{r['user']} at {r['time']} from {r['terminal']}" for r in audit
              if users.get(r["user"], {}).get("kind") == "technical" and r["audit_class"] == "Dialog logon"]
    out.append(("SL03", "FAIL" if dialog else "OK", "Dialog logons by technical users: " + ("; ".join(dialog)
                                                                                          or "none")))
    # SL04: five or more failed logons for one user within 15 minutes.
    bursts, failed = [], {}
    for r in audit:
        if r["audit_class"] == "Dialog logon" and r["outcome"] == "failed":
            failed.setdefault(r["user"], []).append(when(r["time"]))
    for user, times in sorted(failed.items()):
        for i in range(len(times) - 4):
            if times[i + 4] - times[i] <= dt.timedelta(minutes=15):
                bursts.append(f"{user}: {len(times)} failed from {times[i]:%Y-%m-%d %H:%M}")
                break
    out.append(("SL04", "WARN" if bursts else "OK", "Failed logon bursts: " + ("; ".join(bursts) or "none")))
    # SL05: every user master change by a person names a ticket.
    untracked = [f"{r['time']} {r['event']} by {r['user']} ({r['detail']})" for r in audit
                 if r["audit_class"] == "User master change" and r["tcode"] and "ticket" not in r["detail"]]
    out.append(("SL05", "FAIL" if untracked else "OK", "User master changes without a ticket: "
                + ("; ".join(untracked) or "none")))
    # SL06: the emergency ID logs on only inside a recorded session.
    sessions = [(when(s["start"]), when(s["end"])) for s in data["emergency_sessions.csv"]]
    stray = [r["time"] for r in audit if users.get(r["user"], {}).get("kind") == "emergency"
             and r["audit_class"] == "Dialog logon"
             and not any(a <= when(r["time"]) <= b for a, b in sessions)]
    out.append(("SL06", "FAIL" if stray else "OK", "Emergency ID logons outside a session: "
                + (", ".join(stray) or "none")))
    # SL07: supplier bank details are read only by the jobs that need them (or inside an emergency session).
    odd = {}
    for r in reads:
        if r["data"] == "Supplier bank details" and r["user"] not in BANK_READERS \
                and users.get(r["user"], {}).get("kind") != "emergency":
            odd[r["user"]] = odd.get(r["user"], 0) + 1
    out.append(("SL07", "WARN" if odd else "OK", "Bank detail reads outside the needed jobs: "
                + ("; ".join(f"{u}: {n} read(s)" for u, n in odd.items()) or "none")))
    # SL08: on a working day the production audit log has a record at least every two hours, 08:00-17:00.
    gaps = []
    times = sorted(when(r["time"]) for r in audit)
    for day in WEEK:
        if day in HOLIDAYS or day.weekday() > 4:
            continue
        marks = [dt.datetime.combine(day, dt.time(8))] + \
                [t for t in times if t.date() == day and 8 <= t.hour < 17] + \
                [dt.datetime.combine(day, dt.time(17))]
        for a, b in zip(marks, marks[1:]):
            if b - a > dt.timedelta(hours=2):
                gaps.append(f"{a:%Y-%m-%d %H:%M} to {b:%H:%M}")
    out.append(("SL08", "FAIL" if gaps else "OK", "Silent stretches in the audit log: " + ("; ".join(gaps)
                                                                                        or "none")))
    return out


def timeline(data, user):
    rows = []
    for r in data["audit_log.csv"]:
        if r["user"] == user:
            rows.append((r["time"], "audit ", f"{r['event']} {r['tcode']} {r['terminal']} {r['detail']}".strip()))
    for r in data["signins.csv"]:
        if r["user"] == user:
            rows.append((r["time"], "signin", f"{r['application']}: {r['result']} {r['reason']}".strip()))
    for r in data["read_access.csv"]:
        if r["user"] == user:
            rows.append((r["time"], "read  ", f"{r['data']}, {r['record']} ({r['channel']})"))
    return sorted(rows)


def print_checks(results):
    print(f"Calder security pack, {SYSTEM} client {CLIENT}, week of {WEEK[0]}, checked on {AS_OF}")
    for rule, verdict, text in results:
        print(f"  {verdict:<5} {rule}  {text}")
    counts = {v: sum(1 for _, x, _ in results if x == v) for v in ("OK", "WARN", "FAIL")}
    print(f"{counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL (synthetic data)")


def selftest():
    folder = pathlib.Path(tempfile.mkdtemp())
    try:
        write_pack(folder)
        got = {rule: verdict for rule, verdict, _ in check(read_pack(folder))}
        want = {"SL01": "FAIL", "SL02": "FAIL", "SL03": "FAIL", "SL04": "WARN", "SL05": "FAIL",
                "SL06": "FAIL", "SL07": "WARN", "SL08": "FAIL"}
        assert got == want, f"expected {want}, got {got}"
        rows = read_pack(folder)
        rows["users.csv"] = [u for u in rows["users.csv"] if not u["left_on"]]
        rows["audit_log.csv"] = [r for r in rows["audit_log.csv"]
                                 if r["user"] not in ("00100094",) and r["terminal"] != "RKLT-0457"]
        assert {r: v for r, v, _ in check(rows)}["SL03"] == "OK", "SL03 should pass once the laptop logon is gone"
        assert len(timeline(read_pack(folder), "00100094")) == 3, "the leaver's week should have 3 entries"
    finally:
        shutil.rmtree(folder)
    print("Self-test passed.")


def main():
    parser = argparse.ArgumentParser(description="Calder's security sample pack (Unit 27 setup).")
    parser.add_argument("--init", action="store_true", help="write the sample pack to unit27/pack/")
    parser.add_argument("--user", help="show one user's week across all logs")
    parser.add_argument("--selftest", action="store_true", help="check the checks")
    args = parser.parse_args()
    if args.selftest:
        selftest()
        return 0
    if args.init:
        if (PACK / "audit_log.csv").exists():
            print(f"{PACK} already exists; delete it first if you want the sample back.")
            return 0
        write_pack(PACK)
        sizes = {name: len(rows) for name, (_, rows) in build_rows().items()}
        print(f"Wrote {PACK}: " + ", ".join(f"{n} ({c} rows)" for n, c in sizes.items()))
        return 0
    try:
        data = read_pack(PACK)
    except (FileNotFoundError, KeyError, ValueError) as err:
        print(f"Cannot read the pack: {err}")
        return 2
    if args.user:
        rows = timeline(data, args.user)
        print(f"{args.user}: {len(rows)} entries in the week of {WEEK[0]}")
        for time, source, text in rows:
            print(f"  {time}  {source}  {text}")
        return 0
    try:
        print_checks(check(data))
    except (KeyError, ValueError) as err:
        print(f"Cannot read the pack: a column or value is broken ({err})")
        return 2
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

2. Run the self-test. It writes the pack to a temporary folder, checks that every planted case is found, and deletes the folder:

   - **Windows (PowerShell):**

     ```powershell
     python unit27\security_pack.py --selftest
     ```

   - **macOS / Linux:**

     ```bash
     python unit27/security_pack.py --selftest
     ```

3. You should see:

   ```text
   Self-test passed.
   ```

#### Step 3: Write the week and read it against the rules

1. Write the pack:

   ```bash
   python unit27/security_pack.py --init
   ```

   ```text
   Wrote .../orchestrate-course/unit27/pack: users.csv (12 rows), audit_log.csv (219 rows), signins.csv (42 rows), read_access.csv (16 rows), emergency_sessions.csv (1 rows)
   ```

   Your path differs. `--init` never overwrites: if the pack exists, it says so and stops.

2. Read it against the rules:

   ```bash
   python unit27/security_pack.py
   ```

   ```text
   Calder security pack, S4P client 100, week of 2026-11-23, checked on 2026-11-30
     FAIL  SL01  Sign-ins and logons after leaving: 00100094 from 2026-11-24 10:11 (2 event(s))
     FAIL  SL02  Leavers not locked: 00100094
     FAIL  SL03  Dialog logons by technical users: TU_MES_RFC at 2026-11-24 16:40 from RKLT-0457
     WARN  SL04  Failed logon bursts: 00100241: 5 failed from 2026-11-23 07:41
     FAIL  SL05  User master changes without a ticket: 2026-11-27 11:05 Role assigned by 00100331 (user 00100241; role ZD_P2P_AP_SUPERVISOR_US)
     FAIL  SL06  Emergency ID logons outside a session: 2026-11-24 19:20
     WARN  SL07  Bank detail reads outside the needed jobs: 00100259: 14 read(s)
     FAIL  SL08  Silent stretches in the audit log: 2026-11-25 13:14 to 17:00
   0 OK, 2 WARN, 6 FAIL (synthetic data)
   ```

> **Note** Every user, event and finding here is synthetic: a made-up week for a fictional company, planted to show the method. It says nothing about how often these cases happen at a real SAP customer.

3. Open `unit27/pack/audit_log.csv` in VS Code or a spreadsheet and find each finding's rows. Read them by kind:

   - **Leaver (`SL01`, `SL02`):** the technician left on 16 October; the HR feed reached nobody who could lock the user.
   - **Technical user (`SL03`):** the MES's RFC user logged on from a laptop and started `SE16`, a table browser. Someone knows its password.
   - **Failed logons (`SL04`):** five wrong passwords, a lock, and an unlock with ticket `REQ-4471`. Probably a forgotten password; it is a `WARN`, not a `FAIL`.
   - **User change (`SL05`):** the security administrator gave the AP accountant the AP supervisor's role, with no ticket. In the [roles topic](https://erpfde.com/topics/roles-and-authorization-design/)'s rule set that pair breaks `P006`, post invoices and run payments.
   - **Emergency ID (`SL06`):** Monday's use was inside session `FF-0009`. Tuesday's 19:20 logon from the AP supervisor's PC, followed by a payment run, has no session.
   - **Bank details (`SL07`):** a buyer read fourteen suppliers' bank details in twelve minutes.
   - **Silent log (`SL08`):** the audit log stops on Wednesday afternoon. The bank-detail reads at 17:30 appear only in the read access log.

#### Step 4: Follow one user through the week

1. Ask for the leaver's week:

   ```bash
   python unit27/security_pack.py --user 00100094
   ```

   ```text
   00100094: 3 entries in the week of 2026-11-23
     2026-11-24 10:11  signin  S4P launchpad: success
     2026-11-24 10:12  audit   Logon successful  RKSF-0012
     2026-11-24 10:15  audit   Transaction started ME51N RKSF-0012
   ```

   The identity provider let him in and the SAP system did too. Both needed closing.

2. Now the emergency ID:

   ```bash
   python unit27/security_pack.py --user FF_P2P_CP10
   ```

   ```text
   FF_P2P_CP10: 5 entries in the week of 2026-11-23
     2026-11-23 09:31  audit   Logon successful  RKPC-0250 session FF-0009
     2026-11-23 09:40  audit   Transaction started BP RKPC-0250
     2026-11-23 09:42  read    Supplier bank details, supplier 20000002 (Dynpro)
     2026-11-24 19:20  audit   Logon successful  RKPC-0244
     2026-11-24 19:26  audit   Transaction started F110 RKPC-0244
   ```

   A user with no entries prints `0 entries`. That is a valid result: the user did nothing that week, or the ID is misspelled.

#### Step 5: Break the pack on purpose

1. Open `unit27/pack/users.csv`. On the `00100094` line, change the last value from `no` to `yes`. Save.
2. Run `python unit27/security_pack.py`. `SL02` now shows `OK`; `SL01` still shows `FAIL`, because locking today doesn't undo Tuesday's logon.
3. Rename `unit27/pack/signins.csv` to `signins.old` and run again:

   ```text
   Cannot read the pack: .../unit27/pack/signins.csv is missing; run: python unit27/security_pack.py --init
   ```

4. Rename it back. Leave the `yes` in place for the exercise.

#### Step 6: Run the Unit 27 check

This unit adds no Python libraries, so `requirements.txt` doesn't change.

1. In the course folder (not in `unit27`), create `check_unit27.py`, paste the code below and save:

```python
"""Check that your course folder is ready for Unit 27 (security, identity and compliance).

Run it from your course folder:  python check_unit27.py
Built-in Python only. It runs the security pack's self-test, looks for the earlier units' tools the
unit reuses, and reads your BTP trial date from .env; it calls no SAP service and changes nothing.
"""
import datetime
import importlib.util
import os
import subprocess
import sys

problems = 0


def report(ok: bool, label: str, fix: str = "", optional: bool = False) -> None:
    """Print one line: OK, MISSING (must fix) or LATER (optional for now)."""
    global problems
    if ok:
        print(f"  OK       {label}")
    elif optional:
        print(f"  LATER    {label}  ->  {fix}")
    else:
        problems += 1
        print(f"  MISSING  {label}  ->  {fix}")


def env_value(name: str) -> str:
    """Read one line NAME=value from .env without extra libraries."""
    if not os.path.exists(".env"):
        return ""
    with open(".env", encoding="utf-8") as handle:
        for line in handle:
            if line.strip().startswith(name + "="):
                return line.split("=", 1)[1].strip().strip('"').strip("'")
    return ""


def main() -> int:
    today = datetime.date.today()
    print(f"Unit 27 check, {today.isoformat()}")

    report(sys.version_info >= (3, 10), f"Python {sys.version.split()[0]}", "install Python 3.10 or newer")
    report(os.path.isdir("unit27"), "folder unit27/", "run this from orchestrate-course, then: mkdir unit27")

    script = os.path.join("unit27", "security_pack.py")
    if os.path.exists(script):
        done = subprocess.run([sys.executable, script, "--selftest"], capture_output=True, text=True, timeout=60)
        last = (done.stdout.strip().splitlines() or ["no output"])[-1]
        report(done.returncode == 0, f"security_pack.py self-test: {last if done.returncode == 0 else 'failed'}",
               f"run: python {script} --selftest and read the error")
    else:
        report(False, "unit27/security_pack.py", "create it in the walkthrough")
    report(os.path.exists(os.path.join("unit27", "pack", "audit_log.csv")), "unit27/pack/ sample files",
           "run: python unit27/security_pack.py --init")

    # Reused from earlier units; useful, not required to start.
    report(os.path.exists(os.path.join("unit01", "role_matrix.py")), "unit01/role_matrix.py (role matrix)",
           "optional; build it in the roles and authorization design topic", optional=True)
    report(importlib.util.find_spec("presidio_analyzer") is not None, "presidio-analyzer (from Unit 11)",
           "optional; install it as in Set up for Unit 11 (privacy topics use it)", optional=True)

    value = env_value("BTP_TRIAL_START")
    if not value:
        report(False, "SAP BTP trial (holds the Identity Services trial tenant)",
               "optional; add BTP_TRIAL_START=YYYY-MM-DD to .env when you start it", optional=True)
    else:
        try:
            left = 90 - (today - datetime.date.fromisoformat(value)).days
        except ValueError:
            left = None
            report(False, f"BTP_TRIAL_START '{value}'", "use the form YYYY-MM-DD")
        if left is not None and left > 0:
            report(True, f"SAP BTP trial: {left} day(s) left of 90 (the Identity Services tenant ends with it)")
        elif left is not None:
            report(False, f"SAP BTP trial ended {-left} day(s) ago", "register again only when a topic needs it",
                   optional=True)

    print("Ready for Unit 27." if problems == 0 else f"{problems} item(s) to fix before Unit 27.")
    return 0 if problems == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
```

2. Run it:

   ```bash
   python check_unit27.py
   ```

3. Without the earlier tools or a trial, the output looks like this (your date and Python version differ):

   ```text
   Unit 27 check, 2026-11-30
     OK       Python 3.12.7
     OK       folder unit27/
     OK       security_pack.py self-test: Self-test passed.
     OK       unit27/pack/ sample files
     LATER    unit01/role_matrix.py (role matrix)  ->  optional; build it in the roles and authorization design topic
     LATER    presidio-analyzer (from Unit 11)  ->  optional; install it as in Set up for Unit 11 (privacy topics use it)
     LATER    SAP BTP trial (holds the Identity Services trial tenant)  ->  optional; add BTP_TRIAL_START=YYYY-MM-DD to .env when you start it
   Ready for Unit 27.
   ```

   `LATER` lines are fine. With the earlier tools they show `OK`.

#### Step 7: Create an Identity Services trial tenant (optional)

This gives you SAP's identity admin console for the single sign-on and identity topics. It is personal and non-productive: use test users only, never your company's people.

1. If you have no BTP trial yet, register at `https://www.sap.com/products/technology-platform/trial.html` as in [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/), and add the date to `.env`:

   ```text
   BTP_TRIAL_START=2026-11-30
   ```

2. Open your trial account in the BTP cockpit and go into your trial subaccount.
3. Choose **Services > Instances and Subscriptions**, then **Create**.
4. Pick service **Cloud Identity Services** (the tutorial calls it *Cloud Identity Service*) and plan **default**. Choose **Next**.
5. Keep the tenant type **PRODUCTIVE**, as SAP's tutorial does, and choose **Create**. The type only names the tenant; the trial's limits still apply.
6. Wait for an email titled *Activate Your Account for Identity Authentication Service*. Choose **Activate your account** and set a password for the admin console.
7. Back in the cockpit, choose **Security > Trust Configuration**, then **Establish Trust**. Choose your new tenant, choose **Next**, keep the defaults and choose **Finish**.

These steps follow SAP's [trial tutorial](https://developers.sap.com/tutorials/application-frontend-trial-setup.html) as it stood on 30 November 2026. If a screen differs, follow the tutorial. Rerun `python check_unit27.py`: the trial line now shows the days left.

> **Warning** The admin console password and any test users' passwords are secrets. Keep them in a password manager, not in `.env`, a script or Git.

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

```bash
git add unit27 check_unit27.py
git commit -m "Unit 27 setup: security sample pack and check"
```

The pack holds only made-up data, so it is safe to commit. Never put a real system's logs in this folder: they hold personal data.

#### How the code works

| Part | What it does |
| --- | --- |
| `USERS`, `DAILY`, `SESSIONS` | The week's cast: who works in `S4P`, their usual transactions, and the emergency session on record |
| `build_rows()` | Writes a normal week (sign-in, logon, a few transactions; the MES polling hourly), then plants the eight cases |
| `write_pack()`, `read_pack()` | Save the five files as CSV and read them back as rows of named columns |
| `check()` | Applies `SL01` to `SL08` and returns one verdict per rule: `OK`, `WARN` or `FAIL` |
| `timeline()` | Joins one user's rows from the audit log, the sign-ins and the read access log, in time order |
| `selftest()` | Builds the pack in a temporary folder and asserts the planted verdicts and the leaver's three entries |
| `check_unit27.py` | Runs the self-test, checks the pack and the earlier tools, and counts down the BTP trial from `.env` |

#### 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/Linux try `python3` |
| `Cannot read the pack: ... is missing` | `--init` hasn't run, or a file was renamed | Run `python unit27/security_pack.py --init`, or rename the file back |
| `already exists; delete it first` | `--init` won't overwrite your edits | Delete `unit27/pack` only if you want the sample back |
| `Cannot read the pack: a column or value is broken` | An edit changed a header or a date's format | Undo the edit, or delete `unit27/pack` and run `--init` |
| Your counts differ from Step 3 | You edited the pack, or pasted the script partly | Compare with the step's output; rerun the self-test |
| `ModuleNotFoundError` | You ran another unit's script by mistake | This script uses built-in modules only; check the file name |
| The trial page or cockpit won't load | A company proxy or firewall blocks sap.com sign-ups | Use a personal network, or skip the trial; no Unit 27 exercise needs it |
| No activation email | It went to spam, or the instance failed | Check spam; in **Instances and Subscriptions**, open the instance's status |

### Where this shows up in SAP

- **The audit log's configuration.** SAP's design documentation says filters by client, user, audit class and weight decide what the security audit log records ([SAP Help](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/41bf80aa601c86e10000000a42189b/content.htm)). Rule `SL08` only finds a silent log; the audit logging topic covers what to record and keep.
- **Reading it.** SAP's 2025 user group deck names `RSAU_READ_LOG` and `SM20` for reading the log, and integration with a central security monitoring tool for watching it ([SAP user group deck](https://assets.dm.ux.sap.com/sap-user-groups/pdfs/250522_security_audit_log_past_present_and_future_01.pdf)). The threat detection topic takes `SL03`, `SL04` and `SL07` there.
- **Read access.** SAP describes read access logging as logging and monitoring read access to sensitive data, usually for legal requirements ([SAP Help](https://help.sap.com/saphelp_nwpi711/helpdata/en/c8/747a52e97b9f11e10000000a441470/content.htm)). Whether to log bank details, and who may read the log, is a privacy decision the unit returns to.
- **Leavers and emergency access.** The [roles topic](https://erpfde.com/topics/roles-and-authorization-design/) already found the leaver and an unreviewed emergency session in Calder's role matrix in October. This week shows the same gaps from the log side; the access control and identity governance topics design the fix.

### Where AI fits

Two ways, both covered later. Agents are one more kind of user: an agent's technical identity should never log on in dialog, like `TU_MES_RFC`, and its reads of sensitive data belong in the same logs, as [agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) set out. And AI can help read logs: summarizing a week like this one, or proposing which findings to look at first. A model reading `detail` and `reason` columns reads text that users and systems wrote, so the rules stay in code and a person decides, as [prompt injection and tool poisoning](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/) showed. Nothing in this setup calls a model.

### Production concerns

- **Real logs are personal data.** They name people and what they did. Keep them in the systems that own them; never copy them to a laptop for practice.
- **Trials are not pilots.** The trial tenant has 50 users, no company user store and ends with the BTP trial. Proofs of concept use a non-production tenant Calder owns.
- **The course rules are not a baseline.** Thresholds such as five failures in 15 minutes or two silent hours were chosen for the lab. A real rule set starts from SAP's guidance, the company's risks and what the security team can actually follow up.
- **Every finding needs an owner.** A rule that fires every week with nobody assigned teaches people to ignore it.

### Pitfalls

- Treating `OK` on a rule as proof of safety: `SL08` can't tell you what happened while the log was silent.
- Locking a leaver in SAP only, and forgetting the identity provider and the cloud apps.
- Giving a technical user a password that works in dialog "just for testing".
- Approving emergency access by phone and recording the session the next day, or not at all.
- Starting the BTP trial on the first day of the unit and losing it before the identity topics.
- Copying trial passwords into `.env` or a script.

### Exercise: record Tuesday's emergency session and add a review rule

The AP supervisor explains on Monday morning that she borrowed the emergency ID on Tuesday evening to run a payment for Tamsfield before its cut-off. Recording the session after the fact makes `SL06` pass, so the review must catch it instead.

1. Open `unit27/pack/emergency_sessions.csv` and add this line at the end. Save.

   ```text
   FF-0010,00100244,2026-11-24 19:00,2026-11-24 19:40,Payment run for Tamsfield before its cut-off,open
   ```

2. Open `unit27/security_pack.py`. In `check()`, find the line `    return out` (the last line of the function). Just above it, paste these lines with the same four-space indent:

   ```python
       # SL09: every emergency session's log is reviewed within 5 days (course rule from the roles topic).
       late = [f"{s['session']} by {s['requested_by']} on {s['start'][:10]}: not reviewed after "
               f"{(AS_OF - when(s['start']).date()).days} days" for s in data["emergency_sessions.csv"]
               if s["review"] != "reviewed" and (AS_OF - when(s["start"]).date()).days > 5]
       out.append(("SL09", "FAIL" if late else "OK", "Emergency sessions not reviewed: " + ("; ".join(late) or "none")))
   ```

3. In `selftest()`, find `"SL08": "FAIL"}` at the end of the `want` list and change it to `"SL08": "FAIL", "SL09": "OK"}`. The fresh sample has no open session, so `SL09` passes there. Save.
4. Run `python unit27/security_pack.py --selftest`, then `python unit27/security_pack.py`. The last lines now read:

   ```text
     FAIL  SL08  Silent stretches in the audit log: 2026-11-25 13:14 to 17:00
     FAIL  SL09  Emergency sessions not reviewed: FF-0010 by 00100244 on 2026-11-24: not reviewed after 6 days
   2 OK, 2 WARN, 5 FAIL (synthetic data)
   ```

   `SL02` is `OK` from Step 5 and `SL06` is `OK` because the session is now on record.
5. In `unit27/notes.md`, write three sentences: who should have approved `FF-0010` before it started, who reviews it now, and what a reviewer should check given that the session ran `F110` from the AP supervisor's own PC.

**Done when** the self-test passes, the check prints `2 OK, 2 WARN, 5 FAIL (synthetic data)` with `SL09` failing for `FF-0010`, and `notes.md` holds your three sentences. The access control topic, planned in Unit 27, designs the emergency access process these notes start.

### Check yourself

1. Why does SL08 look for silent stretches in the audit log instead of trusting that a quiet log means a quiet day?
   - A. The audit log writes a heartbeat record every hour by default
   - B. SAP says auditing stops once the file size limit is hit
   - C. Read access logging deletes audit records it has copied
   - D. Calder's MES stops polling when nobody is logged on

   Answer: B. SAP's design documentation says auditing stops once `rsau/max_diskspace/local` is reached. A stopped log and a quiet afternoon look the same, so something must check for gaps. In the sample, the MES's hourly calls vanish too, which is the clue.

2. The leaver's user is locked today and SL02 turns OK, but SL01 still fails. Why is that the right behaviour?
   - A. SL01 only checks the identity provider, which is still open
   - B. The lock takes effect only at the next audit file rollover
   - C. Locking today can't undo the logon made on Tuesday
   - D. SL01 fails whenever any leaver appears in users.csv

   Answer: C. SL01 reports activity after the leaver date, which is history the lock can't change. SL02 reports the current state of the user. Both matter: one is the incident to investigate, the other the gap to close.

3. In `check()`, how does SL06 decide that the 19:20 logon on Tuesday is a problem?
   - A. It compares the terminal with the requester's own PC
   - B. It flags any emergency ID logon after 17:00
   - C. It looks for transaction F110 after an emergency logon
   - D. No recorded session's window contains the logon time

   Answer: D. SL06 builds a list of session windows from `emergency_sessions.csv` and flags an emergency-ID dialog logon outside all of them. Terminal, hour and transaction play no part, which is why recording a session afterwards makes it pass and the exercise adds a review rule.

4. The MES's technical user logs on in dialog from a laptop and starts SE16. What would you do first as the architect?
   - A. Raise the failed-logon threshold so it isn't flagged again
   - B. Rotate its password and stop it logging on in dialog
   - C. Add the laptop's terminal name to the technical user's allowed list
   - D. Move the MES interface to the emergency ID until it is fixed

   Answer: B. A technical user should only be used by the system it serves. A dialog logon means a person knows its credentials. Rotate them and stop that user from logging on in dialog; the authorization concept topic covers how.

5. The buyer's bank-detail reads appear in read_access.csv but nothing for that evening appears in audit_log.csv. What does this teach?
   - A. Read access logging is a replacement for the security audit log
   - B. The reads must be a fault in the read access log
   - C. Bank detail reads are never recorded by the audit log
   - D. Each log fails on its own, so one can cover another's gap

   Answer: D. The audit log stopped on Wednesday afternoon, while read access logging kept recording reads of sensitive data. They record different things and can fail independently, so a design should know which log answers which question and watch each one.

6. A colleague wants to load last month's real S4P audit log into unit27/pack to practise. What do you say?
   - A. Yes, if the file is converted to the course CSV layout first
   - B. Yes, because audit logs contain only technical events
   - C. No: real logs name people and belong in the owning systems
   - D. No: the script can only read files written by --init

   Answer: C. Real logs are personal data about what named people did. Practise on the synthetic pack and analyse real logs only in the systems and processes that own them. The script would read a file in the right layout, which is exactly why the rule matters.

7. What does the optional Identity Services trial tenant let you do in this unit?
   - A. Sign in your BTP administrators with your company's directory
   - B. Provision users into an on-premise S/4HANA test system
   - C. Try the admin console and trust with test users
   - D. Run access risk analysis across Calder's cloud applications

   Answer: C. SAP's blog post lists the trial's limits: up to 50 users, no Connectivity plan for a corporate store or on-premise provisioning, and no platform users. It suits trying the console and a subaccount trust; risk analysis belongs to other products with no trial we found.

## Sources

- [Start your free trial of SAP Business Technology Platform (sap.com, read 2026-11-30)](https://www.sap.com/products/technology-platform/trial.html): 90 days from registration; a non-commercial, time-limited offering; at least one login every 30 days keeps it active; at the end all subaccounts and services are terminated
- [SAP Cloud Identity Services offered as trial version (SAP Community, Technology Blog Posts by SAP, read 2026-11-30)](https://community.sap.com/t5/technology-blog-posts-by-sap/sap-cloud-identity-services-offered-as-trial-version/ba-p/13552272): Cloud Identity Services default plan in the BTP trial's Service Marketplace; one tenant per BTP global trial account; up to 50 users; no Connectivity plan, so no corporate user store or on-premise provisioning; application identity provider only, not for platform users; ends with the trial; deployed in US East
- [Set Up Application Frontend service in your BTP trial account (SAP Developers tutorial, read 2026-11-30)](https://developers.sap.com/tutorials/application-frontend-trial-setup.html): trial landscape us10-trial; Instances and Subscriptions, Create, service Cloud Identity Service, plan default, service type PRODUCTIVE; Security > Trust Configuration > Establish Trust; activation email for the admin console; this provisioning step is only needed in trial accounts
- [Explaining Users and Identity Providers (SAP Learning, Operating SAP BTP, read 2026-11-30)](https://learning.sap.com/courses/operating-sap-business-technology-platform/explaining-users-and-identity-providers): platform users are administrators, developers or operators; business users are end users of applications; SAP ID service is the default identity provider; SAP strongly recommends a custom Cloud Identity Services tenant, created by self-service, also in a trial; one custom trust per subaccount
- [Explaining Identity and Access Management on SAP BTP (SAP Learning, read 2026-11-30)](https://learning.sap.com/courses/operating-sap-business-technology-platform/explaining-identity-and-access-management-on-sap-btp): components Identity Authentication, Identity Provisioning, Identity Directory, Authorization Management; BTP trial accounts are entitled for one trial tenant
- [Background documentation: The Design of the Security Audit Log (SAP Help, read 2026-11-30)](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/41bf80aa601c86e10000000a42189b/content.htm): records security-related activities in AS ABAP; filters by client, user, audit class and weight; daily audit file per application server; record holds user, client, terminal, transaction, program, audit class, security level and message text among others; audit classes dialog logon, RFC/CPIC logon, RFC function call, transaction start, report start, user master change, system, other; rsau/max_diskspace/local default 1 MB, auditing stops when reached; files not deleted automatically
- [Security Audit Log: past, present and future (SAP user group deck, Patrick Boch, SAP, 2025-05-22)](https://assets.dm.ux.sap.com/sap-user-groups/pdfs/250522_security_audit_log_past_present_and_future_01.pdf): what to look for includes logons of SAP standard users and interesting dialog users, generic table access, downloads, RFC callbacks and changes to the log's own configuration; RSAU_READ_LOG/SM20 to read; SIEM integration
- [SAP Cloud Identity Access Governance (sap.com product page, read 2026-11-30)](https://www.sap.com/canada/products/financial-management/cloud-iam.html): standard and integration editions with Buy now; a cloud test and demo edition for partners; no free trial offered
- [SAP Enterprise Threat Detection (sap.com product page, read 2026-11-30)](https://www.sap.com/india/products/financial-management/enterprise-threat-detection.html): paid editions and a non-productive cloud test, demo and development edition for partners; no free trial offered
- [Read Access Logging (SAP Help, read 2026-11-30)](https://help.sap.com/saphelp_nwpi711/helpdata/en/c8/747a52e97b9f11e10000000a441470/content.htm): logs and monitors read access to sensitive data, usually for legal requirements; channels RFC, Dynpro, Web Dynpro and web services; can log which UI elements were visible and their content
