# SAP Cloud Identity Services: authentication, provisioning and the identity directory

> How SAP's identity layer signs people in, feeds users and groups from HR to SAP systems, and keeps one directory, and how to design it so leavers lose access.

- Course: Orchestrate, Unit 27 · Security, identity and compliance
- Page: https://erpfde.com/topics/sap-cloud-identity-services/
- Updated: 2026-12-01
- Reading time: Foundational 8 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

**SAP Cloud Identity Services** is SAP's identity layer for its cloud products. A company gets its own **tenant** of it, and the tenant does three jobs:

- **Identity Authentication** signs people in. It can check a password itself or, more often, pass the person on to the company's own identity provider, such as Microsoft Entra ID, and hand the result back to the SAP application. Once signed in, a person can open other SAP applications without signing in again: single sign-on.
- **Identity Provisioning** copies users and groups between systems: from HR or the corporate directory into SAP, and from there into each application that keeps its own user list.
- **Identity Directory** is the tenant's own user store. It holds each person once, with a **global user ID** that SAP applications use to recognise the same person everywhere.

A fourth part, **Authorization Management**, lets some newer applications keep their permission rules in the tenant as policies.

The design question is never "do we use it": SAP products that bundle it expect it. The questions are how many tenants, which identity provider signs in whom, where users come from, and how a leaver is removed everywhere.

### Why it matters to the business

**Leavers keep access.** A person who left in October can still sign in to S/4HANA in December when the HR feed only reads active employees. Nothing fails, so nobody notices until an audit or an incident.

**New joiners wait.** A buyer who starts on Tuesday and gets SAP access the following Monday spends a week borrowing a colleague's screen, which is its own control failure.

**Partners and employees mix.** A distributor portal that sends everyone to the company's Microsoft sign-in locks out every distributor; one that lets employees use a separate SAP password skips the company's multifactor rules.

**AI depends on it.** As of December 2026, SAP's Joule documentation says every system Joule uses must sign people in through one SAP Cloud Identity Services tenant, and that agents need full user identities in its directory ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/identity-and-access-management-for-joule-050287e.md)). A messy identity layer becomes a blocked AI rollout.

**Example:** Calder Pumpworks, the course's fictional pump maker, found its maintenance technician `00100094`, who left on 16 October 2026, signing in to its S/4HANA system on 24 November. The [Unit 27 setup](https://erpfde.com/topics/set-up-for-unit-27/) planted that sign-in; this topic finds its cause in the identity design.

### How SAP does it

As of 1 December 2026, SAP's documentation describes the service like this:

- **Tenants.** A company buying an SAP cloud solution that bundles the service is entitled to one productive and one test tenant; buying another solution reuses them. Productive and test tenants are technically the same; the type is a label for structuring the landscape ([Tenants](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/tenants-93160eb.md)). SAP recommends one productive tenant for all SAP cloud solutions, because that is what makes single sign-on and integration work out of the box ([Get Your Tenant](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/get-your-tenant-460766b.md)).
- **Price.** Identity Authentication, Identity Provisioning and Identity Directory are commercially included for SAP cloud solutions and applications on SAP BTP. SAP charges for each successful sign-in from a non-SAP application that uses the tenant ([Tenants](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/tenants-93160eb.md)).
- **Corporate identity provider.** The tenant can act as a proxy for the company's own provider over SAML 2.0 or OpenID Connect, so employees use their usual sign-in and its multifactor rules ([Corporate Identity Providers](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/corporate-identity-providers-19f3eca.md)).
- **SAP-managed or customer-managed.** For some products, SAP now sets up and runs the trust and provisioning itself; the company keeps the business decisions ([SAP-Managed SAP Cloud Identity](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/sap-managed-sap-cloud-identity-6039a38.md)). Joule uses this model.
- **Agents.** SAP documents agent identities, where an AI agent is registered in the tenant and administrators decide who may call it. SAP marks this as part of an Early Adopter Care program as of December 2026 ([Agents](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/agents-12bef24.md)).

> **Note** **For functional consultants.** Where provisioning is in place, SAP users and their role assignments are created from HR data and groups, not typed into the system. A new role for buyers means a group and a mapping to the role, approved by the role owner; test cases need a test user fed through the same route. If a role is renamed in S/4HANA, the mapping breaks quietly: SAP's documentation says the group's members are then not updated.

### Four decisions to take early

| Decision | Calder's choice | What goes wrong otherwise |
| --- | --- | --- |
| How many tenants | One productive (`calder-ias`), one test (`calder-ias-test`) | A second productive tenant for a pilot breaks single sign-on and Joule's one-tenant rule |
| Who signs employees in | Calder's Microsoft Entra ID (`calder-entra`), through the tenant | Separate SAP passwords without the company's multifactor rules |
| Where people come from | SAP SuccessFactors Employee Central (`SF-EC`), Calder's HR system, into the directory, then into each application | Accounts typed by hand, joiners waiting, leavers forgotten |
| Who may change it | Two or three named administrators | Five administrators, one of them a contractor who left |

The deep layer replays one week of Calder's HR changes through a draft design and the reviewed one. With the draft, the October leaver could sign in on all eight days, and the new buyer had no working access all week. With the reviewed design, the leaver was refused from the first morning and the buyer worked from his second day. These are results of a course simulation on made-up data, not measurements from a real tenant.

### Questions to ask

- How many productive SAP Cloud Identity Services tenants do we have, and which SAP products use each one?
- Which identity provider signs in employees, and which signs in partners and customers?
- Where do users come from: HR, the corporate directory, or typed by hand? How long until a joiner can work?
- When someone leaves, which job removes them, how fast, and who checks it ran?
- Which of our SAP products does SAP manage the identity integration for, and what can we still change there?
- Who are the tenant's administrators, and who reviews that list?
- What does our Joule plan require from the directory, and are we ready for it?

### Common misconceptions

- **"Disabling someone in Microsoft Entra ID removes them from SAP."** It stops sign-ins through Entra. An application that lets the tenant check its own passwords, or a user who keeps a password in the ABAP system itself, is not covered.
- **"The HR feed deletes leavers automatically."** SAP's documentation says deletions reach a target only in a full read, and only when the target was told beforehand to delete entities it already knew. A feed that reads only active employees never sees the leaver again.
- **"A second tenant is a harmless way to start a pilot."** SAP recommends one productive tenant, and Joule requires one tenant for all the systems it uses.
- **"Identity Services is another licence line."** For SAP cloud solutions and BTP applications it is included. Sign-ins to non-SAP applications through the tenant are charged.
- **"SAP manages it, so we don't need to understand it."** Where SAP manages the integration, the company still chooses the identity provider, keeps HR data right, assigns roles and decides who may use agents.

### Key terms

- **SAP Cloud Identity Services:** SAP's identity layer, delivered as a tenant per company.
- **Identity Authentication:** the part that signs people in and provides single sign-on.
- **Identity Provisioning:** the part that copies users and groups from source systems to target systems.
- **Identity Directory:** the tenant's user store, reachable through a SCIM 2.0 API.
- **Global user ID:** the identifier the directory gives each person, used to link that person's records across SAP systems.
- **Corporate identity provider:** the company's own sign-in service, such as Microsoft Entra ID, which the tenant can pass people on to.
- **Source and target system:** in provisioning, where users are read from and where they are written to.
- **SAP-managed integration:** a model where SAP configures and runs trust and provisioning for its products.

### Check yourself

1. Calder plans a pilot of a new SAP cloud product and the vendor offers a fresh productive Identity Services tenant for it. What does SAP's guidance say?
   - A. Take it, because separate tenants keep a pilot's users and settings away from production
   - B. Reuse the existing productive tenant, which single sign-on and integration rely on
   - C. Take it, because each SAP product needs its own tenant to be supported
   - D. Reuse the test tenant for the pilot, because productive tenants carry an extra charge

   Answer: B. SAP recommends one productive tenant for all SAP cloud solutions, because integration and out-of-the-box single sign-on depend on it. Joule also requires one tenant for every system it uses, so a second productive tenant would block it later.

2. An employee who left in October still signs in to S/4HANA in December. The HR feed reads only active employees. What is the most likely cause?
   - A. The corporate identity provider keeps a cache of old passwords for each user
   - B. SuccessFactors deletes leavers too late in the month for the feed to notice the change
   - C. The feed reads only active people, so it never reads him again and he stays active
   - D. Identity Services keeps every user for 90 days after they leave, by design

   Answer: C. A filter on active employees means the leaver simply disappears from what the feed reads. Nothing tells the directory to change them, so the user stays active wherever it was copied.

3. Which job does Identity Provisioning do?
   - A. It checks each person's password and multifactor sign-in at the corporate provider
   - B. It decides which business data a user may see inside an application
   - C. It copies users and groups from source systems, such as HR, into target systems
   - D. It stores the company's audit logs for the period an auditor needs

   Answer: C. Identity Provisioning reads users and groups from a source and writes them to targets. Signing in belongs to Identity Authentication, and permissions inside an application are the application's own roles or Authorization Management's policies.

4. A distributor portal must admit Calder's employees and Hallam's staff. Which sign-in design fits?
   - A. Send everyone to Calder's Microsoft Entra ID, which then decides who is a partner
   - B. Employees by e-mail domain to Entra ID; everyone else signed in by the tenant
   - C. Give everyone, employees included, a separate password in Identity Services
   - D. Create a Microsoft Entra ID account for every distributor user who needs access

   Answer: B. Rules by e-mail domain send employees to the company's provider with its multifactor rules, while partners, who have no Entra account, are signed in by the tenant. Separate passwords for employees would bypass the company's sign-in policy.

5. What does Identity Services cost a company that uses it only for SAP cloud solutions and BTP applications?
   - A. A fee per user per month, charged on top of each SAP cloud subscription
   - B. A fee for each productive tenant, while test tenants come free of charge
   - C. Nothing extra; only sign-ins from non-SAP applications through it are charged
   - D. Nothing at all, including sign-ins from any non-SAP application through the tenant

   Answer: C. SAP's documentation says the main services are commercially included for SAP cloud solutions and BTP applications. Every successful sign-in from a third-party application through the tenant is charged.

6. Where SAP manages the identity integration for a product, what stays with the company?
   - A. Nothing, since SAP runs the tenant, the provisioning jobs and every decision made in it
   - B. Only the choice of tenant region, which is fixed after the first sign-in
   - C. The identity provider choice, HR data quality, role and agent assignments
   - D. Writing the provisioning jobs and transformations for each of SAP's own products

   Answer: C. SAP takes the technical integration: trust, connectors and provisioning jobs. The business decisions stay with the company, and SAP warns against adding customer jobs that duplicate the ones it manages.

## Deep layer

### Mental model

Think of the tenant as **a switchboard with a register**. The register (Identity Directory) holds each person once. The switchboard (Identity Authentication) takes every sign-in call from an SAP application and routes it: to the company's identity provider for employees, to its own password check for partners. The couriers (Identity Provisioning jobs) carry the register's entries out to every application that keeps its own user list, and carry HR's changes in.

Most identity failures are not sign-in failures. They are **copies that stopped updating**: a courier that only carries new entries, never removals; a register entry the switchboard doesn't consult; an application that finds users by e-mail when the e-mail changed. The architect's work is to decide where each person's truth lives and to make sure every copy follows it, including when the person leaves.

### How it works

#### The four services in one tenant

| Service | What it does | Main settings an architect owns |
| --- | --- | --- |
| Identity Authentication | Sign-in, single sign-on, multifactor and risk-based rules, proxy to corporate identity providers | Default identity provider per application, conditional authentication rules, identity federation, subject name identifier |
| Identity Provisioning | Jobs that read users and groups from source systems and write them to target systems; proxy mode for an external identity management tool | Source and target systems, schedules, full or delta read, transformations, deletion behaviour |
| Identity Directory | The user and group store, with predefined and custom schemas, the global user ID, and a SCIM 2.0 API | Which attributes are stored, group design, who may call the API |
| Authorization Management | Authorization policies for applications built to use them | Which applications use policies instead of their own roles |

SAP's documentation lists the Identity Authentication features in its [Product Details](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/product-details-4d404b1.md) and describes the directory's role as the persistency layer in [Centralized Provisioning with Identity Directory](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/centralized-provisioning-with-identity-directory-9d0235c.md). [Authorization Policies](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/authorization-policies-01ddefa.md) covers functional and instance-based authorizations for applications that declare them, with client libraries for Node.js, Java and Go and CAP integration.

#### Users, groups and administrators

SAP's [Users](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/users-70e95d1.md) page sorts users into three categories, as of December 2026:

- **Administrators.** *User administrators* are people who manage the tenant, applications, identity providers, provisioning, users and groups. *System administrators* are technical users for system-to-system calls, such as provisioning; SAP notes they have the same authorizations as user administrators.
- **End users**, with a user type: Customer, Employee, Partner, Public, External, Onboardee or Alumni. User type is one of the criteria conditional authentication can use.
- **Technical users**, which authenticate with secrets or certificates and are managed in their own tile.

[Groups](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/groups-d93be69.md) come as *user groups* (people with something in common), *authorization groups* (created with authorization policies) and *application-specific groups*, which belong to one application and can be created by provisioning jobs. A group is the unit an architect designs: it is what a token carries to a BTP application, what conditional authentication can test, and what provisioning maps to a role in an ABAP system.

#### Sign-in: who authenticates whom

```mermaid
sequenceDiagram
  participant B as Browser
  participant A as SAP application
  participant T as Identity Authentication<br/>(calder-ias)
  participant E as calder-entra
  B->>A: open S4P launchpad
  A->>T: authentication request
  T->>T: rules: e-mail domain, user type,<br/>group, IP range
  T->>E: employee: delegate (OIDC)
  E-->>T: token for the employee
  T->>T: identity federation: user in<br/>directory and active?
  T-->>A: assertion, subject = login name
  A->>A: map subject to its own user
```

Each application connected to the tenant has a **default identity provider**: the tenant itself or a corporate one. **Conditional authentication** rules can override it per person, by e-mail domain, user type, user group or IP range, evaluated in priority order until one matches. SAP's [conditional authentication](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-conditional-authentication-for-an-application-0143dce.md) page adds two constraints: rules only apply when the default is the tenant itself, and if no person should ever be signed in by the tenant, the last rule must be a catch-all on IP range `0.0.0.0/0`.

When a corporate provider signs a person in, **identity federation** decides what the tenant does with the result ([Configure Identity Federation](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-identity-federation-c029bbb.md)). Both options are off by default:

- **Use Identity Authentication user store.** The tenant looks the person up in its directory and sends the application the directory's attributes. Off, it passes on what the corporate provider sent.
- **Allow Identity Authentication users only.** Only people who exist in the directory get through. Off, anyone the corporate provider authenticates is allowed. Restricting by group or e-mail domain works only with this option on.

That second switch is what connects the HR feed to sign-in. With it on, a leaver marked inactive in the directory can't reach the application even if their corporate account was never disabled. The lab models an inactive directory user as refused; confirm this behaviour in your own tenant before you rely on it alone.

The tenant tells the application who signed in through the **subject name identifier**: the name ID in SAML 2.0, the subject in OpenID Connect ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-the-subject-name-identifier-sent-to-the-application-1d020e3.md)). From the directory it can be the global user ID, user ID, e-mail, display name, login name or employee number. SAP warns that the tenant does not check employee numbers for uniqueness. E-mail is unique but changes when a mailbox is renamed, and an application that maps users by e-mail then finds nobody.

#### Provisioning: sources, targets and the directory

```mermaid
flowchart LR
  HR[SF-EC<br/>source] -->|read: filter,<br/>full or delta| IPS((Identity<br/>Provisioning))
  IPS -->|write| DIR[(Identity Directory<br/>global user ID)]
  DIR -->|read| IPS2((Identity<br/>Provisioning))
  IPS2 -->|write: groups to roles<br/>via Cloud Connector| S4P[S4P<br/>AS ABAP target]
  DIR -. SAP-managed jobs .-> J[Joule and<br/>SAP-managed products]
```

A **source system** is read; a **target system** is written to; a **proxy system** lets an external identity management tool read and write through the service ([Provisioning Systems](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/provisioning-systems-15da6af.md)). Each system has **properties** (connection, filters, behaviour) and **transformations**: a read transformation turns the source's format into a common JSON format, and a write transformation turns that into the target's ([Transformations](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/transformations-81f5204.md)).

SAP's recommended shape is **centralized**: read people from the company's user store into the directory, which gives each new user a global user ID, then provision from the directory to each SAP application ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/centralized-provisioning-with-identity-directory-9d0235c.md)).

Four documented behaviours decide whether leavers leave:

1. **Delta read reads only changes.** In delta mode a job reads only new and changed entities. Entities deleted in the source are deleted in the target only by a **full read** that read the source successfully. The property `ips.full.read.force.count` forces a full read after a number of scheduled delta reads; the first read of a source is always full ([Manage Full and Delta Read](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/manage-full-and-delta-read-b7f817c.md)).
2. **Known entities are not deleted by default.** A target deletes users it already knew only when `ips.delete.existedbefore.entities` is `true` on that target **before** the deleting job runs. Set afterwards, the remaining users must be deleted by hand or script ([Manage Deleted Entities](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/manage-deleted-entities-3d6bdf1.md)).
3. **The SuccessFactors source reads active users.** It defaults to delta read, and `sf.user.filter` starts as `active eq true`. The property `sf.user.read.deactivatedafter` adds users set to inactive from a given date, so their new status can travel ([SAP SuccessFactors source](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/sap-successfactors-f29b5c6.md)).
4. **ABAP roles must already exist.** With SAP Application Server ABAP as a target, groups become role assignments. The service can't create or delete roles; a group must match an existing role's name exactly, case included, or an error is raised and the group's members are not updated. A `valueMapping` in the transformation can translate group names to role names. The connection runs through the Cloud Connector over RFC SNC, with a technical user authorized as SAP Note 3666721 describes ([SAP Application Server ABAP target](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/sap-application-server-abap-7a0c6e7.md)).

Put the first three together and you get Calder's October leaver: a delta feed filtered to active employees never reads him again, and nothing removes him downstream.

#### Tenants, regions and SAP-managed products

A tenant runs in one region; SAP lists the regions and data centers on its [Regional Availability](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/regional-availability-be600ca.md) page. Moving a tenant to another region goes through an incident on component `BC-IAM-IDS`, needs planned downtime, and policy-based authorizations must be configured again afterwards ([Get Your Tenant](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/get-your-tenant-460766b.md)). SAP's [disaster recovery page](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/disaster-recovery-high-availability-2c1a055.md) describes replication between zones, failover between data centers where a country has two, and a daily backup at 01:00 UTC kept for 90 days.

For SAP-managed products, SAP preconfigures the source and target systems, hides them from the admin console, runs their jobs every 30 minutes, and makes some application settings read-only. SAP cautions against customer jobs or transformations that duplicate or overlap these flows, because running both for the same back end causes inconsistent data ([SAP-Managed SAP Cloud Identity](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/sap-managed-sap-cloud-identity-6039a38.md)).

For Joule, SAP's page (marked as phased availability) describes two stages. In **Stage 1**, SAP-managed jobs read each application's users as lightweight *consolidatable* records and write the global user ID back; Joule works as a conversational assistant. In **Stage 2**, full identities exist in the directory and are linked to those records; only then can users be assigned to agents. SAP recommends creating full identities before deploying Joule, typically from the corporate identity management system ([Identity and Access Management for Joule](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/identity-and-access-management-for-joule-050287e.md)). The [Joule activation topic](https://erpfde.com/topics/activating-joule-across-products/) checks Calder's readiness step by step.

#### Calder's design

Calder's people live in `SF-EC`; its employees sign in with Microsoft Entra ID (`calder-entra`), as the [Joule beside Microsoft 365 Copilot topic](https://erpfde.com/topics/joule-and-other-assistants/) set up. Its tenants are `calder-ias` (productive) and `calder-ias-test`, as in the [Unit 23 setup](https://erpfde.com/topics/set-up-for-unit-23/). The [BTP security model topic](https://erpfde.com/topics/btp-security-model/) labels the same productive tenant `calder-lab` and uses origins `calder-platform` and `calder-ias` for its trust configurations. The reviewed design:

- Applications on `calder-ias`: `S4P` (S/4HANA launchpad), the AI subaccount `calder-ai-prod`, the distributor portal `dist-portal`, and `joule-prod` (SAP-managed). `S4Q` is on `calder-ias-test`.
- Employees authenticate at `calder-entra`, with identity federation's two options on. Hallam's distributor users sign in at the tenant; employees reach Entra by an e-mail-domain rule.
- One job reads `SF-EC` into the directory every night: delta read, users deactivated since 1 January 2026 included, a forced full read every seventh run, and deletion of known users allowed. A second job writes users and job-based groups into `S4P`, where each group maps to one existing role.
- Three named user administrators: `00100316` and `00100317` (BTP platform administrators) and `00100331` (security administrator).

The groups, job codes, role names other than `ZD_P2P_*` and all rules in the lab are course labels.

### Build it yourself: Calder's identity lab

You will review a partner's draft identity design for Calder against 13 rules, replay one week of HR changes through it, trace single sign-ins hop by hop, and compare the result with the reviewed design.

```mermaid
flowchart LR
  P[people.json<br/>HR and events] --> R[replay:<br/>night jobs]
  D[design_draft.json /<br/>design_reviewed.json] --> V[review:<br/>ID01-ID13]
  D --> R
  R --> G[09:00 sign-in grid]
  R --> S[signin: one trace]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 27](https://erpfde.com/topics/set-up-for-unit-27/). The [BTP security model topic](https://erpfde.com/topics/btp-security-model/) covered trust from BTP's side; this lab looks from the identity tenant's side.

> **Note** New words. **JSON** is a text format for structured data; the lab keeps the design in two JSON files. A **job** here is a scheduled provisioning run. A **trace** lists each hop a sign-in takes. A **self-test** reruns the lab in a temporary folder and checks the planted results.

> **Note** The lab is a model, not SAP. Property names such as `ips.delete.existedbefore.entities`, `ips.full.read.force.count`, `sf.user.filter` and `sf.user.read.deactivatedafter`, the subject name options and the identity federation switches are SAP's, as documented on 1 December 2026. The simplified job logic, the groups, role mappings, people's e-mail addresses and rules `ID01` to `ID13` are course choices. All people and companies are fictional.

#### What you need

- Your course folder `orchestrate-course` with its `.venv`.
- About 40 to 60 minutes. Free; built-in Python modules only, nothing to install.

#### 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. The `unit27` folder exists from the unit setup. If it doesn't, create it with `mkdir unit27`.

Run every command from the course folder. On macOS or Linux, if `python` isn't found, use `python3`.

#### Step 2: Create the lab script

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

```python
"""Calder's identity design lab: review an SAP Cloud Identity Services design and replay a week.

A local model, not SAP. Tenants, applications, provisioning jobs, groups and rules
ID01-ID13 are course labels shaped like SAP Cloud Identity Services. People and
companies are fictional. Built-in modules only, no randomness.

  python unit27/identity_lab.py --init
  python unit27/identity_lab.py review draft
  python unit27/identity_lab.py replay draft
  python unit27/identity_lab.py signin 00100094 S4P 2026-12-01 draft
  python unit27/identity_lab.py --selftest
"""
import hashlib
import json
import sys
import tempfile
from datetime import date, timedelta
from pathlib import Path

HERE = Path(__file__).resolve().parent / "identity"
DAYS = [date(2026, 11, 30) + timedelta(days=i) for i in range(8)]  # Mon 30 Nov to Mon 7 Dec
DOMAIN = "calder-pumpworks.example"
GOOD_SUBJECTS = {"Global User ID", "User ID", "Login Name"}
HR_ALLOWED = {"userName", "emails", "name", "active", "groups", "employeeNumber", "costCenter"}

# ---------------------------------------------------------------- sample data

def people():
    """HR records in the SuccessFactors stand-in, plus each person's corporate account."""
    def p(pid, email, job, active=True, modified="2026-09-01", entra=True, **extra):
        rec = {"id": pid, "email": email, "job": job, "active": active,
               "modified": modified, "entra": entra}
        rec.update(extra)
        return rec
    return {
        "as_of": "2026-11-29",
        "people": [
            p("00100094", f"mech.tech4@{DOMAIN}", "MAINT_TECH", active=False, modified="2026-10-16"),
            p("00100211", f"buyer@{DOMAIN}", "BUYER"),
            p("00100241", f"ap.accountant@{DOMAIN}", "AP_ACCOUNTANT"),
            p("00100244", f"ap.supervisor@{DOMAIN}", "AP_SUPERVISOR"),
            p("00100265", f"cs.clerk@{DOMAIN}", "CS_CLERK"),
            p("00100266", f"inside.sales@{DOMAIN}", "INSIDE_SALES"),
            p("00100304", f"credit.analyst@{DOMAIN}", "CREDIT_ANALYST"),
        ],
        # Changes HR keys during the replay week (date, time, person, change)
        "events": [
            {"day": "2026-12-01", "person": "00100263", "change": "hire",
             "record": {"id": "00100263", "email": f"rk.buyer2@{DOMAIN}", "job": "BUYER",
                        "active": True, "entra": True}},
            {"day": "2026-12-03", "person": "00100266", "change": "email",
             "value": f"inside.sales.us@{DOMAIN}"},
        ],
        # Users created directly in Identity Services, not fed by HR
        "local_users": [
            {"id": "orders@hallam-fluid.example", "email": "orders@hallam-fluid.example",
             "type": "Partner", "groups": ["DIST-PORTAL-DISTRIBUTORS"], "customer": "10000002"},
        ],
    }


def design(kind):
    """The partner's draft or the reviewed design for Calder's tenant."""
    jobs = {"BUYER": "CAL-S4P-BUYER-US", "AP_ACCOUNTANT": "CAL-S4P-AP-ACCOUNTANT-US",
            "AP_SUPERVISOR": "CAL-S4P-AP-SUPERVISOR-US", "CS_CLERK": "CAL-S4P-O2C-CLERK",
            "INSIDE_SALES": "CAL-S4P-INSIDE-SALES", "CREDIT_ANALYST": "CAL-S4P-CREDIT-ANALYST",
            "MAINT_TECH": "CAL-S4P-MAINT-TECH"}
    roles = {"CAL-S4P-BUYER-US": "ZD_P2P_BUYER_US",
             "CAL-S4P-AP-ACCOUNTANT-US": "ZD_P2P_AP_ACCOUNTANT_US",
             "CAL-S4P-AP-SUPERVISOR-US": "ZD_P2P_AP_SUPERVISOR_US",
             "CAL-S4P-O2C-CLERK": "ZD_O2C_CLERK_US", "CAL-S4P-INSIDE-SALES": "ZD_O2C_INSIDE_SALES_US",
             "CAL-S4P-CREDIT-ANALYST": "ZD_O2C_CREDIT_ANALYST_US",
             "CAL-S4P-MAINT-TECH": "ZD_PM_TECHNICIAN_US"}
    employees_rule = {"email_domain": DOMAIN, "idp": "calder-entra"}
    d = {
        "name": kind,
        "tenants": [{"name": "calder-ias", "type": "productive"},
                    {"name": "calder-ias-test", "type": "test"}],
        "corporate_idps": [{"name": "calder-entra", "protocol": "OpenID Connect",
                            "tenant": "calder-ias"}],
        "administrators": ["00100316", "00100317", "00100331"],
        "leavers": ["00100094", "ext.developer"],
        "applications": [
            {"name": "S4P", "stage": "production", "tenant": "calder-ias", "users": "employees",
             "default_idp": "calder-entra", "rules": [], "subject": "Login Name",
             "federation": {"use_ias_store": True, "ias_users_only": True}, "sap_managed": False},
            {"name": "S4Q", "stage": "test", "tenant": "calder-ias-test", "users": "employees",
             "default_idp": "calder-entra", "rules": [], "subject": "Login Name",
             "federation": {"use_ias_store": True, "ias_users_only": True}, "sap_managed": False},
            {"name": "calder-ai-prod", "stage": "production", "tenant": "calder-ias",
             "users": "employees", "default_idp": "calder-entra", "rules": [],
             "subject": "Global User ID",
             "federation": {"use_ias_store": True, "ias_users_only": True}, "sap_managed": False},
            {"name": "dist-portal", "stage": "production", "tenant": "calder-ias",
             "users": "employees and partners", "default_idp": "Identity Authentication",
             "rules": [employees_rule], "subject": "Global User ID",
             "federation": {"use_ias_store": True, "ias_users_only": True}, "sap_managed": False},
            {"name": "joule-prod", "stage": "production", "tenant": "calder-ias",
             "users": "employees", "default_idp": "calder-entra", "rules": [],
             "subject": "Global User ID",
             "federation": {"use_ias_store": True, "ias_users_only": True}, "sap_managed": True},
        ],
        "s4p_roles": sorted(roles.values()),
        "jobs": [
            {"name": "SF-EC to directory", "source": "SF-EC", "target": "Local Identity Directory",
             "schedule": "daily 02:00", "start_with": "resync",
             "properties": {"ips.delta.read": "enabled", "sf.user.filter": "active eq true",
                            "sf.user.read.deactivatedafter": "2026-01-01",
                            "ips.full.read.force.count": "7",
                            "ips.delete.existedbefore.entities": "true"},
             "attributes": ["userName", "emails", "name", "active", "groups", "employeeNumber"],
             "job_groups": jobs},
            {"name": "directory to S4P", "source": "Local Identity Directory", "target": "S4P",
             "target_type": "SAP Application Server ABAP", "schedule": "daily 02:30",
             "connection": "SCC-RK-P, RFC SNC, technical user TU_IPS_S4P",
             "properties": {}, "value_mapping": roles, "inactive_users": "remove groups"},
        ],
    }
    if kind == "reviewed":
        return d
    # The partner's draft: the same landscape with the planted mistakes
    d["tenants"].append({"name": "calder-ias-joule", "type": "productive"})
    d["administrators"] = ["00100316", "00100317", "00100290", "00100292", "ext.developer"]
    apps = {a["name"]: a for a in d["applications"]}
    apps["S4P"].update(default_idp="Identity Authentication", subject="Email",
                       federation={"use_ias_store": False, "ias_users_only": False})
    apps["S4Q"]["tenant"] = "calder-ias"
    apps["calder-ai-prod"].update(subject="Employee Number",
                                  federation={"use_ias_store": False, "ias_users_only": False})
    apps["dist-portal"].update(default_idp="calder-entra", rules=[])
    apps["joule-prod"]["tenant"] = "calder-ias-joule"
    hr, s4 = d["jobs"]
    hr["start_with"] = "delta"
    for key in ("sf.user.read.deactivatedafter", "ips.full.read.force.count",
                "ips.delete.existedbefore.entities"):
        del hr["properties"][key]
    hr["attributes"] += ["dateOfBirth", "homeAddress"]
    s4["schedule"] = "weekly Monday 03:00"
    s4["value_mapping"] = dict(roles, **{"CAL-S4P-BUYER-US": "ZD_P2P_BUYER_us"})
    s4["inactive_users"] = "no change"
    d["jobs"].append({"name": "directory to Joule", "source": "Local Identity Directory",
                      "target": "joule-prod", "schedule": "daily 04:00", "properties": {}})
    return d


def start_state(pp):
    """Directory and S4P as they stood on Sunday 29 November 2026 after months of delta reads."""
    jobs = design("reviewed")["jobs"][0]["job_groups"]
    roles = design("reviewed")["jobs"][1]["value_mapping"]
    directory, s4p = {}, {}
    for r in pp["people"]:
        directory[r["id"]] = {"email": r["email"], "active": True, "type": "Employee",
                              "groups": [jobs[r["job"]]], "global_id": gid(r["id"]),
                              "source": "SF-EC", "attributes": ["userName", "emails", "name"]}
        s4p[r["id"]] = {"email": r["email"], "roles": [roles[jobs[r["job"]]]], "locked": False}
    for u in pp["local_users"]:
        directory[u["id"]] = {"email": u["email"], "active": True, "type": u["type"],
                              "groups": list(u["groups"]), "global_id": gid(u["id"]),
                              "source": "local", "attributes": ["userName", "emails"]}
    return {"directory": directory, "s4p": s4p}


def gid(key):
    """A repeatable stand-in for the global user ID the directory generates."""
    h = hashlib.sha1(key.encode()).hexdigest()
    return f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"

# ---------------------------------------------------------------- files

def init(folder):
    folder = Path(folder)
    if folder.exists():
        sys.exit(f"{folder} already exists; delete the folder first if you want the sample back")
    folder.mkdir(parents=True)
    files = {"people.json": people(), "design_draft.json": design("draft"),
             "design_reviewed.json": design("reviewed")}
    for name, data in files.items():
        (folder / name).write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
    print(f"Wrote {folder}: " + ", ".join(files))


def load(folder, name):
    path = Path(folder) / name
    if not path.exists():
        sys.exit(f"{path} is missing; run: python unit27/identity_lab.py --init")
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as err:
        sys.exit(f"Cannot read {path}: {err}")

# ---------------------------------------------------------------- review

def review(d):
    """Apply course rules ID01-ID13. Returns a list of (status, rule, text)."""
    out = []
    def add(ok, rule, text, warn=False):
        out.append(("OK" if ok else ("WARN" if warn else "FAIL"), rule, text))
    prod = [t["name"] for t in d["tenants"] if t["type"] == "productive"]
    add(len(prod) == 1, "ID01", f"Productive tenants: {', '.join(prod)}")
    ttype = {t["name"]: t["type"] for t in d["tenants"]}
    leavers = set(d.get("leavers", []))
    for a in d["applications"]:
        want = "productive" if a["stage"] == "production" else "test"
        add(ttype.get(a["tenant"]) == want, "ID02",
            f"{a['name']} ({a['stage']}) on {a['tenant']} ({ttype.get(a['tenant'], 'unknown')})")
        if "employees" in a["users"]:
            corp = a["default_idp"] != "Identity Authentication" or any(
                r.get("email_domain") == DOMAIN and r["idp"] != "Identity Authentication"
                for r in a["rules"])
            add(corp, "ID03", f"{a['name']}: employees authenticate at "
                + ("calder-entra" if corp else "Identity Authentication with local passwords"))
        if "partners" in a["users"]:
            reach = a["default_idp"] == "Identity Authentication" or any(
                r["idp"] == "Identity Authentication" for r in a["rules"])
            add(reach, "ID04", f"{a['name']}: partners " + ("reach Identity Authentication"
                if reach else "are sent to calder-entra, where they have no account"))
        if a["default_idp"] != "Identity Authentication" or a["rules"]:
            f = a["federation"]
            add(f["use_ias_store"] and f["ias_users_only"], "ID05",
                f"{a['name']}: use IAS user store {'on' if f['use_ias_store'] else 'off'}, "
                f"allow IAS users only {'on' if f['ias_users_only'] else 'off'}")
        s = a["subject"]
        add(s in GOOD_SUBJECTS, "ID06", f"{a['name']}: subject name identifier {s}",
            warn=(s == "Email"))
    for j in d["jobs"]:
        p = j.get("properties", {})
        if j["source"] == "SF-EC":
            leaver_read = "sf.user.read.deactivatedafter" in p or "active eq true" not in p.get(
                "sf.user.filter", "")
            add(leaver_read, "ID07", f"{j['name']}: " + ("reads users deactivated since "
                + p.get("sf.user.read.deactivatedafter", "?") if leaver_read
                else "reads active users only, so leavers are never read again"))
            delete = p.get("ips.delete.existedbefore.entities") == "true"
            add(delete, "ID09", f"{j['name']}: ips.delete.existedbefore.entities "
                + ("true" if delete else "not set"), warn=True)
            bad = sorted(set(j["attributes"]) - HR_ALLOWED)
            add(not bad, "ID12", f"{j['name']}: attributes outside the allow list: "
                + (", ".join(bad) or "none"))
        daily = j["schedule"].startswith("daily")
        forced = p.get("ips.delta.read") != "enabled" or int(p.get(
            "ips.full.read.force.count", "0") or 0) in range(1, 8)
        add(daily and forced, "ID08", f"{j['name']}: {j['schedule']}"
            + ("" if forced else ", delta read with no forced full read"))
        if j.get("target_type") == "SAP Application Server ABAP":
            missing = sorted(r for r in j["value_mapping"].values() if r not in d["s4p_roles"])
            add(not missing, "ID10", f"{j['name']}: mapped roles missing in S4P: "
                + (", ".join(missing) or "none"))
    managed = {a["name"] for a in d["applications"] if a["sap_managed"]}
    for j in d["jobs"]:
        if j["target"] in managed:
            add(False, "ID11", f"{j['name']}: a customer job writes into SAP-managed {j['target']}")
    if not any(j["target"] in managed for j in d["jobs"]):
        add(True, "ID11", "No customer job overlaps an SAP-managed flow")
    admins = d["administrators"]
    gone = [a for a in admins if a in leavers]
    add(2 <= len(admins) <= 3 and not gone, "ID13", f"{len(admins)} user administrators"
        + (f", leaver(s) {', '.join(gone)}" if gone else ""))
    return out


def print_review(d):
    results = review(d)
    for status, rule, text in results:
        print(f"  {status:<4}  {rule}  {text}")
    counts = {s: sum(1 for r in results if r[0] == s) for s in ("OK", "WARN", "FAIL")}
    print(f"{d['name']}: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL")
    return counts

# ---------------------------------------------------------------- replay

def hr_on(pp, day):
    """HR records as they stand at the end of a day."""
    recs = {r["id"]: dict(r) for r in pp["people"]}
    for e in pp["events"]:
        if e["day"] > day.isoformat():
            continue
        if e["change"] == "hire":
            recs[e["person"]] = dict(e["record"], modified=e["day"])
        elif e["change"] == "email":
            recs[e["person"]].update(email=e["value"], modified=e["day"])
    return recs


def run_hr_job(job, state, recs, last_run, full):
    """SF-EC to the directory: read, then create, update or (only in a full read) delete."""
    p = job["properties"]
    since = p.get("sf.user.read.deactivatedafter")
    read = {pid: r for pid, r in recs.items()
            if r["active"] or (since and r["modified"] >= since)}
    if not full:
        read = {pid: r for pid, r in read.items() if r["modified"] > last_run}
    log = []
    for pid, r in sorted(read.items()):
        old = state["directory"].get(pid)
        groups = [job["job_groups"][r["job"]]] if r["active"] else []
        new = {"email": r["email"], "active": r["active"], "type": "Employee", "groups": groups,
               "global_id": old["global_id"] if old else gid(pid), "source": "SF-EC",
               "attributes": list(job["attributes"])}
        same = old and {k: v for k, v in old.items() if k != "attributes"} == {
            k: v for k, v in new.items() if k != "attributes"}
        if not same:
            log.append(("created" if not old else "updated") + f" {pid}"
                       + ("" if r["active"] else " (inactive)"))
            state["directory"][pid] = new
    if full and p.get("ips.delete.existedbefore.entities") == "true":
        for pid in [k for k, v in state["directory"].items()
                    if v["source"] == "SF-EC" and k not in read]:
            del state["directory"][pid]
            log.append(f"deleted {pid}")
    return log


def run_s4_job(job, state, roles_in_s4):
    """Directory to S4P: users and role assignments by group, as an AS ABAP target."""
    log = []
    for pid, u in sorted(state["directory"].items()):
        if u["source"] != "SF-EC":
            continue
        groups = u["groups"] if (u["active"] or job["inactive_users"] == "no change") else []
        if not u["active"] and job["inactive_users"] == "no change":
            continue
        want, errors = [], []
        for g in groups:
            role = job["value_mapping"].get(g)
            if role in roles_in_s4:
                want.append(role)
            else:
                errors.append(f"group {g}: no role {role} in S4P")
        user = state["s4p"].get(pid)
        if errors:
            log += [f"error {pid}: {e}" for e in errors]
            if user:  # SAP: on an error the group's members are not updated
                want = user["roles"]
        new = {"email": u["email"], "roles": sorted(want),
               "locked": user["locked"] if user else False}
        if user != new:
            log.append(("created" if not user else "updated") + f" S4P user {pid}"
                       + (f" roles {', '.join(new['roles']) or 'none'}"))
            state["s4p"][pid] = new
    return log


def due(schedule, day):
    return schedule.startswith("daily") or (schedule.startswith("weekly Monday")
                                            and day.weekday() == 0)


def signin(d, pp, state, person, app_name, day):
    """Trace one browser sign-in at 09:00. Returns (result, hops)."""
    app = {a["name"]: a for a in d["applications"]}[app_name]
    recs = hr_on(pp, day)
    local = {u["id"]: u for u in pp["local_users"]}
    email = recs[person]["email"] if person in recs else local.get(person, {}).get("email", person)
    hops = [f"{app_name} sends the browser to Identity Authentication ({app['tenant']})"]
    idp = app["default_idp"]
    for r in app["rules"]:
        if email.endswith("@" + r["email_domain"]):
            idp = r["idp"]
            hops.append(f"rule: e-mail domain {r['email_domain']} -> {idp}")
            break
    else:
        hops.append(f"no rule matched -> default {idp}")
    ias = state["directory"].get(person)
    if idp == "Identity Authentication":
        if not ias:
            return "REFUSED", hops + ["no user in the directory"]
        if not ias["active"]:
            return "REFUSED", hops + ["directory user is inactive"]
        hops.append("password checked by Identity Authentication (no MFA rule)")
    else:
        if not (person in recs and recs[person]["entra"]):
            return "REFUSED", hops + ["no account in calder-entra"]
        hops.append("calder-entra authenticates (MFA by Calder's policy)")
        f = app["federation"]
        if f["use_ias_store"] and f["ias_users_only"]:
            if not ias or not ias["active"]:
                return "REFUSED", hops + ["identity federation: no active directory user"]
            hops.append("identity federation: active directory user found")
        else:
            hops.append("identity federation off: any calder-entra user passes")
    use_store = idp == "Identity Authentication" or app["federation"]["use_ias_store"]
    subject = {"Login Name": person, "User ID": person, "Email":
               (ias["email"] if use_store and ias else email),
               "Global User ID": ias["global_id"] if ias else "?",
               "Employee Number": person}[app["subject"]]
    hops.append(f"subject ({app['subject']}): {subject}")
    if app_name != "S4P":
        groups = ias["groups"] if ias else []
        return "OK", hops + [f"groups in token: {', '.join(groups) or 'none'}"]
    key = "email" if app["subject"] == "Email" else "id"
    match = [pid for pid, u in state["s4p"].items() if (u["email"] if key == "email" else pid)
             == subject]
    if not match:
        return "REFUSED", hops + [f"S4P has no user whose {key} is {subject}"]
    user = state["s4p"][match[0]]
    if user["locked"]:
        return "REFUSED", hops + [f"S4P user {match[0]} is locked"]
    if not user["roles"]:
        return "NO ROLES", hops + [f"S4P user {match[0]} has no roles"]
    return "OK", hops + [f"S4P user {match[0]}, roles {', '.join(user['roles'])}"]


WATCH = [("00100094", "S4P", "leaver since 2026-10-16"),
         ("00100263", "S4P", "joiner, starts 2026-12-01"),
         ("00100266", "S4P", "e-mail renamed 2026-12-03"),
         ("orders@hallam-fluid.example", "dist-portal", "Hallam's distributor user"),
         ("00100265", "dist-portal", "customer service clerk")]


def replay(d, pp, quiet=False, until=None):
    """Run every job that is due at night, then try the watched sign-ins at 09:00."""
    state = start_state(pp)
    last_run = pp["as_of"]
    hr_job = next(j for j in d["jobs"] if j["source"] == "SF-EC")
    s4_job = next(j for j in d["jobs"] if j["target"] == "S4P")
    roles_in_s4 = set(d["s4p_roles"])
    force = int(hr_job["properties"].get("ips.full.read.force.count", "0") or 0)
    delta = hr_job["properties"].get("ips.delta.read") == "enabled"
    grid = {w: [] for w in WATCH}
    for n, day in enumerate(DAYS):
        if until and day > until:
            break
        recs = hr_on(pp, day - timedelta(days=1))
        first = n == 0 and hr_job.get("start_with") == "resync"
        full = (not delta) or first or (force and n % force == 0 and n > 0)
        lines = run_hr_job(hr_job, state, recs, last_run, full)
        mode = "resync" if first else ("full" if full else "delta")
        lines = [f"SF-EC ({mode}): {x}" for x in lines]
        if due(s4_job["schedule"], day):
            lines += [f"S4P: {x}" for x in run_s4_job(s4_job, state, roles_in_s4)]
        last_run = (day - timedelta(days=1)).isoformat()
        if not quiet:
            print(f"{day:%a %d %b} night jobs: " + ("; ".join(lines) if lines else "no changes"))
        for w in WATCH:
            res, _ = signin(d, pp, state, w[0], w[1], day)
            grid[w].append(res)
    return state, grid


def print_replay(d, pp):
    _, grid = replay(d, pp)
    print()
    print("Sign-in at 09:00           " + " ".join(f"{x:%d%b}" for x in DAYS))
    for w, results in grid.items():
        cells = " ".join(f"{(r if r != 'NO ROLES' else 'NOROLE')[:5]:<5}" for r in results)
        print(f"{w[0][:14]:<14} {w[1]:<12}{cells}  {w[2]}")
    leaked = grid[WATCH[0]].count("OK")
    print(f"{d['name']}: leaver signed in on {leaked} of {len(DAYS)} days; "
          f"joiner working on {grid[WATCH[1]][1:].count('OK')} of 7 days from 1 Dec; "
          f"refusals for staying users {sum(r != 'OK' for w in WATCH[2:] for r in grid[w])}")
    return grid

# ---------------------------------------------------------------- self-test

def selftest():
    with tempfile.TemporaryDirectory() as tmp:
        folder = Path(tmp) / "identity"
        init(folder)
        pp = load(folder, "people.json")
        draft, good = load(folder, "design_draft.json"), load(folder, "design_reviewed.json")
        bad = {(s, r) for s, r, _ in review(draft) if s != "OK"}
        for rule in ("ID01", "ID02", "ID03", "ID04", "ID05", "ID06", "ID07", "ID08", "ID10",
                     "ID11", "ID12", "ID13"):
            assert ("FAIL", rule) in bad, f"draft should fail {rule}"
        assert ("WARN", "ID09") in bad and ("WARN", "ID06") in bad
        assert all(s == "OK" for s, r, _ in review(good) if r <= "ID13"), "reviewed should pass ID01-ID13"
        _, g1 = replay(draft, pp, quiet=True)
        _, g2 = replay(good, pp, quiet=True)
        assert g1[WATCH[0]].count("OK") == 8 and g2[WATCH[0]].count("OK") == 0
        assert g1[WATCH[1]][1:].count("OK") == 0 and g2[WATCH[1]][1:].count("OK") == 6
        assert g1[WATCH[3]].count("REFUSED") == 8 and g2[WATCH[3]].count("OK") == 8
        assert g1[WATCH[2]][4] == "REFUSED" and g2[WATCH[2]].count("OK") == 8
    print("Self-test passed: 13 rules and 5 sign-in traces behave as planted (synthetic data)")


def main(argv):
    if not argv or argv[0] in ("-h", "--help"):
        print(__doc__)
        return 0
    if argv[0] == "--init":
        init(HERE)
        return 0
    if argv[0] == "--selftest":
        selftest()
        return 0
    cmd, rest = argv[0], argv[1:]
    kind = rest[-1] if rest and rest[-1] in ("draft", "reviewed") else "reviewed"
    d = load(HERE, f"design_{kind}.json")
    pp = load(HERE, "people.json")
    if cmd == "review":
        return 2 if print_review(d)["FAIL"] else 0
    if cmd == "replay":
        print_replay(d, pp)
        return 0
    if cmd == "signin" and len(rest) >= 3:
        person, app, day = rest[0], rest[1], date.fromisoformat(rest[2])
        state, _ = replay(d, pp, quiet=True, until=day)
        result, hops = signin(d, pp, state, person, app, day)
        print(f"{person} -> {app} on {day:%a %d %b %Y} 09:00 ({d['name']} design)")
        for i, h in enumerate(hops, 1):
            print(f"  {i}. {h}")
        print(f"  Result: {result}")
        return 0
    print("Unknown command. Try: --init, review, replay, signin, --selftest")
    return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
```

#### Step 3: Write the sample and review the draft

1. Write the sample files:

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

   ```text
   Wrote .../orchestrate-course/unit27/identity: people.json, design_draft.json, design_reviewed.json
   ```

2. Review the partner's draft:

   ```bash
   python unit27/identity_lab.py review draft
   ```

   ```text
     FAIL  ID01  Productive tenants: calder-ias, calder-ias-joule
     OK    ID02  S4P (production) on calder-ias (productive)
     FAIL  ID03  S4P: employees authenticate at Identity Authentication with local passwords
     WARN  ID06  S4P: subject name identifier Email
     FAIL  ID02  S4Q (test) on calder-ias (productive)
     ...
     FAIL  ID05  calder-ai-prod: use IAS user store off, allow IAS users only off
     FAIL  ID06  calder-ai-prod: subject name identifier Employee Number
     ...
     FAIL  ID04  dist-portal: partners are sent to calder-entra, where they have no account
     ...
     FAIL  ID07  SF-EC to directory: reads active users only, so leavers are never read again
     WARN  ID09  SF-EC to directory: ips.delete.existedbefore.entities not set
     FAIL  ID12  SF-EC to directory: attributes outside the allow list: dateOfBirth, homeAddress
     FAIL  ID08  SF-EC to directory: daily 02:00, delta read with no forced full read
     FAIL  ID08  directory to S4P: weekly Monday 03:00
     FAIL  ID10  directory to S4P: mapped roles missing in S4P: ZD_P2P_BUYER_us
     OK    ID08  directory to Joule: daily 04:00
     FAIL  ID11  directory to Joule: a customer job writes into SAP-managed joule-prod
     FAIL  ID13  5 user administrators, leaver(s) ext.developer
   draft: 15 OK, 2 WARN, 13 FAIL
   ```

   The command ends with exit code 2 because something fails. The `...` lines are `OK` lines left out here.

3. Read the 13 rules. They are course rules; the right-hand column says where each comes from.

   | Rule | Checks | Basis |
   | --- | --- | --- |
   | `ID01` | One productive tenant | SAP's recommendation |
   | `ID02` | Production apps on the productive tenant, test apps on the test tenant | Course rule |
   | `ID03` | Employees authenticate at the corporate identity provider | Course rule |
   | `ID04` | Partners can reach the tenant's own sign-in | Conditional authentication as SAP documents it |
   | `ID05` | Identity federation's two options on where a corporate provider signs in | Course rule built on SAP's options |
   | `ID06` | Subject is the global user ID, user ID or login name; e-mail warns | SAP's uniqueness note on employee numbers; course rule on e-mail |
   | `ID07` | The HR source reads leavers | SAP's SuccessFactors properties |
   | `ID08` | Jobs run at least daily; delta sources force a full read at least every 7 runs | Course rule built on SAP's full and delta read |
   | `ID09` | The HR-fed target may delete known users | SAP's deleted-entities guidance |
   | `ID10` | Every role a group maps to exists in the ABAP target, case included | SAP's AS ABAP target behaviour |
   | `ID11` | No customer job overlaps an SAP-managed flow | SAP's caution |
   | `ID12` | HR attributes stay on an allow list (no birth date or home address) | Course rule, data minimisation |
   | `ID13` | Two or three named user administrators, none a leaver | Course rule |

4. Review the reviewed design:

   ```bash
   python unit27/identity_lab.py review reviewed
   ```

   ```text
   ...
   reviewed: 30 OK, 0 WARN, 0 FAIL
   ```

#### Step 4: Replay the week through the draft

1. Run the replay. Each day, the jobs that are due run at night, then five people try to sign in at 09:00:

   ```bash
   python unit27/identity_lab.py replay draft
   ```

   ```text
   Mon 30 Nov night jobs: S4P: error 00100211: group CAL-S4P-BUYER-US: no role ZD_P2P_BUYER_us in S4P
   Tue 01 Dec night jobs: no changes
   Wed 02 Dec night jobs: SF-EC (delta): created 00100263
   Thu 03 Dec night jobs: no changes
   Fri 04 Dec night jobs: SF-EC (delta): updated 00100266
   Sat 05 Dec night jobs: no changes
   Sun 06 Dec night jobs: no changes
   Mon 07 Dec night jobs: S4P: error 00100211: group CAL-S4P-BUYER-US: no role ZD_P2P_BUYER_us in S4P; S4P: error 00100263: group CAL-S4P-BUYER-US: no role ZD_P2P_BUYER_us in S4P; S4P: created S4P user 00100263 roles none; S4P: updated S4P user 00100266 roles ZD_O2C_INSIDE_SALES_US

   Sign-in at 09:00           30Nov 01Dec 02Dec 03Dec 04Dec 05Dec 06Dec 07Dec
   00100094       S4P         OK    OK    OK    OK    OK    OK    OK    OK     leaver since 2026-10-16
   00100263       S4P         REFUS REFUS REFUS REFUS REFUS REFUS REFUS NOROL  joiner, starts 2026-12-01
   00100266       S4P         OK    OK    OK    OK    REFUS REFUS REFUS OK     e-mail renamed 2026-12-03
   orders@hallam- dist-portal REFUS REFUS REFUS REFUS REFUS REFUS REFUS REFUS  Hallam's distributor user
   00100265       dist-portal OK    OK    OK    OK    OK    OK    OK    OK     customer service clerk
   draft: leaver signed in on 8 of 8 days; joiner working on 0 of 7 days from 1 Dec; refusals for staying users 11
   ```

   > **Note** These numbers come from a course simulation on made-up people and events. They show the method, not results from a real SAP system.

2. Read the grid row by row:
   - **The leaver** `00100094` signs in every day. The feed never reads him again, and `S4P` lets the tenant check his old password.
   - **The joiner** `00100263`, a new Rockford buyer keyed by HR on his first day, reaches the directory on Wednesday but `S4P` only on Monday, through the weekly job, and then without a role: the draft maps his group to `ZD_P2P_BUYER_us`, which doesn't exist. The same error stopped every change to existing buyers.
   - **The renamed mailbox**: `00100266`'s e-mail changes on Thursday. From Friday the tenant sends the new address as the subject, and `S4P` still has the old one until Monday.
   - **Hallam's user** can't sign in at all: the portal sends everyone to `calder-entra`.

3. Trace the leaver's sign-in on Tuesday:

   ```bash
   python unit27/identity_lab.py signin 00100094 S4P 2026-12-01 draft
   ```

   ```text
   00100094 -> S4P on Tue 01 Dec 2026 09:00 (draft design)
     1. S4P sends the browser to Identity Authentication (calder-ias)
     2. no rule matched -> default Identity Authentication
     3. password checked by Identity Authentication (no MFA rule)
     4. subject (Email): mech.tech4@calder-pumpworks.example
     5. S4P user 00100094, roles ZD_PM_TECHNICIAN_US
     Result: OK
   ```

#### Step 5: Replay the same week through the reviewed design

1. Run it:

   ```bash
   python unit27/identity_lab.py replay reviewed
   ```

   ```text
   Mon 30 Nov night jobs: SF-EC (resync): updated 00100094 (inactive); S4P: updated S4P user 00100094 roles none
   Tue 01 Dec night jobs: no changes
   Wed 02 Dec night jobs: SF-EC (delta): created 00100263; S4P: created S4P user 00100263 roles ZD_P2P_BUYER_US
   Thu 03 Dec night jobs: no changes
   Fri 04 Dec night jobs: SF-EC (delta): updated 00100266; S4P: updated S4P user 00100266 roles ZD_O2C_INSIDE_SALES_US
   Sat 05 Dec night jobs: no changes
   Sun 06 Dec night jobs: no changes
   Mon 07 Dec night jobs: no changes

   Sign-in at 09:00           30Nov 01Dec 02Dec 03Dec 04Dec 05Dec 06Dec 07Dec
   00100094       S4P         REFUS REFUS REFUS REFUS REFUS REFUS REFUS REFUS  leaver since 2026-10-16
   00100263       S4P         REFUS REFUS OK    OK    OK    OK    OK    OK     joiner, starts 2026-12-01
   00100266       S4P         OK    OK    OK    OK    OK    OK    OK    OK     e-mail renamed 2026-12-03
   orders@hallam- dist-portal OK    OK    OK    OK    OK    OK    OK    OK     Hallam's distributor user
   00100265       dist-portal OK    OK    OK    OK    OK    OK    OK    OK     customer service clerk
   reviewed: leaver signed in on 0 of 8 days; joiner working on 6 of 7 days from 1 Dec; refusals for staying users 0
   ```

   > **Note** Synthetic results again: the same made-up week, a different design.

2. Note what changed. The first run after the property change is a **resync**, a full read, because a delta read would never revisit a record last changed in October. It reads the leaver as inactive; the directory marks him inactive and drops his groups, and the `S4P` job removes his role. The joiner still loses his first day, because HR keyed him that morning; keying hires a few days ahead would close that gap.

3. Trace the leaver again:

   ```bash
   python unit27/identity_lab.py signin 00100094 S4P 2026-12-01 reviewed
   ```

   ```text
   00100094 -> S4P on Tue 01 Dec 2026 09:00 (reviewed design)
     1. S4P sends the browser to Identity Authentication (calder-ias)
     2. no rule matched -> default calder-entra
     3. calder-entra authenticates (MFA by Calder's policy)
     4. identity federation: no active directory user
     Result: REFUSED
   ```

   His Entra account still works; the tenant refuses him because identity federation checks the directory.

4. Trace Hallam's user on the portal:

   ```bash
   python unit27/identity_lab.py signin orders@hallam-fluid.example dist-portal 2026-12-01 reviewed
   ```

   ```text
   orders@hallam-fluid.example -> dist-portal on Tue 01 Dec 2026 09:00 (reviewed design)
     1. dist-portal sends the browser to Identity Authentication (calder-ias)
     2. no rule matched -> default Identity Authentication
     3. password checked by Identity Authentication (no MFA rule)
     4. subject (Global User ID): a9f60e7b-f5f5-e1c2-5e49-295109b99ec3
     5. groups in token: DIST-PORTAL-DISTRIBUTORS
     Result: OK
   ```

   The global user ID is a stand-in the lab derives from the user name so runs repeat; the directory generates real ones.

> **Warning** Refusing the browser sign-in is not the whole leaver process. An ABAP user with its own password can still log on through SAP GUI or RFC, which is what the [Unit 27 setup](https://erpfde.com/topics/set-up-for-unit-27/) pack showed with rule `SL02`. Lock or expire the ABAP user as well; the identity governance topic later in Unit 27 covers the full leaver process.

#### Step 6: Run the self-test and save your work

1. Run the self-test:

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

   ```text
   Wrote .../identity: people.json, design_draft.json, design_reviewed.json
   Self-test passed: 13 rules and 5 sign-in traces behave as planted (synthetic data)
   ```

2. Save your work with Git:

   ```bash
   git add unit27/identity_lab.py unit27/identity
   git commit -m "Unit 27: identity services lab"
   ```

To start over, delete the folder `unit27/identity` and run `--init` again.

#### How the code works

| Part | What it does |
| --- | --- |
| `people()` | HR records in a SuccessFactors stand-in (job, e-mail, active, last changed), the week's events and Hallam's partner user |
| `design()` | The reviewed design and the draft with its planted mistakes: tenants, applications, identity providers, jobs, role mappings, administrators |
| `start_state()` | The directory and `S4P` as they stood on Sunday 29 November, the leaver still active |
| `review()` | Applies `ID01` to `ID13` and returns `OK`, `WARN` or `FAIL` lines |
| `run_hr_job()` | Reads HR with the filter, `sf.user.read.deactivatedafter`, and full or delta mode; creates and updates directory users; deletes only in a full read with `ips.delete.existedbefore.entities` |
| `run_s4_job()` | Writes users and roles to `S4P` through the role mapping; a missing role raises an error and leaves the existing assignment unchanged |
| `signin()` | Follows the default identity provider and rules, the corporate sign-in, identity federation, the subject, and `S4P`'s user mapping |
| `replay()` | Runs the due jobs each night, then the five sign-ins each morning |
| `selftest()` | Replays everything in a temporary folder and asserts the planted results |

#### 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 `.venv` is off | Turn on `.venv` (Step 1); on macOS/Linux try `python3` |
| `design_draft.json is missing` | `--init` hasn't run | Run `python unit27/identity_lab.py --init` |
| `already exists; delete the folder first` | `--init` won't overwrite your work | Delete `unit27/identity` only if you want the sample back |
| `Cannot read ... json` | A hand edit broke the JSON | Undo the edit, or delete the folder and run `--init` |
| `KeyError: 'S4X'` or similar | A typo in an application name | Use `S4P`, `S4Q`, `calder-ai-prod`, `dist-portal` or `joule-prod` |
| `Invalid isoformat string` | The date isn't written as `YYYY-MM-DD` | Type it like `2026-12-01` |
| `review` ends with exit code 2 | Expected while a rule fails | Nothing; it lets scripts stop on a `FAIL` |
| A corporate proxy blocks Git or Python downloads | Not this lab: it needs no network | Follow the course setup topic's proxy notes for the other steps |

### The SAP way

In a real tenant, the lab's settings live here (names as in SAP's documentation on 1 December 2026):

| Lab | SAP Cloud Identity Services admin console | Notes |
| --- | --- | --- |
| `default_idp`, `rules` | **Applications** > the application > **Conditional Authentication** | Rules only when the default is Identity Authentication |
| `federation` | **Identity Providers** > **Corporate Identity Providers** > **Identity Federation** | Both options off by default |
| `subject` | The application's subject name identifier setting | Employee number isn't checked for uniqueness |
| `jobs`, `properties` | **Identity Provisioning** > **Source Systems** / **Target Systems**, **Properties** tab | Property names as in the lab |
| `value_mapping` | The target system's **Transformations** tab, `valueMapping` | Role names case-sensitive |
| `administrators` | **Users & Authorizations** > **Administrators** | User and system administrators |
| `start_with: resync` | A **Resync** job | Full read to bring source and target back in line |

Three SAP-side points the lab leaves out:

- **Connection to an ABAP target.** The Cloud Connector exposes the listed function modules over RFC SNC, and the technical user's authorizations follow SAP Note 3666721. Calder's connector is `SCC-RK-P` from the [connectivity topic](https://erpfde.com/topics/btp-connectivity/).
- **API versions.** SAP's [Identity Authentication proxy page](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/identity-authentication-d45c8a3.md) says the version 1 SCIM API of Identity Authentication will be decommissioned on 30 November 2028, and connectors must move to the Identity Directory SCIM API (version 2). Check `ias.api.version` on older systems.
- **Agents.** In the Early Adopter Care program, agents built in Joule Studio appear in an **Agents** tile, where administrators control which users or groups may call them ([Agents](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/agents-12bef24.md)).

> **Note** **Sketch, needs a tenant.** Everything in this section needs a productive or test tenant with administrator rights, and the provisioning steps need source and target systems. The Unit 27 setup's trial tenant has no Connectivity plan, so it can't reach an on-premise ABAP system. Calder's tenants are fictional; the lab is the free path.

### Build vs. SAP

| Need | Use SAP Cloud Identity Services | Build something |
| --- | --- | --- |
| Sign-in and single sign-on to SAP cloud products | Always: SAP products that bundle it expect it | Never a custom identity provider in front of SAP products |
| Users from HR into SAP applications | Identity Provisioning with the directory in the middle, or SAP-managed jobs where SAP offers them | A custom script only for a system with no connector, and then through the SCIM API |
| Leaver checks across systems | Full reads and deletion settings, plus an identity governance tool if licensed | A daily read-only comparison like the lab's, joining HR leavers with each system's active users |
| Fine-grained permissions in your own BTP app | Authorization policies, if the app is built for them | Roles and attributes in the app, as the BTP security model topic showed |
| Joiner, mover, leaver approvals and certification | An identity governance product, covered later in Unit 27 | Not in provisioning transformations |

### Architecture view

**Where it sits.** The tenant sits between Calder's corporate provider and every SAP application, and between HR and every SAP user store:

```mermaid
flowchart LR
  E[calder-entra] --- T[calder-ias<br/>productive]
  SF[SF-EC] --> T
  T --> S4P[S4P via SCC-RK-P]
  T --> BTP[calder-ai-prod,<br/>dist-portal]
  T --> J[joule-prod<br/>SAP-managed]
  SFT[SF-EC-T] -.-> TT[calder-ias-test] --> S4Q[S4Q]
```

**Non-functional requirements that decide the design:**

| Requirement | Calder's target | What breaks if missed |
| --- | --- | --- |
| Leaver removal | Browser access refused by the morning after HR records the leaving | Leavers sign in for weeks, as in the draft |
| Joiner readiness | Working access the morning after HR keys the hire | Shared screens and borrowed sessions |
| Availability | SAP's documented zone replication and backup; a tested break-glass path to BTP for administrators | Nobody can sign in to anything SAP while the tenant is unreachable |
| Data held | Only the attributes on the allow list | Birth dates and home addresses copied to a system that doesn't need them |
| Cost | No non-SAP application signs in through the tenant without a business case | Per-sign-in charges nobody budgeted |

**Integration and identity.** People enter from `SF-EC` and get a global user ID in the directory; groups follow from their job. Employees authenticate at `calder-entra` over OpenID Connect; the tenant sends `S4P` the login name and BTP applications the global user ID with groups in the token. Provisioning to `S4P` uses the Cloud Connector over RFC SNC with technical user `TU_IPS_S4P` (a course label). Joule's flows are SAP-managed and stay out of Calder's jobs. When an application calls S/4HANA for the user, [principal propagation](https://erpfde.com/topics/principal-propagation/) carries the identity further.

**The decision to record.** Using the form from [the design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/):

- **Context:** a leaver signed in to `S4P` five weeks after leaving; the partner's draft feeds HR by delta read of active users only and lets `S4P` check tenant passwords.
- **Options:** (a) keep the draft and run a monthly leaver report; (b) reviewed design: leavers read as inactive, identity federation checks the directory, a forced weekly full read, daily jobs; (c) also delete leavers from the directory and `S4P` at once.
- **Decision:** (b). Deactivating keeps the record for audit; deletion follows Calder's retention rules, through the governance process.
- **Consequences:** HR's inactive date becomes a security event, so HR data quality is now a control. The first run after the change must be a resync. `S4P` users still need locking for SAP GUI access.

**What a design review will ask:**

1. How many productive tenants do we have, and is every SAP product on the one SAP recommends?
2. Show a leaver's path: which job, which property and which setting refuses them, and how fast.
3. What subject identifier does each application receive, and what happens when an e-mail changes?
4. Which flows are SAP-managed, and which customer jobs touch the same systems?
5. Who administers the tenant, and how is that list reviewed?

### Production concerns

- **Security.** Treat tenant administrators like BTP global administrators: few, named, reviewed. Use certificates for system administrators where SAP offers them; SAP's own procedures recommend certificate-based authentication over basic for connections. Keep the technical user for an ABAP target to the function modules SAP lists.
- **SAP authorizations.** Provisioning assigns roles; it doesn't design them. Role owners approve the group-to-role mapping as they would a role change, as [roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/) set out.
- **Evaluation.** Test with real cases: a joiner, a mover, a leaver, a renamed mailbox, a partner. The lab's five rows are a minimum.
- **Operations.** Someone reads the job logs every morning; a failed job means changes stopped flowing. After any change to filters or deletion properties, run a resync. For SAP-managed products you can't see the job logs, so agree with SAP how failures reach you.
- **Cost.** Count non-SAP applications that sign in through the tenant before connecting them.
- **Clean core.** The tenant keeps identity outside S/4HANA; provisioning uses the function modules SAP lists, not custom user tables.

### Where AI fits

**Agents become identities too.** As of December 2026, SAP describes agent identity in SAP Cloud Identity Services as part of an Early Adopter Care program ([Agents](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/agents-12bef24.md)). Each deployed agent is registered as an application with a technical agent user that can't sign in through a browser. Agents act for a human user, and an action succeeds only when both the agent's policies and the user's own authorizations allow it. Assigning a user to a Joule assistant does not give access to the agents it calls; each needs its own assignment.

For Calder this means the identity design comes first: Joule's Stage 2 and any agent access need full identities in the directory, fed from HR, as the reviewed design does. The [AI Agent Hub topic](https://erpfde.com/topics/ai-agent-hub-and-governance/) covers registering agents; [agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) covers what they may do.

**AI can help read the logs**, not run them: summarising a failed job's log for the on-call person is a reasonable assistant task. Changing group mappings or deletion settings is not something to hand to an agent.

### Pitfalls

- **Filtering the HR source to active employees** and assuming leavers disappear downstream.
- **Running only delta reads**, so deletions never happen.
- **Setting `ips.delete.existedbefore.entities` after the fact**, when the leavers it should have removed are already known to the target.
- **Leaving identity federation off**, so anyone the corporate provider accepts gets in, inactive in the directory or not.
- **Mapping users by e-mail or employee number** where the login name or global user ID would stay stable and unique.
- **Renaming a role in S/4HANA** without updating the group mapping; members silently stop updating.
- **A second productive tenant for a pilot**, later blocking Joule.
- **Customer jobs beside SAP-managed ones** for the same system.
- **Copying every HR attribute** into the directory because the connector can.

### Exercise: give the test tenant its own HR feed

`S4Q` sits on `calder-ias-test`, but no job feeds that tenant. Testers get users typed by hand, and test cases never cover joiners and leavers. Add rule `ID14` and the missing job. Calder's SuccessFactors test instance is `SF-EC-T` on `calder-ias-test`, as in the Joule activation topic.

1. Open `unit27/identity_lab.py`. In `review()`, find the last two lines, `+ (f", leaver(s) ..." if gone else ""))` and `return out`. Between them, add `out += rule_id14(d)` so the end of the function reads:

   ```python
       add(2 <= len(admins) <= 3 and not gone, "ID13", f"{len(admins)} user administrators"
           + (f", leaver(s) {', '.join(gone)}" if gone else ""))
       out += rule_id14(d)
       return out
   ```

2. Below `review()`, add the new rule:

   ```python
   def rule_id14(d):
       """ID14: every tenant that serves test applications has its own HR feed."""
       out = []
       for t in sorted({a["tenant"] for a in d["applications"] if a["stage"] == "test"}):
           feeds = [j["name"] for j in d["jobs"]
                    if j["source"].startswith("SF-EC") and j.get("tenant") == t]
           out.append(("OK" if feeds else "FAIL", "ID14", f"test tenant {t}: HR feed "
                       + (", ".join(feeds) if feeds else "missing")))
       return out
   ```

3. Run `python unit27/identity_lab.py review reviewed`. Expect `FAIL  ID14  test tenant calder-ias-test: HR feed missing`.
4. Open `unit27/identity/design_reviewed.json`. In the `"jobs"` list, after the closing `}` of the `"directory to S4P"` job, type a comma and add:

   ```json
   {"name": "SF-EC-T to test directory", "source": "SF-EC-T",
    "target": "Local Identity Directory", "tenant": "calder-ias-test",
    "schedule": "daily 03:00", "start_with": "resync",
    "properties": {"ips.delta.read": "enabled", "sf.user.filter": "active eq true",
                   "sf.user.read.deactivatedafter": "2026-01-01",
                   "ips.full.read.force.count": "7",
                   "ips.delete.existedbefore.entities": "true"},
    "attributes": ["userName", "emails", "name", "active", "groups", "employeeNumber"],
    "job_groups": {}}
   ```

5. Run the review again, then the self-test. The self-test checks the 13 planted rules and still passes.
6. Run `python unit27/identity_lab.py review draft` and note that the draft now also fails `ID14`, for `calder-ias`, because its `S4Q` sits on the productive tenant.
7. Commit: `git add unit27 && git commit -m "Unit 27: test tenant HR feed"`.

**Done when:** `review reviewed` ends with `reviewed: 32 OK, 0 WARN, 0 FAIL`, `review draft` ends with `draft: 15 OK, 2 WARN, 14 FAIL`, and the self-test passes. Keep the design file: the single sign-on, principal propagation and identity governance topics later in Unit 27 build on the same tenants and people.

### Check yourself

1. Calder's HR feed from SuccessFactors uses delta read and the default filter `active eq true`. A technician leaves in October. What happens to his directory user?
   - A. The next delta read sees the status change and marks him inactive in the directory
   - B. Nothing: delta reads only records inside the filter, which he has left, so he stays active
   - C. The directory deletes him at the next run, because he no longer matches the filter
   - D. SuccessFactors pushes the deletion to the directory through its own real-time interface at once

   Answer: B. The filter keeps him out of every read, and delta mode never compares the full list. Adding `sf.user.read.deactivatedafter` makes his inactive record readable, and only a full read can delete.

2. You add `ips.delete.existedbefore.entities = true` to a target six months after go-live. What does SAP's documentation say about users already removed from the source?
   - A. The next full read deletes every one of them from the target automatically
   - B. The next delta read deletes them, because the property applies at once
   - C. Known users can no longer be deleted by the job; remove them by hand or script
   - D. They are moved to an inactive state in the target instead of being deleted

   Answer: C. SAP says the property must be set before the job that should delete the entities runs. Set afterwards, those previously existing entities have to be deleted by hand or by script.

3. Why does identity federation's "Allow Identity Authentication users only" matter for leavers?
   - A. It forces the corporate identity provider to disable the accounts of leavers as well
   - B. With it on, only directory users get through, so an inactive directory user can be refused
   - C. It deletes users from the directory when the corporate provider stops sending them
   - D. It makes the tenant check passwords itself instead of passing people to the corporate provider

   Answer: B. With the option off, anyone the corporate provider authenticates is allowed. With it on, the directory's view of the person, fed from HR, can refuse them even when their corporate account was never disabled.

4. The draft maps group `CAL-S4P-BUYER-US` to role `ZD_P2P_BUYER_us`, but `S4P` has `ZD_P2P_BUYER_US`. What happens in the provisioning job?
   - A. The service creates the missing role in S4P and assigns it to the group's members
   - B. The service ignores letter case in role names and assigns the existing role as usual
   - C. An error is raised and the group's members aren't updated, for old and new buyers
   - D. The job stops completely, so no user changes reach S4P that night

   Answer: C. SAP documents that AS ABAP roles can't be created by the service and must match exactly, case included. In the lab the error left the existing buyer unchanged and created the new buyer without a role.

5. Which subject name identifier suits `S4P` best in Calder's design, and why?
   - A. Email, because every employee already has one and it is unique in the tenant
   - B. Employee number, because HR owns it and it never changes for a person
   - C. Login name, the personnel number: unique, and unchanged when a mailbox is renamed
   - D. Display name, because it is what people see and recognise at the top of the launchpad

   Answer: C. The renamed mailbox in the lab broke sign-in for three days when `S4P` matched by e-mail. SAP warns that employee numbers aren't checked for uniqueness, and display names aren't unique at all.

6. After you change the HR job's filter and deletion properties, what should the next run be, and why?
   - A. A delta read, because it is faster and picks up every change made since the last run
   - B. A resync or full read, since delta won't revisit records last changed before the fix
   - C. No run at all until the forced full read count is reached on its own schedule
   - D. A test run against the test tenant only, because productive tenants reject resyncs

   Answer: B. The leaver's record last changed in October, so a delta read wouldn't read it again. A resync reads everything with the new settings and brings the directory back in line.

7. A partner proposes a customer provisioning job from the directory into `joule-prod`, which SAP manages. What do you answer?
   - A. Approve it, because more frequent jobs give Joule fresher user data than SAP's own
   - B. Refuse it: SAP warns that overlapping its managed flows causes inconsistent data
   - C. Approve it, provided the job runs at night when SAP's managed jobs are paused
   - D. Refuse it, because Joule doesn't use the directory and has no users to provision

   Answer: B. SAP-managed jobs already run every 30 minutes for those systems, and SAP cautions against duplicate or overlapping customer flows. Joule does use the directory, so the right answer is to leave the flow to SAP.

8. In SAP's agent identity model, a user is assigned to a Joule assistant that calls two agents. Can the user use both agents?
   - A. Yes, because assistant access is inherited by every agent the assistant calls
   - B. Yes, as long as the agents' technical users hold the business roles they need
   - C. Only if the user is also assigned to each agent; assignments aren't inherited
   - D. No, because agents can act only on their own behalf, never for a person

   Answer: C. SAP's documentation says assistant and agents are separate identities, each needing its own assignment. Agents act for a person, and an action succeeds only when both the agent's policies and the user's authorizations allow it.

## Sources

- [Tenants (SAP Cloud Identity Services documentation, SAP-docs on GitHub, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/tenants-93160eb.md): bundled with an SAP cloud solution: one productive and one test tenant, reused for further solutions; Identity Authentication, Identity Provisioning, Identity Directory and Authorization and Trust Management commercially included for SAP cloud solutions and apps on BTP; every successful logon from a third-party solution charged; productive and test tenants technically identical; Identity Provisioning not sold standalone since 2020-10-20
- [Get Your Tenant (SAP Cloud Identity Services documentation, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/get-your-tenant-460766b.md): SAP recommends one productive tenant for all SAP cloud solutions for integration and out-of-the-box SSO; extra tenants per region possible but SSO not guaranteed out of the box; tenant migration through component BC-IAM-IDS needs planned downtime and policy-based authorizations must be configured again
- [Centralized Provisioning with Identity Directory (SAP Cloud Identity Services documentation, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/centralized-provisioning-with-identity-directory-9d0235c.md): Identity Directory as the persistency layer for users and groups; Identity Provisioning reads from the customer's user store into the directory and on to SAP cloud systems; the directory generates a Global User ID for every new user; access through the Local Identity Directory connector, the SCIM 2.0 API or the admin console
- [Manage Full and Delta Read (Identity Provisioning, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/manage-full-and-delta-read-b7f817c.md): delta read reads only new and changed entities; entities deleted in the source are deleted in the target only by a full read job that read the source successfully; ips.full.read.force.count forces a full read after N scheduled delta reads; first read is always full; SAP SuccessFactors defaults to delta read
- [Manage Deleted Entities (Identity Provisioning, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/manage-deleted-entities-3d6bdf1.md): entities recognized as previously existing are not deleted from the target unless ips.delete.existedbefore.entities is true on the target before the deleting job runs; set afterwards, they must be deleted by hand or script
- [SAP SuccessFactors as a source system (Identity Provisioning, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/sap-successfactors-f29b5c6.md): sf.user.filter added at system creation with default active eq true; sf.user.read.deactivatedafter reads users set to inactive from a date on; lastModifiedDateTime must stay in the attribute list
- [SAP Application Server ABAP as a target system (Identity Provisioning, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/sap-application-server-abap-7a0c6e7.md): needs the Cloud Connector with RFC SNC access to listed function modules (BAPI_USER_CREATE1, BAPI_USER_ACTGROUPS_ASSIGN and others) and a technical user per SAP Note 3666721; groups map to roles; groups can't be created or deleted in AS ABAP; the role must exist with the exact, case-sensitive name or the group's members aren't updated; valueMapping for differing names
- [Configure Conditional Authentication for an Application (Identity Authentication, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-conditional-authentication-for-an-application-0143dce.md): rules choose the authenticating identity provider by e-mail domain, user type, user group and IP range; evaluated by priority, first match wins; rules only when the default identity provider is Identity Authentication; catch-all 0.0.0.0/0 at lowest priority when only corporate providers should authenticate
- [Configure Identity Federation (Identity Authentication, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-identity-federation-c029bbb.md): Use Identity Authentication user store (off by default) takes attributes from the directory; Allow Identity Authentication users only (off by default) admits only users that exist there; restrict to groups or e-mail domains only with that option on; otherwise everyone the corporate provider authenticates is allowed
- [Identity and Access Management for Joule (SAP Cloud Identity Services documentation, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/identity-and-access-management-for-joule-050287e.md): phased availability; one SAP Cloud Identity Services tenant for all systems Joule uses; global user ID required; SAP-managed read and write-back jobs; Stage 1 conversational only, Stage 2 needs full identities in the directory and unlocks agents; SAP-managed is the only supported path for public cloud applications with Joule
