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.

Principal propagation end to end: carrying the user from a cloud app to S/4HANA

How a signed-in person's identity travels from a BTP app or agent through the Cloud Connector into S/4HANA, where each link is configured, and how it breaks.

Updated Dec 1, 2026
Foundational layer · 8 min read

The 60-second version

When a person uses a cloud app or an AI agent that reads S/4HANA, someone has to log on to S/4HANA. There are two ways. The app can log on with one shared account, a technical user, for everybody. Or it can pass along who the person is, so S/4HANA logs that person on and checks their own roles. The second way is principal propagation: the "principal" is the signed-in person, and "propagation" means carrying them through every hop.

At Calder Pumpworks, our fictional pump maker, a customer service clerk asks the order exceptions agent about a blocked order. The agent runs on SAP BTP. The order lives in S/4HANA in Calder's private network. With principal propagation, S/4HANA sees the clerk, not "the agent", and shows only what the clerk may see.

The chain has several links, owned by different teams: the identity service, the app, the BTP destination, the Cloud Connector in Calder's data center, and the S/4HANA system. Each link must trust the one before it. When one link is set up carelessly, the chain either fails for real users or, worse, works for the wrong ones.

Why it matters to the business

  • The right person sees the right data. S/4HANA already knows what each clerk, buyer and planner may do. Principal propagation reuses those roles. A technical user ignores them and sees whatever the technical user was given, usually far more.
  • The audit trail names people. With propagation, a change document says 00100265, the clerk. With a shared account, it says the account's name for everyone, and an auditor can't tell who did what.
  • Agents stay inside the user's rights. An agent acting for a clerk can do no more than the clerk. That is the single most useful control for AI in SAP, covered in agent permissions and SAP authorizations.
  • The cost is setup and care. Certificates, trust lists and mapping rules need owners and a renewal calendar. A missed renewal stops every user at once.

A concrete case: in Calder's order-to-cash process, the inside sales rep may display direct orders (channel 10) but not distributor orders (channel 20). Asked through the agent about Hallam's distributor order 1000002, the rep gets a refusal from S/4HANA itself. Through a shared technical user, the agent would have shown it.

How SAP does it

As of December 2026, SAP's BTP Connectivity documentation describes two routes (SAP):

  • Cloud to on-premise. For systems in your own network, including S/4HANA Cloud Private Edition reached over a private connection. A BTP destination of type PrincipalPropagation hands the user's token to the Connectivity service; the Cloud Connector, SAP's small agent in your data center, checks it and logs the person on to the back end with a short-lived certificate. This is the main subject of this topic.
  • Cloud to cloud. For SAP cloud systems on the internet, such as S/4HANA Cloud Public Edition or SuccessFactors, destinations exchange the user's token for one the target accepts (OAuth2SAMLBearerAssertion or OAuth2JWTBearer) (SAP).

For jobs that belong to no person, SAP offers a sibling: technical user propagation, where the Cloud Connector logs on a named technical identity instead of a person (SAP). Joule and SAP's agent services use the same ideas under the hood, as how Joule works explains.

Where the chain breaks: a field guide

What users report Where it usually broke Who fixes it
Everyone fails at once, from one morning The identity service rotated its signing key and the Cloud Connector's trust list wasn't refreshed; or a certificate expired Integration or Basis team
One person fails after a name or mailbox change The certificate carries the e-mail address and S/4HANA maps by e-mail Security team (mapping rule)
New joiners fail, existing staff work Someone keeps a hand-made table of certificate-to-user rows Security team
A nightly job works, but its log shows a strange user The connector's own certificate logs on when no person is present Integration team
A contractor who left can still read data The connector trusts an identity provider it shouldn't, and an old mapping row survives Security team, urgently
The person is refused, correctly Their S/4HANA role doesn't allow it Nobody: the control works

The last row matters. A refusal at the final step is S/4HANA doing its job. Test plans should include it on purpose.

Questions to ask

  1. For each app or agent that reads or changes SAP data: whose identity reaches S/4HANA, the person's or a shared account's?
  2. Which jobs genuinely have no person behind them, and what named technical identity do they use?
  3. Which attribute identifies the person in the certificate, and does it survive an e-mail or name change?
  4. How are certificates mapped to SAP users: by a rule, or by a hand-kept table?
  5. Which identity providers does the Cloud Connector trust, and who reviews that list?
  6. When do the Cloud Connector's certificates expire, and who gets the reminder 60 days before?
  7. How long may a certificate or an expired sign-in be reused, and why that long?

Common misconceptions

  • "Single sign-on to the app means S/4HANA knows the user." Signing in to a BTP app proves nothing to S/4HANA. Without propagation, the app reaches S/4HANA as whoever its destination is configured as.
  • "A technical user is simpler and just as safe if we filter in the app." The app's filter becomes your only control, and S/4HANA's roles, logs and segregation-of-duties checks stop applying.
  • "Once it works, it keeps working." Keys rotate, certificates expire, people rename mailboxes and leave. The chain needs an owner like any production system.
  • "Every refusal is a defect." A refusal at S/4HANA's authorization check usually means the design works.
  • "Principal propagation is only for on-premise systems." The cloud-to-cloud route carries the user to SAP cloud systems with token exchanges; the principle is the same.

Key terms

All course terms, A to Z, in the glossary

  • Principal: the identity on whose behalf a request runs, here the signed-in person.
  • Principal propagation: carrying that person's identity across systems, so the back end logs on and checks the same person; SAP also calls it user propagation.
  • Technical user: an account for a system or job, not a person.
  • Technical user propagation: SAP's way to log on a named technical identity through the Cloud Connector, for work that has no person behind it.
  • Cloud Connector: SAP software in your network that links BTP to internal systems and turns the cloud user into a back-end logon.
  • Short-lived certificate: a digital ID card the Cloud Connector issues for one user, valid for minutes, which S/4HANA accepts as a logon.
  • Certificate mapping: the S/4HANA rule that turns the name in a certificate into an SAP user ID.
  • Trust list: the identity providers whose tokens the Cloud Connector accepts.

Check yourself

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

1What does principal propagation change about a call from an agent to S/4HANA?

Answer: C. The point is that S/4HANA sees the real person, so its existing roles, logs and checks apply. A copied role or an app-side filter would rebuild that control somewhere weaker.

2Calder's inside sales rep asks the agent about a distributor order and S/4HANA refuses. How should the project team read this?

Answer: A. The rep may display only direct orders, so a refusal at S/4HANA's own check is the intended outcome. Test plans should include such refusals on purpose.

3Every user of an app suddenly fails one morning, though nothing was deployed. What is a likely cause to check first?

Answer: D. Failures that hit everyone at once point to shared links: a key the Cloud Connector no longer recognizes or an expired certificate. A role or mailbox change affects one person.

4A partner proposes mapping certificates to SAP users by e-mail address. What risk should a leader raise?

Answer: B. E-mail addresses change and SAP warns against attributes users can influence. A stable identifier such as the login name or global user ID keeps the mapping right through renames.

5Which job should run under technical user propagation rather than principal propagation?

Answer: A. Principal propagation needs a signed-in person. Work with nobody behind it should run as a named, narrow technical identity, not borrow the connector's own logon.

6What should a leader ask about the Cloud Connector's trust list?

Answer: C. The trust list decides whose tokens can become S/4HANA logons. Trusting an extra provider lets its users, such as an old contractor account, into the chain.
Deep layer · 40 min read

Mental model

Principal propagation is a relay of trust, re-signed at one border. In the cloud, the person is a signed token from the identity service. At Calder's network edge, the Cloud Connector checks that token and re-issues the same person as a short-lived X.509 certificate signed by a CA it holds. S/4HANA never sees the cloud token: it trusts the Cloud Connector as a reverse proxy, trusts the CA, and maps the certificate's subject to an SAP user. Then S/4HANA's normal authorization check runs.

So there are two trust domains, joined by one translator:

  • Cloud side: identity provider → BTP app → destination → Connectivity service. Currency: signed JSON Web Tokens (JWT).
  • Network side: Cloud Connector → ICM → user mapping → authorization check. Currency: X.509 certificates over mutual TLS.

Every failure lands on one of seven hops, and every hop has one owner. Debugging means finding the first hop that said no.

How it works

SAP's cloud-to-on-premise page describes the flow in five steps. This topic splits it into seven hops so each has one owner:

sequenceDiagram
  participant U as Clerk (browser)
  participant I as calder-ias
  participant A as Agent app (calder-ai-prod)
  participant C as Connectivity service
  participant S as Cloud Connector SCC-RK-P
  participant H as S4P (ICM, mapping, roles)
  U->>I: H1 sign in
  I-->>A: signed token
  A->>A: H2 exchange for user exchange token
  A->>C: H3 call via destination S4_ODATA
  C->>S: token through the tunnel
  S->>S: H4 verify issuer, key, expiry
  S->>S: H5 issue short-lived certificate
  S->>H: mTLS + SSL_CLIENT_CERT
  H->>H: H6 trust proxy, map certificate to user
  H->>H: H7 authorization check
  H-->>U: data or refusal

H1 and H2: the token and its exchange

The person signs in through SAP Cloud Identity Services, as set up in the identity services topic. The app holds a user token. To call the Connectivity service, it exchanges that token for a user exchange token with the OAuth JWT bearer grant and sends it in the Proxy-Authorization header, SAP's recommended option (SAP). SAP warns that an exchanged token may lose some fields. That matters at H5: if the attribute your subject pattern needs isn't in the token, no certificate is issued. Applications whose users carry Identity Authentication tokens, or tokens from a corporate identity provider, have their own documented header variants on the same page set.

H3: the destination

The destination names the route. For principal propagation to an internal HTTP system, SAP's destination page requires Type HTTP, Authentication PrincipalPropagation, ProxyType OnPremise and the virtual URL; CloudConnectorLocationId selects the connector when several serve one subaccount. Calder's S4_ODATA uses location RK and virtual host s4p-api:443, as in BTP connectivity. For RFC destinations, SAP's Java Connector (JCo) handles the token step, and the back-end hop needs SNC (below).

H4: the Cloud Connector's trust check

By default the Cloud Connector trusts no token issuer. An administrator synchronizes the subaccount's identity providers into the connector and marks the ones it trusts for principal propagation (Set Up Trust). Two consequences:

  • The list should hold only the providers that sign in people who may reach the back end. Trusting the SAP ID service as well lets anyone with an SAP ID account in that subaccount into the chain.
  • The connector checks signatures against keys it learned at the last synchronization. SAP recommends turning on Automatic Trust Synchronization when automatic signing key rotation is active. Otherwise the first token signed with a new key is rejected, for everybody.

The connector also checks expiry. Its Expiration Tolerance, 0 to 336 hours, lets an application keep using a principal after the cloud token has expired (Configure Subject Patterns). Any value above zero lets a stored token act after the person's session ended.

H5: the short-lived certificate

The connector's security token service issues an X.509 certificate for the user. Three settings decide it:

  • The CA certificate. Since Cloud Connector 2.7.0, the CA that signs short-lived certificates is separate from the system certificate; it can be a local CA (imported as PKCS#12, requested by CSR, or self-signed) or a Secure Login Server. SAP notes that only RSA CA certificates work at runtime and that the CA should carry the keyCertSign key usage (Configure a CA Certificate). Self-signed is described as useful for demos or a dedicated CA.
  • Subject pattern rules. An ordered list; each rule has a condition on token attributes and a subject (CN, EMAIL, O, OU, L, ST, C) built from variables such as ${login_name}, ${user_uuid}, ${email} or ${name}. The last rule has no condition and always matches. For business users, ${name} resolves to the first of user_name, email, mail, user_uuid, sub found in the token; for technical users, to client_id, cid, sub, azp. SAP's security note on the page: never use attributes the user can modify.
  • Validity. Certificate Validity (0 to 43,200 minutes) sets how long a generated certificate may be reused against the back end, for performance.

The access control mapping must allow it: from Cloud Connector 2.15, each HTTP mapping has Allow Principal Propagation and a Principal Type (X.509 Certificate), plus System Certificate for Logon. With the last switch on, the connector's own system certificate logs on when no principal arrives. SAP recommends keeping it off (Configure Access Control (HTTP)).

The connector can also propagate users with Kerberos (constrained delegation) instead of certificates; SAP lists it beside X.509 on the same configuration pages. This topic follows the certificate path, the one used for ABAP.

H6: S/4HANA logs the user on

For HTTPS, the TLS handshake uses the connector's system certificate; the user's certificate travels in the SSL_CLIENT_CERT header. S/4HANA must accept that header only from the connector (HTTPS page):

  1. STRUST, SSL server standard: import the issuer of the connector's system certificate.
  2. RZ10: icm/trusted_reverse_proxy_<x> = SUBJECT="<system certificate subject>", ISSUER="<its issuer>". Kernels below 7.53 need a blank after each comma. The HTTPS port's VCLIENT must be 1 or 2, not 0. Restart the ICM in SMICM and check the parameters there.
  3. Map certificates to users. From release 7.31, SAP recommends rule-based mapping: set login/certificate_mapping_rulebased to 1, generate a sample certificate in the connector, import it in CERTRULE and build a rule (SAP). Older systems use a table of rows in EXTID_DN, one per user.

SAP also notes that strict CRL checking can't be used in profile SSL_SERVER with this setup, and that an SAP Web Dispatcher in front of the system needs the same trust parameters.

For RFC, principal propagation needs SNC: an SNC0 entry for the connector's SNC name with the RFC and certificate entries activated, and an RFC SNC mapping in the connector (RFC page). The user mapping is the same.

H7: SAP's own check

Now the request runs as an ordinary SAP user. Authorization objects, organizational levels and logs apply exactly as in the authorization concept. This is the step that makes the rest worth it.

Jobs with no person

A batch job has no user token. With System Certificate for Logon on, the call would log on as whatever user the connector's system certificate maps to: one identity for every job, usually with broad roles. SAP's alternative is a destination of type OAuth2TechnicalUserPropagation: the Destination service fetches a client credentials token, the connector applies a subject pattern rule for ${user_type} Technical, and the back end maps it to a named technical user (SAP). SAP documents it for the Cloud Foundry environment only.

Build it yourself: trace Calder's chain hop by hop

You will review a partner's draft principal propagation design for Calder's calder-ai-prod subaccount and S4P against 12 rules, then replay eight requests through all seven hops and see where each one stops.

flowchart LR
  W[world.json<br/>people, users, requests] --> T[trace / replay:<br/>H1-H7]
  D[design_draft.json /<br/>design_reviewed.json] --> V[review:<br/>PP01-PP12]
  D --> T

Before you start: complete Set up your computer for this course and Set up for Unit 27. BTP connectivity set up Calder's Cloud Connectors and destinations; SAP Cloud Identity Services set up the identity tenant this chain starts from.

What you need

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

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):

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

      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/propagation_lab.py, paste the code below and save.

"""Calder's principal propagation lab: review a design and trace requests hop by hop.

A local model, not SAP. Destinations, Cloud Connector settings, ABAP parameters and
transactions are named as SAP documents them; the people, users, roles, certificates,
dates and rules PP01-PP12 are course labels. Built-in modules only, no randomness.

  python unit27/propagation_lab.py --init
  python unit27/propagation_lab.py review draft
  python unit27/propagation_lab.py trace R04 draft
  python unit27/propagation_lab.py replay draft
  python unit27/propagation_lab.py --selftest
"""
import json
import sys
import tempfile
from datetime import date, datetime, timedelta
from pathlib import Path

HERE = Path(__file__).resolve().parent / "propagation"
DOMAIN = "calder-pumpworks.example"
REVIEW_DAY = date(2026, 12, 1)
SCC_SUBJECT = "CN=rkscc01, OU=Rockford IT, O=Calder Pumpworks, C=US"
SCC_ISSUER = "CN=Calder Issuing CA 1, O=Calder Pumpworks, C=US"

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

def world():
    """People, SAP users, documents, identity providers and the requests to replay."""
    return {
        "as_of": "2026-12-01",
        # Who the identity providers know (calder-ias reads them from SF-EC)
        "people": {
            "00100265": {"email": f"cs.clerk@{DOMAIN}", "idp": "calder-ias"},
            "00100266": {"email": f"inside.sales@{DOMAIN}", "idp": "calder-ias",
                         "email_from": {"2026-12-03": f"inside.sales.us@{DOMAIN}"}},
            "00100211": {"email": f"buyer@{DOMAIN}", "idp": "calder-ias"},
            # A contract developer's old SAP ID service account (left 2026-10-30)
            "ext.developer": {"email": f"ext.developer@{DOMAIN}", "idp": "sap.default"},
        },
        # Signing keys: calder-ias rotates its key on 2026-12-04 at 06:00
        "idp_keys": {"calder-ias": [["2026-06-01T00:00", "k-2026-06"],
                                    ["2026-12-04T06:00", "k-2026-12"]],
                     "sap.default": [["2026-01-01T00:00", "sapid-2026"]]},
        # SAP users in S4P: what each may display (course roles)
        "s4p_users": {
            "00100265": {"locked": False, "orders": ["10", "20", "30"], "po_orgs": []},
            "00100266": {"locked": False, "orders": ["10"], "po_orgs": []},
            "00100211": {"locked": False, "orders": [], "po_orgs": ["PUUS"]},
            "TU_ORDER_EXC_JOB": {"locked": False, "orders": ["10", "20", "30"], "po_orgs": [],
                                 "read_only": True},
            "TU_SCC_RKP": {"locked": False, "orders": ["10", "20", "30"], "po_orgs": ["PUUS", "PUDE"],
                           "note": "broad integration role Z_INTEGRATION_ALL"},
            "EXT_DEV01": {"locked": False, "orders": ["10", "20", "30"], "po_orgs": ["PUUS"]},
        },
        "documents": {"1000002": {"kind": "sales order", "channel": "20"},
                      "1000003": {"kind": "sales order", "channel": "10"},
                      "4500000002": {"kind": "purchase order", "org": "PUUS"}},
        # Each request: who, when, which destination, what, and what should happen
        "requests": [
            {"id": "R01", "at": "2026-12-01T09:05", "who": "00100265", "doc": "1000002",
             "app": "AGT_ORDER_EXC", "dest": "S4_ODATA", "expect": "ALLOWED as 00100265"},
            {"id": "R02", "at": "2026-12-01T09:10", "who": "00100266", "doc": "1000002",
             "app": "AGT_ORDER_EXC", "dest": "S4_ODATA", "expect": "REFUSED at H7"},
            {"id": "R03", "at": "2026-12-01T10:30", "who": "00100211", "doc": "4500000002",
             "app": "AGT_SUPPLY_WATCH", "dest": "S4_ODATA", "expect": "ALLOWED as 00100211"},
            {"id": "R04", "at": "2026-12-03T09:00", "who": "00100266", "doc": "1000003",
             "app": "AGT_ORDER_EXC", "dest": "S4_ODATA", "expect": "ALLOWED as 00100266"},
            {"id": "R05", "at": "2026-12-03T02:00", "who": None, "doc": "1000002",
             "app": "AGT_ORDER_EXC nightly summary", "dest": "job",
             "expect": "ALLOWED as TU_ORDER_EXC_JOB"},
            {"id": "R06", "at": "2026-12-03T14:00", "who": "00100265", "doc": "1000003",
             "app": "AGT_ORDER_EXC resumed run", "dest": "S4_ODATA",
             "token_issued": "2026-12-03T09:00", "expect": "REFUSED at H4"},
            {"id": "R07", "at": "2026-12-03T15:00", "who": "ext.developer", "doc": "1000002",
             "app": "AGT_ORDER_EXC", "dest": "S4_ODATA", "expect": "REFUSED at H4"},
            {"id": "R08", "at": "2026-12-04T09:00", "who": "00100265", "doc": "1000002",
             "app": "AGT_ORDER_EXC", "dest": "S4_ODATA", "expect": "ALLOWED as 00100265"},
        ],
    }


def design(kind):
    """The partner's draft or the reviewed design for calder-ai-prod to S4P."""
    reviewed = kind == "reviewed"
    d = {
        "name": kind,
        "subaccount": "calder-ai-prod",
        "token_minutes": 60,
        "destinations": {
            "S4_ODATA": {"Type": "HTTP", "ProxyType": "OnPremise",
                         "Authentication": "PrincipalPropagation",
                         "URL": "http://s4p-api:443", "CloudConnectorLocationId": "RK",
                         "callers": ["people"] if reviewed else ["people", "job"]},
        },
        "connector": {
            "id": "SCC-RK-P", "location_id": "RK",
            "system_certificate": {"subject": SCC_SUBJECT, "issuer": SCC_ISSUER},
            "trusted_idps": ["calder-ias"] if reviewed else ["calder-ias", "sap.default"],
            "automatic_trust_sync": reviewed,
            "last_sync": "2026-11-20T08:00",
            "ca": ({"alias": "CT05", "subject": "CN=rkscc01 PP CA, O=Calder Pumpworks, C=US",
                    "key": "RSA", "keyCertSign": True, "self_signed": False,
                    "valid_to": "2028-03-01"} if reviewed else
                   {"alias": "rkscc01 demo CA", "subject": "CN=rkscc01 demo CA",
                    "key": "RSA", "keyCertSign": True, "self_signed": True,
                    "valid_to": "2026-12-31"}),
            # Ordered rules; the last one has no condition (SAP's default rule)
            "subject_patterns": ([
                {"condition": ["user_type", "is", "Technical"], "CN": "${name}"},
                {"condition": None, "CN": "${login_name}", "O": "Calder Pumpworks"},
            ] if reviewed else [
                {"condition": None, "CN": "${email}"},
            ]),
            "certificate_validity_min": 10 if reviewed else 43200,
            "expiration_tolerance_h": 0 if reviewed else 336,
            "mappings": [{"virtual": "s4p-api:443", "internal": "s4p-app.calder.internal:44300",
                          "protocol": "HTTPS", "allow_principal_propagation": True,
                          "principal_type": "X.509 Certificate",
                          "system_certificate_for_logon": not reviewed}],
            "owner": "00100316",
        },
        "abap": {
            "system": "S4P",
            "icm/trusted_reverse_proxy_0": {"SUBJECT": SCC_SUBJECT, "ISSUER": SCC_ISSUER},
            "VCLIENT": 1,
            "strust_ssl_server_standard": [SCC_ISSUER],
            "login/certificate_mapping_rulebased": 1 if reviewed else 0,
            # CERTRULE: take the CN as the SAP user ID (course: login name = personnel number)
            "certrule": ([{"issuer": "CN=rkscc01 PP CA, O=Calder Pumpworks, C=US",
                           "take": "CN", "as": "user ID"}] if reviewed else []),
            # EXTID_DN: one hand-kept row per person (the draft's way)
            "extid_dn": ({} if reviewed else {
                f"CN=cs.clerk@{DOMAIN}": "00100265",
                f"CN=inside.sales@{DOMAIN}": "00100266",
                f"CN=credit.analyst@{DOMAIN}": "00100304",
                f"CN=ext.developer@{DOMAIN}": "EXT_DEV01",
            }),
            "system_certificate_user": "TU_SCC_RKP",
            "mapping_owner": "00100331" if reviewed else None,
        },
    }
    if reviewed:
        d["destinations"]["S4_ODATA_JOB"] = {
            "Type": "HTTP", "ProxyType": "OnPremise",
            "Authentication": "OAuth2TechnicalUserPropagation", "URL": "http://s4p-api:443",
            "CloudConnectorLocationId": "RK", "client_id": "TU_ORDER_EXC_JOB",
            "callers": ["job"]}
    return d


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

def write_json(path, data):
    path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")


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


def init(folder):
    if folder.exists():
        sys.exit(f"{folder} already exists; delete the folder first to start over")
    folder.mkdir(parents=True)
    write_json(folder / "world.json", world())
    write_json(folder / "design_draft.json", design("draft"))
    write_json(folder / "design_reviewed.json", design("reviewed"))
    print(f"Wrote {folder}: world.json, design_draft.json, design_reviewed.json")


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

def review(d):
    """Rules PP01-PP12. Returns (rule, verdict, text) lines."""
    out = []
    add = lambda r, ok, text, warn=False: out.append((r, "OK" if ok else ("WARN" if warn else "FAIL"), text))
    con, abap = d["connector"], d["abap"]

    for name, dest in d["destinations"].items():
        want = {"people": "PrincipalPropagation", "job": "OAuth2TechnicalUserPropagation"}
        for c in dest["callers"]:
            add("PP01", dest["Authentication"] == want[c],
                f"{name} serves {c}: {dest['Authentication']} (want {want[c]})")
        add("PP01", dest["CloudConnectorLocationId"] == con["location_id"]
            and dest["ProxyType"] == "OnPremise",
            f"{name} reaches {con['id']} by location ID {dest['CloudConnectorLocationId']}")

    extra = [i for i in con["trusted_idps"] if i != "calder-ias"]
    add("PP02", not extra, "Cloud Connector trusts only calder-ias"
        if not extra else f"Cloud Connector also trusts {', '.join(extra)}")
    add("PP03", con["automatic_trust_sync"], "automatic trust synchronization "
        + ("on" if con["automatic_trust_sync"] else f"off, last sync {con['last_sync']}"))

    ca = con["ca"]
    good = ca["key"] == "RSA" and ca["keyCertSign"] and ca["subject"] != con["system_certificate"]["subject"]
    add("PP04", good and not ca["self_signed"], f"CA {ca['alias']}: {ca['key']}, keyCertSign "
        f"{ca['keyCertSign']}, {'self-signed' if ca['self_signed'] else 'issued by Calder PKI'}",
        warn=good)
    days = (date.fromisoformat(ca["valid_to"]) - REVIEW_DAY).days
    add("PP05", days > 60, f"CA {ca['alias']} valid to {ca['valid_to']} ({days} days)")

    for rule in con["subject_patterns"]:
        cn = rule["CN"]
        stable = cn in ("${login_name}", "${user_uuid}") or (
            rule["condition"] and rule["condition"][2] == "Technical")
        add("PP06", stable, f"subject CN={cn}" + ("" if stable else
            ": e-mail changes and can be edited, so the mapping breaks or can be spoofed"))

    v, t = con["certificate_validity_min"], con["expiration_tolerance_h"]
    add("PP07", v <= 60 and t <= 1, f"certificate validity {v} min, expiration tolerance {t} h")

    for m in con["mappings"]:
        ok = m["allow_principal_propagation"] and m["principal_type"] == "X.509 Certificate"
        add("PP08", ok and not m["system_certificate_for_logon"],
            f"mapping {m['virtual']}: principal type {m['principal_type']}, "
            f"System Certificate for Logon {'on' if m['system_certificate_for_logon'] else 'off'}")

    p = abap["icm/trusted_reverse_proxy_0"]
    sc = con["system_certificate"]
    add("PP09", p["SUBJECT"] == sc["subject"] and p["ISSUER"] == sc["issuer"] and abap["VCLIENT"] in (1, 2),
        f"icm/trusted_reverse_proxy_0 matches {con['id']}'s system certificate, VCLIENT={abap['VCLIENT']}")
    add("PP10", sc["issuer"] in abap["strust_ssl_server_standard"],
        "STRUST SSL server standard trusts the system certificate's issuer")
    rb = abap["login/certificate_mapping_rulebased"] == 1 and abap["certrule"]
    add("PP11", rb and not abap["extid_dn"],
        "rule-based mapping with a CERTRULE rule" if rb else
        f"EXTID_DN table with {len(abap['extid_dn'])} hand-kept rows")
    add("PP12", bool(con["owner"]) and bool(abap["mapping_owner"]),
        f"owners: connector {con['owner']}, back-end mapping {abap['mapping_owner'] or 'none'}",
        warn=bool(con["owner"]))
    return out


def print_review(d):
    lines = review(d)
    for rule, verdict, text in lines:
        print(f"  {rule}  {verdict:<4}  {text}")
    counts = {k: sum(1 for x in lines if x[1] == k) for k in ("OK", "WARN", "FAIL")}
    print(f"{d['name']}: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL")
    return counts


# ---------------------------------------------------------------- the chain

def key_at(w, idp, when):
    """The identity provider's signing key valid at a moment."""
    current = None
    for start, kid in w["idp_keys"][idp]:
        if datetime.fromisoformat(start) <= when:
            current = kid
    return current


def synced_keys(w, con, when):
    """Keys the Cloud Connector knows: all keys up to the last sync, or now if automatic."""
    upto = when if con["automatic_trust_sync"] else datetime.fromisoformat(con["last_sync"])
    return {kid for idp in con["trusted_idps"] for start, kid in w["idp_keys"].get(idp, [])
            if datetime.fromisoformat(start) <= upto}


def email_on(person, day):
    email = person["email"]
    for start, new in sorted(person.get("email_from", {}).items()):
        if day >= start:
            email = new
    return email


def trace(w, d, req):
    """Follow one request through hops H1-H7. Returns (hops, result)."""
    hops = []
    at = datetime.fromisoformat(req["at"])
    con, abap = d["connector"], d["abap"]

    def stop(hop, text):
        hops.append((hop, "FAIL", text))
        return hops, f"REFUSED at {hop}"

    # H1 sign-in: an identity provider issues a token (or a client gets one for a job)
    if req["who"]:
        person = w["people"][req["who"]]
        issued = datetime.fromisoformat(req.get("token_issued", req["at"]))
        claims = {"user_type": "Business", "login_name": req["who"] if person["idp"] == "calder-ias" else None,
                  "email": email_on(person, req["at"][:10]), "iss": person["idp"],
                  "kid": key_at(w, person["idp"], issued),
                  "exp": issued + timedelta(minutes=d["token_minutes"])}
        hops.append(("H1", "OK", f"{claims['iss']} signed a token for {claims['login_name'] or claims['email']}"
                     f" with key {claims['kid']}, valid to {claims['exp']:%H:%M}"))
        hops.append(("H2", "OK", f"{req['app']} exchanged it for a user exchange token"))
        dest = d["destinations"][req["dest"]]
        dname = req["dest"]
    else:
        # A job with no person: which destination does the design give it?
        dname, dest = next((n, x) for n, x in d["destinations"].items() if "job" in x["callers"])
        if dest["Authentication"] == "OAuth2TechnicalUserPropagation":
            claims = {"user_type": "Technical", "name": dest["client_id"], "iss": "calder-ias",
                      "kid": key_at(w, "calder-ias", at), "exp": at + timedelta(minutes=60)}
            hops.append(("H1", "OK", f"client {dest['client_id']} got a token by client credentials"))
            hops.append(("H2", "OK", "no exchange: technical user token"))
        else:
            claims = None
            hops.append(("H1", "OK", "no person signed in: the job has no user token"))
            hops.append(("H2", "OK", "nothing to exchange"))

    # H3 destination and Connectivity service
    hops.append(("H3", "OK", f"{dname}: {dest['Authentication']}, location {dest['CloudConnectorLocationId']}"))
    if dest["CloudConnectorLocationId"] != con["location_id"]:
        return stop("H3", f"no Cloud Connector with location ID {dest['CloudConnectorLocationId']}")

    mapping = con["mappings"][0]
    if claims is None:
        # H4/H5: no principal. The mapping decides whether the system certificate logs on.
        if mapping["system_certificate_for_logon"]:
            hops.append(("H4", "OK", "no principal to verify"))
            hops.append(("H5", "WARN", "System Certificate for Logon: the connector logs on as itself"))
            sap_user = abap["system_certificate_user"]
            hops.append(("H6", "WARN", f"ICM maps {con['id']}'s system certificate to {sap_user}"))
        else:
            hops.append(("H4", "OK", "no principal to verify"))
            return stop("H5", "no principal and System Certificate for Logon is off: 401")
    else:
        # H4 Cloud Connector trust
        if claims["iss"] not in con["trusted_idps"]:
            return stop("H4", f"issuer {claims['iss']} is not trusted for principal propagation")
        if claims["kid"] not in synced_keys(w, con, at):
            return stop("H4", f"signature key {claims['kid']} unknown: trust last synchronized "
                        f"{con['last_sync']}, automatic synchronization off")
        late = at - claims["exp"]
        if late > timedelta(hours=con["expiration_tolerance_h"]):
            return stop("H4", f"token expired {claims['exp']:%H:%M}, "
                        f"{late.seconds // 3600} h ago; tolerance {con['expiration_tolerance_h']} h")
        note = "" if late <= timedelta(0) else f" (expired {late.seconds // 3600} h ago, within tolerance)"
        hops.append(("H4", "OK" if not note else "WARN",
                     f"issuer {claims['iss']} trusted, key {claims['kid']} known{note}"))

        # H5 short-lived certificate from the first matching subject pattern rule
        rule = next(r for r in con["subject_patterns"]
                    if r["condition"] is None or claims.get(r["condition"][0]) == r["condition"][2])
        var = rule["CN"][2:-1]
        value = claims.get(var)
        if not value:
            return stop("H5", f"subject pattern needs ${{{var}}}, not in the token")
        cn = f"CN={value}"
        if not (mapping["allow_principal_propagation"] and mapping["principal_type"] == "X.509 Certificate"):
            return stop("H5", f"mapping {mapping['virtual']} doesn't allow principal propagation")
        hops.append(("H5", "OK", f"{con['ca']['alias']} issued {cn}, valid "
                     f"{con['certificate_validity_min']} min, sent in SSL_CLIENT_CERT"))

        # H6 back-end logon: ICM trust, then certificate-to-user mapping
        p = abap["icm/trusted_reverse_proxy_0"]
        sc = con["system_certificate"]
        if p["SUBJECT"] != sc["subject"] or p["ISSUER"] != sc["issuer"]:
            return stop("H6", "ICM doesn't trust the connector as reverse proxy: SSL_CLIENT_CERT ignored")
        if abap["login/certificate_mapping_rulebased"] == 1 and abap["certrule"]:
            sap_user = value
            how = "CERTRULE takes the CN as user ID"
        else:
            sap_user = abap["extid_dn"].get(cn)
            if not sap_user:
                near = [k for k in abap["extid_dn"] if k.split("@")[0] == cn.split("@")[0].replace(".us", "")]
                hint = f"; the table still has {near[0]}" if near else ""
                return stop("H6", f"no EXTID_DN row for {cn}{hint}")
            how = "EXTID_DN row"
        user = w["s4p_users"].get(sap_user)
        if not user or user["locked"]:
            return stop("H6", f"SAP user {sap_user} doesn't exist or is locked")
        hops.append(("H6", "OK", f"{how}: logged on as {sap_user}"))

    # H7 SAP's own authorization check
    user = w["s4p_users"][sap_user]
    doc = w["documents"][req["doc"]]
    if doc["kind"] == "sales order":
        allowed, what = doc["channel"] in user["orders"], f"channel {doc['channel']}"
    else:
        allowed, what = doc["org"] in user["po_orgs"], f"purchasing org {doc['org']}"
    if not allowed:
        return stop("H7", f"{sap_user} may not display {doc['kind']}s in {what}")
    hops.append(("H7", "OK", f"{sap_user} may display {doc['kind']} {req['doc']} ({what})"))
    return hops, f"ALLOWED as {sap_user}"


def print_trace(w, d, rid):
    req = next((r for r in w["requests"] if r["id"] == rid), None)
    if not req:
        sys.exit(f"No request {rid}; use R01 to R{len(w['requests']):02d}")
    who = req["who"] or "no user"
    print(f"{rid}  {req['at'].replace('T', ' ')}  {who} reads {req['doc']} via {req['app']}  ({d['name']})")
    hops, result = trace(w, d, req)
    names = {"H1": "sign-in", "H2": "exchange", "H3": "destination", "H4": "trust",
             "H5": "certificate", "H6": "logon", "H7": "authorization"}
    for hop, verdict, text in hops:
        print(f"  {hop} {names[hop]:<13} {verdict:<4}  {text}")
    mark = "as expected" if result == req["expect"] else f"expected {req['expect']}"
    print(f"  result: {result}  ({mark})")
    return result


def replay(w, d):
    print(f"{'Request':<8}{'When':<18}{'Who':<15}{'Result':<30}Expected")
    good = 0
    for req in w["requests"]:
        _, result = trace(w, d, req)
        ok = result == req["expect"]
        good += ok
        print(f"{req['id']:<8}{req['at'].replace('T', ' '):<18}{(req['who'] or 'job'):<15}"
              f"{result:<30}{'yes' if ok else 'NO: ' + req['expect']}")
    print(f"{d['name']}: {good} of {len(w['requests'])} requests as expected (synthetic data)")
    return good


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

def selftest():
    with tempfile.TemporaryDirectory() as tmp:
        folder = Path(tmp) / "propagation"
        init(folder)
        w = read_json(folder / "world.json")
        draft = read_json(folder / "design_draft.json")
        rev = read_json(folder / "design_reviewed.json")
        def count(d):
            lines = review(d)
            return tuple(sum(1 for x in lines if x[1] == k) for k in ("OK", "WARN", "FAIL"))
        assert count(draft) == (4, 2, 8), count(draft)
        assert count(rev) == (16, 0, 0), count(rev)
        results = {r["id"]: trace(w, draft, r)[1] for r in w["requests"]}
        assert results["R04"] == "REFUSED at H6" and results["R08"] == "REFUSED at H4", results
        assert results["R05"] == "ALLOWED as TU_SCC_RKP" and results["R07"] == "ALLOWED as EXT_DEV01"
        assert sum(trace(w, draft, r)[1] == r["expect"] for r in w["requests"]) == 2
        assert all(trace(w, rev, r)[1] == r["expect"] for r in w["requests"])
    print("Self-test passed: 12 rules and 8 request traces behave as planted (synthetic data)")


def main(argv):
    if argv[:1] == ["--init"]:
        return init(HERE)
    if argv[:1] == ["--selftest"]:
        return selftest()
    if len(argv) >= 2 and argv[0] in ("review", "replay", "trace"):
        kind = argv[-1]
        if kind not in ("draft", "reviewed"):
            sys.exit("Name a design: draft or reviewed")
        d = read_json(HERE / f"design_{kind}.json")
        w = read_json(HERE / "world.json")
        if argv[0] == "review":
            counts = print_review(d)
            sys.exit(2 if counts["FAIL"] else 0)
        if argv[0] == "replay":
            return replay(w, d)
        if len(argv) == 3:
            return print_trace(w, d, argv[1].upper())
    print(__doc__)


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

Step 3: Write the sample and review the draft

  1. Write the three sample files:

    python unit27/propagation_lab.py --init
    Wrote .../unit27/propagation: world.json, design_draft.json, design_reviewed.json
  2. Review the partner's draft:

    python unit27/propagation_lab.py review draft
      PP01  OK    S4_ODATA serves people: PrincipalPropagation (want PrincipalPropagation)
      PP01  FAIL  S4_ODATA serves job: PrincipalPropagation (want OAuth2TechnicalUserPropagation)
      PP01  OK    S4_ODATA reaches SCC-RK-P by location ID RK
      PP02  FAIL  Cloud Connector also trusts sap.default
      PP03  FAIL  automatic trust synchronization off, last sync 2026-11-20T08:00
      PP04  WARN  CA rkscc01 demo CA: RSA, keyCertSign True, self-signed
      PP05  FAIL  CA rkscc01 demo CA valid to 2026-12-31 (30 days)
      PP06  FAIL  subject CN=${email}: e-mail changes and can be edited, so the mapping breaks or can be spoofed
      PP07  FAIL  certificate validity 43200 min, expiration tolerance 336 h
      PP08  FAIL  mapping s4p-api:443: principal type X.509 Certificate, System Certificate for Logon on
      PP09  OK    icm/trusted_reverse_proxy_0 matches SCC-RK-P's system certificate, VCLIENT=1
      PP10  OK    STRUST SSL server standard trusts the system certificate's issuer
      PP11  FAIL  EXTID_DN table with 4 hand-kept rows
      PP12  WARN  owners: connector 00100316, back-end mapping none
    draft: 4 OK, 2 WARN, 8 FAIL

    The script ends with exit code 2 while any rule fails, so a pipeline could stop on it.

  3. Review the reviewed design. It ends with reviewed: 16 OK, 0 WARN, 0 FAIL.

The draft is typical of a proof of concept that went live: it works for the people who tested it, with settings chosen to stop errors rather than to control access.

Rule What it checks Source
PP01 Destinations for people use PrincipalPropagation, jobs use OAuth2TechnicalUserPropagation; location ID matches a connector SAP's two propagation types; course rule on which serves which
PP02 The connector trusts only Calder's identity tenant Course rule, after SAP's trust page
PP03 Automatic Trust Synchronization on SAP's advice with automatic key rotation
PP04 CA is RSA, has keyCertSign, isn't the system certificate; self-signed warns SAP's CA page
PP05 CA certificate valid more than 60 days ahead Course rule
PP06 Subject from a stable attribute (${login_name}, ${user_uuid}, or the client for technical users) SAP's security note; course rule on which attributes
PP07 Certificate Validity at most 60 minutes, Expiration Tolerance at most 1 hour Course rule within SAP's ranges
PP08 Mapping allows X.509 principals; System Certificate for Logon off SAP's access control page
PP09 icm/trusted_reverse_proxy_<x> matches the system certificate; VCLIENT 1 or 2 SAP's HTTPS page
PP10 STRUST trusts the system certificate's issuer SAP's HTTPS page
PP11 Rule-based mapping with a CERTRULE rule, no EXTID_DN rows for people SAP recommends rule-based from 7.31; course rule against tables
PP12 Named owners for the connector and the back-end mapping Course rule

Step 4: Replay the requests through the draft

  1. Replay all eight requests:

    python unit27/propagation_lab.py replay draft
    Request When              Who            Result                        Expected
    R01     2026-12-01 09:05  00100265       ALLOWED as 00100265           yes
    R02     2026-12-01 09:10  00100266       REFUSED at H7                 yes
    R03     2026-12-01 10:30  00100211       REFUSED at H6                 NO: ALLOWED as 00100211
    R04     2026-12-03 09:00  00100266       REFUSED at H6                 NO: ALLOWED as 00100266
    R05     2026-12-03 02:00  job            ALLOWED as TU_SCC_RKP         NO: ALLOWED as TU_ORDER_EXC_JOB
    R06     2026-12-03 14:00  00100265       ALLOWED as 00100265           NO: REFUSED at H4
    R07     2026-12-03 15:00  ext.developer  ALLOWED as EXT_DEV01          NO: REFUSED at H4
    R08     2026-12-04 09:00  00100265       REFUSED at H4                 NO: ALLOWED as 00100265
    draft: 2 of 8 requests as expected (synthetic data)
  2. Trace the renamed mailbox. On Thursday 3 December, 00100266's mailbox becomes inside.sales.us@, as in the identity services lab:

    python unit27/propagation_lab.py trace R04 draft
    R04  2026-12-03 09:00  00100266 reads 1000003 via AGT_ORDER_EXC  (draft)
      H1 sign-in       OK    calder-ias signed a token for 00100266 with key k-2026-06, valid to 10:00
      H2 exchange      OK    AGT_ORDER_EXC exchanged it for a user exchange token
      H3 destination   OK    S4_ODATA: PrincipalPropagation, location RK
      H4 trust         OK    issuer calder-ias trusted, key k-2026-06 known
      H5 certificate   OK    rkscc01 demo CA issued CN=inside.sales.us@calder-pumpworks.example, valid 43200 min, sent in SSL_CLIENT_CERT
      H6 logon         FAIL  no EXTID_DN row for CN=inside.sales.us@calder-pumpworks.example; the table still has CN=inside.sales@calder-pumpworks.example
      result: REFUSED at H6  (expected ALLOWED as 00100266)

    Every cloud hop is green. The break is in a table in S4P that nobody updated. R03 fails the same way for the buyer, who joined the agent pilot after the table was typed.

  3. Trace the nightly job:

    python unit27/propagation_lab.py trace R05 draft
    R05  2026-12-03 02:00  no user reads 1000002 via AGT_ORDER_EXC nightly summary  (draft)
      H1 sign-in       OK    no person signed in: the job has no user token
      H2 exchange      OK    nothing to exchange
      H3 destination   OK    S4_ODATA: PrincipalPropagation, location RK
      H4 trust         OK    no principal to verify
      H5 certificate   WARN  System Certificate for Logon: the connector logs on as itself
      H6 logon         WARN  ICM maps SCC-RK-P's system certificate to TU_SCC_RKP
      H7 authorization OK    TU_SCC_RKP may display sales order 1000002 (channel 20)
      result: ALLOWED as TU_SCC_RKP  (expected ALLOWED as TU_ORDER_EXC_JOB)

    The job "works", as TU_SCC_RKP with a broad integration role. Any app on the subaccount that calls S4_ODATA without a user gets the same access.

  4. Trace the key rotation. calder-ias rotates its signing key at 06:00 on Friday 4 December:

    python unit27/propagation_lab.py trace R08 draft
    R08  2026-12-04 09:00  00100265 reads 1000002 via AGT_ORDER_EXC  (draft)
      H1 sign-in       OK    calder-ias signed a token for 00100265 with key k-2026-12, valid to 10:00
      H2 exchange      OK    AGT_ORDER_EXC exchanged it for a user exchange token
      H3 destination   OK    S4_ODATA: PrincipalPropagation, location RK
      H4 trust         FAIL  signature key k-2026-12 unknown: trust last synchronized 2026-11-20T08:00, automatic synchronization off
      result: REFUSED at H4  (expected ALLOWED as 00100265)

    This one stops everybody. R06 and R07 show the opposite risk: a token four hours expired still works because of the 336-hour tolerance, and a contractor's old SAP ID service account reaches S4P through a trust entry and a mapping row nobody removed.

Step 5: Replay the same requests through the reviewed design

  1. Replay:

    python unit27/propagation_lab.py replay reviewed
    Request When              Who            Result                        Expected
    R01     2026-12-01 09:05  00100265       ALLOWED as 00100265           yes
    R02     2026-12-01 09:10  00100266       REFUSED at H7                 yes
    R03     2026-12-01 10:30  00100211       ALLOWED as 00100211           yes
    R04     2026-12-03 09:00  00100266       ALLOWED as 00100266           yes
    R05     2026-12-03 02:00  job            ALLOWED as TU_ORDER_EXC_JOB   yes
    R06     2026-12-03 14:00  00100265       REFUSED at H4                 yes
    R07     2026-12-03 15:00  ext.developer  REFUSED at H4                 yes
    R08     2026-12-04 09:00  00100265       ALLOWED as 00100265           yes
    reviewed: 8 of 8 requests as expected (synthetic data)
  2. See how the reviewed design runs the nightly job:

    python unit27/propagation_lab.py trace R05 reviewed
    R05  2026-12-03 02:00  no user reads 1000002 via AGT_ORDER_EXC nightly summary  (reviewed)
      H1 sign-in       OK    client TU_ORDER_EXC_JOB got a token by client credentials
      H2 exchange      OK    no exchange: technical user token
      H3 destination   OK    S4_ODATA_JOB: OAuth2TechnicalUserPropagation, location RK
      H4 trust         OK    issuer calder-ias trusted, key k-2026-06 known
      H5 certificate   OK    CT05 issued CN=TU_ORDER_EXC_JOB, valid 10 min, sent in SSL_CLIENT_CERT
      H6 logon         OK    CERTRULE takes the CN as user ID: logged on as TU_ORDER_EXC_JOB
      H7 authorization OK    TU_ORDER_EXC_JOB may display sales order 1000002 (channel 20)
      result: ALLOWED as TU_ORDER_EXC_JOB  (as expected)

What changed: the subject is ${login_name}, which at Calder is the personnel number and the S4P user ID, so one CERTRULE rule maps everyone, joiners included, and a mailbox rename changes nothing. The CA is CT05, Calder's principal propagation CA from the integration security register, valid to 2028. The connector trusts only calder-ias and synchronizes automatically. Certificates live ten minutes; expired tokens are refused. The job has its own destination and a read-only identity.

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

  1. Run the self-test:

    python unit27/propagation_lab.py --selftest
    Wrote .../propagation: world.json, design_draft.json, design_reviewed.json
    Self-test passed: 12 rules and 8 request traces behave as planted (synthetic data)
  2. Save your work with Git:

    git add unit27/propagation_lab.py unit27/propagation
    git commit -m "Unit 27: principal propagation lab"

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

How the code works

Part What it does
world() People and their identity providers, the calder-ias key rotation, S4P users with what they may display, three documents, and requests R01 to R08 with the expected outcome
design() The reviewed design and the draft: destinations, the connector's trust list, CA, subject pattern rules, validity, mapping switches, and the S4P side (ICM parameter, STRUST, rule-based mapping or EXTID_DN rows)
review() Applies PP01 to PP12 and returns OK, WARN or FAIL lines
trace() Follows one request through H1 to H7 and stops at the first hop that refuses; a job without a person takes the design's job destination
synced_keys() The signing keys the connector knows: up to its last manual synchronization, or up to now when synchronization is automatic
replay() Traces every request and compares with the expected result
selftest() Runs everything in a temporary folder and asserts the planted counts

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/propagation_lab.py --init
already exists; delete the folder first --init won't overwrite your work Delete unit27/propagation 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
No request R10 The request ID doesn't exist Use R01 to R08 (or R09 after the exercise)
KeyError after editing world.json A request names a person, user or document that isn't defined Add it under people, s4p_users or documents
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

The real configuration is spread over four places. As documented on 1 December 2026:

Place Who What to set SAP page
BTP subaccount Platform team Trust to SAP Cloud Identity Services; destinations PrincipalPropagation (people) and OAuth2TechnicalUserPropagation (jobs) with the location ID Principal Propagation
Application Developers Exchange the user token and send it to the Connectivity service; SAP's XSUAA token client library implements the exchange, and JCo does it for RFC User exchange token
Cloud Connector Integration or Basis team Cloud To On-Premise > Principal Propagation: synchronize and mark trusted providers, Automatic Trust Synchronization; Configuration > On Premise: system certificate, CA certificate, subject pattern rules, validity; access control mapping switches Set Up Trust, CA, subject patterns
ABAP back end Basis and security teams STRUST, icm/trusted_reverse_proxy_<x>, VCLIENT, ICM restart; login/certificate_mapping_rulebased and CERTRULE; for RFC, SNC and SNC0 HTTPS, RFC

Useful details from SAP's pages:

  • Sample certificate. The connector's Generate Sample Certificate produces a DER file shaped like the runtime certificates; import it in CERTRULE to build the mapping rule before any user tries.
  • Subject pattern API. The connector exposes /api/v1/configuration/connector/onPremises/subjectPatternRules for reading and changing rules (SAP), so the rules can be checked by script instead of screenshots. From version 2.18.0, a rule's Details show when it was last used.
  • Kubernetes. On Kyma, the Transparent Proxy handles PrincipalPropagation destinations; the app sends the user's token as a bearer token and the proxy passes it on to the Connectivity proxy and the Cloud Connector (SAP).
  • Cloud targets. For S/4HANA Cloud Public Edition, SuccessFactors and other BTP apps, the destination wraps the user in a SAML assertion signed with the subaccount's key and trades it for an OAuth token at the target (SAP). The trust is set up in the target, not in a Cloud Connector.

Licensing: these are features of the BTP Connectivity and Destination services and the Cloud Connector, not separate products. Check your BTP contract for the services themselves.

Build vs. SAP

Need Build it yourself Use SAP's mechanism Choose
App reads S/4HANA for a person Technical user plus filtering in the app PrincipalPropagation destination and the Cloud Connector SAP: S/4HANA keeps the control and the log
Job with no person Shared service account with a password in a destination OAuth2TechnicalUserPropagation to a named, narrow technical user SAP, one identity per job
Map certificates to users Scripts that fill EXTID_DN from HR Rule-based mapping with one CERTRULE rule SAP's rule, with a stable subject
Reach S/4HANA Cloud Public Edition as the user Pass passwords or API keys per user OAuth2SAMLBearerAssertion or OAuth2JWTBearer SAP
Agent from another platform acting for a user Custom token relay SAP's token exchange and agent services, see the cross-platform agent project SAP's route where it exists, custom only behind it

Architecture view

Where it sits. The chain crosses the BTP subaccount, the Cloud Connector in Rockford and S4P in Calder's RISE landscape, reached over the private connection:

flowchart LR
  E[calder-entra] --> I[calder-ias]
  I --> A[calder-ai-prod<br/>agents, apps]
  A -- S4_ODATA / S4_ODATA_JOB --> C[Connectivity<br/>service]
  C --> S[SCC-RK-P<br/>rkscc01 + rkscc02<br/>CA CT05]
  S -- mTLS + SSL_CLIENT_CERT --> P[S4P ICM<br/>CERTRULE<br/>roles]

Non-functional requirements that decide the design:

Requirement Calder's target What breaks if missed
Identity fidelity Every call that acts for a person reaches S4P as that person Change documents name a shared user; roles stop applying
Availability No outage on identity key rotation or certificate renewal; connector pair in master and shadow Everyone refused at once, as in R08
Session bound A certificate or token never acts more than 1 hour after the sign-in it came from Long-running agents act after the person has left
Joiners and movers New users work the morning after provisioning, with no extra mapping step Help desk tickets and borrowed sessions
Latency Certificate reuse within its 10-minute validity keeps the hop cheap Each call pays for a new certificate

Integration and identity. The person's identity starts as an OpenID Connect token from calder-ias, federated from calder-entra; the app exchanges it and sends it through S4_ODATA. SCC-RK-P re-issues it as CN=<login name> signed by CT05; S4P's ICM trusts rkscc01's system certificate as reverse proxy and CERTRULE maps the CN to the user ID that Identity Provisioning created. Jobs use S4_ODATA_JOB and named technical users. Identity data flows from SF-EC, as the identity services topic designed.

The decision to record. Using the form from the design-doc topic:

  • Context: the agent pilot went live on the partner's draft: subject by e-mail, a hand-kept EXTID_DN table, System Certificate for Logon on, manual trust synchronization, 336-hour tolerance.
  • Options: (a) keep the draft and add a monthly table check; (b) subject ${login_name}, rule-based mapping, technical user propagation for jobs, automatic synchronization, short validity; (c) as (b), with subject ${user_uuid} and a mapping of global user IDs to SAP users.
  • Decision: (b). At Calder the login name is the personnel number and already the S4P user ID, so one rule maps everyone. Option (c) is the fallback if user IDs ever diverge from login names.
  • Consequences: a person's login name may never be reused; long-running agents must ask for a fresh sign-in instead of replaying old tokens; every job needs a technical identity with an owner.

What a design review will ask:

  1. Show one request's path: which hop decides who the user is, and which hop could make it someone else?
  2. Which attribute is in the certificate subject, and who can change it?
  3. What happens on the day the identity service rotates its key, and on the day CT05 expires?
  4. Which calls run without a person, and as whom?
  5. Which identity providers does SCC-RK-P trust, and why each one?

Production concerns

  • Security and SAP authorizations. Treat the connector's trust list, CA and subject rules as security configuration: changes go through change control, and only named administrators hold the connector's Administrator role. Map certificates only from your own CA; a rule that accepts any issuer turns any certificate into a logon. Propagation doesn't stop a user's own password logon through SAP GUI or RFC; handle that in the leaver process, as the identity services topic warned.
  • Evaluation. Keep a test set like R01 to R08 per environment and rerun it after every change: allowed users, refused users, a renamed user, a joiner, a job, an expired token, an untrusted issuer.
  • Operations. Calendar every certificate: CT05 to 2028-03-01, rkscc01's system certificate to 2027-05-10 (both from the integration security register), with a 60-day reminder. Alert on connector errors in the trust and certificate steps. The audit log of S4P now names real users; route it as the audit logging topic of Unit 27 will describe.
  • Cost. Little run cost; the cost is setup across four teams and the discipline to keep it. The draft's hidden cost is incident time: an outage for everyone at each key rotation.
  • Clean core. Nothing here modifies S/4HANA; it uses standard trust, mapping and authorization. That keeps upgrades simple.

Where AI fits

AI changes who calls S/4HANA, not how the chain works. An agent is one more consumer of the same destination, with two new risks:

  • Agents run longer than sessions. A resumed agent run holding a morning token is R06. Keep Expiration Tolerance at zero and design agents to pause and ask for a fresh sign-in, as in agent memory and long-running agents.
  • Agents do work nobody started. Scheduled agent tasks are jobs. Give them technical user propagation and a narrow role, never the connector's system certificate.

SAP's own agent services move the same idea into the platform: SAP describes the Agent Gateway as handling authentication and principal propagation for Joule and agents; its status is discussed in how Joule works and agent permissions and SAP authorizations. Agents from Microsoft or AWS reach SAP through token exchange first, as the cross-platform agent project builds. AI can also help operate the chain: summarizing connector logs or comparing subject rules with CERTRULE. Those are read-only uses; changes stay with people.

Pitfalls

  • E-mail as the subject. Renames break access; worse, an attribute users can edit lets them choose who they become. SAP warns against it.
  • Hand-kept mapping tables. They miss joiners and keep leavers, as R03 and R07 show.
  • System Certificate for Logon left on. Every call without a user becomes the connector's user. SAP recommends it off.
  • Manual trust synchronization. Works until the first key rotation, then fails for everyone.
  • Long tolerances and validities. The maximums (336 hours, 30 days) exist; production rarely needs more than minutes.
  • ECDSA or demo CAs. SAP notes ECDSA CA certificates import but fail at runtime; a self-signed demo CA tends to expire unnoticed.
  • Copying the ICM subject string by eye. Old kernels need blanks after commas; a mismatch means SSL_CLIENT_CERT is ignored.
  • Testing with one admin user. It hides every authorization gap until go-live.

Exercise: onboard a joiner and bound certificate reuse

Calder's new Rockford buyer 00100263 (rk.buyer2@) starts on Monday 7 December, as in the identity services lab. Show that the reviewed design needs no back-end change for a joiner, and add a rule that keeps certificates from outliving the sign-in they came from.

  1. Open unit27/propagation/world.json in VS Code.

  2. Under "people", add:

    "00100263": {"email": "rk.buyer2@calder-pumpworks.example", "idp": "calder-ias"},
  3. Under "s4p_users", add the user that Identity Provisioning created:

    "00100263": {"locked": false, "orders": [], "po_orgs": ["PUUS"]},
  4. At the end of the "requests" list, after R08's closing brace, add a comma and:

    {"id": "R09", "at": "2026-12-07T09:00", "who": "00100263", "doc": "4500000002",
     "app": "AGT_SUPPLY_WATCH", "dest": "S4_ODATA", "expect": "ALLOWED as 00100263"}
  5. Save, then replay both designs:

    python unit27/propagation_lab.py replay draft
    python unit27/propagation_lab.py replay reviewed

    The draft refuses R09 at H4 (the rotated key; with that fixed, the missing EXTID_DN row would stop it at H6). The reviewed design allows it with no change in S4P.

  6. In unit27/propagation_lab.py, find the PP07 line in review() and add this rule directly below it:

        add("PP13", v <= d["token_minutes"],
            f"certificate validity {v} min within the {d['token_minutes']}-min sign-in token")
  7. In selftest(), change (4, 2, 8) to (4, 2, 9) and (16, 0, 0) to (17, 0, 0), then run:

    python unit27/propagation_lab.py review draft
    python unit27/propagation_lab.py review reviewed
    python unit27/propagation_lab.py --selftest

Done when: replay reviewed ends with reviewed: 9 of 9 requests as expected (synthetic data), replay draft ends with draft: 2 of 9 requests as expected (synthetic data), review draft ends with draft: 4 OK, 2 WARN, 9 FAIL, review reviewed ends with reviewed: 17 OK, 0 WARN, 0 FAIL, and the self-test passes. Keep the design files: the access control, identity governance and audit logging topics of Unit 27 build on the same chain.

Going further

For readers who want the standards and the edge cases under the chain.

  • The token exchange. The user exchange token uses the JWT bearer grant of RFC 7523, section 2.1, which SAP's user exchange page links. Reading it explains why an exchanged token may carry fewer claims than the original: the authorization server issues a new token, it doesn't forward the old one.
  • Corporate tokens. When the corporate identity provider's own token must reach the back end, SAP documents a variant where that token is embedded in the BTP token and propagated by the Connectivity service (SAP). It needs the trust synchronization to fetch the corporate provider's key set, and it changes which attributes reach H5.
  • App-to-app chains. When one BTP app calls a second app that then propagates the user, SAP's trust page says the second app must be marked trusted in the connector's principal propagation tab. Chains of apps are where identities quietly turn into technical ones; draw each hop.
  • Certificate revocation. Short-lived certificates are usually not revoked; they simply expire. That is why validity is the real revocation control, and why SAP notes strict CRL checking can't be combined with this setup in profile SSL_SERVER.
  • RFC and SNC. SNC uses the same mapping but different trust: the connector's SNC identity in SNC0, and the same SNC product on both sides, as SAP's RFC page stresses.

Check yourself

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

1In the HTTPS path, which certificate does S/4HANA use to decide who the user is?

Answer: B. The system certificate only proves the caller is the trusted connector; icm/trusted_reverse_proxy_<x> lets ICM accept the header from it. The user's identity comes from the short-lived certificate in SSL_CLIENT_CERT, which the mapping turns into an SAP user.

2Every request fails at the Cloud Connector from 06:00 on Friday with an unknown signing key. What fixes it for good?

Answer: B. The identity provider rotated its key and the connector only knows keys from its last synchronization. SAP recommends automatic synchronization when key rotation is active; tolerance and CA changes don't touch signature checks.

3Why does the reviewed design use ${login_name} in the subject pattern instead of ${email}?

Answer: D. The login name is the personnel number and already the SAP user ID, so one rule maps everyone and survives a mailbox rename. SAP also warns against using attributes that users can modify.

4A nightly agent job calls a PrincipalPropagation destination with no user, and the mapping has System Certificate for Logon on. What happens?

Answer: D. With the switch on, the system certificate is used for authentication when no principal arrives, so the job gets whatever that user can do. SAP recommends keeping it off and giving jobs technical user propagation.

5What does Expiration Tolerance on the Cloud Connector control?

Answer: A. Tolerance, in hours, extends the use of a principal beyond the token's expiry; Certificate Validity, in minutes, is the reuse window for generated certificates. A long tolerance lets resumed agent runs act on old sign-ins.

6Principal propagation must reach an ABAP system over RFC instead of HTTPS. What must be in place?

Answer: A. SAP's RFC page requires SNC: the connector's SNC name in SNC0 with RFC and certificate entries activated, and an RFC SNC mapping. User mapping works as for HTTPS, so rule-based mapping still applies.

7A contractor who left still reads orders through the agent with an SAP ID service account. Which two settings let this happen in the draft?

Answer: D. The trust list let SAP ID service tokens through H4, and the hand-kept table still mapped the contractor's certificate to an active user. Trusting only Calder's tenant stops it at H4, before any mapping is consulted.

8You are asked to let a resumed agent run finish a task four hours after the user signed in. What fits this topic's design?

Answer: D. Keeping tolerance at zero means stored tokens can't act after the session ends. The agent pauses and resumes with a new sign-in, so the person is still the one acting and the logs stay true.
Next · What's changingPreparing for SAP's AI certificationsSAP replaced multiple-choice tests with timed, open-book practical exams. Learn which AI-related certifications exist, how they are graded, and how to prepare.

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