# Integration security: authentication between systems, certificates, OAuth, message-level security and secrets

> Decide how each system proves who it is, keep every certificate renewed before it breaks an interface, and know when TLS is not enough.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/integration-security/
- Updated: 2026-11-30
- Reading time: Foundational 8 min, Deep 40 min

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

## Foundational layer

### The 60-second version

Every interface is a conversation between two systems that have never met a person. Each one has to prove who it is, and the other has to decide whether to believe it. **Integration security** is the set of choices that make those proofs strong, keep them working, and keep the data safe on the way.

Four questions cover most of it:

1. **How does each system prove who it is?** A password, an OAuth token, a certificate, or the signed-in person's identity passed along. Passwords are the weakest and the most common.
2. **Who owns each certificate and key, and when does it expire?** Certificates run out on a fixed date. When one does, every interface that relies on it stops at once, often on a weekend.
3. **Is the data protected only in transit, or also at rest between hops?** Encryption on the wire (TLS) ends at every server it passes through. Bank statements and payroll files need the content itself signed and encrypted.
4. **Where do the secrets live?** A password typed into an integration flow, a proxy policy or a configuration file on a plant PC is a password many people can read.

The decision for a leader: **keep one register of every connection with its owner, its proof method and its expiry dates, and fund the person who keeps it current.** This topic uses the course's fictional company, **Calder Pumpworks**, and eleven of its connections.

### Why it matters to the business

Integration security fails in two ways: an outage nobody planned, and a breach nobody noticed. Using Calder (all values are course values):

- **The certificate nobody watched.** Tessaly, a distributor, sends orders over AS2 with a certificate that expires on 15 December. Nobody gets an alert. On the 15th, orders stop flowing, and the first sign is a customer asking where the confirmation is.
- **SAP's yearly key change.** Calder's integration tenant signs messages with a key SAP renews every year. SAP prepares the new key 60 days ahead and switches it on by itself one day before the old one expires ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/activating-a-new-key-pair-provided-by-sap-383be7a.md)). If Hallam and Tessaly don't have the new certificate by then, they reject Calder's signed messages.
- **One password, two partners.** The EDI provider and a freight carrier log on to Calder's integration tenant with the same user. When the carrier's laptop is stolen, both connections must be shut down and reset together.
- **The changed amount.** A bank statement sits on an SFTP server between hops. Transfer encryption protected it on the wire, not on the disk. One changed digit raises cash by 33,994.71 USD in Calder's books, and nothing checks it.
- **The agent that sees everything.** A Copilot Studio agent reads sales orders with one shared key. SAP logs every call as the same technical user, so a sales rep can read distributor orders their own roles would refuse, and the audit log can't say who did.

The cost of getting this right is mostly discipline: a register, an owner per line, an alert per certificate, and a rule that passwords are the exception.

### How SAP does it

As of November 2026, these SAP pieces carry integration security. Each is linked to the SAP page it comes from.

- **SAP Integration Suite, Cloud Integration** offers per-adapter authentication. For incoming HTTPS, IDoc, AS2 and AS4 calls, SAP lists client certificates and OAuth with the client credentials grant as recommended, and basic authentication as a fallback ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/adapters-authentication-methods-9f7cf82.md)). It supports TLS 1.2 and 1.3 in both directions ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/security-aspects-of-data-data-flow-for-cloud-integration-7895724.md)).
- **The tenant keystore** holds certificates and key pairs, and **security material** holds passwords, OAuth clients, PGP keys and SSH known hosts, referenced from flows by name ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/keystore-b163513.md)).
- **Message-level security** steps sign, verify, encrypt and decrypt content with PGP, PKCS#7/CMS, XML Signature or WS-Security ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-message-level-security-9036c0c.md)).
- **SAP Cloud ALM** health monitoring tracks certificate validity across all Cloud Integration tenants and can alert by email, chat or ticket ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Operations/central-monitoring-and-alerting-solutions-605fc6e.md)).
- **The Cloud Connector** links BTP to systems inside your network. The route to the cloud is always TLS-encrypted, and the route to the back end can be TLS or SNC ([SAP documentation](https://github.com/SAP-docs/btp-connectivity/blob/main/docs/1-connectivity-documentation/recommendations-for-secure-setup-e7ea82a.md)). It can also pass the signed-in person's identity to the back end, which the [connectivity topic](https://erpfde.com/topics/btp-connectivity/) covers.

SAP gives you strong options and sensible defaults. Choosing per connection, keeping the register and renewing on time are yours.

### A decision guide: how should this connection prove who it is?

| Situation | Use | Avoid |
| --- | --- | --- |
| A trading partner or EDI provider sends messages to Cloud Integration | A client certificate per partner, or OAuth client credentials per partner, each with its own custom role | One shared user with the generic send role |
| Cloud Integration calls an SAP API on a technical job | OAuth client credentials or a client certificate, stored as security material | A password typed into a header in the flow |
| An app or agent acts for a signed-in person | Pass the person's identity (principal propagation or an OAuth token exchange) so SAP checks their roles | One technical user or API key for everyone |
| Files with payments, bank data or personal data | SFTP with keys, plus signed and encrypted content | Plain FTP, or SFTP alone |
| SAP-to-SAP calls by RFC inside your network | SNC on the connection, with a technical user per caller | Plain RFC with passwords in a config file |
| A connection retires within months | Accept the gap in writing, with an approver and an end date | Silently leaving it as it is |

> **Note** **For functional consultants.** Security changes your test plan more than your configuration. Add a test for every certificate renewal (does the partner's message still arrive the morning after?), and when a process goes through an agent or app acting for users, test with a user who should be refused, not only one who should be allowed.

### Questions to ask

- Do we have one list of every connection, with how it authenticates, who owns it, and when each certificate expires?
- Which connections still log on with a password? Which of those cross the internet?
- Who is alerted 60 days before a certificate expires, and who tells the partner?
- When SAP renews its yearly key on our integration tenant, which partners need the new certificate, and who sends it?
- Does any partner share a user or key with another partner?
- Where an agent or app acts for a person, does SAP see that person or a shared technical user?
- Which files and messages carry payment or personal data, and are they signed and encrypted, not only sent over SFTP?
- Where are our integration passwords stored? Could a developer read one from a flow, a proxy or a log?

### Common misconceptions

- **"HTTPS makes it secure."** TLS protects the transfer between two points. It ends at every load balancer and server on the way, and it says nothing about who is calling or whether the content was changed at rest.
- **"Certificates are an IT detail."** An expired certificate stops orders, payments or shipments at once. It is a business continuity risk with a known date.
- **"SAP renews its keys, so we don't have to do anything."** SAP prepares and activates its own key. Your partners still need the new certificate before the switch, and that is your job.
- **"A technical user is fine for an agent."** For a nightly job, yes. For an agent acting for many people, a shared user hides who did what and gives everyone the agent's rights.
- **"We'll fix the passwords later."** Each password left in a flow or a policy is copied into transports, exports and backups. The longer it stays, the more places it lives.

### Key terms

- **Authentication:** proving who a caller is, with a password, a token, a certificate or a key.
- **Client certificate (mutual TLS):** a certificate the caller presents during the TLS handshake, so both sides prove who they are.
- **OAuth client credentials:** a flow in which a system exchanges its client ID and secret for a short-lived access token, then calls the API with the token.
- **Principal propagation:** passing the signed-in person's identity to the back end, so it checks that person's roles.
- **Keystore:** the store of key pairs and certificates a system uses to prove who it is and to trust others.
- **Certificate expiry:** the fixed date after which a certificate is no longer accepted; renewal must reach every party before then.
- **Message-level security:** signing and encrypting the content itself, so it stays protected and provably unchanged across every hop.
- **SNC:** Secure Network Communications, SAP's way of authenticating and encrypting RFC and SAP GUI connections.
- **Security material:** passwords, OAuth clients, PGP keys and SSH known hosts stored in the integration tenant and referenced by name.
- **Credential register:** a list of every connection with its authentication method, owner, secrets and expiry dates.

### Check yourself

1. Why should a leader insist on one register of every integration connection?
   - A. Auditors ask for a diagram of the landscape every year
   - B. It names each connection's owner, method and expiry
   - C. It replaces the need for an integration platform
   - D. It lets the team skip testing after certificate renewals

   Answer: B. Most integration security failures are quiet until they break: an expiry nobody watched, a shared password, a missing owner. A register with owners, methods and dates is how someone acts before that happens.

2. Tessaly's AS2 certificate expires on 15 December and nobody is alerted. What happens?
   - A. SAP renews the partner's certificate automatically on that day
   - B. Orders keep flowing until the next yearly audit
   - C. Orders from Tessaly stop, and a customer may notice first
   - D. Calder's integration tenant switches to a password

   Answer: C. An expired certificate breaks the connection on a fixed date. Without an alert and an owner, the first sign is often a missing order confirmation. SAP renews only its own keys, not a partner's certificate.

3. SAP renews its yearly key on Calder's integration tenant. What does Calder still have to do?
   - A. Nothing, because SAP activates the new key by itself in time
   - B. Buy a new certificate from a public authority
   - C. Rebuild the integration flows that use the key
   - D. Send the new certificate to partners before the switch

   Answer: D. SAP prepares the new key 60 days ahead and activates it one day before expiry if nobody does. Partners who verify Calder's signatures need the new certificate first, or they reject Calder's messages.

4. The EDI provider and a carrier share one logon to Calder's integration tenant. What is the main risk?
   - A. The two partners can read each other's messages in monitoring
   - B. One leak forces both connections to be reset together
   - C. The tenant refuses two senders on the same user
   - D. Message processing slows down for both partners

   Answer: B. A shared credential widens the damage of a leak and makes rotation a joint project. One credential per partner keeps a leak, and its fix, to that partner.

5. Why isn't SFTP enough for Calder's bank statements?
   - A. SFTP doesn't support files of the size banks send
   - B. SFTP is not offered by SAP Integration Suite
   - C. Files rest unprotected on the server
   - D. Banks refuse connections that use SFTP keys

   Answer: C. SFTP encrypts the transfer, not the file on the server. A signature on the content shows any change, so a tampered statement is rejected instead of loaded.

6. A Copilot Studio agent reads SAP data for many clerks with one shared key. What should change?
   - A. Remove roles from the shared technical user in S/4HANA
   - B. Rotate the shared key every week and after each leaver
   - C. Log every call in the agent platform instead of in SAP
   - D. Pass each person's identity so SAP checks their roles

   Answer: D. With one shared key SAP sees one technical user, so everyone gets its rights and the audit log can't say who acted. Passing the person's identity lets SAP apply each person's own roles.

## Deep layer

### Mental model

Draw every interface as a chain of **hops**. On each hop, one party proves who it is and the other decides whether to trust it. Security is the weakest hop, and it is only as durable as the earliest expiry date on the chain.

Four properties decide each hop:

1. **Proof**: how the caller authenticates (password, token, certificate, SSH key, SNC, or the person's identity) and how strong that is.
2. **Trust anchor**: what the receiver checks the proof against (a role on a service key, a trusted CA, a known host key), and who owns it.
3. **Lifetime**: when the proof stops working (certificate expiry, key rotation, password policy), and who renews it with whom.
4. **Reach**: what the proof unlocks if stolen (one partner or several, one API or a whole system), and where the secret is stored.

Transport encryption is a fifth, near-universal property, and it protects only between two points. When content must stay protected and provably unchanged across hops, the content itself needs a signature and encryption. That is message-level security.

### How it works

#### Proof methods and their strength

SAP's design guideline lists Cloud Integration's methods "roughly ordered from low to high security": none, basic, principal propagation, SASL, OAuth, client certificate, public key ([SAP guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/use-secure-authentication-methods-3d46d45.md)). The ordering explains itself once you ask what an attacker gets:

| Method | What travels | What a thief gets | Lifetime |
| --- | --- | --- | --- |
| Basic (user, password) | The password on every call | Lasting access until someone changes the password | Password policy |
| API key | The key on every call | Lasting access, usually without a user behind it | Until rotated |
| OAuth client credentials | Secret goes only to the token endpoint; calls carry a token | A token valid for minutes, or the secret if the store leaks | Token short, secret rotated |
| Client certificate (mTLS) | Only the public certificate; the private key never leaves | Nothing usable without the private key | Fixed expiry date |
| SSH public key | Only a signature; the private key stays home | Nothing without the private key | Until the key is replaced |
| Principal propagation, token exchange | The person's identity, vouched for by a trusted issuer | Short-lived assertions | Minutes |

SAP adds why basic authentication is risky even over TLS: TLS ends at intermediate hops such as load balancers, where a password can surface in logs or monitoring tools, and weak passwords invite brute force and lockouts ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/security-aspects-of-data-data-flow-for-cloud-integration-7895724.md)). Client certificates usually give the highest security, at the price that they expire and must be rotated ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/adapters-authentication-methods-9f7cf82.md)).

The [secrets and OAuth topic](https://erpfde.com/topics/secrets-api-authentication-and-oauth/) teaches the OAuth flows with a hands-on token script. This topic uses them as building blocks.

#### Inbound to Cloud Integration

Inbound calls to Cloud Integration are always authenticated ([SAP guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/use-secure-authentication-methods-3d46d45.md)). In the Cloud Foundry environment, a sender's proof lives in a **service key** of the Process Integration Runtime service with plan `integration-flow`. The key holds either client credentials or a certificate, SAP-generated or the partner's own. At runtime, Cloud Integration finds the service key that matches the caller and checks that its instance carries the role named in the sender adapter ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/client-certificate-authentication-for-integration-flow-processing-7f84d16.md)).

```mermaid
flowchart LR
  P[Partner system] -- TLS + client certificate --> LB[SAP load balancer]
  LB --> W[Cloud Integration worker]
  W -- which service key holds this certificate? --> K[Service key<br/>plan integration-flow]
  K -- role on its instance --> R{Role = sender<br/>adapter's User Role?}
  R -- yes --> F[Integration flow runs]
  R -- no --> X[403]
```

Two design choices follow:

- **The role.** The standard role is `ESBMessaging.send`. SAP's guideline says to avoid generic roles for sender authorization and create a custom role per inbound scenario ([SAP guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/use-secure-authentication-methods-3d46d45.md)). With the generic role, any sender's key can call any flow.
- **One key per partner.** If the EDI provider and a carrier share one key, a leak exposes both, and rotation needs both to move at once.

> **Note** Service instances that still use the grant type `client_x509` are deprecated: SAP says updates fail and new keys can't be created until the grant type is changed to `client_credentials`. Certificate-based inbound authentication itself remains supported ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/update-service-instance-that-contains-deprecated-client-x509-grant-type-0a38373.md)).

#### Outbound from Cloud Integration

Outbound, the flow's receiver adapter names a credential by alias: a user credential, an OAuth2 client credentials artifact, an OAuth2 SAML bearer assertion artifact, a key pair alias for client certificates, or principal propagation through the Cloud Connector. SAP lists three OAuth grant types for outbound calls: client credentials, SAML bearer assertion and authorization code ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/oauth-2-0-3823134.md)).

Two keystore behaviors catch teams out ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/keystore-b163513.md)):

- If the receiver trusts several of the tenant's key pairs, Cloud Integration picks one at random for the TLS handshake. Set **Private Key Alias** in the adapter so a renewal of one key doesn't surprise you.
- Even with basic authentication, the tenant must trust the receiver's root certificate. A receiver that changes its certificate authority breaks the connection unless the new root is in the keystore.

The keystore doesn't check the signatures of certificates you upload; SAP says root certificates in particular must be verified by hand. When you exchange public keys with a partner, use a secure channel or confirm the fingerprint by phone ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/securely-exchanging-key-material-908d93e.md)).

#### The person's identity, or a technical user

A technical user is right for a job that belongs to no one: the nightly file, the EDI provider's feed. When an app or agent acts **for** a person, the back end should see that person. The BTP Destination and Connectivity services support this as principal propagation: `PrincipalPropagation` to on-premise systems through the Cloud Connector, `OAuth2SAMLBearerAssertion` or `OAuth2JWTBearer` to cloud systems ([SAP documentation](https://github.com/SAP-docs/btp-connectivity/blob/main/docs/1-connectivity-documentation/principal-propagation-e2cbb48.md)). For on-premise systems, the Cloud Connector issues short-lived X.509 certificates for the signed-in user from a CA certificate you install ([SAP documentation](https://github.com/SAP-docs/btp-connectivity/blob/main/docs/1-connectivity-documentation/configure-a-ca-certificate-d0c4d56.md)).

Principal propagation has its own topic in Unit 27: [principal propagation end to end](https://erpfde.com/topics/principal-propagation/), beside identity services and single sign-on. Here the architect's rule is enough: **if a hop acts for people, record whose identity reaches SAP, and treat a shared technical user as a finding.**

#### Certificates and their lifecycle

A certificate is a public key with an owner's name, signed by a certificate authority (CA), valid between two dates. Renewing one is a small job that involves people on both sides. SAP's renewal guides make two points that shape every plan ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/basic-security-artifact-renewal-processes-c70b1f2.md)):

- The tenant administrator coordinates, because they know every connected system's administrator.
- A key pair is usually used in several flows and channels; you need to know them all to plan the renewal.

**SAP's own keys.** SAP delivers the tenant's key pair with a certificate chain renewed every year, under aliases such as `sap_cloudintegrationcertificate` ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/keys-provided-by-sap-9d8a60b.md)). The sequence:

```mermaid
sequenceDiagram
  participant S as SAP
  participant T as Tenant administrator
  participant P as Partners (Hallam, Tessaly)
  S->>T: new key pair in New SAP Keys (60 days before expiry)
  T->>T: download new certificate and chain
  T->>P: send certificate, agree a date
  P->>P: import into their trust store
  T->>T: activate the new key
  Note over S,T: If nobody activates it, a daily job does,<br/>one day before the old key expires
```

The steps come from SAP's renewal and activation pages ([renewal](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/renewal-of-keys-provided-by-sap-5db16f5.md), [activation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/activating-a-new-key-pair-provided-by-sap-383be7a.md)). The automatic activation keeps the tenant working, but partners who don't have the new certificate will reject what the tenant signs.

**Message-level certificates fail silently.** SAP notes that the keystore doesn't check expiry in its encryption, decryption and signing steps ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/keystore-b163513.md)). An expired signing key keeps signing at Calder; the break shows up at the partner, or at the auditor. So message-level keys need the same calendar as transport certificates, even though nothing at your end will remind you.

**Alerts.** Three places can warn you:

| Where | What it watches | Source |
| --- | --- | --- |
| SAP Cloud ALM health monitoring | Certificate validity across all Cloud Integration tenants | [SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Operations/central-monitoring-and-alerting-solutions-605fc6e.md) |
| Cloud Connector alerting | Its own certificates; warns 30 days ahead by default and repeats the alert | [SAP documentation](https://github.com/SAP-docs/btp-connectivity/blob/main/docs/1-connectivity-documentation/alerting-87bffd9.md) |
| Keystore in the Integration Suite monitor | Shows each entry's expiry date, in red once expired | [SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/managing-keystore-entries-2dc8942.md) |

A red date in a monitor nobody opens is not an alert. The register needs a named owner per certificate and a route that reaches a person.

#### Message-level security

TLS and SFTP protect data only while it moves; once received, it is decrypted and in clear text, and SFTP doesn't protect the file on the server ([SAP guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-message-level-security-9036c0c.md)). Message-level security protects the content itself:

- **Encryption** with the receiver's public key: only the receiver's private key can read it.
- **Signature** with the sender's private key over a hash of the content: anyone with the sender's public key can check it wasn't changed and who wrote it.

Cloud Integration's steps support PGP and PKCS#7/CMS for encryption, PKCS#7/CMS and XML Signature for signing, and WS-Security in the SOAP adapter ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/features-that-support-message-level-security-0c58bdc.md)). SAP recommends different keys for message level and transport level ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/keystore-b163513.md)).

Use it when content crosses hops you don't control or rests in between: bank files, payroll, documents with personal data, B2B messages (AS2 already signs and encrypts). The partner must support the same standard, so it is a design decision for both sides.

#### Secrets: where they may live

A secret should live in one store built for it and be referenced by name:

| Secret for | Store | Not here |
| --- | --- | --- |
| Cloud Integration outbound | Security material (user credentials, OAuth artifacts, secure parameters, PGP keyrings, known hosts) | A content modifier header, a Groovy script, an externalized parameter in clear |
| API Management to a back end | Encrypted key value map | The proxy policy text |
| BTP apps | Bindings, or SAP Credential Store for third-party secrets | Environment files in Git |
| Cloud Connector | Its secure storage, on a machine with few OS users | A shared admin password |

SAP's guideline adds a quieter leak: anything written to the message processing log is visible in monitoring, and logging all headers can include the `Authorization` header ([SAP guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/remove-sensitive-or-secret-content-before-logging-or-forwarding-4686862.md)). Log by allow list.

#### Network paths

The path decides what an attacker can reach. Inbound calls to Cloud Integration always arrive over HTTPS; outbound, an `http://` address is possible and SAP advises against it for confidential data ([SAP guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/use-secure-protocols-c9b8cae.md)). For systems inside your network, the Cloud Connector opens the tunnel from inside, so no inbound firewall port is needed; the cloud route is always TLS and the back-end route can be TLS or SNC ([SAP documentation](https://github.com/SAP-docs/btp-connectivity/blob/main/docs/1-connectivity-documentation/recommendations-for-secure-setup-e7ea82a.md)). For SFTP, the tenant's known hosts file should contain only the servers your flows use and trust ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/known-hosts-file-5d7e2e7.md)). The [connectivity topic](https://erpfde.com/topics/btp-connectivity/) covers destinations and the Cloud Connector in depth; Unit 27 covers network security for SAP systems as a whole.

#### Calder's connections

The lab works with eleven hops from Calder's interfaces (see the [integration platform topic](https://erpfde.com/topics/integration-platform-and-clean-core/) for the interface list):

| Hop | Interface | From → to | Draft proof |
| --- | --- | --- | --- |
| H01 | I10 | EDI provider → Cloud Integration | basic, user `CPI_INBOUND`, `ESBMessaging.send` |
| H02 | I10 | Cloud Integration → `S4P` via `SCC-RK-P` | basic `TU_I10_ORDERS`, password in a header |
| H03 | I10 | Hallam → Cloud Integration (AS2) | client certificate, signed and encrypted |
| H04 | I10 | Tessaly → Cloud Integration (AS2) | client certificate, certificate expires 2026-12-15 |
| H05 | I08 | Cloud Integration → bank SFTP | password, no signature on statements |
| H06 | I03 | `S4P` report → CRM file server | plain FTP with a password |
| H07 | I02 | Rockford MES → `S4P` by RFC | plain RFC, password in the MES config file |
| H08 | A04 | Copilot Studio agent → MCP server → `S4P` | shared API key, runs as `TU_COPILOT_MCP` |
| H09 | I11 | Augsburg ECC → `S4P` by SOAP | basic on the private network, retires 2027-07-05 |
| H10 | I14 | API Management → `S4P` | basic `TU_APIM_ORDERS`, password in the policy |
| H11 | I06 | Larkspur → Cloud Integration | basic, the same `CPI_INBOUND` as H01, no owner |

### Build it yourself: review Calder's trust register and plan the renewals

You will run a lab with four parts. **Review** checks Calder's connections and certificates against twelve course rules. **Calendar** lists when each certificate renewal must start and whom to tell. **Trace** shows which user SAP sees on a hop. **Simulate** shows why the rules exist: certificates expiring with nobody acting, a tampered bank statement, and a leaked shared credential.

```mermaid
flowchart LR
  I[--init] --> D[register_draft.json]
  I --> V[register_reviewed.json]
  D --> R[review: IS01-IS12]
  V --> R
  D --> C[calendar]
  D --> T[trace H08]
  D --> S[simulate expiry,<br/>tamper, leak]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 26](https://erpfde.com/topics/set-up-for-unit-26/). This walkthrough needs none of the setup's trials.

> **Note** New words. A **register** here is a JSON file listing every hop and certificate. **JSON** is a text format for structured data. A **hop** is one connection between two systems. An **HMAC** is a fingerprint of a text made with a secret key; anyone without the key can't make a matching one. **Exit code** is the number a program returns; `2` means at least one rule failed, which a pipeline can use to block a change.

> **Warning** Hop IDs `H01` to `H11`, certificate IDs `CT01` to `CT09`, rule IDs `IS01` to `IS12`, users, dates and values are course labels, not SAP formats. The rules follow SAP's guidance where the table in Step 4 says so; the rest are course choices.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`, from the setup topic.
- No account, no network and no extra libraries. The script uses built-in modules only and has no randomness, so your output matches the samples exactly.
- About 40 minutes. Everything is free.

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

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

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

4. Create the unit folder if it doesn't exist yet:

   - **Windows (PowerShell):**

     ```powershell
     New-Item -ItemType Directory -Force unit26
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p unit26
     ```

#### Step 2: Create the script

1. In VS Code, create a new file `unit26/intsec_lab.py`.
2. Paste the code below and save.

```python
"""Review who trusts whom across Calder's interfaces, plan certificate renewals,
and see why the rules exist.

Course lab for Unit 26, "Integration security".
Built-in modules only, no randomness, no network, no SAP system.

  python unit26/intsec_lab.py --init                  write the sample registers
  python unit26/intsec_lab.py review                  review unit26/intsec/register_draft.json
  python unit26/intsec_lab.py review --file unit26/intsec/register_reviewed.json
  python unit26/intsec_lab.py calendar                renewal calendar for the next 120 days
  python unit26/intsec_lab.py trace H08               who the back end sees as the user
  python unit26/intsec_lab.py simulate expiry         what breaks, day by day, if nobody renews
  python unit26/intsec_lab.py simulate tamper         a changed statement, with and without a signature
  python unit26/intsec_lab.py simulate leak CPI_INBOUND   who is exposed when a credential leaks
  python unit26/intsec_lab.py --self-test             check the built-in samples

Hop IDs H01 to H11, certificate IDs CT01 to CT09, rule IDs IS01 to IS12,
names, users, dates and values are course labels for the fictional Calder
Pumpworks. The signature in "simulate tamper" is an HMAC stand-in: real
message-level security uses public-key signatures (PKCS#7/CMS, XML Signature,
OpenPGP), which Python's built-in modules don't provide.
"""

import argparse
import copy
import hashlib
import hmac
import json
import sys
from datetime import date, timedelta
from pathlib import Path

FOLDER = Path("unit26/intsec")
AS_OF = date(2026, 11, 30)

# Approved places for a secret (course rule IS07).
APPROVED_STORES = {"tenant-security-material", "credential-store",
                   "encrypted-kvm", "cloud-connector", "service-key-binding",
                   "abap-secure-store"}
# Authentication methods, weakest first (after SAP's guideline list).
STRENGTH = {"none": 0, "basic": 1, "password": 1, "api-key": 1,
            "principal-propagation": 2, "oauth-saml-bearer": 3,
            "oauth-cc": 3, "oauth-token-exchange": 3, "snc": 4,
            "client-cert": 4, "ssh-key": 4}
UNENCRYPTED = {"http", "ftp", "rfc"}

# ---------------------------------------------------------------- the registers

HOPS_DRAFT = [
    {"id": "H01", "interface": "I10", "name": "EDI provider sends distributor orders to Cloud Integration",
     "from": "EDI provider", "to": "Cloud Integration calder-int-prod", "network": "internet",
     "transport": "https", "tls": "1.2", "auth": "basic", "credential": "CPI_INBOUND",
     "store": "service-key-binding", "inbound_role": "ESBMessaging.send",
     "acts_for_user": False, "sensitivity": "normal", "message_level": "none",
     "logs_all_headers": False, "owner": "00100292", "certs": []},
    {"id": "H02", "interface": "I10", "name": "Cloud Integration creates sales orders in S4P",
     "from": "Cloud Integration calder-int-prod", "to": "S4P via SCC-RK-P", "network": "cloud-connector",
     "transport": "https", "tls": "1.2", "auth": "basic", "credential": "TU_I10_ORDERS",
     "store": "iflow", "inbound_role": None, "acts_for_user": False,
     "sensitivity": "normal", "message_level": "none", "logs_all_headers": True,
     "owner": "00100292", "certs": ["CT04", "CT07"]},
    {"id": "H03", "interface": "I10", "name": "Hallam sends ORDERS over AS2",
     "from": "Hallam (HALLAMFS)", "to": "Cloud Integration calder-int-prod", "network": "internet",
     "transport": "as2", "tls": "1.2", "auth": "client-cert", "credential": "HALLAMFS-AS2",
     "store": "tenant-security-material", "inbound_role": "Calder.B2B.Send",
     "acts_for_user": False, "sensitivity": "normal", "message_level": "sign+encrypt",
     "logs_all_headers": False, "owner": "00100292", "certs": ["CT01", "CT02"]},
    {"id": "H04", "interface": "I10", "name": "Tessaly sends ORDERS over AS2",
     "from": "Tessaly (TESSALYFP)", "to": "Cloud Integration calder-int-prod", "network": "internet",
     "transport": "as2", "tls": "1.2", "auth": "client-cert", "credential": "TESSALYFP-AS2",
     "store": "tenant-security-material", "inbound_role": "Calder.B2B.Send",
     "acts_for_user": False, "sensitivity": "normal", "message_level": "sign+encrypt",
     "logs_all_headers": False, "owner": "00100292", "certs": ["CT01", "CT03"]},
    {"id": "H05", "interface": "I08", "name": "Cloud Integration fetches bank statements by SFTP",
     "from": "Cloud Integration calder-int-prod", "to": "bank SFTP server", "network": "internet",
     "transport": "sftp", "tls": None, "auth": "password", "credential": "BANK_SFTP_PW",
     "store": "tenant-security-material", "inbound_role": None, "acts_for_user": False,
     "sensitivity": "payment", "message_level": "none", "logs_all_headers": False,
     "owner": "00100280", "certs": []},
    {"id": "H06", "interface": "I03", "name": "S4P report puts open order items for the CRM",
     "from": "S4P (custom report)", "to": "CRM file server", "network": "internet",
     "transport": "ftp", "tls": None, "auth": "password", "credential": "CRM_FTP_PW",
     "store": "abap-secure-store", "inbound_role": None, "acts_for_user": False,
     "sensitivity": "normal", "message_level": "none", "logs_all_headers": False,
     "owner": "00100296", "certs": []},
    {"id": "H07", "interface": "I02", "name": "Rockford MES reads production orders by RFC",
     "from": "Rockford MES", "to": "S4P", "network": "private",
     "transport": "rfc", "tls": None, "auth": "password", "credential": "TU_MES_RFC",
     "store": "mes-config-file", "inbound_role": None, "acts_for_user": False,
     "sensitivity": "normal", "message_level": "none", "logs_all_headers": False,
     "owner": "00100314", "certs": []},
    {"id": "H08", "interface": "A04", "name": "Copilot Studio agent reads sales orders through Calder's MCP server",
     "from": "Copilot Studio agent", "to": "S4P via MCP server", "network": "internet",
     "transport": "https", "tls": "1.2", "auth": "api-key", "credential": "CALDER_MCP_API_KEY",
     "store": "credential-store", "inbound_role": None, "acts_for_user": True,
     "sensitivity": "normal", "message_level": "none", "logs_all_headers": False,
     "owner": "00100292", "certs": [], "backend_user": "TU_COPILOT_MCP"},
    {"id": "H09", "interface": "I11", "name": "Augsburg ECC sends impeller lot statuses to S4P by SOAP",
     "from": "ECP (CP20)", "to": "S4P", "network": "private",
     "transport": "https", "tls": "1.2", "auth": "basic", "credential": "TU_IC_SOAP",
     "store": "abap-secure-store", "inbound_role": None, "acts_for_user": False,
     "sensitivity": "normal", "message_level": "none", "logs_all_headers": False,
     "owner": "00100292", "certs": [], "retire": "2027-07-05"},
    {"id": "H10", "interface": "I14", "name": "API Management calls the sales order API for distributors",
     "from": "API Management", "to": "S4P via SCC-RK-P", "network": "cloud-connector",
     "transport": "https", "tls": "1.2", "auth": "basic", "credential": "TU_APIM_ORDERS",
     "store": "proxy-policy", "inbound_role": None, "acts_for_user": False,
     "sensitivity": "normal", "message_level": "none", "logs_all_headers": False,
     "owner": "00100292", "certs": ["CT04", "CT07"]},
    {"id": "H11", "interface": "I06", "name": "Larkspur posts shipment status to Cloud Integration",
     "from": "Larkspur Freight Lines", "to": "Cloud Integration calder-int-prod", "network": "internet",
     "transport": "https", "tls": "1.2", "auth": "basic", "credential": "CPI_INBOUND",
     "store": "service-key-binding", "inbound_role": "ESBMessaging.send",
     "acts_for_user": False, "sensitivity": "normal", "message_level": "none",
     "logs_all_headers": False, "owner": None, "certs": []},
]

CERTS_DRAFT = [
    {"id": "CT01", "alias": "sap_cloudintegrationcertificate", "kind": "sap-key-pair",
     "system": "calder-int-prod", "not_after": "2027-01-21", "use": "message",
     "partners": ["Hallam", "Tessaly"], "monitored": "none", "auto_renew": "sap",
     "partner_has_new": False, "stage": "prod", "owner": "00100292"},
    {"id": "CT02", "alias": "HALLAMFS-AS2", "kind": "partner-cert",
     "system": "calder-int-prod", "not_after": "2027-08-31", "use": "message",
     "partners": ["Hallam"], "monitored": "none", "auto_renew": None,
     "stage": "prod", "owner": "00100292"},
    {"id": "CT03", "alias": "TESSALYFP-AS2", "kind": "partner-cert",
     "system": "calder-int-prod", "not_after": "2026-12-15", "use": "message",
     "partners": ["Tessaly"], "monitored": "none", "auto_renew": None,
     "stage": "prod", "owner": "00100292"},
    {"id": "CT04", "alias": "rkscc01 system certificate", "kind": "client-cert",
     "system": "SCC-RK-P", "not_after": "2027-05-10", "use": "transport",
     "partners": [], "monitored": "scc-alert", "auto_renew": None,
     "stage": "prod", "owner": "00100316"},
    {"id": "CT05", "alias": "rkscc01 principal propagation CA", "kind": "ca-cert",
     "system": "SCC-RK-P", "not_after": "2028-03-01", "use": "transport",
     "partners": [], "monitored": "scc-alert", "auto_renew": None,
     "stage": "prod", "owner": "00100316"},
    {"id": "CT06", "alias": "auscc11 subaccount certificate", "kind": "client-cert",
     "system": "SCC-AU-NP", "not_after": "2026-12-12", "use": "transport",
     "partners": [], "monitored": "none", "auto_renew": False,
     "stage": "nonprod", "owner": None},
    {"id": "CT07", "alias": "s4p-app.calder.internal server certificate", "kind": "server-cert",
     "system": "S4P", "not_after": "2027-02-14", "use": "transport",
     "partners": [], "monitored": "none", "auto_renew": None,
     "stage": "prod", "owner": "00100316"},
]

def reviewed_registers():
    hops = {h["id"]: copy.deepcopy(h) for h in HOPS_DRAFT}
    hops["H01"].update(auth="client-cert", credential="sk-i10-ediprov",
                       inbound_role="Calder.I10.Send", certs=["CT09"])
    hops["H02"].update(auth="oauth-cc", credential="I10_S4P_OAUTH",
                       store="tenant-security-material", logs_all_headers=False)
    hops["H05"].update(auth="ssh-key", credential="calder_bank_sftp",
                       message_level="sign+encrypt", certs=["CT08"])
    hops["H06"].update(transport="sftp", auth="ssh-key", credential="calder_crm_sftp",
                       store="abap-secure-store")
    hops["H07"].update(transport="rfc-snc", auth="snc", credential="MES SNC PSE",
                       store="mes-pse")
    hops["H08"].update(auth="oauth-token-exchange", credential="calder-copilot-connector",
                       backend_user="the signed-in person")
    hops["H10"].update(store="encrypted-kvm", credential="calder-s4-orders",
                       exception={"approver": "00100290", "exit_by": "2027-06-30",
                                  "reason": "OAuth once the API artifact pilot is decided"})
    hops["H11"].update(auth="oauth-cc", credential="sk-i06-larkspur",
                       inbound_role="Calder.I06.Send", owner="00100322")
    certs = {c["id"]: copy.deepcopy(c) for c in CERTS_DRAFT}
    certs["CT01"].update(monitored="cloud-alm", partner_has_new=True)
    for cid in ("CT02", "CT03", "CT07"):
        certs[cid]["monitored"] = "cloud-alm"
    certs["CT03"].update(not_after="2027-12-15")  # Tessaly's renewed certificate
    certs["CT06"].update(auto_renew=True, monitored="scc-alert", owner="00100316")
    certs["CT07"].update(renewal_planned="2027-01-19")
    certs["CT08"] = {"id": "CT08", "alias": "bank PGP signing key", "kind": "pgp-public",
                     "system": "calder-int-prod", "not_after": "2027-03-31", "use": "message",
                     "partners": ["bank"], "monitored": "cloud-alm", "auto_renew": None,
                     "stage": "prod", "owner": "00100280"}
    certs["CT09"] = {"id": "CT09", "alias": "EDI provider client certificate", "kind": "partner-cert",
                     "system": "calder-int-prod", "not_after": "2027-11-02", "use": "transport",
                     "partners": ["EDI provider"], "monitored": "cloud-alm", "auto_renew": None,
                     "stage": "prod", "owner": "00100292"}
    # A store for the MES's SNC key is a PSE on the MES host, kept as approved.
    return {"as_of": AS_OF.isoformat(), "hops": list(hops.values()),
            "certs": [certs[k] for k in sorted(certs)]}

def draft_register():
    return {"as_of": AS_OF.isoformat(), "hops": copy.deepcopy(HOPS_DRAFT),
            "certs": copy.deepcopy(CERTS_DRAFT)}

# ---------------------------------------------------------------- the rules

def days_left(cert, as_of):
    return (date.fromisoformat(cert["not_after"]) - as_of).days

def review(reg):
    """Return a list of (subject, rule, level, text). Level is OK, WARN or FAIL."""
    as_of = date.fromisoformat(reg["as_of"])
    out = []
    certs = {c["id"]: c for c in reg["certs"]}
    users = {}
    for h in reg["hops"]:
        users.setdefault(h["credential"], []).append(h["id"])
    approved = APPROVED_STORES | {"mes-pse"}
    for h in reg["hops"]:
        s = h["id"]
        def add(rule, level, text):
            out.append((s, rule, level, text))
        # IS01 owner
        add("IS01", "OK" if h["owner"] else "FAIL",
            f"owner {h['owner']}" if h["owner"] else "no owner")
        # IS02 encrypted transport
        if h["transport"] in UNENCRYPTED and h["network"] != "private":
            add("IS02", "FAIL", f"{h['transport']} over {h['network']}: not encrypted")
        elif h["transport"] in UNENCRYPTED:
            add("IS02", "WARN", f"plain {h['transport']} on the private network; use SNC or TLS")
        else:
            add("IS02", "OK", f"{h['transport']} encrypted")
        # IS03 TLS version
        if h["tls"] is not None:
            add("IS03", "OK" if h["tls"] in ("1.2", "1.3") else "FAIL", f"TLS {h['tls']}")
        # IS04 authentication strength
        strength = STRENGTH[h["auth"]]
        if strength == 0:
            add("IS04", "FAIL", "no authentication")
        elif strength == 1 and h["network"] in ("internet", "cloud-connector"):
            ex = h.get("exception")
            if ex and ex.get("approver") and ex["approver"] != h["owner"] and ex.get("exit_by"):
                add("IS04", "WARN", f"{h['auth']} accepted by {ex['approver']} until {ex['exit_by']}: {ex['reason']}")
            else:
                add("IS04", "FAIL", f"{h['auth']} on a path to or from production; use a certificate or OAuth")
        elif strength == 1:
            note = f" (retires {h['retire']})" if h.get("retire") else ""
            add("IS04", "WARN", f"{h['auth']} on the private network{note}")
        else:
            add("IS04", "OK", h["auth"])
        # IS05 inbound role
        if h["inbound_role"]:
            if h["inbound_role"] == "ESBMessaging.send":
                add("IS05", "WARN", "generic role ESBMessaging.send; give the sender a custom role")
            else:
                add("IS05", "OK", f"custom role {h['inbound_role']}")
        # IS06 one credential per partner
        sharing = users[h["credential"]]
        if len(sharing) > 1:
            add("IS06", "FAIL", f"credential {h['credential']} shared with {', '.join(x for x in sharing if x != s)}")
        else:
            add("IS06", "OK", f"credential {h['credential']} used here only")
        # IS07 approved store
        add("IS07", "OK" if h["store"] in approved else "FAIL",
            f"secret kept in {h['store']}")
        # IS08 the person's identity reaches the back end
        if h["acts_for_user"]:
            if h["auth"] in ("principal-propagation", "oauth-saml-bearer", "oauth-token-exchange"):
                add("IS08", "OK", f"back end sees {h.get('backend_user', 'the user')}")
            else:
                add("IS08", "FAIL", f"acts for people but back end sees {h.get('backend_user', 'a technical user')}")
        # IS09 message-level security for payment or personal data
        if h["sensitivity"] in ("payment", "personal"):
            add("IS09", "OK" if h["message_level"] == "sign+encrypt" else "FAIL",
                f"{h['sensitivity']} data, message level: {h['message_level']}")
        # IS12 headers in the log
        if h["logs_all_headers"]:
            add("IS12", "FAIL", "logs all headers: the Authorization header lands in monitoring")
        # IS10 and IS11 are judged per certificate below.
        for cid in h["certs"]:
            if cid not in certs:
                add("IS10", "FAIL", f"{cid} named but not in the certificate list")
    for c in reg["certs"]:
        s = c["id"]
        def add(rule, level, text):
            out.append((s, rule, level, text))
        left = days_left(c, as_of)
        if left < 0:
            add("IS10", "FAIL", f"{c['alias']} expired {-left} days ago")
        elif left < 30:
            level = "FAIL" if c["stage"] == "prod" else "WARN"
            add("IS10", level, f"{c['alias']} expires in {left} days ({c['not_after']})")
        elif left < 60:
            add("IS10", "WARN", f"{c['alias']} expires in {left} days ({c['not_after']})")
        else:
            add("IS10", "OK", f"{c['alias']} valid {left} days")
        if c["kind"] == "sap-key-pair" and not c.get("partner_has_new") and left <= 60:
            add("IS10", "FAIL", f"SAP's new key is waiting; {', '.join(c['partners'])} not sent it yet")
        watched = c["monitored"] != "none" or c.get("auto_renew") is True
        if watched and c["owner"]:
            add("IS11", "OK", f"watched by {c['monitored']}, owner {c['owner']}")
        elif not c["owner"]:
            add("IS11", "FAIL", "no owner for the renewal")
        else:
            add("IS11", "FAIL", "nobody is alerted before it expires")
    return out

def print_review(reg, quiet=False):
    rows = review(reg)
    names = {h["id"]: h["name"] for h in reg["hops"]}
    names.update({c["id"]: c["alias"] for c in reg["certs"]})
    current = None
    for subject, rule, level, text in rows:
        if quiet and level == "OK":
            continue
        if subject != current:
            print(f"{subject}  {names[subject]}")
            current = subject
        print(f"  {level:<4} {rule}  {text}")
    counts = {k: sum(1 for r in rows if r[2] == k) for k in ("OK", "WARN", "FAIL")}
    print(f"{counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL "
          f"across {len(reg['hops'])} hops and {len(reg['certs'])} certificates")
    return counts

# ---------------------------------------------------------------- renewal calendar

LEAD = {"sap-key-pair": 60, "partner-cert": 45, "client-cert": 30, "ca-cert": 30,
        "server-cert": 30, "pgp-public": 45}

def calendar(reg, horizon):
    as_of = date.fromisoformat(reg["as_of"])
    hops_by_cert = {}
    for h in reg["hops"]:
        for cid in h["certs"]:
            hops_by_cert.setdefault(cid, []).append(h["id"])
    rows = []
    for c in reg["certs"]:
        end = date.fromisoformat(c["not_after"])
        start = end - timedelta(days=LEAD[c["kind"]])
        if start > as_of + timedelta(days=horizon):
            continue
        who = ", ".join(c["partners"]) or "internal only"
        silent = " (message level: no error at Calder when it expires; the partner's side decides)" \
            if c["use"] == "message" else ""
        rows.append((start, c, end, who, hops_by_cert.get(c["id"], []), silent))
    rows.sort(key=lambda r: r[0])
    for start, c, end, who, hops, silent in rows:
        late = "  LATE" if start < as_of else ""
        print(f"{start}  start  {c['id']} {c['alias']}{late}")
        print(f"            expires {end}, tell: {who}, hops: {', '.join(hops) or '-'}{silent}")
    print(f"{len(rows)} renewals start within {horizon} days of {as_of}")
    return rows

# ---------------------------------------------------------------- trace and simulations

def trace(reg, hop_id):
    h = next((x for x in reg["hops"] if x["id"] == hop_id), None)
    if h is None:
        print(f"No hop {hop_id}")
        return None
    print(f"{h['id']}  {h['name']}")
    print(f"  1 {h['from']} -> {h['to']} over {h['transport']} ({h['network']})")
    print(f"  2 proves itself with {h['auth']} ({h['credential']}, kept in {h['store']})")
    seen = h.get("backend_user", h["credential"])
    print(f"  3 the back end logs the call as: {seen}")
    if h["acts_for_user"]:
        if h["auth"] in ("principal-propagation", "oauth-saml-bearer", "oauth-token-exchange"):
            print("  4 a clerk reads order 1000002: allowed by the clerk's own roles")
            print("    a rep without channel 20 reads it: refused by the rep's own roles")
        else:
            print("  4 a clerk reads order 1000002: allowed, logged as " + seen)
            print("    a rep without channel 20 reads it: allowed, logged as " + seen)
    return seen

def simulate_expiry(reg, days):
    as_of = date.fromisoformat(reg["as_of"])
    events = []
    hops_by_cert = {}
    for h in reg["hops"]:
        for cid in h["certs"]:
            hops_by_cert.setdefault(cid, []).append(h["id"])
    for c in reg["certs"]:
        end = date.fromisoformat(c["not_after"])
        if c["kind"] == "sap-key-pair":
            switch = end - timedelta(days=1)  # SAP's job activates the new key one day before
            if switch <= as_of + timedelta(days=days):
                if c.get("partner_has_new"):
                    events.append((switch, c["id"], "SAP's new key activated; partners already trust it: no break"))
                else:
                    events.append((switch, c["id"], f"SAP's new key activated; {', '.join(c['partners'])} "
                                   f"still trust the old one: signed messages rejected on {', '.join(hops_by_cert.get(c['id'], []))}"))
            continue
        if end <= as_of + timedelta(days=days):
            if c.get("renewal_planned") and date.fromisoformat(c["renewal_planned"]) < end:
                events.append((date.fromisoformat(c["renewal_planned"]), c["id"],
                               "renewed as planned, partners told: no break"))
            elif c.get("auto_renew") is True:
                when = max(end - timedelta(days=30), as_of + timedelta(days=1))
                events.append((when, c["id"], "renewed automatically: no break"))
            elif c["use"] == "message":
                events.append((end, c["id"], f"{c['alias']} expired: no error at Calder; "
                               f"the partner may reject messages on {', '.join(hops_by_cert.get(c['id'], []))}"))
            else:
                events.append((end, c["id"], f"{c['alias']} expired: TLS handshakes fail on "
                               f"{', '.join(hops_by_cert.get(c['id'], [])) or 'its connections'}"))
    events.sort()
    for d, cid, text in events:
        print(f"{d}  {cid}  {text}")
    breaks = sum(1 for e in events if "no break" not in e[2])
    print(f"{breaks} breaks in the next {days} days with the plans in this register")
    return breaks

STATEMENT = ("STATEMENT;CP10;2026-11-27;account RRCB-0099-1104\n"
             "LINE;incoming;BRENNOCK WATER UTILITY;8648.75\n"
             "LINE;incoming;HFS HOLDINGS LLC;3777.19\n"
             "CLOSING;1482337.50\n")
LAB_KEY = b"calder-lab-signing-key"  # course value; a real key never sits in code

def sign(payload):
    return hmac.new(LAB_KEY, payload.encode("utf-8"), hashlib.sha256).hexdigest()

def simulate_tamper():
    signature = sign(STATEMENT)
    print("bank writes the statement and signs it")
    print(f"  signature {signature[:16]}...")
    changed = STATEMENT.replace("HFS HOLDINGS LLC;3777.19", "HFS HOLDINGS LLC;37771.90")
    print("file rests on the SFTP server, where TLS no longer protects it;")
    print("someone with access changes one amount: 3777.19 -> 37771.90")
    print("receiver with transport security only:")
    print("  SFTP session encrypted: OK -> statement loaded, cash overstated by 33994.71")
    ok = hmac.compare_digest(sign(changed), signature)
    print("receiver that verifies the signature:")
    print(f"  signature matches: {ok} -> " + ("loaded" if ok else "rejected, treasury alerted"))
    return ok

def simulate_leak(reg, credential):
    hit = [h for h in reg["hops"] if h["credential"] == credential]
    if not hit:
        print(f"No hop uses {credential}")
        return 0
    print(f"{credential} leaked. Exposed hops:")
    for h in hit:
        print(f"  {h['id']}  {h['name']}")
    parties = sorted({h["from"] for h in hit} | {h["to"] for h in hit})
    print(f"Rotating it means coordinating {len(parties)} parties: {', '.join(parties)}")
    return len(hit)

# ---------------------------------------------------------------- files and self-test

def write_init():
    FOLDER.mkdir(parents=True, exist_ok=True)
    for name, reg in (("register_draft.json", draft_register()),
                      ("register_reviewed.json", reviewed_registers())):
        (FOLDER / name).write_text(json.dumps(reg, indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {FOLDER / name}")

def load(path):
    p = Path(path)
    if not p.exists():
        sys.exit(f"{p} not found. Run: python unit26/intsec_lab.py --init")
    return json.loads(p.read_text(encoding="utf-8"))

def counts_of(reg):
    rows = review(reg)
    return tuple(sum(1 for r in rows if r[2] == k) for k in ("OK", "WARN", "FAIL"))

def self_test():
    import io
    import contextlib
    checks = []
    d, r = draft_register(), reviewed_registers()
    checks.append(("draft counts", counts_of(d) == (54, 7, 24)))
    checks.append(("reviewed counts", counts_of(r) == (83, 4, 0)))
    rules = {x[1] for x in review(d) if x[2] == "FAIL"}
    checks.append(("draft fails IS02", "IS02" in rules))
    checks.append(("draft fails IS06", "IS06" in rules))
    checks.append(("draft fails IS08", "IS08" in rules))
    checks.append(("draft fails IS09", "IS09" in rules))
    checks.append(("draft fails IS12", "IS12" in rules))
    with contextlib.redirect_stdout(io.StringIO()):
        checks.append(("draft breaks in 120 days", simulate_expiry(d, 120) == 4))
        checks.append(("reviewed breaks in 120 days", simulate_expiry(r, 120) == 0))
        checks.append(("tamper rejected", simulate_tamper() is False))
        checks.append(("leak hits two hops", simulate_leak(d, "CPI_INBOUND") == 2))
        checks.append(("trace draft H08", trace(d, "H08") == "TU_COPILOT_MCP"))
        checks.append(("trace reviewed H08", trace(r, "H08") == "the signed-in person"))
        checks.append(("calendar draft", len(calendar(d, 120)) == 4))
    passed = sum(1 for _, ok in checks if ok)
    for name, ok in checks:
        if not ok:
            print(f"  failed: {name}")
    print(f"{passed} of {len(checks)} self-test checks passed")
    return passed == len(checks)

def main():
    ap = argparse.ArgumentParser(description="Integration security lab (course)")
    ap.add_argument("--init", action="store_true", help="write the sample registers")
    ap.add_argument("--self-test", action="store_true", help="check the built-in samples")
    ap.add_argument("command", nargs="?", choices=["review", "calendar", "trace", "simulate"])
    ap.add_argument("arg", nargs="?", help="hop ID for trace; expiry, tamper or leak for simulate")
    ap.add_argument("extra", nargs="?", help="credential name for simulate leak")
    ap.add_argument("--file", default=str(FOLDER / "register_draft.json"))
    ap.add_argument("--days", type=int, default=120)
    ap.add_argument("--quiet", action="store_true", help="show only WARN and FAIL lines")
    a = ap.parse_args()
    if a.init:
        write_init()
    elif a.self_test:
        sys.exit(0 if self_test() else 1)
    elif a.command == "review":
        counts = print_review(load(a.file), a.quiet)
        sys.exit(2 if counts["FAIL"] else 0)
    elif a.command == "calendar":
        calendar(load(a.file), a.days)
    elif a.command == "trace":
        trace(load(a.file), a.arg or "H08")
    elif a.command == "simulate":
        reg = load(a.file)
        if a.arg == "expiry":
            simulate_expiry(reg, a.days)
        elif a.arg == "tamper":
            simulate_tamper()
        elif a.arg == "leak":
            simulate_leak(reg, a.extra or "CPI_INBOUND")
        else:
            print("Choose: simulate expiry | simulate tamper | simulate leak <credential>")
    else:
        ap.print_help()

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

#### Step 3: Write the registers and check them

1. Write the two registers:

   ```bash
   python unit26/intsec_lab.py --init
   ```

   ```text
   Wrote unit26/intsec/register_draft.json
   Wrote unit26/intsec/register_reviewed.json
   ```

2. Run the self-test:

   ```bash
   python unit26/intsec_lab.py --self-test
   ```

   ```text
   14 of 14 self-test checks passed
   ```

3. Open `unit26/intsec/register_draft.json` in VS Code. Each hop has its proof (`auth`), the secret's name (`credential`) and where it is kept (`store`), its owner, and the certificates it relies on. Each certificate has its expiry date (`not_after`), who must be told on renewal (`partners`) and how it is watched (`monitored`).

> **Note** The registers describe the fictional Calder and use course dates relative to Monday 2026-11-30, fixed in the script as `AS_OF`. They show the method, not a real landscape.

#### Step 4: Review the draft register

1. Run the review, showing only findings:

   ```bash
   python unit26/intsec_lab.py review --quiet
   ```

   ```text
   H01  EDI provider sends distributor orders to Cloud Integration
     FAIL IS04  basic on a path to or from production; use a certificate or OAuth
     WARN IS05  generic role ESBMessaging.send; give the sender a custom role
     FAIL IS06  credential CPI_INBOUND shared with H11
   H02  Cloud Integration creates sales orders in S4P
     FAIL IS04  basic on a path to or from production; use a certificate or OAuth
     FAIL IS07  secret kept in iflow
     FAIL IS12  logs all headers: the Authorization header lands in monitoring
   H05  Cloud Integration fetches bank statements by SFTP
     FAIL IS04  password on a path to or from production; use a certificate or OAuth
     FAIL IS09  payment data, message level: none
   H06  S4P report puts open order items for the CRM
     FAIL IS02  ftp over internet: not encrypted
     FAIL IS04  password on a path to or from production; use a certificate or OAuth
   H07  Rockford MES reads production orders by RFC
     WARN IS02  plain rfc on the private network; use SNC or TLS
     WARN IS04  password on the private network
     FAIL IS07  secret kept in mes-config-file
   H08  Copilot Studio agent reads sales orders through Calder's MCP server
     FAIL IS04  api-key on a path to or from production; use a certificate or OAuth
     FAIL IS08  acts for people but back end sees TU_COPILOT_MCP
   H09  Augsburg ECC sends impeller lot statuses to S4P by SOAP
     WARN IS04  basic on the private network (retires 2027-07-05)
   H10  API Management calls the sales order API for distributors
     FAIL IS04  basic on a path to or from production; use a certificate or OAuth
     FAIL IS07  secret kept in proxy-policy
   H11  Larkspur posts shipment status to Cloud Integration
     FAIL IS01  no owner
     FAIL IS04  basic on a path to or from production; use a certificate or OAuth
     WARN IS05  generic role ESBMessaging.send; give the sender a custom role
     FAIL IS06  credential CPI_INBOUND shared with H01
   CT01  sap_cloudintegrationcertificate
     WARN IS10  sap_cloudintegrationcertificate expires in 52 days (2027-01-21)
     FAIL IS10  SAP's new key is waiting; Hallam, Tessaly not sent it yet
     FAIL IS11  nobody is alerted before it expires
   CT02  HALLAMFS-AS2
     FAIL IS11  nobody is alerted before it expires
   CT03  TESSALYFP-AS2
     FAIL IS10  TESSALYFP-AS2 expires in 15 days (2026-12-15)
     FAIL IS11  nobody is alerted before it expires
   CT06  auscc11 subaccount certificate
     WARN IS10  auscc11 subaccount certificate expires in 12 days (2026-12-12)
     FAIL IS11  no owner for the renewal
   CT07  s4p-app.calder.internal server certificate
     FAIL IS11  nobody is alerted before it expires
   54 OK, 7 WARN, 24 FAIL across 11 hops and 7 certificates
   ```

   Without `--quiet`, the review also prints every `OK` line. The exit code is `2` because there are failures.

2. Read the rules behind the findings:

   | Rule | Checks | Basis |
   | --- | --- | --- |
   | IS01 | Every hop names an owner | Course rule |
   | IS02 | Transport is encrypted; plain FTP, HTTP or RFC across networks fails, plain RFC inside warns | SAP: prefer encrypted protocols; Cloud Connector supports RFC with SNC |
   | IS03 | TLS 1.2 or 1.3 | SAP: Cloud Integration supports TLS 1.2 and 1.3 |
   | IS04 | No password or API key on paths to or from production, unless accepted in writing by someone other than the owner, with an end date | SAP: avoid basic in production; the exception form is a course rule |
   | IS05 | Inbound senders get a custom role, not `ESBMessaging.send` | SAP guideline |
   | IS06 | One credential per hop | Course rule |
   | IS07 | Secrets only in approved stores | SAP: security material, encrypted key value maps; the list is a course rule |
   | IS08 | A hop that acts for people passes their identity | Course rule, after SAP's principal propagation |
   | IS09 | Payment or personal data is signed and encrypted at message level | SAP guideline on message-level security; the trigger is a course rule |
   | IS10 | Certificates more than 60 days from expiry; under 30 days fails in production; SAP's new key sent to partners | SAP's 60-day window; thresholds are course rules |
   | IS11 | Every certificate has an owner and an alert or automatic renewal | Course rule, after Cloud ALM and Cloud Connector alerting |
   | IS12 | No integration flow logs all headers | SAP guideline on sensitive content |

#### Step 5: Plan the renewals

1. Print the renewal calendar for the next 120 days:

   ```bash
   python unit26/intsec_lab.py calendar
   ```

   ```text
   2026-10-31  start  CT03 TESSALYFP-AS2  LATE
               expires 2026-12-15, tell: Tessaly, hops: H04 (message level: no error at Calder when it expires; the partner's side decides)
   2026-11-12  start  CT06 auscc11 subaccount certificate  LATE
               expires 2026-12-12, tell: internal only, hops: -
   2026-11-22  start  CT01 sap_cloudintegrationcertificate  LATE
               expires 2027-01-21, tell: Hallam, Tessaly, hops: H03, H04 (message level: no error at Calder when it expires; the partner's side decides)
   2027-01-15  start  CT07 s4p-app.calder.internal server certificate
               expires 2027-02-14, tell: internal only, hops: H02, H10
   4 renewals start within 120 days of 2026-11-30
   ```

2. Read it. Three renewals should already have started. The lead times are course values: 60 days for SAP's own key (SAP's window), 45 for partner certificates and PGP keys, 30 for internal ones.

#### Step 6: Watch what breaks if nobody acts

1. Simulate the next 120 days:

   ```bash
   python unit26/intsec_lab.py simulate expiry
   ```

   ```text
   2026-12-12  CT06  auscc11 subaccount certificate expired: TLS handshakes fail on its connections
   2026-12-15  CT03  TESSALYFP-AS2 expired: no error at Calder; the partner may reject messages on H04
   2027-01-20  CT01  SAP's new key activated; Hallam, Tessaly still trust the old one: signed messages rejected on H03, H04
   2027-02-14  CT07  s4p-app.calder.internal server certificate expired: TLS handshakes fail on H02, H10
   4 breaks in the next 120 days with the plans in this register
   ```

2. Note the 2027-01-20 line. SAP's job switches the key one day before expiry, as SAP documents, so Calder's tenant keeps working. The break is at Hallam and Tessaly, who still trust the old certificate.

#### Step 7: See whose identity reaches SAP

1. Trace the Copilot Studio hop:

   ```bash
   python unit26/intsec_lab.py trace H08
   ```

   ```text
   H08  Copilot Studio agent reads sales orders through Calder's MCP server
     1 Copilot Studio agent -> S4P via MCP server over https (internet)
     2 proves itself with api-key (CALDER_MCP_API_KEY, kept in credential-store)
     3 the back end logs the call as: TU_COPILOT_MCP
     4 a clerk reads order 1000002: allowed, logged as TU_COPILOT_MCP
       a rep without channel 20 reads it: allowed, logged as TU_COPILOT_MCP
   ```

2. Trace the same hop in the reviewed register:

   ```bash
   python unit26/intsec_lab.py trace H08 --file unit26/intsec/register_reviewed.json
   ```

   ```text
   H08  Copilot Studio agent reads sales orders through Calder's MCP server
     1 Copilot Studio agent -> S4P via MCP server over https (internet)
     2 proves itself with oauth-token-exchange (calder-copilot-connector, kept in credential-store)
     3 the back end logs the call as: the signed-in person
     4 a clerk reads order 1000002: allowed by the clerk's own roles
       a rep without channel 20 reads it: refused by the rep's own roles
   ```

   The [Copilot Studio topic](https://erpfde.com/topics/microsoft-copilot-studio-and-azure-with-sap/) builds this difference as a running MCP server with lab tokens.

#### Step 8: See why message-level security exists

1. Simulate a changed bank statement:

   ```bash
   python unit26/intsec_lab.py simulate tamper
   ```

   ```text
   bank writes the statement and signs it
     signature e520126846f20fff...
   file rests on the SFTP server, where TLS no longer protects it;
   someone with access changes one amount: 3777.19 -> 37771.90
   receiver with transport security only:
     SFTP session encrypted: OK -> statement loaded, cash overstated by 33994.71
   receiver that verifies the signature:
     signature matches: False -> rejected, treasury alerted
   ```

> **Note** The signature here is an HMAC with a lab key, a stand-in. Real message-level security uses public-key signatures (PGP or PKCS#7/CMS): the bank signs with its private key and Calder verifies with the bank's public key, so Calder never holds a secret that could forge one. The statement and amounts are synthetic.

#### Step 9: See why one credential per partner exists

1. Simulate a leak of the shared inbound user:

   ```bash
   python unit26/intsec_lab.py simulate leak CPI_INBOUND
   ```

   ```text
   CPI_INBOUND leaked. Exposed hops:
     H01  EDI provider sends distributor orders to Cloud Integration
     H11  Larkspur posts shipment status to Cloud Integration
   Rotating it means coordinating 3 parties: Cloud Integration calder-int-prod, EDI provider, Larkspur Freight Lines
   ```

#### Step 10: Review the corrected register

1. Run the review on the reviewed register:

   ```bash
   python unit26/intsec_lab.py review --quiet --file unit26/intsec/register_reviewed.json
   ```

   ```text
   H09  Augsburg ECC sends impeller lot statuses to S4P by SOAP
     WARN IS04  basic on the private network (retires 2027-07-05)
   H10  API Management calls the sales order API for distributors
     WARN IS04  basic accepted by 00100290 until 2027-06-30: OAuth once the API artifact pilot is decided
   CT01  sap_cloudintegrationcertificate
     WARN IS10  sap_cloudintegrationcertificate expires in 52 days (2027-01-21)
   CT06  auscc11 subaccount certificate
     WARN IS10  auscc11 subaccount certificate expires in 12 days (2026-12-12)
   83 OK, 4 WARN, 0 FAIL across 11 hops and 9 certificates
   ```

2. Run the expiry simulation on it:

   ```bash
   python unit26/intsec_lab.py simulate expiry --file unit26/intsec/register_reviewed.json
   ```

   ```text
   2026-12-01  CT06  renewed automatically: no break
   2027-01-19  CT07  renewed as planned, partners told: no break
   2027-01-20  CT01  SAP's new key activated; partners already trust it: no break
   0 breaks in the next 120 days with the plans in this register
   ```

3. Compare the two files in VS Code. The fixes, hop by hop:

   | Hop or certificate | Draft | Reviewed |
   | --- | --- | --- |
   | H01 | shared basic user, generic role | the EDI provider's own client certificate (`CT09`), role `Calder.I10.Send` |
   | H02 | password in a header, all headers logged | OAuth client credentials `I10_S4P_OAUTH` in security material, allow-list logging |
   | H05 | SFTP password, unsigned statements | SSH key, statements signed and encrypted with PGP (`CT08`) |
   | H06 | plain FTP | SFTP with a key |
   | H07 | plain RFC, password in a config file | SNC, with the MES's key in its own PSE |
   | H08 | shared API key | OAuth token exchange, the person's identity reaches SAP |
   | H10 | password in the proxy policy | encrypted key value map, basic accepted by the enterprise architect until 2027-06-30 |
   | H11 | shared user, no owner | its own OAuth client, role `Calder.I06.Send`, owner `00100322` |
   | CT01 | partners not told | partners have the new certificate, Cloud ALM watches |
   | CT03 | expires in 15 days | Tessaly's renewed certificate to 2027-12-15 |
   | CT06 | no owner, automatic renewal off | owner `00100316`, automatic renewal on |
   | CT07 | nobody watches | Cloud ALM, renewal planned for 2027-01-19 |

   The remaining warnings are accepted: H09 retires with the July 2027 rollout, H10 has a signed exception, CT01 is in SAP's renewal window with partners ready, and CT06 renews on the next job run.

#### Step 11 (sketch): Apply it to your landscape

> **Note** This step is a **sketch**. It needs an SAP Integration Suite tenant with the Integration Developer or tenant administrator role, which the [Unit 26 setup](https://erpfde.com/topics/set-up-for-unit-26/) trial gives you.

1. In the Integration Suite, open **Monitor > Integrations and APIs** and, under **Manage Security**, open **Keystore**. List every entry with its alias and expiry date; check the **New SAP Keys** tab.
2. Open **Security Material** and list every credential with its type.
3. For each integration flow, note which credential and which key alias each adapter uses, and which role each sender adapter requires.
4. Write these into your own `register.json` in the lab's format and run the review. Every `FAIL` is a backlog item with an owner.

#### Step 12: Save your work

```bash
git add unit26/intsec_lab.py unit26/intsec/
git commit -m "Unit 26: integration security register and renewal calendar"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `HOPS_DRAFT`, `CERTS_DRAFT` | Calder's connections and certificates as the partner found them |
| `reviewed_registers()` | Copies the draft and applies the fixes, so the two registers stay in step |
| `STRENGTH`, `APPROVED_STORES` | Course scales for proof strength and where secrets may live |
| `review()` | Applies rules IS01 to IS12 to each hop and certificate and returns findings |
| `calendar()` | Subtracts a lead time from each expiry and lists who to tell and which hops depend on it |
| `simulate_expiry()` | Walks the days ahead: SAP's one-day-early activation, automatic renewals, planned renewals and plain expiries |
| `trace()` | Prints the hop's proof and which user the back end sees |
| `simulate_tamper()` | Signs a statement with an HMAC stand-in, changes it at rest, and verifies |
| `simulate_leak()` | Lists every hop and party that one leaked credential touches |
| `self_test()` | Checks counts and outcomes against the expected samples |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your path, or the environment isn't on | Turn on `.venv` (Step 1); on macOS/Linux try `python3` |
| `No module named ...` | You pasted part of the script, or an older Python | Paste the whole script again; the lab needs Python 3.9 or newer and no libraries |
| `register_draft.json not found` | `--init` hasn't run in this folder | Run `python unit26/intsec_lab.py --init` from `orchestrate-course` |
| Your counts differ from the samples | You edited a register, or the script differs | Run `--init` again to rewrite the registers; compare the script |
| `json.decoder.JSONDecodeError` | A comma or bracket went missing while editing a register | VS Code underlines the error; fix it or run `--init` |
| The review exits with code `2` | At least one rule failed | Expected for the draft; read the `FAIL` lines |
| A network or proxy message | The lab doesn't use the network | Nothing to fix: the message comes from something else in your terminal |

### The SAP way

As of November 2026, these are the SAP pieces an architect configures, with what each is for:

| Need | SAP piece | Notes |
| --- | --- | --- |
| Authenticate senders to Cloud Integration | Service instance of Process Integration Runtime, plan `integration-flow`, one service key per sender with client credentials or a certificate | Use a custom role per scenario, per SAP's guideline |
| Authenticate Cloud Integration to receivers | Adapter credential: user credentials, OAuth2 client credentials, OAuth2 SAML bearer assertion, OAuth2 authorization code, client certificate by key alias, principal propagation | Set Private Key Alias for client certificates |
| Keep keys and trust | Tenant keystore (SAP-owned and your entries) | SAP renews its key yearly; you tell partners |
| Keep passwords and tokens | Security material, secure parameters, PGP keyrings, SSH known hosts | Referenced by name from flows |
| Protect content | Encryptor, Decryptor, Signer, Verifier steps; WS-Security in the SOAP adapter; Message Digest for integrity of selected elements | Partner must support the standard |
| Watch certificates | SAP Cloud ALM health monitoring; Cloud Connector alerting | Route alerts to a person |
| Reach the network | Cloud Connector with TLS or SNC to the back end; principal propagation with short-lived certificates | Secure setup recommendations, Security Status view |
| Secrets for BTP apps | Bindings and SAP Credential Store | See [bindings](https://erpfde.com/topics/btp-services-and-bindings/) |

Related topics cover the neighbors: [API Management](https://erpfde.com/topics/api-management-in-depth/) for API keys, OAuth policies and encrypted key value maps; [B2B and EDI](https://erpfde.com/topics/b2b-and-edi-integration/) for AS2 certificates in partner agreements; [RFC and BAPI](https://erpfde.com/topics/rfc-and-bapi-in-depth/) for SNC and the `S_RFC` authorization; [SOAP and OData](https://erpfde.com/topics/soap-and-odata-services-in-depth/) for WS-Security; [Edge Integration Cell](https://erpfde.com/topics/edge-integration-cell/) for keys you operate yourself in a customer-managed runtime.

> **Note** ECC and SAP Process Orchestration landscapes keep certificates in the ABAP and Java systems' own stores, and RFC uses SNC configured per system. The register method is the same; the stores and the people are different.

### Build vs. SAP

| Concern | Build it yourself | Use SAP's piece | Choose |
| --- | --- | --- | --- |
| Register of connections and certificates | A JSON or spreadsheet register reviewed in a pipeline, like the lab | No single SAP register spans all hops | Build the register; feed it from SAP's monitors |
| Certificate alerts | A scheduled script reading expiry dates | Cloud ALM health monitoring, Cloud Connector alerting | SAP's alerts, routed to named owners |
| Secret storage | A vault you run | Security material, Credential Store, encrypted key value maps | SAP's stores; a vault only for non-SAP runtimes |
| Message signing | Code in each app | Cloud Integration steps, AS2, WS-Security | SAP's steps where the flow runs in Integration Suite |
| User identity across hops | Custom token handling | Principal propagation, OAuth SAML or JWT bearer | SAP's; custom only where no SAP route exists |

### Architecture view

**Where it sits.** Every hop in Calder's landscape crosses at least one trust boundary: partners and carriers to Cloud Integration over the internet, Cloud Integration and API Management to `S4P` through the Cloud Connector `SCC-RK-P`, Augsburg's ECC and the Rockford MES to `S4P` on the private network, and agents to `S4P` through an MCP server.

```mermaid
flowchart LR
  subgraph Internet
    EP[EDI provider] ; HL[Hallam AS2] ; TS[Tessaly AS2] ; LK[Larkspur] ; BK[Bank SFTP] ; CP[Copilot Studio agent]
  end
  subgraph BTP[SAP BTP]
    CI[Cloud Integration<br/>keystore + security material] ; AM[API Management] ; MCP[MCP server]
  end
  subgraph Calder[Calder network]
    SCC[Cloud Connector SCC-RK-P] ; S4P[S/4HANA S4P] ; MES[Rockford MES] ; ECP[ECC ECP]
  end
  EP & HL & TS & LK -- cert or OAuth --> CI
  CI -- SSH key + PGP --> BK
  CP -- token exchange --> MCP
  CI & AM & MCP --> SCC -- TLS / SNC --> S4P
  MES -- SNC --> S4P
  ECP -- HTTPS --> S4P
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Certificate renewal lead time | Started 60 days before expiry for partner-facing keys | A partner rejects messages on a fixed date |
| Secret rotation | Any one credential rotated within a day, touching one partner | A leak takes several partners down together |
| Identity in the audit log | Person-level for every hop that acts for people | Nobody can say who read or changed data |
| Transport | TLS 1.2 or 1.3; SNC for RFC | Credentials and data readable on the wire |
| Content protection | Signed and encrypted for payment and personal data | Tampered or exposed files go undetected |

**Integration and identity.** Technical jobs authenticate with OAuth client credentials or certificates per partner, each with its own role. Hops that act for people pass the person's identity through principal propagation or token exchange, so `S4P` applies that person's roles. Secrets live in security material, encrypted key value maps, bindings or the Credential Store, referenced by name.

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

- **Context:** Calder's integration tenant receives messages from an EDI provider, distributors and carriers. Two senders share one basic user with `ESBMessaging.send`.
- **Options:** (a) a basic user per sender; (b) OAuth client credentials per sender; (c) a client certificate per sender where the sender can manage one, OAuth client credentials otherwise.
- **Decision:** (c). One service key per sender, each instance with a custom role per scenario. No basic authentication inbound.
- **Consequences:** Certificates join the renewal calendar with an owner and a Cloud ALM alert. Onboarding a sender needs a certificate exchange or an OAuth client, which takes a day longer than a password. A leak affects one sender.

**What a design review will ask.**

1. Which connections still use passwords, and when does each stop?
2. Who renews each certificate, and who tells each partner?
3. For each hop that acts for people, whose identity does SAP see?
4. What content is signed and encrypted at message level, and why that and not more?
5. How long does it take to rotate one credential, and how many parties does it touch?

### Production concerns

- **Authorizations.** Limit who can read or change security material and the keystore. SAP flags `MessagePayloadsRead` and `DataStorePayloadsRead` as roles that expose message content, and recommends access policies to restrict integration content ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/recommendations-for-tasks-and-permissions-2986851.md)). Unit 27 covers the SAP authorization concept behind back-end technical users.
- **Operations.** Treat a renewal like a change: date, partner contacts, test the morning after. Route certificate alerts like interface errors, to a named owner, as the [interface monitoring topic](https://erpfde.com/topics/interface-monitoring-and-error-handling/) sets out. Keep the Cloud Connector's audit log on in production and restrict access to its machine, as SAP recommends.
- **Evaluation.** Run the register review in a pipeline; a `FAIL` blocks the change that introduced it.
- **Cost.** The work is people's time: certificate exchanges and partner coordination. Budget it per partner per year.
- **Clean core.** Security fixes live outside the core: in Integration Suite, the Cloud Connector and identity services. Avoid custom RFC modules that bypass released APIs and their authorizations; the [RFC topic](https://erpfde.com/topics/rfc-and-bapi-in-depth/) shows the replacements.

### Where AI fits

- **Agents are one more consumer, with a new rule.** An agent acting for people must carry their identity to SAP; a shared key turns it into a privileged back door. The [agent permissions topic](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) and [MCP security lessons](https://erpfde.com/topics/mcp-security-lessons-2026/) go deeper.
- **AI helps build the register.** A model can read exported flow and proxy configurations and draft the register's lines; the review rules, not the model, decide what passes. Never paste keystore exports or security material into an AI tool.
- **AI in Integration Suite** generates flows and mappings ([topic](https://erpfde.com/topics/ai-in-sap-integration-suite/)); review what it generates against the same rules, especially credentials in headers and header logging.

### Pitfalls

- **Watching only transport certificates.** Message-level keys expire silently at your end. Put them on the same calendar.
- **Letting SAP's automatic activation be the plan.** It keeps your tenant running and breaks partners who weren't told.
- **One inbound user for everyone.** It feels simpler until the first leak or the first partner offboarding.
- **Secrets in flows, policies and parameters.** They travel with every transport and export. Move them to security material and rotate them, since they were exposed.
- **Logging all headers while debugging.** The `Authorization` header goes to monitoring, readable by more people than you think.
- **Trusting an uploaded root certificate.** The keystore doesn't check it. Verify the fingerprint with its owner.
- **Treating SFTP as content protection.** It isn't, once the file is on disk.
- **Exceptions without end dates.** "Accepted" with no date and no approver is just a finding nobody owns.

### Exercise

Add a rule and a hop: Calder's buyer wants Ridgeline's monthly price list (interface `I16` from the [file interfaces topic](https://erpfde.com/topics/file-and-batch-interfaces/)) fetched by SFTP, and you add a rule that every SFTP server's host key is pinned in the tenant's known hosts, as SAP's guidance on known hosts files suggests.

1. In `unit26/intsec_lab.py`, inside `review()`, find the line `# IS08 the person's identity reaches the back end` and paste these lines just above it, at the same indentation:

   ```python
           # IS13 SFTP servers pinned in the known hosts file
           if h["transport"] == "sftp":
               pinned = h.get("known_host", False)
               add("IS13", "OK" if pinned else "FAIL",
                   "server host key pinned in known hosts" if pinned else "server host key not pinned")
   ```

2. Open `unit26/intsec/register_reviewed.json`. In hops `H05` and `H06`, add `"known_host": true,` on a new line after `"owner": ...,`.
3. Add a new hop at the end of the `"hops"` list (put a comma after the closing brace of `H11` first):

   ```json
   {"id": "H12", "interface": "I16", "name": "Cloud Integration fetches Ridgeline's monthly price list by SFTP",
    "from": "Cloud Integration calder-int-prod", "to": "Ridgeline SFTP server", "network": "internet",
    "transport": "sftp", "tls": null, "auth": "ssh-key", "credential": "calder_ridgeline_sftp",
    "store": "tenant-security-material", "inbound_role": null, "acts_for_user": false,
    "sensitivity": "normal", "message_level": "none", "logs_all_headers": false,
    "owner": "00100211", "certs": [], "known_host": false}
   ```

4. Run the review:

   ```bash
   python unit26/intsec_lab.py review --quiet --file unit26/intsec/register_reviewed.json
   ```

   The last line reads `90 OK, 4 WARN, 1 FAIL across 12 hops and 9 certificates`, with `FAIL IS13  server host key not pinned` under H12.
5. Ridgeline confirms its host key fingerprint by phone. Change `"known_host": false` to `true` in H12 and run the review again.

**Done when:** the review of the reviewed register prints `91 OK, 4 WARN, 0 FAIL across 12 hops and 9 certificates`, with three `OK IS13` lines (H05, H06, H12). The register and its review feed the interface inventory and operating model later in the course.

### Check yourself

1. Why does SAP rank basic authentication low even when the connection uses TLS?
   - A. TLS can't carry an Authorization header at all
   - B. Basic authentication only works over plain HTTP
   - C. The password can surface where TLS ends
   - D. Cloud Integration refuses basic logons from outside

   Answer: C. TLS protects only between two points and ends at intermediate hops, where a password can reach logs or monitoring tools. Passwords are also open to brute force and lockouts. Cloud Integration still offers basic authentication; SAP advises against it in production.

2. How does Cloud Integration decide that an inbound caller with a client certificate may run a flow?
   - A. It looks up the certificate's subject in the S/4HANA user master list
   - B. It finds the service key with that certificate and checks its role
   - C. It accepts any certificate signed by a CA the load balancer trusts
   - D. It compares the certificate to the flow's sender address

   Answer: B. The sender's certificate is stored in a service key of plan integration-flow. At runtime Cloud Integration finds that key and checks that its instance carries the role named in the sender adapter. A trusted CA alone isn't enough.

3. Calder's tenant signs AS2 messages with SAP's key, which expires on 2027-01-21. Nobody acts. What happens?
   - A. The tenant stops signing and AS2 traffic halts at Calder
   - B. SAP sends the new certificate to Calder's partners directly
   - C. Nothing, because AS2 signatures don't use the tenant's key
   - D. SAP's job switches keys; partners reject until they get it

   Answer: D. SAP prepares the new key 60 days ahead and a daily job activates it one day before expiry. The tenant keeps working. Partners who still trust the old certificate reject the newly signed messages, so telling them is Calder's job.

4. Why does the lab put message-level keys on the same renewal calendar as TLS certificates?
   - A. Nothing at your end checks their expiry
   - B. Message-level keys always expire before TLS certificates
   - C. SAP renews message-level keys only if they are on a calendar
   - D. TLS certificates can't be monitored in SAP Cloud ALM

   Answer: A. SAP notes that expiry isn't checked in the signing and encryption steps, so an expired key keeps working at Calder and the failure appears at the partner. Only a calendar with an owner catches it.

5. The bank statement hop uses SFTP. What does adding a PGP signature protect that SFTP doesn't?
   - A. The password used to log on to the SFTP server
   - B. The speed of the transfer between bank and tenant
   - C. The file's content while it rests on the server
   - D. The host key of the bank's SFTP server

   Answer: C. SFTP encrypts the session, not the file at rest. A signature over the content lets the receiver detect any change, so the tampered statement in Step 8 is rejected instead of loaded.

6. In the draft, a Copilot Studio agent calls SAP with one API key. What does the trace show is wrong?
   - A. The key is stored in SAP Credential Store, which agents can't read
   - B. The call crosses the internet without TLS
   - C. The agent can't reach S4P without principal propagation
   - D. SAP logs every person as TU_COPILOT_MCP and applies its roles

   Answer: D. With one key, SAP sees one technical user, so a rep reads orders their own roles would refuse and the log can't say who acted. Token exchange lets SAP see and check the person.

7. What would you do if two inbound senders share one service key with ESBMessaging.send?
   - A. Keep the key and rotate its secret every month
   - B. Give each sender its own key and a custom role
   - C. Move both senders to basic users with strong passwords
   - D. Add an IP filter to the shared key and keep it

   Answer: B. One key per sender limits a leak, and its rotation, to that sender. A custom role per scenario stops a sender's key from calling flows it shouldn't, as SAP's guideline advises against the generic role.

8. The API Management hop keeps basic authentication in the reviewed register. Why is it a WARN, not a FAIL?
   - A. The password moved to an encrypted key value map, which is enough
   - B. Basic authentication is allowed for API Management by SAP
   - C. An approver other than the owner accepted it until 2027-06-30
   - D. The hop runs on the private network through the Cloud Connector

   Answer: C. The course rule turns the finding into a warning only with a written exception: a different approver, a reason and an end date. Moving the secret fixed IS07, but basic authentication on a production path still needs the exception.

## Sources

- [Adapters Authentication Methods (SAP Integration Suite documentation, SAP-docs on GitHub, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/adapters-authentication-methods-9f7cf82.md): Per-adapter table of sender and receiver authentication methods; HTTPS, IDoc, AS2 and AS4 senders offer client certificate (recommended), OAuth with client credentials grant (recommended) and basic; always use TLS where possible; client certificates usually give the highest security but expire and need rotation; avoid Basic or None in production
- [Use Secure Authentication Methods (SAP Integration Suite design guidelines, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/use-secure-authentication-methods-3d46d45.md): Methods listed roughly from low to high security: None, Basic, Principal Propagation, SASL, OAuth, Client Certificate, Public Key; basic passwords can be read where TLS is terminated, can be brute-forced and lock users; OAuth exchanges secrets only with the authorization server and tokens are short-lived; inbound to Cloud Integration is always authenticated; avoid generic user roles for sender authorization and create a custom role
- [Security Aspects of Data, Data Flow for Cloud Integration (SAP-docs on GitHub, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/60-Security/security-aspects-of-data-data-flow-for-cloud-integration-7895724.md): TLS 1.2 and 1.3 supported inbound and outbound; symmetric keys at least 128 bits, SAP's asymmetric keys 2048 bits by default; mTLS equals client certificate authentication; HTTP receiver URLs possible but not recommended; basic authentication not recommended in production because credentials can become visible where TLS terminates, e.g. load balancers; SFTP with password or public key, SSH 2
- [Keystore (SAP Integration Suite documentation, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/keystore-b163513.md): One keystore per tenant for transport- and message-level keys; if a server trusts several key pairs one is chosen at random unless Private Key Alias is set; use different keys for message and transport level; expiration is not checked in encryption, decryption and signing steps; SAP-owned aliases start with sap_ or are hcicertificate, hcicertificate1, hcimsgcertificate; uploads are not signature-checked, so verify root certificates manually; sap_cloudintegrationcertificate preinstalled
- [Renewal of Keys Provided by SAP (SAP Integration Suite documentation, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/renewal-of-keys-provided-by-sap-5db16f5.md): SAP prepares the new key pair 60 days before expiry under the same alias in New SAP Keys; the tenant administrator downloads the new certificate, tells the administrators of connected systems, they update their keystores, then the tenant administrator activates the new key; renewal must be coordinated to avoid downtime
- [Activating a New Key Pair Provided by SAP (SAP Integration Suite documentation, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/activating-a-new-key-pair-provided-by-sap-383be7a.md): Monitor > Keystore > New SAP Keys > Activate; if the key isn't renewed, a daily system job activates the new key automatically one day before the old one expires
- [Client Certificate Authentication for Integration Flow Processing (SAP Integration Suite documentation, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/40-RemoteSystems/client-certificate-authentication-for-integration-flow-processing-7f84d16.md): Recommended inbound option alongside OAuth client credentials; the sender's certificate sits in a service key of plan integration-flow whose instance carries ESBMessaging.send or a custom role, checked at runtime; SAP-generated or external certificate signed by a CA the load balancer supports
- [Apply Message-Level Security (SAP Integration Suite design guidelines, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-message-level-security-9036c0c.md): TLS and SFTP protect data only in transfer; files on an SFTP server are not protected; message-level encryption and signing (PGP, PKCS#7/CMS, XML Signature, WS-Security) protect content across hops and prove authorship; the partner must support the algorithms; a certificate signed by a trusted CA in production
- [Central Monitoring and Alerting Solutions (SAP Cloud Integration documentation, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Operations/central-monitoring-and-alerting-solutions-605fc6e.md): SAP Cloud ALM health monitoring tracks the validity of certificates across all Cloud Integration tenants and JMS resources; alerts by email, chat or tickets; SAP Focused Run as an alternative for service providers and large on-premise landscapes
- [Recommendations for Secure Setup (SAP BTP Connectivity documentation, Cloud Connector, read 2026-11-30)](https://github.com/SAP-docs/btp-connectivity/blob/main/docs/1-connectivity-documentation/recommendations-for-secure-setup-e7ea82a.md): Security Status overview; restrict OS access; separate Cloud Connector and BTP administrators; route to the cloud always TLS, to the back end TLS or SNC; supported protocols HTTP, HTTPS, RFC, RFC with SNC, LDAP, LDAPS, TCP, TCP over TLS; keep the audit log on in production
