# Services, instances and bindings: how a BTP app gets its credentials

> Know how BTP services, plans, instances, bindings and keys fit together, how each runtime hands an app its credentials, and how to rotate and audit them.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/btp-services-and-bindings/
- Updated: 2026-11-26
- Reading time: Foundational 8 min, Deep 38 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

Most of what a BTP app uses is a **service**: a database, the destination store, SAP AI Core, the login service. Using one takes four steps, and each has its own name:

1. **The marketplace** lists the services your subaccount may use.
2. **A plan** is a size or variant of a service, like a t-shirt size.
3. **An instance** is your own copy of a service, created with one plan.
4. **Credentials** let an app use the instance. There are two kinds. A **binding** connects the instance to an app that runs on BTP, and the platform hands the app its credentials. A **service key** creates credentials for something outside BTP: a laptop, a test tool, another system.

A binding is delivered by the platform and nobody copies it. A service key is copied by a person, so it can end up anywhere: in a chat, an email, a file on a laptop. Most credential trouble on BTP starts with a key used where a binding would do.

This topic explains the difference, how credentials are replaced ("rotated"), and how to keep a register of who holds what.

### Why it matters to the business

Credentials are machine passwords. Whoever holds one can act as the app.

- **Risk.** A service key copied into a team chat still works after the person who made it leaves. Nothing in BTP knows where the copy went. The deep layer's example finds exactly this.
- **Outages.** Some credentials expire. SAP's login service can issue certificates instead of secrets, and the certificates it generates are valid for 7 days by default and 30 at most ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/parameters-for-x-509-certificates-managed-by-sap-authorization-and-trust-management-ser-436ed68.md)). If nobody renews them, the app stops on a known date.
- **Changes forced by SAP.** As of 19 January 2026, SAP's login service no longer accepts one older credential type, the **instance secret**, for new bindings and keys ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/service-instance-secrets-5578ec4.md)). Old ones still work, but every app still on them needs a planned migration.
- **Audit questions.** An auditor will ask "which systems can call your AI service, and when were their credentials last changed?" Without a register, the answer takes days.

> **Example:** Calder Pumpworks, the course's fictional pump maker, has eight credentials across its BTP apps. A review on 26 November 2026 finds four that fail its rules: a key left by a technician who left in October, a production key on a developer's laptop, an AI gateway still on the old instance secret, and a portal certificate that expires in six days.

### How SAP does it

As of 26 November 2026, SAP's documentation describes the pieces like this:

- **Service Marketplace and plans.** In the BTP cockpit, each subaccount has a **Service Marketplace** showing the services and plans it is entitled to. SAP describes a plan as a configuration variant of a service ([About Services](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/about-services-d1d0fc8.md)).
- **SAP Service Manager** keeps track of instances and bindings. The btp command-line tool can list, create, share and delete instances and bindings through it ([btp CLI documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/working-with-resources-of-the-sap-service-manager-using-the-btp-cli-fe6a53b.md)).
- **How the app receives credentials depends on the runtime.** On Cloud Foundry the platform puts them in the app's environment. On Kyma the **SAP BTP Operator** writes them into a Kubernetes Secret ([SAP BTP Service Operator](https://github.com/SAP/sap-btp-service-operator)).
- **Rotation.** On Kyma, the operator can rotate bindings on a schedule you set ([Rotating Service Bindings](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/rotating-service-bindings-37ac30a.md)). On Cloud Foundry, you unbind and rebind, or redeploy a multitarget application (MTA) that names its keys with a timestamp ([Service Keys](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/service-keys-32297f1.md)).
- **SAP's advice.** For its login service, SAP recommends a separate secret for each binding, and automated deployments that keep up with certificate lifetimes ([security recommendations](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/60-security/security-recommendations-for-sap-authorization-and-trust-management-service-0578b80.md)).

### Binding or key: a decision guide

| Situation | Use | Why |
| --- | --- | --- |
| App runs on Cloud Foundry or Kyma in the same subaccount | Binding | The platform delivers it; nobody copies it |
| App runs outside BTP (another cloud, an on-premise server) | Service key, kept in a secret store | There is no platform to deliver it |
| A developer tests from a laptop | Service key on a **non-production** instance | Production keys don't belong on personal computers |
| A test tool or pipeline | Service key in the pipeline's secret store, owned by a team | A person's chat or mailbox outlives their job |
| Several apps need the same service | One binding each | Each can be rotated or removed alone |

> **Note** **For functional consultants.** Nothing changes in SAP configuration, but test plans do. When an integration or AI app moves to production, add test cases for "credential rotated" (the app keeps working after its binding is replaced) and "credential removed" (the app fails cleanly). When someone leaves a project, include their service keys in the offboarding checklist, next to their user roles.

### Questions to ask

- Which of our apps use bindings, and which use copied service keys? Why?
- Where does every copy of a service key live, and who owns it?
- How often are credentials replaced, and is that automated?
- Which apps still use the instance secret type, and when do they migrate?
- When do our certificates expire, and what renews them?
- When someone leaves, how do we find the keys they created?
- Who may create service keys on production instances?

### Common misconceptions

- **"A binding and a service key are the same thing."** They hold similar credentials, but a binding is delivered to an app by the platform and a key is handed to a person.
- **"Deleting the person's user removes their access."** Their service keys keep working until someone deletes the keys.
- **"Rotation happens by itself."** Only where it is set up: a Kyma rotation policy, or a pipeline that redeploys. Otherwise someone must do it.
- **"An expired certificate is a security problem only."** It is also an outage, on a date you could have known.
- **"One shared key for all apps is simpler."** It is, until one app leaks it and all of them must change at once.

### Key terms

- **Service:** a capability on BTP that apps consume, such as SAP AI Core or the destination service.
- **Service plan:** a size or variant of a service; entitlements decide which plans a subaccount may use.
- **Service instance:** your own copy of a service, created with one plan.
- **Binding:** the link between an instance and an app on BTP; the platform hands the app its credentials.
- **Service key:** credentials created for a consumer outside the app, copied by a person.
- **Credential rotation:** replacing a credential with a new one and retiring the old one.
- **Instance secret:** an older credential type of SAP's login service shared by all bindings of an instance; not allowed for new bindings since 19 January 2026.
- **Credential register:** a list of every binding and key, with owner, age, storage place and next rotation date.

### Check yourself

1. A Calder app runs on Cloud Foundry in the same subaccount as the service it uses. How should it get its credentials?
   - A. From a service key that a developer copies into the app's settings
   - B. From a binding, so the platform delivers the credentials
   - C. From a shared key that every Calder app uses for the same service
   - D. From the personal user and password of the app's developer

   Answer: B. An app on BTP can be bound to the instance, and the platform hands it the credentials without anyone copying them. Copied keys and shared keys are the usual source of leaks.

2. A technician who created a service key for testing left the company in October. What happens to the key?
   - A. It stops working when the technician's user account is deleted
   - B. It expires automatically 30 days after the technician leaves
   - C. It keeps working until someone deletes the key itself
   - D. It moves to the technician's manager as the new owner

   Answer: C. A service key isn't tied to a person's user. Deleting the user changes nothing, so keys belong in the offboarding checklist and in a credential register with an owner.

3. Why can an expiring certificate turn into an outage?
   - A. Because SAP deletes the app's service instance when its certificate expires
   - B. Because a new certificate needs a new contract with SAP
   - C. Because expired certificates lock every user of the subaccount
   - D. Because the app's credential stops working on a known date unless renewed

   Answer: D. SAP's login service can issue certificates that last days, not years. If no deployment or person renews them in time, the app can no longer authenticate.

4. SAP no longer accepts the instance secret type for new bindings since January 2026. What should a leader ask for?
   - A. A list of apps still on it and a planned migration to binding secrets
   - B. An immediate shutdown of every app that uses SAP's login service
   - C. A new global account, because old accounts can't use the binding secret type
   - D. Nothing, since SAP migrates existing apps automatically

   Answer: A. Existing instance-secret bindings still work, so nothing breaks today. But new bindings can't use the type, and SAP recommends removing old ones, which takes a planned migration per app.

5. A developer wants to test against SAP AI Core from a laptop. What fits the guide in this layer?
   - A. A service key on the production instance, deleted after the test
   - B. A service key on a non-production instance, owned and recorded
   - C. A binding from the laptop to the production instance
   - D. The production app's binding credentials, copied for the test

   Answer: B. Laptops are outside BTP, so they need a service key, but production keys don't belong on personal computers. A key on a test instance with an owner in the register keeps the risk small.

6. What makes a credential register useful in an audit?
   - A. It replaces the need to rotate credentials on a schedule
   - B. It stores every secret value in one shared, encrypted file
   - C. It shows who holds each credential, where, and since when
   - D. It proves that no app in the landscape uses service keys

   Answer: C. Auditors ask which systems can call a service and when their access last changed. A register with owner, storage place and dates answers that; it never holds the secret values themselves.

## Deep layer

### Mental model

Think of a BTP service as a utility company, an instance as your meter, and a credential as the key to the meter cupboard. There is one meter per need, but there can be many keys. A **binding** is a key the platform puts in the app's pocket at start-up and takes back when you unbind. A **service key** is a key cut for someone to carry away.

Everything an architect decides here follows from that picture:

- **How many keys exist, and who holds each.** Every binding and every service key is a separate credential with its own lifetime.
- **How a key reaches the app.** That depends on the runtime: an environment variable or file on Cloud Foundry, a Kubernetes Secret on Kyma.
- **How a key is replaced.** Rotation means making a new credential, moving the consumer to it, and removing the old one. The order matters, and each runtime has its own way.

[BTP foundations for AI builders](https://erpfde.com/topics/btp-foundations-for-ai-builders/) showed one service key in use. This topic is about the whole set: designing, rotating and auditing all of a landscape's credentials.

### How it works

```mermaid
flowchart LR
  E[Entitlement<br/>plan + quota] --> M[Service Marketplace]
  M --> I[Service instance<br/>one plan]
  I --> B1[Binding<br/>to an app]
  I --> B2[Binding<br/>to another app]
  I --> K[Service key<br/>for an outside caller]
  B1 --> CF[Cloud Foundry:<br/>VCAP_SERVICES]
  B2 --> KY[Kyma: Secret<br/>from SAP BTP Operator]
  K --> P[Person copies it<br/>to a secret store]
  SM[SAP Service Manager] -.tracks.-> I
  SM -.tracks.-> B1
  SM -.tracks.-> K
```

#### Offerings, plans and instances

SAP's documentation describes the Cloud Foundry environment the way the Cloud Foundry project does: services sit in a **marketplace**, and you create **service instances** from them on demand. Each instance is created with one **plan**, which SAP calls a configuration variant of a service ([About Services](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/about-services-d1d0fc8.md)). A plan appears only when the subaccount is entitled to it; [the BTP account model](https://erpfde.com/topics/btp-account-model/) covers entitlements.

Instances can also hold **parameters** given at creation. For SAP's login service, the SAP Authorization and Trust Management service (XSUAA), the main one is the application security descriptor, `xs-security.json`. It decides, among other things, which credential types bindings may use (below).

SAP Service Manager keeps track of instances and bindings in a subaccount. With the btp CLI you can work with them directly, and from any runtime ([btp CLI documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/working-with-resources-of-the-sap-service-manager-using-the-btp-cli-fe6a53b.md)):

| Task | Command |
| --- | --- |
| See offerings and plans | `btp list services/offering`, `btp list services/plan` |
| See and create instances | `btp list services/instance`, `btp create services/instance` |
| See and create bindings | `btp list services/binding`, `btp create services/binding` |
| Share an instance across environments | `btp share services/instance` |

SAP adds a catch: `--show-parameters` on `btp get services/instance` or `btp get services/binding` returns parameters only when the offering sets `instances_retrievable` or `bindings_retrievable` to true. So don't count on reading back how an instance was configured; keep the parameter files in Git.

#### Bindings and service keys

Both create a credential at the service's **broker**, the component that provisions instances and issues credentials. They differ in where the credential goes:

- **A binding** joins an instance to an app. On Cloud Foundry you run `cf bind-service APP INSTANCE`, or list the instance in the app's manifest. On Kyma you create a `ServiceBinding` resource and the SAP BTP Operator stores the result in a Kubernetes Secret ([SAP BTP Service Operator](https://github.com/SAP/sap-btp-service-operator)).
- **A service key** is a credential with no app attached: `cf create-service-key INSTANCE KEY` on Cloud Foundry. For instances created in the cockpit's *Other* environment or through SAP Service Manager, the same thing is a binding with no app, created with `btp create services/binding`. Someone then copies the values to wherever the consumer runs.

For XSUAA, SAP spells out the consequence: the service creates a client ID and secret when you bind an app or create a service key ([Service Instance Secrets](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/service-instance-secrets-5578ec4.md)). Every binding and every key is one more credential to rotate and audit.

#### How the app receives the credentials

On Cloud Foundry, the Cloud Foundry documentation lists three delivery methods, and an app uses exactly one ([Delivering service credentials to an app](https://github.com/cloudfoundry/docs-dev-guide/blob/master/services/application-binding.html.md.erb)):

| Method | Where the app looks | Limit |
| --- | --- | --- |
| Default | The `VCAP_SERVICES` environment variable, one JSON document | 130 KB |
| File-based | A file whose path is in `VCAP_SERVICES_FILE_PATH` | 1 MB |
| Service binding files | Folders under `SERVICE_BINDING_ROOT`, one file per value, in the servicebinding.io layout | 1 MB in all |

Two rules from that page matter for design. An app sees a new or changed binding only after a **restart or re-push**. And `--binding-name` gives the binding a stable name, so code can find it without knowing the instance name, which often differs between stages.

On Kyma, the binding becomes a Secret. By default it holds one key-value pair per credential plus the instance's GUID, name, plan and offering. `secretKey` puts the credentials under one key as JSON, `secretRootKey` puts credentials and instance details together, and `secretTemplate` lets you shape the Secret yourself. A pod reads the Secret as environment variables or as files in a mounted volume, which is ordinary Kubernetes behavior.

> **Tip** Write one function that reads credentials whichever way they arrive, and call it everywhere. Step 6 of the walkthrough builds one. It is what lets the same code run on Cloud Foundry, on Kyma and on your laptop.

#### Credential types in SAP's login service

XSUAA, the service most custom apps bind to, offers three secret types. The `credential-types` list in `xs-security.json` decides which ones the instance allows ([Service Instance Secrets](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/service-instance-secrets-5578ec4.md)):

| Type | What it is | Lifetime | Status as of 26 November 2026 |
| --- | --- | --- | --- |
| `instance-secret` | One secret shared by all bindings of the instance | As long as the instance | Not supported for new bindings and keys since 19 January 2026; SAP recommends removing old ones |
| `binding-secret` | A secret per binding or key | As long as the binding or key | The default |
| `x509` | A certificate and private key per binding or key | As long as the certificate | Generated by XSUAA (1 to 30 days, default 7) or brought from your own PKI |

Three details from SAP's pages change how you run them:

- **Certificates aren't checked for revocation.** To stop a certificate that is still valid, delete its binding or key.
- **XSUAA-generated certificates are short.** The `validity` parameter runs from 1 to 30 days ([X.509 parameters](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/parameters-for-x-509-certificates-managed-by-sap-authorization-and-trust-management-ser-436ed68.md)). SAP's security recommendation BTP-UAA-0014 tells operators to automate deployments to keep up ([security recommendations](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/60-security/security-recommendations-for-sap-authorization-and-trust-management-service-0578b80.md)).
- **Moving off instance secrets is a sequence, not a switch.** SAP's [migration procedure](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/migrate-from-instance-secrets-to-binding-secrets-dcee867.md) allows both types first, rebinds every app, replaces every key, checks that the instance secret is no longer used (the `instanceSecretLastUsedAt` field of `GET /sap/rest/authorization/v2/apps/{id}`), and only then removes the old type. Removing it too early breaks every remaining binding and key at once.

> **Note** SAP's pages aren't fully consistent here. The Service Instance Secrets page calls the binding secret the default; the migration page still says instances use the instance secret by default. Check `credential-types` in each instance's `xs-security.json` rather than relying on either.

#### Rotation, by runtime

| Where | How you rotate | Downtime |
| --- | --- | --- |
| Cloud Foundry binding | `cf unbind-service`, `cf bind-service`, then restart or restage | Yes, unless you use blue-green |
| Cloud Foundry binding, rolling | `cf bind-service --strategy multiple`, `cf restage --strategy rolling`, `cf cleanup-outdated-service-bindings` | No; Cloud Foundry calls it experimental, it needs cf CLI 8.18.0 and a platform that allows two bindings per app and instance |
| MTA-managed service key | Name the key `...-${timestamp}`; each deployment creates a new key and deletes the old one ([Service Keys](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/service-keys-32297f1.md)) | No, if the app reads the key through a fixed `env-var-name` |
| Kyma binding | `credentialsRotationPolicy` on the `ServiceBinding`: `enabled`, `rotationFrequency`, `rotatedBindingTTL` ([Rotating Service Bindings](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/rotating-service-bindings-37ac30a.md)) | No: the old credentials stay in a Secret labeled `services.cloud.sap.com/stale` until the TTL ends |
| Plain service key | Create the new key, move the consumer, delete the old key | No, if done in that order |

The Kyma policy has two limits worth stating in a design. It doesn't change how long the credentials themselves are valid; the service decides that. And rotation happens in the operator's next reconciliation loop, not at an exact time. To rotate at once, for example after a leak, add the annotation `services.cloud.sap.com/forceRotate: "true"`; it works only when rotation is enabled.

### Build it yourself: Calder's credential register

You will write Calder's credentials as data, check them against eight rules, print the rotation steps for any one of them, and see how an app finds its credentials on each runtime. Everything runs on your computer with no account. One optional step binds a real service to the app you deployed in the Unit 21 setup.

```mermaid
flowchart LR
  I[--init] --> J[calder_credentials.json]
  J --> R[credential_register.py<br/>rules K01-K08]
  R --> T[register with<br/>OK / WARN / FAIL]
  R --> S[--rotate ID<br/>steps per runtime]
  D[--env-demo / --cf-env] --> E[how the app<br/>finds its bindings]
  R --> W[--write]
  W --> M[calder_credential_register.md]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/). This walkthrough doesn't repeat their steps.

> **Note** New words. A **credential** is anything that proves who a program is: a client ID and secret, or a certificate and private key. **Rotation** replaces it with a new one. **JSON** is a text format for structured data. An **environment variable** is a named value the operating system gives a program when it starts. A **register** here is a file listing every credential with its owner and dates, never the secret values.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`.
- No account for Steps 1 to 6 and 8. Step 7 optionally uses your trial, the cf CLI and the `hello-btp` app from the Unit 21 setup.
- 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. The `unit21` folder exists from the setup topic. If it doesn't, create it with `mkdir unit21`.

#### Step 2: Create the script

1. In VS Code, create a new file `unit21/credential_register.py`.
2. Paste the whole script below and save. It uses built-in Python modules only, so there is nothing to install.

```python
"""Calder's BTP credential register: every binding and service key, checked.

Unit 21, Services, instances and bindings. Built-in modules only, no randomness.

  python unit21/credential_register.py --init        write unit21/calder_credentials.json (Calder's draft)
  python unit21/credential_register.py               check every credential against rules K01-K08
  python unit21/credential_register.py --rotate C02  print the rotation steps for one credential
  python unit21/credential_register.py --write       write unit21/calder_credential_register.md
  python unit21/credential_register.py --env-demo    show how an app reads its bindings (made-up values)
  python unit21/credential_register.py --cf-env FILE list the bindings in saved `cf env` output, masked
  python unit21/credential_register.py --today 2026-12-01   check as of another date

All names, people, dates and rules are course values. Calder Pumpworks is fictional.
"""
import argparse
import json
import os
import sys
import tempfile
from datetime import date
from pathlib import Path

DATA = Path("unit21/calder_credentials.json")
REPORT = Path("unit21/calder_credential_register.md")
TODAY = "2026-11-26"            # fixed so every run gives the same answer
ROTATE_DAYS = 90                # course policy for client secrets
X509_WARN_DAYS = 14             # renew certificates this many days before they expire
SAFE_STORES = {"binding", "kyma secret", "ci secret store", "sap credential store"}

SAMPLE = {
    "as_of": TODAY,
    "people": {
        "00100288": {"role": "integration developer", "left": None},
        "00100292": {"role": "integration lead", "left": None},
        "00100094": {"role": "maintenance technician", "left": "2026-10-16"},
    },
    "instances": {
        "order-exc-xsuaa": {"offering": "xsuaa", "plan": "application", "subaccount": "calder-ai-prod",
                            "credential_types": ["binding-secret", "x509"]},
        "calder-ai-gw-xsuaa": {"offering": "xsuaa", "plan": "application", "subaccount": "calder-ai-prod",
                               "credential_types": ["binding-secret", "instance-secret"]},
        "calder-aicore": {"offering": "aicore", "plan": "extended", "subaccount": "calder-ai-prod"},
        "calder-aicore-qa": {"offering": "aicore", "plan": "extended", "subaccount": "calder-ai-test"},
        "calder-dest": {"offering": "destination", "plan": "lite", "subaccount": "calder-ext-prod"},
        "portal-xsuaa-test": {"offering": "xsuaa", "plan": "application", "subaccount": "calder-ext-test",
                              "credential_types": ["binding-secret"]},
        "portal-xsuaa": {"offering": "xsuaa", "plan": "application", "subaccount": "calder-ext-prod",
                         "credential_types": ["binding-secret", "x509"]},
        "mes-dest": {"offering": "destination", "plan": "lite", "subaccount": "calder-ext-prod"},
    },
    "credentials": [
        {"id": "C01", "kind": "binding", "runtime": "cloud-foundry", "instance": "order-exc-xsuaa",
         "consumer": "order-exc-api (W01)", "consumer_on_btp": True, "credential_type": "binding-secret",
         "created": "2026-09-14", "owner": "00100288", "stored": "binding"},
        {"id": "C02", "kind": "binding", "runtime": "cloud-foundry", "instance": "calder-ai-gw-xsuaa",
         "consumer": "calder-ai-gw (W03)", "consumer_on_btp": True, "credential_type": "instance-secret",
         "created": "2026-05-04", "owner": "00100292", "stored": "binding"},
        {"id": "C03", "kind": "key", "runtime": "cloud-foundry", "instance": "calder-aicore",
         "name": "calder-aicore-gw", "consumer": "calder-ai-gw (W03)", "consumer_on_btp": True,
         "credential_type": "client-secret", "created": "2026-10-21", "owner": "00100292",
         "stored": "user-provided service calder-ai-gw-secrets"},
        {"id": "C04", "kind": "key", "runtime": "cloud-foundry", "instance": "calder-aicore-qa",
         "name": "calder-aicore-gw-qa", "consumer": "gw-qa host", "consumer_on_btp": False,
         "credential_type": "client-secret", "created": "2026-10-21", "owner": "00100292",
         "stored": "CI secret store"},
        {"id": "C05", "kind": "key", "runtime": "cloud-foundry", "instance": "calder-dest",
         "name": "dest-laptop-00100288", "consumer": "laptop of 00100288", "consumer_on_btp": False,
         "credential_type": "client-secret", "created": "2026-07-30", "owner": "00100288",
         "stored": ".env on a laptop"},
        {"id": "C06", "kind": "key", "runtime": "cloud-foundry", "instance": "portal-xsuaa-test",
         "name": "portal-test-key", "consumer": "API test collection", "consumer_on_btp": False,
         "credential_type": "binding-secret", "created": "2026-03-02", "owner": "00100094",
         "stored": "team chat"},
        {"id": "C07", "kind": "binding", "runtime": "cloud-foundry", "instance": "portal-xsuaa",
         "consumer": "distributor-portal (W02)", "consumer_on_btp": True, "credential_type": "x509",
         "created": "2026-11-02", "expires": "2026-12-02", "owner": "00100288", "stored": "binding"},
        {"id": "C08", "kind": "binding", "runtime": "kyma", "instance": "mes-dest",
         "consumer": "mes-listener (W04)", "consumer_on_btp": True, "credential_type": "client-secret",
         "created": "2026-11-20", "owner": "00100288", "stored": "Kyma secret",
         "rotation_policy": {"enabled": True, "rotationFrequency": "600h", "rotatedBindingTTL": "48h"}},
    ],
}

RULES = {
    "K01": "An app that runs on BTP gets a binding, not a copied service key",
    "K02": "No credential uses the instance-secret type",
    "K03": "Every credential has an owner who still works at Calder",
    "K04": f"Client secrets are replaced within {ROTATE_DAYS} days",
    "K05": f"X.509 certificates are renewed at least {X509_WARN_DAYS} days before they expire",
    "K06": "Keys on production instances go to named systems, never to a person's computer",
    "K07": "Kyma bindings have a rotation policy",
    "K08": "Every copy of a key sits in an approved store",
}


def days(a, b):
    return (date.fromisoformat(b) - date.fromisoformat(a)).days


def check(cred, data, today):
    """Return a list of (rule, verdict, text) for one credential."""
    out = []
    inst = data["instances"].get(cred["instance"])
    if inst is None:
        return [("K00", "FAIL", f"instance {cred['instance']} is not in the register")]
    prod = inst["subaccount"].endswith("-prod")
    age = days(cred["created"], today)
    ctype = cred.get("credential_type", "client-secret")

    if cred["kind"] == "key" and cred.get("consumer_on_btp"):
        out.append(("K01", "WARN", "app on BTP uses a copied key; bind it if the service supports bindings"))
    if ctype == "instance-secret":
        out.append(("K02", "FAIL", "instance secret: migrate the instance to binding secrets"))
    person = data["people"].get(cred.get("owner"))
    if person is None:
        out.append(("K03", "FAIL", "no owner recorded"))
    elif person.get("left") and person["left"] <= today:
        out.append(("K03", "FAIL", f"owner {cred['owner']} left on {person['left']}"))
    if ctype != "x509":
        if cred["runtime"] == "kyma" and cred.get("rotation_policy", {}).get("enabled"):
            pass  # the operator replaces it on its own schedule
        elif age > ROTATE_DAYS:
            out.append(("K04", "FAIL", f"{age} days old, due after {ROTATE_DAYS}"))
    else:
        left = days(today, cred["expires"]) if cred.get("expires") else None
        if left is None:
            out.append(("K05", "FAIL", "certificate without a recorded expiry date"))
        elif left < 0:
            out.append(("K05", "FAIL", f"expired {-left} days ago"))
        elif left < X509_WARN_DAYS:
            out.append(("K05", "FAIL", f"expires in {left} days: renew now"))
    if cred["kind"] == "key" and prod and not cred.get("consumer_on_btp") and "laptop" in cred["consumer"].lower():
        out.append(("K06", "FAIL", "production key on a person's computer"))
    if cred["runtime"] == "kyma" and not cred.get("rotation_policy", {}).get("enabled"):
        out.append(("K07", "FAIL", "no credentialsRotationPolicy on the ServiceBinding"))
    store = cred.get("stored", "").lower()
    if cred["kind"] == "key" and store not in SAFE_STORES and not store.startswith("user-provided service"):
        out.append(("K08", "FAIL", f"copy kept in '{cred.get('stored')}'"))
    return out


def label(cred):
    return cred.get("name") or f"{cred['consumer'].split(' ')[0]} -> {cred['instance']}"


def rotation_steps(cred, data):
    """Print the rotation steps for one credential, by runtime and kind."""
    inst = cred["instance"]
    app = cred["consumer"].split(" ")[0]
    ctype = cred.get("credential_type", "client-secret")
    lines = [f"Rotation for {cred['id']} ({cred['kind']}, {cred['runtime']}, {ctype}): {label(cred)}", ""]
    if ctype == "instance-secret":
        lines += [
            "Migrate the instance to binding secrets first (XSUAA):",
            '  1. In xs-security.json set "oauth2-configuration": {"credential-types": ["binding-secret","instance-secret"]}',
            f"  2. cf update-service {inst} -c xs-security.json",
            f"  3. cf unbind-service {app} {inst}",
            f"  4. cf bind-service {app} {inst}",
            f"  5. cf restage {app}            (or a blue-green deployment to avoid downtime)",
            "  6. Replace every service key on the instance with a new one",
            "  7. Check instanceSecretLastUsedAt (GET /sap/rest/authorization/v2/apps/{id}) is no longer moving",
            '  8. Set "credential-types": ["binding-secret"] and run step 2 again',
        ]
    elif cred["kind"] == "binding" and cred["runtime"] == "cloud-foundry":
        extra = " -c parameters.json" if ctype == "x509" else ""
        lines += [
            f"  1. cf unbind-service {app} {inst}",
            f"  2. cf bind-service {app} {inst}{extra}",
            f"  3. cf restage {app}            (downtime; use blue-green to avoid it)",
            "  Without downtime, where the platform allows two bindings per app and instance",
            "  (Cloud Foundry calls this experimental; cf CLI 8.18.0 or later):",
            f"     cf bind-service {app} {inst} --strategy multiple",
            f"     cf restage {app} --strategy rolling",
            f"     cf cleanup-outdated-service-bindings {app}",
        ]
        if ctype == "x509":
            lines.append("  For an MTA: redeploy before the certificate expires, from a scheduled pipeline.")
    elif cred["kind"] == "binding" and cred["runtime"] == "kyma":
        name = f"{app}-binding"
        lines += [
            "  The SAP BTP Operator rotates it when the ServiceBinding has:",
            "    spec:",
            "      credentialsRotationPolicy:",
            "        enabled: true",
            "        rotationFrequency: 600h",
            "        rotatedBindingTTL: 48h",
            "  Rotate now (works only when rotation is enabled):",
            f'    kubectl annotate servicebinding {name} services.cloud.sap.com/forceRotate="true"',
            "  Restart or reload the pods that read the Secret, then check status.lastCredentialsRotationTime.",
        ]
    else:  # service key
        new = f"{cred.get('name', 'key')}-{data['as_of'].replace('-', '')}"
        lines += [
            f"  1. cf create-service-key {inst} {new}",
            f"  2. cf service-key {inst} {new}      (copy the values into the approved store, nowhere else)",
            "  3. Point the consumer at the new values and test one call",
            f"  4. cf delete-service-key {inst} {cred.get('name')}",
            "  For an MTA-managed key: name it with ${timestamp} so each deployment creates a new one.",
        ]
    return "\n".join(lines)


def run_checks(data, today):
    results = []
    for cred in data["credentials"]:
        results.append((cred, check(cred, data, today)))
    return results


def print_register(results, today):
    print(f"Calder credential register, as of {today}")
    print()
    print(f"{'ID':<4} {'Kind':<8} {'Runtime':<14} {'Credential':<34} {'Age':>4}  Verdict")
    fails = warns = 0
    for cred, findings in results:
        age = days(cred["created"], today)
        worst = "FAIL" if any(v == "FAIL" for _, v, _ in findings) else ("WARN" if findings else "OK")
        fails += worst == "FAIL"
        warns += worst == "WARN"
        print(f"{cred['id']:<4} {cred['kind']:<8} {cred['runtime']:<14} {label(cred)[:34]:<34} {age:>4}  {worst}")
        for rule, verdict, text in findings:
            print(f"{'':<5}{rule} {verdict}: {text}")
    print()
    print(f"{len(results)} credentials: {len(results) - fails - warns} OK, {warns} WARN, {fails} FAIL")
    return fails


def write_report(data, results, today):
    lines = [f"# Calder credential register ({today})", "",
             "Course values. Calder Pumpworks is fictional.", "",
             "## Rules", ""]
    lines += [f"- **{k}** {v}" for k, v in RULES.items()]
    lines += ["", "## Credentials", "",
              "| ID | Kind | Runtime | Instance (offering/plan) | Consumer | Created | Owner | Stored | Verdict |",
              "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"]
    for cred, findings in results:
        inst = data["instances"][cred["instance"]]
        verdict = "; ".join(f"{r} {v}" for r, v, _ in findings) or "OK"
        lines.append(f"| {cred['id']} | {cred['kind']} | {cred['runtime']} | {cred['instance']} "
                     f"({inst['offering']}/{inst['plan']}) | {cred['consumer']} | {cred['created']} | "
                     f"{cred['owner']} | {cred['stored']} | {verdict} |")
    lines += ["", "## Actions", ""]
    for cred, findings in results:
        for rule, verdict, text in findings:
            lines.append(f"- {cred['id']} {rule} {verdict}: {text}")
    lines += ["", "## Decision record: how Calder's apps get credentials", "",
              "- **Context:** apps on Cloud Foundry and Kyma, agents calling SAP AI Core, tests and laptops.",
              "- **Options:** service keys copied into each app; bindings for apps and keys only for outside callers;",
              "  everything through one shared technical key.",
              "- **Decision:** _fill in_",
              "- **Consequences:** _fill in_", ""]
    REPORT.write_text("\n".join(lines), encoding="utf-8")
    print(f"Wrote {REPORT}")


SECRET_WORDS = ("secret", "password", "key", "certificate", "token")


def mask(name, value):
    if isinstance(value, (dict, list)):
        return "{...}" if isinstance(value, dict) else "[...]"
    text = str(value)
    if any(w in name.lower() for w in SECRET_WORDS):
        return text[:4] + "..." if len(text) > 4 else "***"
    return text


def read_bindings(env):
    """Return [(source, service, binding name, {credential: value})] the way an app finds them."""
    found = []
    root = env.get("SERVICE_BINDING_ROOT")
    if root and Path(root).is_dir():
        for folder in sorted(Path(root).iterdir()):
            if folder.is_dir():
                values = {f.name: f.read_text(encoding="utf-8").strip() for f in sorted(folder.iterdir()) if f.is_file()}
                found.append(("SERVICE_BINDING_ROOT", values.get("type", "?"), folder.name, values))
        return found
    text = None
    if env.get("VCAP_SERVICES_FILE_PATH") and Path(env["VCAP_SERVICES_FILE_PATH"]).is_file():
        text, source = Path(env["VCAP_SERVICES_FILE_PATH"]).read_text(encoding="utf-8"), "VCAP_SERVICES_FILE_PATH"
    elif env.get("VCAP_SERVICES"):
        text, source = env["VCAP_SERVICES"], "VCAP_SERVICES"
    if text:
        for service, entries in json.loads(text).items():
            for entry in entries:
                found.append((source, service, entry.get("name", "?"), entry.get("credentials", {})))
    return found


def show_bindings(found):
    if not found:
        print("No bindings found. On Cloud Foundry, bind an instance and restart the app.")
        return
    for source, service, name, creds in found:
        print(f"[{source}] service {service}, binding {name}")
        for k in sorted(creds):
            print(f"    {k:<16} {mask(k, creds[k])}")


DEMO_CREDS = {"clientid": "sb-demo-clone!b123|destination-xsappname!b62",
              "clientsecret": "demo-secret-not-real", "url": "https://demo.authentication.us10.hana.ondemand.com",
              "uri": "https://destination-configuration.cfapps.us10.hana.ondemand.com"}


def env_demo():
    vcap = {"destination": [{"name": "course-destination", "label": "destination", "plan": "lite",
                             "credentials": DEMO_CREDS}]}
    print("1. Cloud Foundry default: one JSON document in VCAP_SERVICES")
    show_bindings(read_bindings({"VCAP_SERVICES": json.dumps(vcap)}))
    print()
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / "vcap.json"
        path.write_text(json.dumps(vcap), encoding="utf-8")
        print("2. Cloud Foundry file-based: the same JSON in a file named by VCAP_SERVICES_FILE_PATH")
        show_bindings(read_bindings({"VCAP_SERVICES_FILE_PATH": str(path)}))
        print()
        folder = Path(tmp) / "bindings" / "course-destination"
        folder.mkdir(parents=True)
        for k, v in {**DEMO_CREDS, "type": "destination", "plan": "lite"}.items():
            (folder / k).write_text(v, encoding="utf-8")
        print("3. One file per value under SERVICE_BINDING_ROOT (servicebinding.io layout; a mounted Kyma Secret looks alike)")
        show_bindings(read_bindings({"SERVICE_BINDING_ROOT": str(Path(tmp) / "bindings")}))
    print()
    print("Same credentials, three deliveries. Read them in one function, never hard-code them.")


def cf_env_file(path):
    text = Path(path).read_text(encoding="utf-8", errors="replace")
    at = text.find("VCAP_SERVICES")
    if at < 0:
        sys.exit("No VCAP_SERVICES in that file: bind a service, restart the app and save cf env again.")
    start = text.find("{", at)
    vcap, _ = json.JSONDecoder().raw_decode(text[start:])
    show_bindings(read_bindings({"VCAP_SERVICES": json.dumps(vcap)}))
    print()
    print(f"Delete {path} now: it holds real credentials.")


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--init", action="store_true")
    p.add_argument("--rotate", metavar="ID")
    p.add_argument("--write", action="store_true")
    p.add_argument("--env-demo", action="store_true")
    p.add_argument("--cf-env", metavar="FILE")
    p.add_argument("--today", default=TODAY)
    a = p.parse_args()

    if a.env_demo:
        return env_demo()
    if a.cf_env:
        return cf_env_file(a.cf_env)
    if a.init:
        if DATA.exists():
            sys.exit(f"{DATA} already exists; delete it first if you want the sample back.")
        DATA.parent.mkdir(parents=True, exist_ok=True)
        DATA.write_text(json.dumps(SAMPLE, indent=2), encoding="utf-8")
        print(f"Wrote {DATA}: {len(SAMPLE['instances'])} instances, {len(SAMPLE['credentials'])} credentials")
        return
    if not DATA.exists():
        sys.exit(f"{DATA} not found. Run: python unit21/credential_register.py --init")
    try:
        data = json.loads(DATA.read_text(encoding="utf-8"))
    except json.JSONDecodeError as err:
        sys.exit(f"{DATA} is not valid JSON: {err}")
    data["as_of"] = a.today
    if a.rotate:
        cred = next((c for c in data["credentials"] if c["id"] == a.rotate), None)
        if cred is None:
            sys.exit(f"No credential {a.rotate}. IDs: " + ", ".join(c["id"] for c in data["credentials"]))
        print(rotation_steps(cred, data))
        return
    results = run_checks(data, a.today)
    print_register(results, a.today)
    if a.write:
        print()
        write_report(data, results, a.today)


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

#### Step 3: Write Calder's credentials and read them

1. Run:

   ```bash
   python unit21/credential_register.py --init
   ```

2. Expected:

   ```text
   Wrote unit21/calder_credentials.json: 8 instances, 8 credentials
   ```

3. Open `unit21/calder_credentials.json`. It has three parts: `people` (personnel numbers and whether they left), `instances` (offering, plan, subaccount and, for XSUAA, the allowed `credential_types`) and `credentials`. All values are course values for the fictional Calder; the workloads W01 to W04 are the ones placed in [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/), and the subaccount names follow [the BTP account model](https://erpfde.com/topics/btp-account-model/).

The eight credentials:

| ID | Kind | Consumer | Instance | What is special |
| --- | --- | --- | --- | --- |
| C01 | Binding (Cloud Foundry) | Order-exceptions agent API (W01) | `order-exc-xsuaa` | Binding secret, 73 days old |
| C02 | Binding (Cloud Foundry) | AI gateway `calder-ai-gw` (W03) | `calder-ai-gw-xsuaa` | Still on the instance secret |
| C03 | Service key | AI gateway (W03) | `calder-aicore` | Copied into a user-provided service when the gateway moved to Cloud Foundry |
| C04 | Service key | QA gateway host, outside BTP | `calder-aicore-qa` | Kept in the CI secret store |
| C05 | Service key | Laptop of integration developer `00100288` | `calder-dest` (production) | In a `.env` file |
| C06 | Service key | API test collection | `portal-xsuaa-test` | Created by `00100094`, who left on 2026-10-16; shared in a team chat |
| C07 | Binding (Cloud Foundry) | Distributor portal (W02) | `portal-xsuaa` | X.509 certificate, expires 2026-12-02 |
| C08 | Binding (Kyma) | MES listener (W04) | `mes-dest` | Rotation policy every 600 hours |

> **Note** The file holds no secret values, only facts about each credential. A register must never become one more place where secrets leak.

#### Step 4: Check the register

1. Run:

   ```bash
   python unit21/credential_register.py
   ```

2. Expected (the date is fixed, so your output matches exactly):

   ```text
   Calder credential register, as of 2026-11-26

   ID   Kind     Runtime        Credential                          Age  Verdict
   C01  binding  cloud-foundry  order-exc-api -> order-exc-xsuaa     73  OK
   C02  binding  cloud-foundry  calder-ai-gw -> calder-ai-gw-xsuaa  206  FAIL
        K02 FAIL: instance secret: migrate the instance to binding secrets
        K04 FAIL: 206 days old, due after 90
   C03  key      cloud-foundry  calder-aicore-gw                     36  WARN
        K01 WARN: app on BTP uses a copied key; bind it if the service supports bindings
   C04  key      cloud-foundry  calder-aicore-gw-qa                  36  OK
   C05  key      cloud-foundry  dest-laptop-00100288                119  FAIL
        K04 FAIL: 119 days old, due after 90
        K06 FAIL: production key on a person's computer
        K08 FAIL: copy kept in '.env on a laptop'
   C06  key      cloud-foundry  portal-test-key                     269  FAIL
        K03 FAIL: owner 00100094 left on 2026-10-16
        K04 FAIL: 269 days old, due after 90
        K08 FAIL: copy kept in 'team chat'
   C07  binding  cloud-foundry  distributor-portal -> portal-xsuaa   24  FAIL
        K05 FAIL: expires in 6 days: renew now
   C08  binding  kyma           mes-listener -> mes-dest              6  OK

   8 credentials: 3 OK, 1 WARN, 4 FAIL
   ```

3. Read it against the rules:

| Rule | Where it comes from |
| --- | --- |
| K01 An app on BTP gets a binding, not a copied key | Bindings deliver credentials to apps; keys are for consumers outside (SAP's About Services page) |
| K02 No instance secret | Not supported for new XSUAA bindings and keys since 19 January 2026; SAP recommends removing old ones |
| K03 Every credential has an active owner | Course rule; keys outlive their creator's user |
| K04 Client secrets replaced within 90 days | Course policy; SAP tells you to rotate credentials regularly but sets no number |
| K05 Certificates renewed 14 days before expiry | Course rule built on SAP's BTP-UAA-0014 (automate for certificate lifetimes) |
| K06 No production keys on personal computers | Course rule |
| K07 Kyma bindings have a rotation policy | Course rule using the SAP BTP Operator's `credentialsRotationPolicy` |
| K08 Every key copy in an approved store | Course rule; the approved stores are a binding, a Kyma Secret, the CI secret store, SAP Credential Store and a user-provided service |

C03 gets a warning, not a failure, on purpose. Whether an app can bind SAP AI Core instead of copying a key depends on the service and the runtime, so the rule asks a person to check. C08 passes K04 at any age: its policy replaces the credential every 600 hours (25 days).

> **Note** These verdicts come from made-up Calder data. They show the method, not findings from a real BTP account.

#### Step 5: Print the rotation steps

1. Ask for the steps for the AI gateway's instance secret:

   ```bash
   python unit21/credential_register.py --rotate C02
   ```

2. Expected:

   ```text
   Rotation for C02 (binding, cloud-foundry, instance-secret): calder-ai-gw -> calder-ai-gw-xsuaa

   Migrate the instance to binding secrets first (XSUAA):
     1. In xs-security.json set "oauth2-configuration": {"credential-types": ["binding-secret","instance-secret"]}
     2. cf update-service calder-ai-gw-xsuaa -c xs-security.json
     3. cf unbind-service calder-ai-gw calder-ai-gw-xsuaa
     4. cf bind-service calder-ai-gw calder-ai-gw-xsuaa
     5. cf restage calder-ai-gw            (or a blue-green deployment to avoid downtime)
     6. Replace every service key on the instance with a new one
     7. Check instanceSecretLastUsedAt (GET /sap/rest/authorization/v2/apps/{id}) is no longer moving
     8. Set "credential-types": ["binding-secret"] and run step 2 again
   ```

3. Try `--rotate C03` (a plain key), `--rotate C07` (a certificate binding) and `--rotate C08` (Kyma). Each prints a different procedure, from the rotation table in "How it works". The order in the key procedure matters: the new key exists and works before the old one is deleted.

> **Warning** These commands change real credentials when run against a real account. In this walkthrough you only read them. Never run a rotation in production without the consumer's owner ready to test.

#### Step 6: See how an app finds its credentials

1. Run:

   ```bash
   python unit21/credential_register.py --env-demo
   ```

2. Expected (the values are made up and the secret is masked):

   ```text
   1. Cloud Foundry default: one JSON document in VCAP_SERVICES
   [VCAP_SERVICES] service destination, binding course-destination
       clientid         sb-demo-clone!b123|destination-xsappname!b62
       clientsecret     demo...
       uri              https://destination-configuration.cfapps.us10.hana.ondemand.com
       url              https://demo.authentication.us10.hana.ondemand.com
   ```

   followed by the same binding delivered as a file (`VCAP_SERVICES_FILE_PATH`) and as one file per value (`SERVICE_BINDING_ROOT`). The third form also shows `type` and `plan`, because they are files in the folder too.

3. Open the function `read_bindings()` in the script. It checks the three places in a fixed order and returns the same list each time. That is the function to reuse in your own apps. The script masks any value whose name contains `secret`, `password`, `key`, `certificate` or `token`, so you can show the output on screen.

#### Step 7 (optional): Bind a real service in your trial

This step needs your trial, the cf CLI logged in as in the Unit 21 setup, and the `hello-btp` app deployed there. Skip it if any is missing.

1. List the instances in your space:

   ```bash
   cf services
   ```

2. If `course-destination` from Unit 18 isn't listed (trials are deleted after 90 days), create it in the cockpit as in [BTP foundations for AI builders](https://erpfde.com/topics/btp-foundations-for-ai-builders/), or from the terminal. First see the plans:

   ```bash
   cf marketplace -e destination
   ```

   then create it with the plan shown (replace `PLAN`):

   ```bash
   cf create-service destination PLAN course-destination
   ```

3. Bind it and restart the app, so the app sees the binding:

   ```bash
   cf bind-service hello-btp course-destination
   cf restart hello-btp
   ```

   If the app was stopped (trial apps stop every day), `cf restart` starts it.

4. Save the app's environment to a file:

   - **Windows (PowerShell):**

     ```powershell
     cf env hello-btp | Out-File -Encoding utf8 unit21/cf-env.txt
     ```

   - **macOS / Linux:**

     ```bash
     cf env hello-btp > unit21/cf-env.txt
     ```

5. Read it with the script:

   ```bash
   python unit21/credential_register.py --cf-env unit21/cf-env.txt
   ```

   You see `course-destination` with its `clientid`, `url` and `uri`, and the secret masked. The last line reminds you to delete the file.

6. Delete the file, because it holds real credentials:

   - **Windows (PowerShell):** `Remove-Item unit21/cf-env.txt`
   - **macOS / Linux:** `rm unit21/cf-env.txt`

7. Look at the same binding from the account side with the btp CLI (log in with `btp login --sso` if needed, and pick your trial subaccount with `btp target`):

   ```bash
   btp list services/binding
   ```

   The exact columns depend on your btp CLI version. If the list is empty, the binding may be visible only through the Cloud Foundry side; `cf services` shows it under **bound apps**.

8. Make and delete a service key, to see the second kind of credential:

   ```bash
   cf create-service-key course-destination register-test
   cf service-keys course-destination
   cf delete-service-key -f course-destination register-test
   ```

9. Unbind and restart, so the trial is as before:

   ```bash
   cf unbind-service hello-btp course-destination
   cf restart hello-btp
   ```

> **Warning** `cf env` and `cf service-key` print secrets in clear text. Don't paste their output into a chat, a ticket or a commit. Add `unit21/cf-env.txt` to your `.gitignore` if you plan to repeat this step.

#### Step 8: Write the register document

1. Run:

   ```bash
   python unit21/credential_register.py --write
   ```

2. The last line:

   ```text
   Wrote unit21/calder_credential_register.md
   ```

3. Open `unit21/calder_credential_register.md`. It holds the rules, the credentials table with verdicts, an action list, and an empty decision record. Fill in the decision and consequences (the Architecture view below shows one way).

4. Save your work in Git:

   ```bash
   git add unit21/credential_register.py unit21/calder_credentials.json unit21/calder_credential_register.md
   git commit -m "Unit 21: Calder credential register"
   ```

#### How the code works

| Part | What it does |
| --- | --- |
| Constants at the top | The fixed date, the 90-day and 14-day course limits, and the approved stores |
| `SAMPLE` | Calder's people, instances and eight credentials |
| `RULES` and `check()` | One `if` per rule K01 to K08, returning OK, WARN or FAIL with a reason |
| `rotation_steps()` | Picks the procedure by credential type, kind and runtime, with real cf and kubectl commands |
| `print_register()`, `write_report()` | The terminal table and the markdown deliverable with an empty decision record |
| `read_bindings()` | Finds credentials in `SERVICE_BINDING_ROOT`, `VCAP_SERVICES_FILE_PATH` or `VCAP_SERVICES`, in that order |
| `mask()`, `env_demo()`, `cf_env_file()` | Hide secret values; show the three delivery forms; read saved `cf env` output |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is not recognized, or `command not found` | Python isn't installed, or the terminal can't find it | Repeat the Python step of Set up your computer, then open a new terminal; on macOS/Linux use `python3` until `.venv` is active |
| `No module named ...` | You added an import, or pasted a different script | The script needs built-in modules only; paste it again from Step 2 |
| `calder_credentials.json not found` | Step 3 hasn't run | Run `python unit21/credential_register.py --init` |
| `already exists; delete it first` | `--init` won't overwrite your edits | Delete the file only if you want the sample back |
| `is not valid JSON` | A comma or quote is missing after an edit | VS Code marks the line in red; fix it and run again |
| `No VCAP_SERVICES in that file` | The app has no binding yet, or the file holds an error | Bind, restart, and save `cf env` again (Step 7.3 and 7.4) |
| `cf` says `Not logged in` | The cf session ended | `cf login --sso` with the API endpoint from the setup topic |
| cf says the destination offering or plan isn't found | The subaccount isn't entitled to the plan | Add the Destination service plan under **Entitlements** in the cockpit, as in Unit 18 |
| cf or btp time out | A company proxy blocks SAP's hosts | Set `HTTPS_PROXY` (ask IT) or try another network; only Step 7 needs the network |

### The SAP way

What SAP provides around services and credentials, as of 26 November 2026:

- **Cockpit.** Each subaccount's **Service Marketplace** shows entitled services and plans; **Instances and Subscriptions** is where instances are created and bound. On Cloud Foundry, the app's **Service Bindings** page has a **Bind Service Instance** wizard that can also create a new instance.
- **cf CLI** for Cloud Foundry: `cf marketplace`, `cf create-service`, `cf bind-service`, `cf create-service-key`, plus the rolling binding rotation that the Cloud Foundry project marks experimental.
- **btp CLI** for SAP Service Manager: instances, bindings, plans and offerings from any environment, and `btp share services/instance` to use one instance from several environments in the same subaccount.
- **SAP BTP Operator** in Kyma: `ServiceInstance` and `ServiceBinding` resources, Secret formats, and `credentialsRotationPolicy`.
- **MTA deployment**: `service-keys` on a managed-service resource, `org.cloudfoundry.existing-service-key` to consume one, and `${timestamp}` names to renew keys on each deployment.
- **SAP Credential Store**, which SAP's [security overview](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/60-security/security-e129aa2.md) describes as a repository for passwords and keys used by apps in the Cloud Foundry environment. It is one place a copied key can live; this topic doesn't cover its setup.
- **Licensing.** Bindings and keys cost nothing in themselves. The instance's plan is what is metered or subscribed; [BTP commercial models and cost control](https://erpfde.com/topics/btp-commercial-models-and-cost/) covers that.

### Bindings, keys or a store: which when

| Need | Binding | Service key | Key in a secret store |
| --- | --- | --- | --- |
| App on Cloud Foundry or Kyma, same subaccount | Yes | No | No |
| App on another cloud or on-premise | Not possible | Yes | Yes, the key lives there |
| Pipeline or test tool | No | Yes, non-production first | Yes, in the pipeline's store |
| Automatic rotation | Kyma policy, or rebind in a pipeline | MTA `${timestamp}` | The store's own process |
| Who sees the secret | Only the app (and admins of the space) | The person who created it, and everyone they gave it to | Whoever the store allows |
| Audit trail of copies | Not needed: no copies | None | The store's access log |

### Architecture view

**Where it sits.** Credentials connect Calder's workloads to the services they consume. Most stay inside BTP; two cross its edge.

```mermaid
flowchart LR
  subgraph BTP[BTP subaccounts]
    W01[W01 order-exc-api] -->|binding C01| X1[XSUAA order-exc]
    W03[W03 calder-ai-gw] -->|binding C02| X2[XSUAA ai-gw]
    W03 -->|key C03| AIC[SAP AI Core]
    W02[W02 distributor portal] -->|binding C07, X.509| X3[XSUAA portal]
    W04[W04 MES listener, Kyma] -->|binding C08| D[Destination]
  end
  QA[gw-qa host] -->|key C04| AIQ[SAP AI Core QA]
  L[Developer laptop] -->|key C05| D2[Destination prod]
```

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

| Requirement | Typical target | What breaks if it's missed |
| --- | --- | --- |
| Rotation interval | 90 days for secrets (course policy) | Old secrets stay valid long after a leak |
| Certificate renewal lead time | 14 days before expiry | The app stops on the expiry date |
| Rotation downtime | None for customer-facing apps | Restaging a single-instance app drops requests |
| Time to revoke after a leak | Under 1 hour | A leaked key keeps working while people search for its owner |
| Copies per key | One approved store | Nobody can say where the key is |
| Register coverage | Every binding and key | Audit answers take days |

**Integration and identity.** A binding gives the app a **technical identity**: an OAuth client, not a person. Tokens obtained with it carry the app's rights, not the user's. When the user's own SAP authorizations must apply, the app needs principal propagation as well, covered in Unit 27; a binding alone never provides that. Calls to S/4HANA usually go through the destination service, whose own binding is one more credential in the register.

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

- **Context:** apps on Cloud Foundry and Kyma, one AI gateway calling SAP AI Core, a QA host outside BTP, developers who test from laptops; eight credentials, four failing.
- **Options:** (1) keep copying service keys into apps, (2) bindings for every app on BTP, keys only for outside callers and only in approved stores, (3) one shared technical key per service.
- **Decision:** option 2. XSUAA instances allow `binding-secret` and `x509` only; Kyma bindings carry a rotation policy; MTA keys use `${timestamp}`; production keys never go to personal computers.
- **Consequences:** C02 migrates in a planned window; C03 is replaced by a binding if SAP AI Core supports it on Cloud Foundry, else moves to SAP Credential Store; C05 and C06 are deleted today; the portal's pipeline redeploys at least every 16 days while the certificate lasts 30; the register is reviewed monthly and in every offboarding.

**What a design review will ask:**

1. Which credentials cross the BTP boundary, and where does each copy live?
2. How long does it take to revoke a leaked key, and who can do it at night?
3. Which apps still allow `instance-secret`, and when is each migrated?
4. What renews each certificate before it expires, and what alerts if it doesn't?
5. Can each app rotate its credentials without downtime?

### Production concerns

- **Security and authorizations.** Limit who can create service keys on production instances; on Cloud Foundry that follows from space roles, so keep the developer role in production spaces to a few people. Treat `cf env` access as access to secrets. Where an app supports X.509, short certificate lifetimes limit how long a leaked credential works.
- **Evaluation.** Add two test cases per app: the app keeps working after its binding is rotated, and it fails cleanly, with a clear log line, when the credential is removed.
- **Cost.** Credentials are free; the cost is people's time when a leak or an expiry hits. Automating rotation pays for itself after the first unplanned rebind.
- **Operations.** Keep the register next to the deployment descriptors in Git, and review it in every offboarding. Watch SAP's [limits](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/60-security/limits-for-technical-artifacts-of-the-sap-authorization-and-trust-management-service-6d3ef52.md): XSUAA allows at most 1,000 bindings and service keys in total per instance, which a pipeline that creates keys without deleting old ones can reach.
- **Clean core.** Nothing here touches S/4HANA's core. The one link is the communication arrangement on the S/4HANA side, which has its own credentials and its own rotation; record those in the same register.

### Where AI fits

Agents are apps, and they usually hold more credentials than ordinary apps: one for the model service (SAP AI Core), one per tool or system they call, and one for their own API. Three things change:

- **An agent should never see a secret.** Read credentials in the tool layer, outside the model's prompt, so a prompt injection can't make the agent repeat one. [Secrets, API authentication and OAuth](https://erpfde.com/topics/secrets-api-authentication-and-oauth/) covers the pattern.
- **A gateway concentrates credentials.** Calder's AI gateway holds the SAP AI Core key for every agent behind it. That is why its credentials (C02, C03) are the first to fix, and why [AI supply-chain controls](https://erpfde.com/topics/ai-supply-chain-controls/) rotated them after the supply-chain incident.
- **AI can help read the register, not run it.** A model can draft the rotation plan from the register or explain a failing rule. Creating or deleting credentials stays a deliberate human step, because a wrong delete stops production.

As far as this run could find, SAP offers no AI feature that manages bindings or rotates credentials as of 26 November 2026.

### Pitfalls

- **Copying a key into an app that could be bound.** It works on day one and becomes the credential nobody rotates.
- **Rotating in the wrong order.** Deleting the old key before the consumer has the new one is an outage you caused.
- **Forgetting the restart.** On Cloud Foundry a new binding reaches the app only after a restart or re-push.
- **Removing `instance-secret` too early.** Every binding and key still using it fails at the same moment; check `instanceSecretLastUsedAt` first.
- **Short certificates without automation.** A 30-day certificate and a quarterly deployment can't work together.
- **Assuming the Kyma policy rotates on the minute.** It acts in the next reconciliation loop; use `forceRotate` for an urgent change.
- **Secret values in the register.** The register lists facts about credentials, never the credentials.

### Exercise

Add Calder's next workload and apply the decisions, then look ahead to January.

1. Open `unit21/calder_credentials.json`.
2. Under `instances`, add the SAP AI Core instance for the casting porosity check (W08 from the runtime topic's exercise):

   ```json
   "porosity-aicore": {"offering": "aicore", "plan": "extended", "subaccount": "calder-ai-prod"}
   ```

3. Under `credentials`, add its Kyma binding:

   ```json
   {"id": "C09", "kind": "binding", "runtime": "kyma", "instance": "porosity-aicore",
    "consumer": "porosity-check (W08)", "consumer_on_btp": true, "credential_type": "client-secret",
    "created": "2026-11-26", "owner": "00100288", "stored": "Kyma secret"}
   ```

4. Run `python unit21/credential_register.py`. C09 fails K07.
5. Give C09 the same rotation policy as C08 (`"rotation_policy": {"enabled": true, "rotationFrequency": "600h", "rotatedBindingTTL": "48h"}`) and run again: C09 is OK.
6. Apply the decisions from the Architecture view as if done today:
   - Delete the C05 and C06 entries (the keys were deleted).
   - For C02, set `"credential_type": "binding-secret"` and `"created": "2026-11-26"`, and set `calder-ai-gw-xsuaa`'s `credential_types` to `["binding-secret"]`.
   - For C07, set `"created": "2026-11-26"` and `"expires": "2026-12-26"` (the portal was redeployed).
7. Run the check. The last line must read `7 credentials: 6 OK, 1 WARN, 0 FAIL`; C03 keeps its warning until someone confirms whether SAP AI Core can be bound.
8. Look ahead: run `python unit21/credential_register.py --today 2027-01-20`. Four credentials fail: C01, C03 and C04 pass 90 days, and C07's certificate has expired. Add a rotation calendar with their due dates to the decision record in `unit21/calder_credential_register.md` (run `--write` first).

**Done when:** the check prints `7 credentials: 6 OK, 1 WARN, 0 FAIL`, and your register document lists the four credentials due by 2027-01-20 with a date and owner for each. The register feeds [the BTP security model](https://erpfde.com/topics/btp-security-model/) and [CI/CD and transport management on BTP](https://erpfde.com/topics/btp-cicd-and-transport/).

### Check yourself

1. What is the difference between a binding and a service key on BTP?
   - A. A binding is meant for production instances, while a service key is meant for trial instances
   - B. A binding delivers credentials to an app on BTP; a key is copied to an outside consumer
   - C. A binding holds a certificate, while a service key always holds a client secret
   - D. A binding lasts as long as the instance, while a key expires after 90 days

   Answer: B. Both create a credential at the broker. A binding is handed to an app by the platform; a service key is created for a laptop, tool or system outside the app, and someone copies it there.

2. You bind a new instance to a running Cloud Foundry app. The app still can't find the credentials. Why?
   - A. The binding takes 24 hours to reach SAP Service Manager
   - B. Cloud Foundry delivers credentials only to apps deployed as MTAs
   - C. The app sees a new binding only after a restart or re-push
   - D. The credentials go to `SERVICE_BINDING_ROOT`, which Python can't read

   Answer: C. The Cloud Foundry documentation says a new or changed binding is delivered at the next restart or re-push. Until then `VCAP_SERVICES` holds the old set.

3. A team wants to remove `instance-secret` from an XSUAA instance today. What should happen first?
   - A. Delete the instance and create a new one with the same name
   - B. Set the instance's bindings to read-only for a week
   - C. Ask SAP support to convert the instance's secrets on the broker side overnight
   - D. Rebind every app, replace every key, and check `instanceSecretLastUsedAt`

   Answer: D. Removing the type invalidates every binding and key still using it at once. SAP's procedure allows both types, rebinds and replaces keys, confirms the instance secret is no longer used, and only then removes it.

4. In `read_bindings()`, why does the script check `SERVICE_BINDING_ROOT`, then `VCAP_SERVICES_FILE_PATH`, then `VCAP_SERVICES`?
   - A. Because SAP requires apps to support all three at once
   - B. Because an app uses one delivery method, and one reader keeps the code portable
   - C. Because `VCAP_SERVICES` is deprecated on SAP BTP since 2026
   - D. Because the three places hold different credentials for one and the same binding

   Answer: B. Cloud Foundry offers three mutually exclusive delivery methods, and a mounted Kyma Secret looks like the file layout. One function that tries each place lets the same code run on Cloud Foundry, Kyma and a laptop.

5. A Kyma `ServiceBinding` has `credentialsRotationPolicy` with `rotationFrequency: 600h`. A key leaked an hour ago. What do you do?
   - A. Wait: the operator rotates within the hour after a leak
   - B. Lower `rotatedBindingTTL` to zero so the old Secret disappears
   - C. Add the `services.cloud.sap.com/forceRotate: "true"` annotation
   - D. Delete the pods so Kubernetes fetches a new credential

   Answer: C. The policy rotates on its schedule in the next reconciliation loop. The forceRotate annotation triggers an immediate rotation, and it only works because rotation is already enabled.

6. Calder's portal uses an XSUAA-generated certificate valid for 30 days, and the team deploys once a quarter. What follows?
   - A. Nothing: XSUAA renews generated certificates automatically
   - B. The app keeps working, because XSUAA doesn't check revocation
   - C. The certificate can be extended to a full year with the `validity` parameter
   - D. The app stops when the certificate expires, unless deployments are automated

   Answer: D. Generated certificates last 1 to 30 days, and SAP recommends automating deployments to keep up. A quarterly deployment can't renew a 30-day certificate in time.

7. Why does the register store facts about credentials but never their values?
   - A. Because the btp CLI can't export secret values
   - B. Because the values change far too often to keep them in a Git repository
   - C. Because a register full of secrets would be one more place to leak them
   - D. Because SAP forbids storing client IDs outside BTP

   Answer: C. The register answers who holds what, where and since when. Copying the secrets into it would create exactly the uncontrolled copy the register exists to prevent.

8. An agent behind Calder's AI gateway is asked, through a prompt injection, to print its credentials. What design prevents harm?
   - A. The tool layer reads credentials, so the model never has them to print
   - B. A rule in the system prompt telling the model not to reveal secrets
   - C. Rotating the gateway's key every 600 hours with a Kyma policy
   - D. Storing the key in a user-provided service instead of a binding

   Answer: A. A secret the model never sees can't be leaked by the model. Prompt rules can be overridden, and rotation only limits how long a leaked key works.

## Sources

- [About Services (SAP BTP documentation, SAP-docs on GitHub, read 2026-11-26)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/about-services-d1d0fc8.md): services offered in a marketplace; a service instance is a single instantiation created with a plan, a plan is a configuration variant ("t-shirt sizes"); bind instances to deliver credentials to an app, or use service keys to talk to an instance directly; binding in the manifest; user-provided service instances
- [Service Instance Secrets (SAP Authorization and Trust Management service, SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/service-instance-secrets-5578ec4.md): client ID and secret created at binding or service key creation; instance secret shared by all bindings; from 19 January 2026 instance-secret is no longer supported for new bindings and service keys; binding secret is the default and lives as long as the binding or key; X.509 secrets; no revocation check, so delete the binding to stop a certificate; credential-types in xs-security.json
- [Migrate from Instance Secrets to Binding Secrets (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/migrate-from-instance-secrets-to-binding-secrets-dcee867.md): allow both credential types, update the instance, unbind and rebind, replace service keys, check instanceSecretLastUsedAt via GET /sap/rest/authorization/v2/apps/{id}, then allow binding-secret only; removing instance-secret invalidates existing instance-secret bindings and keys
- [Parameters for X.509 Certificates Managed by SAP Authorization and Trust Management Service (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/parameters-for-x-509-certificates-managed-by-sap-authorization-and-trust-management-ser-436ed68.md): parameters.json with credential-type x509, key-length, validity and validity-type; default validity 7, range 1 to 30 DAYS
- [Security Recommendations for SAP Authorization and Trust Management Service (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/60-security/security-recommendations-for-sap-authorization-and-trust-management-service-0578b80.md): developers enable individual secrets for each binding (BTP-UAA-0003); PaaS operators automate deployment to cope with the lifetime of X.509 certificates (BTP-UAA-0014); audit log archiving and integration recommendations
- [Rotating Service Bindings (Kyma environment, SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/rotating-service-bindings-37ac30a.md): credentialsRotationPolicy with enabled, rotationFrequency and rotatedBindingTTL; doesn't manage credential validity; runs in the reconciliation loop; services.cloud.sap.com/forceRotate annotation; old credentials kept in a Secret labeled services.cloud.sap.com/stale; status.lastCredentialsRotationTime; example 600h and 48h
- [Service Keys (multitarget applications, SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/service-keys-32297f1.md): service-keys parameter on a managed-service resource; consumption through org.cloudfoundry.existing-service-key and env-var-name; automatic renewal on redeployment with ${timestamp} in the key name, after which the old key is deleted
- [Working with Resources of the SAP Service Manager Using the btp CLI (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/working-with-resources-of-the-sap-service-manager-using-the-btp-cli-fe6a53b.md): btp list/get/create/delete services/instance and services/binding, share and unshare services/instance, list/get services/plan and services/offering, platforms and brokers; commands run in a subaccount; --show-parameters only when instances_retrievable or bindings_retrievable is true
- [Delivering service credentials to an app (Cloud Foundry documentation source, cloudfoundry/docs-dev-guide, read 2026-11-26)](https://github.com/cloudfoundry/docs-dev-guide/blob/master/services/application-binding.html.md.erb): three mutually exclusive delivery methods (VCAP_SERVICES at most 130 KB, file-based VCAP_SERVICES_FILE_PATH, SERVICE_BINDING_ROOT compatible with servicebinding.io, 1 MB); restart or re-push after binding; --binding-name; update credentials with downtime, blue-green, or experimental binding rotation with --strategy multiple, cf restage --strategy rolling and cf cleanup-outdated-service-bindings (cf CLI 8.18.0, platform must allow two bindings)
- [SAP BTP Service Operator (SAP on GitHub, README, last commit 2026-11-16)](https://github.com/SAP/sap-btp-service-operator): talks to SAP Service Manager over the Open Service Broker API; ServiceInstance with serviceOfferingName and servicePlanName; ServiceBinding creates a Kubernetes Secret; secretKey, secretRootKey and secretTemplate formats; credentialsRotationPolicy reference
