Orchestrate

Report an issue

Something wrong, out of date or unclear? Tell us. Corrections are prioritized over new topics. You don't need to sign in.

0 / 2000

Don't include personal or confidential company details. Reports are reviewed with AI assistance.

The BTP security model: users, trust, role collections and audit logs

Decide who signs in to SAP BTP through which identity provider, what each role collection lets them do, and check Calder's access design before an auditor does.

Updated Nov 26, 2026
Foundational layer · 8 min read

The 60-second version

SAP Business Technology Platform (BTP) never stores passwords of its own. Every person who signs in is a user in an identity provider: SAP's default one, called SAP ID service, or the company's own. BTP keeps a copy of each user it has seen and attaches permissions to that copy.

BTP knows two kinds of users:

  • Platform users run the platform: administrators, developers and operators. They manage accounts, deploy apps and read logs.
  • Business users use the apps that run on BTP: a clerk using an agent, a distributor checking an order.

Permissions come in role collections, bundles of roles you assign to a user or, better, to a group from the identity provider. The audit log records who signed in and who changed security settings.

The security model answers three questions: who can sign in, through which identity provider; what each person can do, at which level; and how you prove it afterwards.

Why it matters to the business

Leavers. When someone leaves, the company disables them in its identity provider. If that person also has a personal SAP account in SAP ID service with administrator rights, the company's switch doesn't reach it. SAP identifies a user by name and identity provider, so the same e-mail address in two providers is two different users.

Strong sign-in. SAP says multifactor authentication can't be enforced for users in SAP ID service. It can be enforced through the company's own SAP Cloud Identity Services tenant or its corporate identity provider.

Concentrated power. A handful of role collections let their holders manage users, trust and every subaccount below. An app support team handed one of them "to fix a logon problem" can now grant itself anything.

Production data. In Cloud Foundry, SAP warns that the Space Developer role can read the credentials of service bindings. A developer with that role in production can read what the production app reads.

Evidence. SAP keeps the platform's own audit records for 90 days at no extra cost. A yearly audit looks back further, so someone has to export them.

Example: Calder Pumpworks, the course's fictional pump maker, runs nine stage subaccounts on BTP for integration, AI agents and a distributor app. Its first BTP administrator set up the global account with his personal SAP account before Calder connected its own identity provider. He still holds Global Account Administrator through both. A contract developer who left in October still has rights in two subaccounts. Nothing fails, which is why nobody noticed.

How SAP does it

As of November 2026, SAP documents these pieces for the BTP multi-environment model (User and Member Management):

  • SAP ID service. The default identity provider, trusted out of the box. SAP positions it for starter scenarios, testing and as a backup (Default Identity Provider).
  • SAP Cloud Identity Services. SAP strongly recommends a company tenant of it as the identity provider, connected to the corporate one (for example Microsoft Entra ID). For a custom platform identity provider, SAP says this tenant is mandatory (Trust and Federation).
  • Trust configurations. One for platform users on the global account, and one per subaccount for business users.
  • SAP Authorization and Trust Management service (often called XSUAA). Issues the tokens apps check, holds roles and role collections, and creates the user copies (shadow users).
  • Predefined role collections such as Global Account Administrator, Subaccount Administrator and Subaccount Viewer, which can't be changed or deleted (Role Collections and Roles).
  • SAP Audit Log service and the Audit Log Viewer. SAP-written records are kept 90 days at no extra cost; records written by your own apps and longer retention need the premium edition, charged by volume (Audit Logging).

Some environments add their own layer: Cloud Foundry has org and space roles, Kyma uses Kubernetes role-based access control, and the ABAP environment keeps a separate user and role concept. Identity across SAP's whole landscape is covered in Unit 27, starting with SAP Cloud Identity Services; single sign-on, principal propagation and identity governance follow there.

Who decides what

Access fails at the boundaries between teams. Agree the owners before go-live. The table shows Calder's split; the team names are course values.

Decision Made where Owner at Calder Typical failure
Who exists, and who has left Corporate identity provider and SAP Cloud Identity Services HR feed and identity team A leaver keeps a second account elsewhere
How people sign in Trust configuration, identity provider policies Identity team Multifactor authentication on one app, not the others
Who administers the platform Global account, directory and subaccount role collections BTP platform team An early personal admin account never removed
Who uses which app Role collections mapped to identity provider groups App owners, approved by the process owner Rights added one person at a time, never reviewed
What a role allows inside the app xs-security.json scopes and attributes App developers A role that sees every customer
Proof Audit Log Viewer, exports Security operations Logs gone after 90 days

Questions to ask

  • Which identity provider do our platform users sign in with, and does anyone still hold rights through SAP ID service?
  • Who holds Global Account Administrator, how many people is that, and where is the break-glass account's password kept?
  • Is the default identity provider still offered to business users in production subaccounts?
  • Do business users get role collections through groups, and who approves group membership?
  • Who has Space Developer in production spaces, and why?
  • How do leavers lose BTP access, and how fast?
  • Where do our audit logs go before SAP deletes them after 90 days?

Common misconceptions

  • "Disabling someone in our identity provider removes all their BTP access." It blocks sign-in through that provider. Rights held through SAP ID service under the same e-mail stay usable, and every assignment stays until someone deletes it.
  • "Subaccount Viewer is harmless, so anyone can have it." It is read-only, but it shows trust settings, users and destinations. SAP also separates out viewing service binding credentials into its own role.
  • "Global account administrators can't see inside subaccounts." SAP lets them add themselves as Subaccount Administrator from the account explorer, unless the company asks SAP to switch that off.
  • "A role collection change applies at once." SAP says authorizations sit in the user's session and change only after the user signs out and in again.
  • "SAP keeps our audit logs." For 90 days. Longer means exporting them or paying for longer retention.

Key terms

All course terms, A to Z, in the glossary

  • Identity provider: the system that holds users and checks their sign-in, such as SAP ID service or a company's SAP Cloud Identity Services tenant.
  • SAP ID service: SAP's default identity provider for BTP, trusted out of the box.
  • Platform user: an administrator, developer or operator who manages accounts, apps and services.
  • Business user: a person who uses the apps deployed on BTP.
  • Trust configuration: the link between a global account or subaccount and an identity provider, named by an origin key.
  • Shadow user: BTP's copy of a user from an identity provider, which carries the role collection assignments.
  • Role collection: a bundle of roles assigned to users or identity provider groups.
  • Role template and scope: an app's definition of a role (the template) and the single permissions it grants (scopes).
  • Audit log: security-relevant records of sign-ins, configuration changes and access to personal data.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1Calder's first BTP administrator still holds Global Account Administrator through SAP ID service. What happens if Calder disables him in its own identity provider?

Answer: D. SAP identifies a user by name and identity provider, so the same e-mail in SAP ID service is a separate user. Calder's identity provider can't disable an account it doesn't hold.

2Why does SAP push companies to their own SAP Cloud Identity Services tenant instead of SAP ID service?

Answer: C. SAP's reasons are control of the user lifecycle and the company's own password and authentication policies. SAP says multifactor authentication can't be enforced for users in SAP ID service.

3An app support lead asks for a custom role collection that includes User and Role Administrator "to fix logon problems". What is the risk?

Answer: A. User and Role Administrator carries the scopes SAP marks as critical: managing users, authorizations and trust configurations. Anyone holding it can grant themselves more.

4A tester reports that a newly assigned role collection "doesn't work". What should the project lead check first?

Answer: B. SAP says authorizations are stored in the user's session and change only after a new sign-in. Most "it doesn't work" reports after a role change are an old session.

5Calder's auditors ask for a year of evidence on who changed security settings in BTP. What has to be in place?

Answer: C. SAP-written audit records are kept 90 days at no extra cost. Longer evidence needs regular exports or paid longer retention.

6Which practice best keeps business access reviewable as Calder's apps grow?

Answer: B. Groups move people in and out through the identity provider, where joiners and leavers are already handled. SAP describes group mapping as the efficient way to give new users the right role collections.
Deep layer · 38 min read

Mental model

Every action on BTP passes three gates, and each one is owned by a different team:

  1. Sign-in (identity team): which identity provider vouches for this person. A user is the pair e-mail plus origin, never the e-mail alone.
  2. Assignment (platform team for the platform, app owners for apps): which role collections that pair holds, at which level, directly or through a group.
  3. Check (the service or app): which scopes the roles grant, read from the token on every request.

An auditor asks the reverse question: show me every pair that can pass all three for a given action. Most findings are a pair nobody meant to keep: a personal SAP ID service account from the first week, a contractor's shadow user, a support group with a critical role.

flowchart LR
  P[Person] --> I{Identity provider<br/>origin}
  I -->|calder-platform| SU1[Shadow user<br/>e-mail + origin]
  I -->|sap.default| SU2[Shadow user<br/>same e-mail, other origin]
  SU1 --> RC[Role collections<br/>direct or by group]
  SU2 --> RC2[Role collections]
  RC --> T[Token with scopes]
  RC2 --> T
  T --> S[Service or app<br/>checks scopes]

How it works

Two kinds of users, separate trust

SAP separates platform users, who manage accounts, environments and services, from business users, who use the apps (Platform Users). They have separate trust configurations: SAP's best practices guide says platform users share the identity providers configured for the global account, which apply down through directories, subaccounts and environments, while business users use the identity provider configured for each subaccount (Security Concepts).

SAP lists exceptions. The ABAP environment doesn't separate the two and keeps its own user and authorization concept. Kyma manages access inside the cluster with Kubernetes role-based access control, gives the user who creates the runtime the cluster-admin role, and lets you bind roles to groups only with a custom identity provider (User and Member Management, Assign Roles in the Kyma Environment). SAP Build Code and SAP Build applications are used by developers as business users.

Identity providers and trust

SAP ID service is trusted by default for both user types. SAP says multifactor authentication can be switched on by users themselves there, but there is no way to enforce it (Default Identity Provider).

Platform trust. On the global account, under Security > Trust Configuration > Establish Trust, you pick an SAP Cloud Identity Services tenant associated with your customer ID. As of November 2026, SAP documents these limits (Custom Identity Providers for Platform Users):

  • up to three tenants per global account, and several global accounts may share one;
  • e-mail addresses in the tenant must be unique and correct, because the e-mail is the user identifier at every account level and in Cloud Foundry;
  • the origin key ends in -platform, has at most 36 characters, and can be set only once for the whole landscape;
  • to enforce multifactor authentication, configure it in every SAP Cloud Identity Services application involved, or once in the corporate identity provider.

Platform users then sign in with a cockpit link that names the tenant, and give the origin key to tools such as the btp CLI (--of-idp when managing users) and the cf CLI.

Business user trust. In each subaccount, Establish Trust connects one SAP Cloud Identity Services tenant over OpenID Connect, with no metadata files to exchange. SAP allows only one tenant per subaccount this way, and changing it later is blocked while subscriptions that rely on it exist (Establish Trust with SAP Cloud Identity Services). The tenant gets an application named after the subaccount. Older SAML trust configurations can be migrated to OpenID Connect.

Retiring the default. Once custom trust works, SAP lets you hide SAP ID service's logon link or set it inactive. Deactivating it requires that the administrator signed in through a custom platform trust and that the subaccount has a custom trust for business users (Deactivate the Default Identity Provider).

Shadow users

BTP keeps a shadow user for every user it has seen from a trusted identity provider; role collections are assigned to it (Add Members to Your Subaccount). By default, a first logon through a custom trust creates one automatically. Switch that off and only users an administrator created, or a provisioning job delivered, can sign in. SAP notes that for subaccounts created after 24 September 2020, automatic creation is already off for SAP ID service (Switch Off Automatic Creation of Shadow Users). The SAP wizard suggests keeping automatic creation on when unsure, because a missing shadow user means a failed logon.

The trade-off is control against effort. Automatic creation plus group mapping means anyone in the right group gets in. Switching it off means a provisioning flow, such as SAP Cloud Identity Services Identity Provisioning, must create users first; SAP's best practices guide recommends creating users in SAP Cloud Identity Services and provisioning them from there (Setting Up Identity Lifecycle).

Shadow users also outlive the person. SAP's Security > Users page filters by Hasn't Logged On and shows User has never logged on for accounts created with a typo (Find Inactive Users).

Role collections, roles, templates and scopes

The layers, from the bottom up (Roles and Role Collections):

Layer Defined by Example
Scope The app's xs-security.json $XSAPPNAME.Display
Role template The app's xs-security.json, grouping scopes and attributes Viewer
Role An instance of a template, created at deployment or by an administrator Viewer with attribute SalesOrg = CPUS
Role collection An administrator, or the app as a predefined collection Distributor Order Status Viewer
Assignment An administrator: to a user, a group or an attribute value group DIST-PORTAL-DISTRIBUTORS

Role collections are account-specific: one created in the global account doesn't exist in a subaccount, and the other way round. SAP's predefined collections can't be changed or deleted (Role Collections and Roles). The ones that run the platform, as documented in November 2026:

Role collection Level Notable roles inside
Global Account Administrator Global account Global Account Admin, User and Role Administrator, Auditlog_Auditor, System Landscape Administrator
Global Account Viewer Global account Global Account Viewer, User and Role Auditor, Auditlog_Auditor
Directory Administrator Directory Directory Admin, User and Role Administrator
Subaccount Administrator Subaccount Subaccount Admin, User and Role Administrator, Destination Administrator, Cloud Connector Administrator, Subaccount Service Administrator, Auditlog_Auditor
Subaccount Viewer Subaccount Subaccount Viewer, User and Role Auditor, Destination Viewer, Cloud Connector Auditor, Auditlog_Auditor
Destination Administrator, Cloud Connector Administrator and others Subaccount One job each

Three details matter for design:

  • User and Role Administrator carries what SAP calls critical security authorizations: scopes prefixed xs_ for reading and managing authorizations, users, trust configurations and API credentials (Application Security Descriptor Configuration Syntax). Every administrator collection includes it.
  • Global account administrators can enter any subaccount. SAP says they don't automatically get subaccount rights, but can grant themselves Subaccount Administrator with Add Me as Admin. The company can opt out through an SAP support case.
  • Binding credentials are separate. Subaccount Viewer doesn't show them; SAP says to build a custom collection with the Service Credentials Viewer role when someone needs that.

Cloud Foundry org and space roles

Inside a Cloud Foundry org, SAP uses the platform's own roles: Org Manager, Org Auditor and Org User, then Space Manager, Space Developer, Space Auditor and Space Supporter per space (About Roles in the Cloud Foundry Environment). SAP's caution is direct: Space Developer has broad rights, including access to the credentials of service and app bindings. The best practices guide recommends it for all developers in development, and in production only for platform team members authorized to see the data (Giving Access Rights to Platform Users). Space Supporter is the narrower choice for troubleshooting.

Authorization in your own apps

An app on Cloud Foundry declares its security model in xs-security.json and gets an SAP Authorization and Trust Management service instance from it. A sketch for Calder's distributor app (a sketch: deploying it needs a Cloud Foundry space and an app, which Unit 5 set up):

{
  "xsappname": "distributor-order-status",
  "scopes": [
    { "name": "$XSAPPNAME.ReadOrders", "description": "Read own orders" },
    { "name": "$XSAPPNAME.Admin", "description": "Manage distributor access" }
  ],
  "attributes": [
    { "name": "Customer", "description": "Distributor customer number", "valueType": "string" }
  ],
  "role-templates": [
    { "name": "DistributorViewer", "scope-references": ["$XSAPPNAME.ReadOrders"],
      "attribute-references": ["Customer"] },
    { "name": "DistributorAdmin", "scope-references": ["$XSAPPNAME.Admin"] }
  ],
  "oauth2-configuration": {
    "token-validity": 1800,
    "redirect-uris": ["https://calder-ext-prod-distributor-portal.example/login/callback"],
    "credential-types": ["binding-secret", "x509"]
  }
}

What each part does, per SAP's syntax page:

  • Scopes are the single permissions the app checks. $XSAPPNAME is replaced by the app's name at deployment.
  • Attributes restrict data, here to one distributor's customer number. The value can be static in the role, or come from the identity provider's token. SAP now recommends SAP Cloud Identity Services Authorization Management for such instance-based rules in new apps; some apps use authorization policies managed there instead of attributes (Attributes).
  • redirect-uris lists where the service may send users after logon. SAP recommends keeping it as narrow as possible and warns that wildcards widen it (Security Considerations).
  • credential-types: SAP says that since 19 January 2026 new bindings use binding secrets or X.509, so each binding's secret can be rotated alone; remove old instance secrets, which can't be rotated. Services, instances and bindings covers the binding side, and secrets and OAuth the token flows.
  • token-validity in seconds. SAP's defaults are 12 hours for access tokens and 7 days for refresh tokens. SAP's advice: as short as possible, but not under 30 minutes. A subaccount-wide default is set under Security > Settings > Token Validity; a value in xs-security.json overrides it for that instance.

Audit logs

SAP Audit Log stores four categories of records: audit.security-events (logons and logoffs), audit.configuration (security-critical configuration changes), audit.data-access and audit.data-modification (access to and changes of sensitive personal data) (Audit Logging). Records written by SAP's services are kept 90 days at no extra cost. Writing records from your own apps, and longer retention, need the premium edition plan, charged by stored volume and available in a listed set of regions (Retention of Audit Data from Customer Applications).

The Audit Log Viewer is available for the global account and each Cloud Foundry subaccount; it returns 500 records per request and can download a time window (Audit Log Viewer). For continuous export, SAP offers a retrieval API per subaccount and global account. SAP's own recommendations for administrators include archiving audit log entries and feeding them to the company's event management system (Security Recommendations for the Authorization and Trust Management Service).

Calder's model

Calder's target model, built on the nine stage subaccounts from the account model topic:

flowchart TB
  subgraph IdP[Identity]
    E[Corporate identity provider] --> CIS[SAP Cloud Identity Services<br/>tenant calder-lab]
  end
  CIS -->|origin calder-platform| GA[Global account<br/>2 named admins + break-glass]
  CIS -->|origin calder-ias, OIDC| SA[9 stage subaccounts<br/>business users by group]
  GA --> D[Directory AI and agents<br/>2 directory admins]
  SA --> CF[Cloud Foundry spaces<br/>Space Developer: platform team only in prod]
  SA --> AL[Audit logs<br/>exported weekly]

The draft the platform team wrote first breaks this in six places. The build section finds them.

Build it yourself

Before you start: finish Set up your computer for this course. The optional Step 8 uses your BTP trial and the btp CLI from Set up for Unit 21. Everything else runs without an account.

You will put Calder's draft access design into a file, list it, check it against SAP's guidance and Calder's rules, ask what one person can do everywhere, simulate a leaver, and write the deliverable unit21/calder_security.md. The draft has six errors and two warnings; you fix them in the exercise.

flowchart LR
  I[--init] --> J[calder_security.json<br/>the draft]
  J --> M[--map]
  J --> C[--check<br/>S01-S12]
  J --> W[--who / --leaver]
  J --> R[--write]
  R --> D[calder_security.md<br/>the deliverable]

The script talks to no SAP system. The file describes what the cockpit shows under Security and in Cloud Foundry's member lists. It doesn't model every role or setting.

What you need

  • The course folder orchestrate-course with its .venv.
  • No account and no key for Steps 1 to 7. The script uses only Python's built-in modules, so requirements.txt doesn't change.
  • For the optional Step 8: your BTP trial and the btp CLI. Free.
  • Time: about 35 minutes.

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

  1. Open VS Code, then File > Open Folder and choose orchestrate-course.

  2. Open a terminal with Terminal > New Terminal.

  3. Turn on the virtual environment:

    • Windows (PowerShell):

      .venv\Scripts\Activate.ps1
    • macOS / Linux:

      source .venv/bin/activate
  4. Make the unit21 folder if you don't have it yet:

    • Windows (PowerShell):

      New-Item -ItemType Directory -Force unit21
    • macOS / Linux:

      mkdir -p unit21

You should see (.venv) at the start of the prompt.

Step 2: Create the script

  1. In VS Code, create the file unit21/security_check.py.
  2. Paste the code below and save.
"""Calder's SAP BTP security model: who can do what, where, and through which identity provider.

Usage (run from the orchestrate-course folder):
  python unit21/security_check.py --init        write the draft model to unit21/calder_security.json
  python unit21/security_check.py --map         list trust, role collections and members per level
  python unit21/security_check.py --check       check the model against SAP's guidance and Calder's rules
  python unit21/security_check.py --who EMAIL   everything one person can do, at every level
  python unit21/security_check.py --leaver EMAIL  what still works if Calder's identity provider disables EMAIL
  python unit21/security_check.py --write       write unit21/calder_security.md (the deliverable)

Options:
  --file PATH     read another model file in the same shape
  --force         let --init overwrite an existing model file

Built-in modules only. No account, no network: the script reads a file that describes what the
cockpit shows under Security (trust configurations, users, role collections) and under
Cloud Foundry (space members). Calder Pumpworks is fictional; e-mail addresses, origins, group
names, custom role collections and rules S03, S06, S07, S08, S10 and S11 are course labels.
Role collection contents follow SAP's documentation for the predefined collections.
"""
import argparse
import datetime as dt
import json
import sys
from pathlib import Path

MODEL_FILE = Path("unit21/calder_security.json")
REPORT_FILE = Path("unit21/calder_security.md")
DEFAULT_ORIGIN = "sap.default"          # SAP ID service, the default identity provider
CRITICAL_ROLE = "User and Role Administrator"   # carries the xs_ scopes SAP marks as critical
INACTIVE_DAYS = 180                     # course rule
MIN_TOKEN, MAX_TOKEN = 1800, 3600       # SAP: not below 30 minutes; the upper bound is a course rule
AUDIT_EXPORT_DAYS = 30                  # course rule, well inside SAP's 90-day default retention

# Predefined role collections and the roles SAP documents in them (subset used here).
PREDEFINED = {
    "Global Account Administrator": ["Global Account Admin", "Global Account Usage Reporting Viewer",
                                     CRITICAL_ROLE, "Auditlog_Auditor", "System Landscape Administrator"],
    "Global Account Viewer": ["Global Account Viewer", "Global Account Usage Reporting Viewer",
                              "Auditlog_Auditor", "User and Role Auditor", "System Landscape Viewer"],
    "Directory Administrator": ["Directory Admin", "Directory Usage Reporting Viewer", CRITICAL_ROLE],
    "Directory Viewer": ["Directory Viewer", "Directory Usage Reporting Viewer", "User and Role Auditor"],
    "Subaccount Administrator": ["Auditlog_Auditor", "Central Disaster Recovery Administrator",
                                 "Cloud Connector Administrator", "Destination Administrator",
                                 "Destination Fragment Administrator", "Subaccount Admin",
                                 "Subaccount Service Administrator", CRITICAL_ROLE],
    "Subaccount Viewer": ["Auditlog_Auditor", "Cloud Connector Auditor", "Destination Fragment Viewer",
                          "Destination Viewer", "Subaccount Service Auditor", "Subaccount Viewer",
                          "User and Role Auditor"],
    "Destination Administrator": ["Destination Administrator"],
    "Cloud Connector Administrator": ["Cloud Connector Administrator"],
}
PLATFORM_COLLECTIONS = set(PREDEFINED)  # role collections that manage the platform itself


def draft_model():
    """The platform team's draft of 2026-11-26: six planted errors and two warnings."""
    dom = "@calder-pumpworks.example"
    people = {
        "btp.admin1" + dom: {"person": "00100316", "job": "BTP platform administrator", "team": "platform",
                             "status": "active", "last_logon": "2026-11-25"},
        "btp.admin2" + dom: {"person": "00100317", "job": "BTP platform administrator", "team": "platform",
                             "status": "active", "last_logon": "2026-11-24"},
        "btp.emergency" + dom: {"person": "break-glass", "job": "emergency account, sealed credentials",
                                "team": "platform", "status": "active", "last_logon": "2026-06-30"},
        "enterprise.architect" + dom: {"person": "00100290", "job": "enterprise architect", "team": "ai",
                                       "status": "active", "last_logon": "2026-11-20"},
        "integration.dev" + dom: {"person": "00100288", "job": "integration developer", "team": "ai",
                                  "status": "active", "last_logon": "2026-11-26"},
        "integration.lead" + dom: {"person": "00100292", "job": "integration lead", "team": "integration",
                                   "status": "active", "last_logon": "2026-11-23"},
        "intgration.lead" + dom: {"person": "00100292", "job": "typo of integration.lead, created by hand",
                                  "team": "integration", "status": "active", "last_logon": None},  # planted S08
        "group.controller" + dom: {"person": "00100280", "job": "group controller", "team": "finance",
                                   "status": "active", "last_logon": "2026-11-02"},
        "ext.developer" + dom: {"person": "contractor", "job": "contract developer, apps team",
                                "team": "apps", "status": "left 2026-10-30", "last_logon": "2026-10-29"},  # S07
    }

    def ua(user, collection, origin="calder-platform"):
        return {"user": user + dom, "origin": origin, "role_collection": collection}

    def ga(group, collection, origin="calder-ias"):
        return {"group": group, "origin": origin, "role_collection": collection}

    def app_trust(stage, default_active=True, link=True):
        return {"default_idp": {"status": "active" if default_active else "inactive", "logon_link": link},
                "custom": {"origin": "calder-ias", "tenant": "calder-lab", "protocol": "OpenID Connect",
                           "shadow_users_on_logon": stage != "prod", "provisioning": stage == "prod"}}

    def sub(stage, assignments, spaces, export_days=7, token=1800):
        hidden = stage == "prod"
        return {"stage": stage, "app_trust": app_trust(stage, default_active=not hidden, link=not hidden),
                "token_validity": {"access": token, "refresh": 43200},
                "audit_export_days": export_days if stage == "prod" else None,
                "assignments": assignments, "spaces": spaces}

    admins = [ua("btp.admin1", "Subaccount Administrator"), ua("btp.admin2", "Subaccount Administrator")]
    dev_spaces = lambda space: {space: {"Space Manager": ["btp.admin1" + dom],
                                        "Space Developer": ["integration.dev" + dom]}}
    prod_spaces = lambda space: {space: {"Space Manager": ["btp.admin1" + dom],
                                         "Space Developer": ["btp.admin2" + dom]}}

    subaccounts = {
        "Integration Dev": sub("dev", admins + [ua("integration.dev", "Subaccount Viewer")], dev_spaces("integration")),
        "Integration Test": sub("test", admins, {}),
        "Integration Prod": sub("prod", admins + [ua("intgration.lead", "Subaccount Viewer")], {}),  # S08
        "AI Dev": sub("dev", admins + [ua("integration.dev", "Subaccount Viewer")], dev_spaces("agents")),
        "AI Test": sub("test", admins, prod_spaces("agents")),
        "AI Prod": sub("prod", admins + [ua("enterprise.architect", "Subaccount Viewer"),
                                         ga("AGT-ORDER-EXC-USERS", "Order Exception Agent User")],
                       {"agents": {"Space Manager": ["btp.admin1" + dom],
                                   "Space Developer": ["btp.admin2" + dom, "integration.dev" + dom]}}),  # S05
        "Ext Dev": sub("dev", admins, {"distributor-portal": {"Space Manager": ["btp.admin1" + dom],
                                                              "Space Developer": ["ext.developer" + dom]}}),  # S07
        "Ext Test": sub("test", admins, prod_spaces("distributor-portal")),
        "Ext Prod": sub("prod", admins + [ua("ext.developer", "Subaccount Viewer"),                          # S07
                                          ga("DIST-PORTAL-DISTRIBUTORS", "Distributor Order Status Viewer"),
                                          ga("DIST-PORTAL-ADMINS", "Distributor Order Status Admin"),
                                          ga("BTP-APP-SUPPORT", "Calder App Support")],                     # S04
                        prod_spaces("distributor-portal")),
    }
    subaccounts["AI Prod"]["app_trust"]["default_idp"] = {"status": "active", "logon_link": True}  # S02
    return {
        "as_of": "2026-11-26",
        "people": people,
        "break_glass": ["btp.emergency" + dom],
        "platform_origins": {DEFAULT_ORIGIN: "SAP ID service (default)",
                             "calder-platform": "Calder's SAP Cloud Identity Services tenant calder-lab"},
        "global_account": {
            "add_me_as_admin": "enabled",                                                       # S11
            "assignments": [ua("btp.admin1", "Global Account Administrator"),
                            ua("btp.admin2", "Global Account Administrator"),
                            ua("btp.admin1", "Global Account Administrator", DEFAULT_ORIGIN),     # S01
                            ua("btp.emergency", "Global Account Administrator", DEFAULT_ORIGIN),
                            ua("group.controller", "Global Account Viewer")]},
        "directories": {
            "AI and agents": {"assignments": [ua("enterprise.architect", "Directory Administrator"),
                                              ua("integration.dev", "Directory Administrator")]}},
        "custom_role_collections": {
            "Order Exception Agent User": {"roles": ["OrderExceptionUser"], "app": "order-exc-agent"},
            "Distributor Order Status Viewer": {"roles": ["DistributorViewer"], "app": "distributor-order-status"},
            "Distributor Order Status Admin": {"roles": ["DistributorAdmin"], "app": "distributor-order-status"},
            "Calder App Support": {"roles": ["Subaccount Viewer", CRITICAL_ROLE], "app": "platform"},     # S04
        },
        "subaccounts": subaccounts,
    }


# ---------------------------------------------------------------- loading
def load(path):
    if not path.exists():
        sys.exit(f"No model file {path}. Run: python unit21/security_check.py --init")
    try:
        model = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        sys.exit(f"{path} is not valid JSON (line {e.lineno}, column {e.colno}): {e.msg}")
    people = model.get("people", {})
    for level, assignments in levels(model):
        for a in assignments:
            if "user" in a and a["user"] not in people:
                sys.exit(f"{level}: user '{a['user']}' is not in 'people' (check the spelling)")
            rc = a.get("role_collection")
            if rc not in PREDEFINED and rc not in model.get("custom_role_collections", {}):
                sys.exit(f"{level}: role collection '{rc}' is neither predefined nor in 'custom_role_collections'")
    return model


def levels(model):
    """Yield (level name, assignment list) for the global account, directories and subaccounts."""
    yield "Global account", model["global_account"]["assignments"]
    for name, d in model.get("directories", {}).items():
        yield f"Directory {name}", d["assignments"]
    for name, s in model["subaccounts"].items():
        yield f"Subaccount {name}", s["assignments"]


def roles_of(model, collection):
    if collection in PREDEFINED:
        return PREDEFINED[collection]
    return model["custom_role_collections"][collection]["roles"]


# ---------------------------------------------------------------- views
def show_map(model):
    print(f"Calder BTP security model as of {model['as_of']}\n")
    print("Platform identity providers (global account):")
    for origin, text in model["platform_origins"].items():
        print(f"  {origin:<16} {text}")
    print(f"  'Add Me as Admin' for global account administrators: {model['global_account']['add_me_as_admin']}\n")
    for level, assignments in levels(model):
        print(level)
        for a in assignments:
            who = a.get("user") or f"group {a['group']}"
            print(f"  {a['role_collection']:<34} {who}  [{a['origin']}]")
        if level.startswith("Subaccount"):
            s = model["subaccounts"][level.split(" ", 1)[1]]
            d = s["app_trust"]["default_idp"]
            c = s["app_trust"]["custom"]
            print(f"  trust: default IdP {d['status']}, logon link {'shown' if d['logon_link'] else 'hidden'}; "
                  f"{c['origin']} ({c['protocol']}), shadow users on logon "
                  f"{'on' if c['shadow_users_on_logon'] else 'off'}")
            for space, roles in s["spaces"].items():
                for role, users in roles.items():
                    print(f"  space {space}: {role:<16} {', '.join(users)}")
        print()


def holdings(model, email):
    """Every role collection and space role this e-mail holds, with origin and level."""
    rows = []
    for level, assignments in levels(model):
        for a in assignments:
            if a.get("user") == email:
                rows.append((level, a["role_collection"], a["origin"], roles_of(model, a["role_collection"])))
    for name, s in model["subaccounts"].items():
        for space, roles in s["spaces"].items():
            for role, users in roles.items():
                if email in users:
                    rows.append((f"Subaccount {name}", f"{role} in space {space}", "calder-platform", [role]))
    return rows


def show_who(model, email):
    person = model["people"].get(email)
    if not person:
        sys.exit(f"'{email}' is not in 'people'. Names are case-sensitive; run --map to see them.")
    print(f"{email}: {person['job']} ({person['person']}), {person['status']}, "
          f"last logon {person['last_logon'] or 'never'}\n")
    rows = holdings(model, email)
    if not rows:
        print("  no role collections and no space roles")
    for level, collection, origin, roles in rows:
        mark = "  CRITICAL" if CRITICAL_ROLE in roles else ""
        print(f"  {level:<28} {collection:<34} via {origin}{mark}")
    print("\nGroups are not resolved here: membership lives in the identity provider.")


def show_leaver(model, email):
    if email not in model["people"]:
        sys.exit(f"'{email}' is not in 'people'.")
    rows = holdings(model, email)
    print(f"If Calder's identity provider disables {email} today:\n")
    still = [r for r in rows if r[2] == DEFAULT_ORIGIN]
    for level, collection, _, _ in still:
        print(f"  STILL USABLE  {level}: {collection}, signed in through SAP ID service, "
              f"which Calder's identity provider doesn't control")
    blocked = len(rows) - len(still)
    print(f"  blocked       {blocked} {'other ' if still else ''}assignment(s): nobody can sign in to use them, "
          f"but they stay in BTP until someone deletes them")
    print(f"\n{len(still)} assignment(s) still usable, {len(rows)} to delete in BTP.")
    still = len(still)
    return still


# ---------------------------------------------------------------- checks
def check(model):
    findings = []
    err = lambda rule, where, text: findings.append(("ERROR", rule, where, text))
    warn = lambda rule, where, text: findings.append(("WARN", rule, where, text))
    people, today = model["people"], dt.date.fromisoformat(model["as_of"])
    platform_team = {e for e, p in people.items() if p["team"] == "platform"}

    for level, assignments in levels(model):
        for a in assignments:
            rc, who = a["role_collection"], a.get("user")
            # S01 platform access only through Calder's platform identity provider (SAP recommendation;
            #     the break-glass exception is a course rule)
            if who and rc in PLATFORM_COLLECTIONS and a["origin"] == DEFAULT_ORIGIN \
                    and who not in model["break_glass"]:
                err("S01", level, f"{who} holds {rc} through SAP ID service; use Calder's platform "
                                  f"identity provider (only the break-glass account stays in the default)")
            # S04 critical security role only for the platform team (course rule on SAP's warning)
            if CRITICAL_ROLE in roles_of(model, rc) and rc not in PREDEFINED:
                holder = who or f"group {a['group']}"
                if who not in platform_team:
                    err("S04", level, f"custom role collection '{rc}' contains {CRITICAL_ROLE} "
                                      f"(critical xs_ scopes) and is assigned to {holder}")
            # S07 nobody who left holds anything (course rule: HR status drives removal)
            if who and people[who]["status"].startswith("left"):
                err("S07", level, f"{who} {people[who]['status']} and still holds {rc}")
            # S08 never logged on, or not for INACTIVE_DAYS (SAP's 'Find Inactive Users'; days are a course rule)
            if who and not people[who]["status"].startswith("left") and who not in model["break_glass"]:
                last = people[who]["last_logon"]
                if last is None:
                    warn("S08", level, f"{who} has never logged on (a typo in a hand-made shadow user?) "
                                       f"and holds {rc}")
                elif (today - dt.date.fromisoformat(last)).days > INACTIVE_DAYS:
                    warn("S08", level, f"{who} last logged on {last}, over {INACTIVE_DAYS} days ago")

    # S03 global account administrators: two to three named, plus break-glass (course rule)
    gaa = {a["user"] for a in model["global_account"]["assignments"]
           if a["role_collection"] == "Global Account Administrator" and a.get("user")}
    named = gaa - set(model["break_glass"])
    if not 2 <= len(named) <= 3:
        err("S03", "Global account", f"{len(named)} named Global Account Administrator(s); keep 2 to 3")
    # S11 'Add Me as Admin' lets every global account administrator enter any subaccount (SAP feature;
    #     opting out is a course rule)
    if model["global_account"].get("add_me_as_admin") != "opted_out":
        warn("S11", "Global account", "'Add Me as Admin' is enabled: every Global Account Administrator can "
                                      "make themselves Subaccount Administrator; request the opt-out")

    for name, s in model["subaccounts"].items():
        where, prod = f"Subaccount {name}", s["stage"] == "prod"
        for space, roles in s["spaces"].items():
            for user in roles.get("Space Developer", []):
                if user in people and people[user]["status"].startswith("left"):
                    err("S07", where, f"{user} {people[user]['status']} and is still Space Developer in {space}")
                # S05 Space Developer in production only for the platform team (SAP best practices guide)
                if prod and user not in platform_team:
                    err("S05", where, f"{user} is Space Developer in production space '{space}'; the role "
                                      f"reads service credentials, so keep it to the platform team")
        if not prod:
            continue
        # S02 default identity provider not offered to business users in production (SAP: deactivate or hide)
        d = s["app_trust"]["default_idp"]
        if d["status"] == "active" and d["logon_link"]:
            err("S02", where, "SAP ID service is active with a logon link; set it inactive or hide the link")
        # S10 audit log export (SAP: archive audit logs; 90-day default retention; interval is a course rule)
        days = s.get("audit_export_days")
        if not days or days > AUDIT_EXPORT_DAYS:
            err("S10", where, f"audit logs exported every {days or 'never'} day(s); "
                              f"export at least every {AUDIT_EXPORT_DAYS} days")
        # S09 token validity (SAP: as short as possible, not under 30 minutes; the cap is a course rule)
        acc = s["token_validity"]["access"]
        if not MIN_TOKEN <= acc <= MAX_TOKEN:
            err("S09", where, f"access tokens valid {acc} s; keep {MIN_TOKEN} to {MAX_TOKEN} s in production")
        # S06 business role collections reach people through groups, not one by one (course rule)
        for a in s["assignments"]:
            if a.get("user") and a["role_collection"] not in PLATFORM_COLLECTIONS:
                warn("S06", where, f"{a['role_collection']} assigned to {a['user']} directly; map it to a group")
        # S12 shadow users: either created on logon or provisioned, otherwise nobody can log on (SAP behavior)
        c = s["app_trust"]["custom"]
        if not c["shadow_users_on_logon"] and not c.get("provisioning"):
            err("S12", where, "shadow users are neither created on logon nor provisioned; logons will fail")
    return findings


def print_findings(findings):
    findings.sort(key=lambda f: (f[1], f[2]))
    for kind, rule, where, text in findings:
        print(f"  {kind:<5} {rule} {where}: {text}")
    errors = sum(1 for f in findings if f[0] == "ERROR")
    print(f"\n{errors} error(s), {len(findings) - errors} warning(s)")
    return errors


# ---------------------------------------------------------------- deliverable
def write_report(model, findings, path):
    L = [f"# Calder BTP security model ({model['as_of']})", "",
         "Calder Pumpworks is fictional. Origins, groups and custom role collections are course labels.", "",
         "## Identity providers", "", "| Level | Origin | What it is |", "| --- | --- | --- |"]
    for origin, text in model["platform_origins"].items():
        L.append(f"| Platform users (global account) | `{origin}` | {text} |")
    seen = set()
    for name, s in model["subaccounts"].items():
        c = s["app_trust"]["custom"]
        if c["origin"] not in seen:
            seen.add(c["origin"])
            L.append(f"| Business users (each subaccount) | `{c['origin']}` | tenant {c['tenant']}, {c['protocol']} |")
    L += ["", "## Administrators", "", "| Level | Role collection | Holder | Origin |", "| --- | --- | --- | --- |"]
    for level, assignments in levels(model):
        for a in assignments:
            if a["role_collection"] in PLATFORM_COLLECTIONS and "Administrator" in a["role_collection"]:
                L.append(f"| {level} | {a['role_collection']} | {a.get('user') or a.get('group')} | `{a['origin']}` |")
    L += ["", "## Business access in production", "", "| Subaccount | Role collection | Group |", "| --- | --- | --- |"]
    for name, s in model["subaccounts"].items():
        if s["stage"] == "prod":
            for a in s["assignments"]:
                if a.get("group"):
                    L.append(f"| {name} | {a['role_collection']} | `{a['group']}` |")
    L += ["", "## Check result", ""]
    if findings:
        L += [f"- {k} {r} {w}: {t}" for k, r, w, t in findings]
    else:
        L.append("No findings.")
    L += ["", "## Decision record", "", "- **Context:**", "- **Options:**", "- **Decision:**",
          "- **Consequences:**", ""]
    path.write_text("\n".join(L), encoding="utf-8")
    print(f"Wrote {path}")


# ---------------------------------------------------------------- main
def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    g = p.add_mutually_exclusive_group(required=True)
    g.add_argument("--init", action="store_true")
    g.add_argument("--map", action="store_true")
    g.add_argument("--check", action="store_true")
    g.add_argument("--who", metavar="EMAIL")
    g.add_argument("--leaver", metavar="EMAIL")
    g.add_argument("--write", action="store_true")
    p.add_argument("--file", type=Path, default=MODEL_FILE)
    p.add_argument("--force", action="store_true")
    args = p.parse_args()

    if args.init:
        if args.file.exists() and not args.force:
            sys.exit(f"{args.file} exists; your edits would be lost. Add --force to start over.")
        args.file.parent.mkdir(parents=True, exist_ok=True)
        args.file.write_text(json.dumps(draft_model(), indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {args.file} (the platform team's draft, with planted errors)")
        return 0
    model = load(args.file)
    if args.map:
        show_map(model)
    elif args.who:
        show_who(model, args.who)
    elif args.leaver:
        return 1 if show_leaver(model, args.leaver) else 0
    elif args.check:
        return 1 if print_findings(check(model)) else 0
    elif args.write:
        write_report(model, check(model), REPORT_FILE)
    return 0


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

Step 3: Write the draft model

Run:

python unit21/security_check.py --init

You should see:

Wrote unit21/calder_security.json (the platform team's draft, with planted errors)

Open unit21/calder_security.json in VS Code. It has six parts: people (each e-mail with its personnel number, team, status and last logon), platform_origins, global_account, directories, custom_role_collections and subaccounts (each with its trust, token validity, audit export interval, assignments and Cloud Foundry spaces). The e-mail addresses use the .example domain on purpose.

Step 4: List the model

python unit21/security_check.py --map

The start of the output:

Calder BTP security model as of 2026-11-26

Platform identity providers (global account):
  sap.default      SAP ID service (default)
  calder-platform  Calder's SAP Cloud Identity Services tenant calder-lab
  'Add Me as Admin' for global account administrators: enabled

Global account
  Global Account Administrator       btp.admin1@calder-pumpworks.example  [calder-platform]
  Global Account Administrator       btp.admin2@calder-pumpworks.example  [calder-platform]
  Global Account Administrator       btp.admin1@calder-pumpworks.example  [sap.default]
  Global Account Administrator       btp.emergency@calder-pumpworks.example  [sap.default]
  Global Account Viewer              group.controller@calder-pumpworks.example  [calder-platform]

Notice btp.admin1 twice: once per origin. To BTP, those are two users.

Step 5: Check the model

python unit21/security_check.py --check

You should see:

  ERROR S01 Global account: btp.admin1@calder-pumpworks.example holds Global Account Administrator through SAP ID service; use Calder's platform identity provider (only the break-glass account stays in the default)
  ERROR S02 Subaccount AI Prod: SAP ID service is active with a logon link; set it inactive or hide the link
  ERROR S04 Subaccount Ext Prod: custom role collection 'Calder App Support' contains User and Role Administrator (critical xs_ scopes) and is assigned to group BTP-APP-SUPPORT
  ERROR S05 Subaccount AI Prod: integration.dev@calder-pumpworks.example is Space Developer in production space 'agents'; the role reads service credentials, so keep it to the platform team
  ERROR S07 Subaccount Ext Dev: ext.developer@calder-pumpworks.example left 2026-10-30 and is still Space Developer in distributor-portal
  ERROR S07 Subaccount Ext Prod: ext.developer@calder-pumpworks.example left 2026-10-30 and still holds Subaccount Viewer
  WARN  S08 Subaccount Integration Prod: intgration.lead@calder-pumpworks.example has never logged on (a typo in a hand-made shadow user?) and holds Subaccount Viewer
  WARN  S11 Global account: 'Add Me as Admin' is enabled: every Global Account Administrator can make themselves Subaccount Administrator; request the opt-out

6 error(s), 2 warning(s)

The exit code is 1 because there are errors. What the rules come from:

Rule Checks Source
S01 Platform role collections only through Calder's platform identity provider; only the break-glass account stays in SAP ID service SAP's recommendation; the exception is a course rule
S02 SAP ID service not offered to business users in production SAP: hide or deactivate the default
S03 Two or three named Global Account Administrators Course rule
S04 No custom role collection with User and Role Administrator outside the platform team SAP's critical-scope warning; course rule
S05 Space Developer in production only for the platform team SAP best practices guide
S06 Business role collections in production through groups, not one by one (warning) Course rule
S07 Leavers hold nothing Course rule
S08 No account that never logged on or not for 180 days (warning) SAP's inactive-user check; the 180 days are a course rule
S09 Production access tokens valid 1,800 to 3,600 seconds SAP: not under 30 minutes; the cap is a course rule
S10 Production audit logs exported at least every 30 days SAP: archive audit logs; the interval is a course rule
S11 Add Me as Admin opted out (warning) SAP feature; course rule
S12 Production subaccounts create or provision shadow users SAP: logons fail without a shadow user

Step 6: Ask what one person can do

python unit21/security_check.py --who integration.dev@calder-pumpworks.example

You should see:

integration.dev@calder-pumpworks.example: integration developer (00100288), active, last logon 2026-11-26

  Directory AI and agents      Directory Administrator            via calder-platform  CRITICAL
  Subaccount Integration Dev   Subaccount Viewer                  via calder-platform
  Subaccount AI Dev            Subaccount Viewer                  via calder-platform
  Subaccount Integration Dev   Space Developer in space integration via calder-platform
  Subaccount AI Dev            Space Developer in space agents    via calder-platform
  Subaccount AI Prod           Space Developer in space agents    via calder-platform

Groups are not resolved here: membership lives in the identity provider.

CRITICAL marks a collection that includes User and Role Administrator. Directory Administrator includes it by SAP's design, so the account model topic's choice of two directory administrators for AI and agents is a choice to give both critical rights there.

Step 7: Simulate a leaver and write the deliverable

  1. Run:

    python unit21/security_check.py --leaver btp.admin1@calder-pumpworks.example

    You should see:

    If Calder's identity provider disables btp.admin1@calder-pumpworks.example today:
    
      STILL USABLE  Global account: Global Account Administrator, signed in through SAP ID service, which Calder's identity provider doesn't control
      blocked       17 other assignment(s): nobody can sign in to use them, but they stay in BTP until someone deletes them
    
    1 assignment(s) still usable, 18 to delete in BTP.

    The exit code is 1 while anything stays usable.

  2. Run:

    python unit21/security_check.py --write

    You should see Wrote unit21/calder_security.md. Open it: it lists the identity providers, every administrator, business access in production by group, the check result, and an empty decision record.

Step 8 (optional): Look at your trial's security settings

This step reads your own trial. It changes nothing.

  1. Open the SAP BTP cockpit and sign in. Open your trial subaccount.

  2. In the left menu choose Security > Trust Configuration. You should see the default identity provider, SAP ID service, with origin sap.default.

  3. Choose Security > Users. You should see your own user. Open it to see your role collections, such as Subaccount Administrator.

  4. Choose Security > Role Collections and open Subaccount Viewer. Compare its roles with the table in How it works.

  5. In the terminal, log in with the btp CLI and target the trial subaccount (its ID is on the subaccount's Overview page):

    btp login --sso
    btp target --subaccount <your-subaccount-id>
    btp list security/trust
    btp list security/role-collection
    btp list security/user

    Run btp help list security/user if a command asks for other parameters; the help shows the exact options for your CLI version.

  6. If your trial has a Cloud Foundry org, list your space's members with the cf CLI:

    cf space-users <your-org> dev

    You should see yourself as Space Manager and Space Developer: fine in a trial, and exactly what S05 forbids in Calder's production.

What the code does

Part What it does
PREDEFINED The roles SAP documents inside the predefined platform role collections
draft_model() Calder's draft: 9 people, 9 subaccounts, one directory, 4 custom role collections, 6 planted errors and 2 warnings
load() Reads the JSON; stops on bad JSON, an unknown person or an unknown role collection
levels() Walks the global account, directories and subaccounts in order
holdings() Every role collection and space role one e-mail holds, with its origin
show_leaver() Separates what still works through SAP ID service from what is only blocked
check() Rules S01 to S12
write_report() Writes the deliverable with an empty decision record

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 the path, or the virtual environment is off Turn on .venv (Step 1); on macOS or Linux try python3
No model file unit21/calder_security.json Step 3 wasn't run, or you're in another folder Run --init from orchestrate-course
... exists; your edits would be lost You ran --init again Keep your file, or add --force to start over
... is not valid JSON (line 52, column 9) An edit left out a comma or quote Open the file at that line; VS Code underlines it
user '...' is not in 'people' An assignment names an e-mail that isn't listed Fix the spelling, or add the person to people
role collection '...' is neither predefined nor in 'custom_role_collections' A typo in a collection name (names are case-sensitive) Use the exact name from the table or the file
Step 8: btp is not recognized The btp CLI isn't installed or not on the path Repeat the install in Set up for Unit 21
Step 8: the cockpit or btp login can't connect A company network or proxy blocks it Try another network, or skip Step 8

The SAP way

As of November 2026, these are SAP's tools for running the security model:

  • Cockpit, Security section on the global account, directories and subaccounts: Trust Configuration, Users (with Hasn't Logged On), Role Collections, Settings (token validity, trusted domains).
  • btp CLI commands btp list|get|delete security/user, btp assign|unassign security/role-collection, and security/role, security/app, security/trust (Managing Users and Their Authorizations Using the btp CLI). SAP notes that the first assignment through the CLI creates a shadow user unless you pass --create-user-if-missing false.
  • REST APIs of the SAP Authorization and Trust Management service for bulk work, and the Terraform provider for SAP BTP for parts of it (Security Administration).
  • SAP Cloud Identity Services: Identity Authentication for sign-in and multifactor policy, Identity Provisioning for user lifecycle, and Authorization Management for policy-based app authorizations.
  • SAP Audit Log service, its viewer and retrieval API; the premium edition for your own records and longer retention.
  • SAP BTP Security Recommendations, SAP's central checklist, which the service pages link to.

Licensing: SAP ID service and the standard audit retention come with BTP. Check SAP Cloud Identity Services entitlements and the Audit Log premium edition price for your contract in SAP Discovery Center before you size a design.

Build vs. SAP

Need Use SAP's Decide or build yourself Why
Sign-in and multifactor authentication SAP Cloud Identity Services, federated to the corporate provider Which provider is the source of truth Can't be enforced in SAP ID service
Joiners and leavers Identity Provisioning from HR or the corporate directory The removal of BTP assignments Disabling sign-in leaves assignments behind
Platform administration rights Predefined role collections Who holds them, how many, break-glass Can't be changed; only their holders can
App permissions xs-security.json or Authorization Management policies Scopes, attributes, group names The app's own model
Access review Cockpit, btp CLI, APIs A model file and checks like this topic's No ready-made cross-level review in BTP
Evidence Audit Log service, viewer and API Export schedule and the receiving system 90 days is shorter than most audits

Architecture view

Where it sits. See Calder's model in How it works: one SAP Cloud Identity Services tenant between the corporate identity provider and BTP, one platform trust on the global account, one business user trust per subaccount, and audit exports leaving each production subaccount.

Non-functional requirements that decide the design

Requirement Typical target (course values) If missed
Sign-in strength Multifactor authentication for every platform user A phished password is a global administrator
Leaver speed Sign-in blocked the same day; BTP assignments deleted within a week A contractor keeps production read access
Concentration 2 to 3 named global account administrators plus one sealed break-glass account Too many people who can change trust
Separation No developer with Space Developer in production Developers read production credentials
Token lifetime 30 to 60 minutes for production access tokens A stolen token works for 12 hours
Evidence Audit logs exported weekly, kept for the audit period Questions about last spring can't be answered

Integration and identity. People exist in the corporate identity provider, which SAP Cloud Identity Services trusts. Platform users reach the cockpit, btp CLI and cf CLI through origin calder-platform. Business users reach apps through calder-ias, and their group memberships arrive in the token's Groups attribute, which SAP maps to role collections (Map Role Collections to User Groups). When an app calls S/4HANA for the user, the identity travels on through the destination, as the connectivity topic shows; principal propagation in depth is covered in Unit 27.

The decision to record (ADR form from Writing a solution design doc):

  • Context: The global account was set up with personal SAP ID service accounts before Calder connected its identity provider. Business users arrive by group, but production still offers SAP ID service.
  • Options: (a) keep SAP ID service in parallel for convenience; (b) all named users through calder-platform and calder-ias, SAP ID service kept only for one sealed break-glass global administrator and hidden or inactive for business users; (c) also deactivate SAP ID service on the global account, with no break-glass path.
  • Decision: (b). SAP describes the default as a possible backup if the custom provider fails; one sealed account keeps that path without leaving personal accounts in place.
  • Consequences: Every named administrator re-onboards through calder-platform. The break-glass account's use is alerted on from the audit log and reviewed each time. Revisit (c) once Calder's identity provider has proven its own fallback.

What a design review will ask

  1. Show every pair of e-mail and origin that holds an administrator collection. Why is each there?
  2. What happens, step by step and by whom, on the day a platform administrator leaves?
  3. Who can change trust configurations, and is that list shorter than the list of administrators?
  4. Which production spaces have Space Developers, and what credentials can they read?
  5. Where will an auditor find a security change from eleven months ago?

Production concerns

  • Security and authorizations. Enforce multifactor authentication for platform users in SAP Cloud Identity Services or the corporate provider. Request the Add Me as Admin opt-out if global administrators shouldn't enter subaccounts by themselves. Keep critical security roles in SAP's administrator collections only, held by named people. Review assignments quarterly with the process owners for business roles, as roles and authorization design describes for the S/4HANA side.
  • Evaluation. Keep the model file in Git and run --check on each change. At each review, compare it with an export from btp list security/user and the role collection lists.
  • Cost. SAP Cloud Identity Services entitlements; the Audit Log premium edition only if you write your own records or need longer retention in SAP; the event management system that receives the exports.
  • Operations. Export audit logs on a schedule and alert on break-glass sign-ins and trust changes. Rotate binding secrets, and remove old instance secrets that can't be rotated. SAP notes that after its 30-minute session timeout an app's logoff no longer reaches the identity provider, whose session lives on; SAP recommends training users to sign out at the identity provider too.
  • Clean core. Nothing here changes S/4HANA. Keep app permissions in each app's own descriptor or policies, not in shared custom role collections that mix platform and business rights.

Where AI fits

AI changes four things here.

  • An agent is one more user. A user-facing agent should act as the signed-in business user, with the user's role collections and token, so the app's scopes stay the limit. A background agent uses its own client credentials and its own narrow role; never a person's or an administrator's. Agent permissions and SAP authorizations covers the patterns.
  • AI administrators act with full rights. SAP's MCP server for BTP administration operates with the full scope of the signed-in SAP user, its sign-in mode for custom identity providers takes the user's SAP Cloud Identity Services credentials from environment variables, and SAP warns that a trial registered under the same e-mail as productive accounts reaches all of them (Connect to the MCP Server for SAP BTP Administration). Register and approve it like any MCP server (Registering and approving MCP servers) and connect it with a viewer identity by default.
  • Joule follows the cockpit. SAP says using Joule in the cockpit is bound to the cockpit authorization, so the user's role collections are its limit too (Platform Users).
  • AI can help review. An assistant can draft group names, explain a role collection or summarize audit log exports. The decisions in the review, such as who keeps an administrator role, stay with named people.

Pitfalls

  • The day-one personal administrator. Set up before the company provider, never removed, out of reach of the leaver process.
  • Same e-mail, two origins. Treated as two users, reviewed as one.
  • Critical roles in custom collections. A support collection with User and Role Administrator can grant itself anything.
  • Space Developer in production "for a hotfix". It reads every binding's credentials and stays after the hotfix.
  • Hand-made shadow users with typos. They never log on, so nobody misses them, and they keep their rights.
  • Testing a role change in the same session. The old session still has the old rights.
  • Twelve-hour tokens by default. Nobody chose them, so nobody shortened them.
  • Relying on 90 days of audit logs. The question always comes later.

Exercise

Fix the draft's six errors and two warnings, onboard an application support analyst, and record the decision.

  1. Open unit21/calder_security.json in VS Code.

  2. S01. In global_account → assignments, delete the block for btp.admin1@calder-pumpworks.example with "origin": "sap.default" (and the comma before or after it, so the list stays valid). Keep the break-glass block.

  3. S11. In global_account, change "add_me_as_admin": "enabled" to "add_me_as_admin": "opted_out".

  4. S02. In subaccounts → "AI Prod" → app_trust → default_idp, set "status": "inactive" and "logon_link": false.

  5. S04. In custom_role_collections → "Calder App Support", replace "User and Role Administrator" with "Destination Viewer".

  6. S05. In "AI Prod" → spaces → agents → "Space Developer", delete "integration.dev@calder-pumpworks.example".

  7. S07. In "Ext Dev" → spaces → distributor-portal → "Space Developer", replace ext.developer with integration.dev@calder-pumpworks.example. In "Ext Prod" → assignments, delete the ext.developer block. Keep the person in people: the record of who left is useful.

  8. S08. In "Integration Prod" → assignments, change intgration.lead to integration.lead. Then delete the "intgration.lead@calder-pumpworks.example" entry from people.

  9. Onboard the support analyst. Add to people:

    "app.support@calder-pumpworks.example": {
      "person": "00100318", "job": "application support analyst", "team": "apps",
      "status": "active", "last_logon": "2026-11-26"
    }

    In "AI Prod" → assignments, add a group assignment:

    {"group": "BTP-APP-SUPPORT", "origin": "calder-ias", "role_collection": "Calder App Support"}

    In "AI Prod" → spaces → agents, add "Space Auditor": ["app.support@calder-pumpworks.example"].

  10. Run python unit21/security_check.py --check. It should end with 0 error(s), 0 warning(s).

  11. Run python unit21/security_check.py --leaver btp.admin1@calder-pumpworks.example. It should end with 0 assignment(s) still usable, 17 to delete in BTP.

  12. Run python unit21/security_check.py --who app.support@calder-pumpworks.example. It should show only Space Auditor in space agents; the role collection comes through the group.

  13. Try a mistake on purpose: in "Ext Prod" → assignments, add {"user": "app.support@calder-pumpworks.example", "origin": "calder-ias", "role_collection": "Distributor Order Status Admin"} and run --check. You should see WARN S06. Delete it again.

  14. Run --write, open unit21/calder_security.md, and fill in the Decision record in your own words. Add one line naming who approves membership of BTP-APP-SUPPORT.

  15. Commit the script, the model and the deliverable with Git.

Done when: --check reports 0 error(s), 0 warning(s) with exit code 0, --leaver btp.admin1@calder-pumpworks.example reports 0 assignment(s) still usable, and unit21/calder_security.md has a filled-in decision record. Keep the file: Unit 27's identity topics take these origins and groups into Calder's landscape-wide identity design, and the Architect capstone (Unit 32) collects it into Calder's target architecture.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1Why does the checker treat btp.admin1@calder-pumpworks.example with origin sap.default as a separate finding from the same e-mail with calder-platform?

Answer: D. SAP states that the concrete user is the combination of user name and identity provider. Calder's leaver process reaches only the calder-platform user, so the sap.default one stays usable.

2An app support team asks for a custom role collection that includes User and Role Administrator. Which rule fires, and why does it matter?

Answer: C. User and Role Administrator includes the scopes SAP marks as critical, such as managing authorizations, users and trust configurations. A group holding it can extend its own rights, so the checker allows it only for the platform team.

3In Cloud Foundry, why should only the platform team hold Space Developer in production spaces?

Answer: D. SAP's caution is that Space Developer has broad rights, including access to binding credentials and other sensitive data. The best practices guide recommends it in production only for platform team members authorized to see the data.

4Calder switches off automatic shadow user creation in a production subaccount but sets up no provisioning. What happens on Monday?

Answer: A. With automatic creation off, only users an administrator or a provisioning job created can sign in, and SAP warns that logons fail without a shadow user. Group mapping assigns rights to existing shadow users; it doesn't create them.

5A production app's xs-security.json has no token-validity, and the subaccount's setting was never changed. What does that mean, and what would you do?

Answer: D. SAP's default is 12 hours for access tokens and 7 days for refresh tokens. SAP advises keeping validity as short as possible but not under 30 minutes, which is why Calder's rule S09 asks for 1,800 to 3,600 seconds in production.

6The --leaver run for btp.admin1 reports 17 blocked assignments after the fix. Why does the checker still count them as work?

Answer: B. Disabling sign-in blocks use, but the shadow users and their role collections remain until someone deletes them. A re-enabled or recreated account with the same e-mail and origin would get them back.

7Calder's auditors want evidence of trust configuration changes from eleven months ago. Which design meets that?

Answer: B. SAP keeps its own audit records for 90 days by default, so records from eleven months ago are gone unless they were exported or longer retention was paid for in time. SAP recommends archiving audit logs and integrating them with the company's event management.

8A colleague wants to connect SAP's MCP server for BTP administration to an AI assistant, signed in with their usual Global Account Administrator user. What do you advise?

Answer: A. SAP says the MCP server operates with the full scope of the signed-in SAP user, and that a trial under the same e-mail reaches all accounts of that identity. A registered server with a narrow identity keeps an AI mistake from becoming an administrator's change.
NextCAP in depth for architects: models, services, events and the design reviewReview a CAP application as an architecture board would, from its model, services, events, database, plugins and runtime, and fix Calder's draft.

Sources

Sign in to track your progress

We'll email you a one-time sign-in link. No password needed.

or

Tell us a little about you

Optional, every field. It helps us pitch answers to your questions at the right level and decide which topics to write next. It is never shown publicly, and you can change or clear it anytime from the account menu.

SAP areas you work in