# The SAP authorization concept in depth

> How an ABAP system decides yes or no: objects, fields, roles, profiles, proposals, derived roles and the user buffer, and how to read a failed check.

- Course: Orchestrate, Unit 27 · Security, identity and compliance
- Page: https://erpfde.com/topics/sap-authorization-concept-in-depth/
- Updated: 2026-12-01
- Reading time: Foundational 8 min, Deep 40 min

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

## Foundational layer

### The 60-second version

Every time someone in an SAP S/4HANA or ECC system starts a transaction, opens an app or calls a function, the system asks one question: does this user hold a permission that covers exactly this action, on exactly this organizational unit? The answer comes from small building blocks. An **authorization object** names what is being protected. Its **fields** say what values are allowed, such as "display" and "company code CP10". **Roles** bundle those permissions, a **profile** is the compiled form the system reads, and each user carries a copy of their profiles in memory while they're logged on.

[Roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/) decided the shape of Calder Pumpworks' access: which jobs, which org units, which conflicts. Calder is the course's fictional pump maker. This topic opens the machine underneath. It explains why a role can look right and still fail, why a new hire can't start a transaction the morning after their role was assigned, and how to read the screen that tells you which permission was missing.

### Why it matters to the business

Most "authorization tickets" are not design problems. They are mechanics: a role changed but never regenerated, an assignment that starts tomorrow, a user who hasn't logged on again, a permission switched off to make a complaint go away. Each one costs time at the service desk. Some cost much more. A check that has been switched off lets every user with the transaction release any blocked invoice, in any company code, and nobody sees it until an auditor or a fraud does.

At Calder, four tickets arrived on Monday 30 November. A new Rockford buyer can't create a purchase order. The Augsburg buyer can't change one, although his role was updated on Friday. The AP supervisor could release an Augsburg invoice last week but a fix "for her" was made in the wrong place. And a buyer covering Augsburg's payables still holds a "temporary" profile from October. All four have the same cause: nobody on the team knew how the pieces fit together.

Leaders don't need to maintain roles. They need to know that the authorization concept has moving parts, that each part has an owner, and that a quick fix in the wrong layer quietly widens access.

### How SAP does it

In ABAP-based systems (SAP S/4HANA Cloud Private Edition, S/4HANA on-premise and ECC), the concept is the same and SAP teaches it in one course on SAP Learning ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/explaining-elements-and-terminology-of-the-abap-authorization-concept)). As read on 1 December 2026, it has these parts:

| Part | What it is | Where it is maintained |
| --- | --- | --- |
| Authorization object and fields | The lock: up to ten fields checked together | Delivered by SAP, or created by a developer for custom code |
| Proposals | Which objects and values a transaction or app usually needs | `SU22` (SAP's defaults), `SU24` (the customer's copy) |
| Role | A menu of transactions or apps plus the authorizations they need | `PFCG` |
| Profile | The compiled authorizations of a role | Generated by `PFCG`, never by hand in normal operation |
| User master | The user's roles and, after a comparison, their profiles | `SU01`, comparison with `PFUD` |
| User buffer | The user's authorizations in memory, built at logon | Read with `SU56` |
| Error analysis | The last failed check, and a full trace | `SU53`, `STAUTHTRACE` |

SAP Fiori apps sit on the same concept: the app's data service has its own start check, and the business checks behind it are ordinary authorization objects ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-fiori-on-sap-s-4hana/explaining-sap-fiori-authorization-model)).

SAP S/4HANA Cloud Public Edition is different: customers build business roles from SAP's business catalogs and set restrictions, without `PFCG`. That model is the next topic, [business roles in cloud editions](https://erpfde.com/topics/business-roles-in-cloud-editions/). The checks underneath are still ABAP checks, which is why the vocabulary here carries over.

### Reading a refusal: a guide for leads

When someone says "I'm not authorized", the system has already recorded which check failed. Ask for that record before anyone changes a role.

| What the record says | What it usually means | Who acts |
| --- | --- | --- |
| The transaction or app itself is not allowed | The role isn't assigned, isn't in the user master yet, or doesn't contain this transaction | User administration: check assignment dates and the comparison |
| The user has the permission, but for different values | Usually correct: the user is outside their org scope. Sometimes a typo in a derived role | The role owner decides; don't widen it to close the ticket |
| No permission for this object at all | The role lacks a piece the transaction needs, or the job shouldn't do this | Role owner and security team, through a change request |
| "All checks have so far been successful" | Not an authorization problem | Back to the application team |
| The check passed although it shouldn't | A check is switched off, a manual profile, or an `*` in an org field | Security team, as an incident |

> **Note** **For functional consultants:** your configuration decides which org values a document carries, and therefore which values a check needs. A new plant, purchasing organization or document type means roles must be extended with it. Add negative test cases to your test plan ("the Rockford buyer can't display an Augsburg purchase order"), not only positive ones. And when you test with a new role, log off and on again first; the system reads your permissions at logon.

### Questions to ask

Ask your security team, basis team or implementation partner:

- Who may switch an authorization check off in `SU24`, and how would we find out it happened?
- When a role assignment starts in the future, which job puts it into the user master on the day? Is it scheduled in every client?
- Do we use derived roles for our org units, and who regenerates them when the master role changes?
- Which users hold profiles that no role generates, and why?
- Which roles contain `*` in an org level, such as company code or plant?
- After the last upgrade, who reviewed the `SU25` results, and was `SAP_NEW` removed from users afterwards?
- When a user reports a refusal, do we ask for `SU53` or a trace before changing anything?

### Common misconceptions

- **"If the role looks right in the role editor, the user has it."** The user gets nothing until the role's profile is generated, the user master is compared and the user logs on again.
- **"Removing the transaction from the menu removes the access."** Only the start check. An authorization left in the role still answers yes to the same check from a report, an API or another transaction.
- **"Switching a check off for one transaction is harmless."** It makes that check pass for everyone who can start the transaction, in every org unit.
- **"A refusal means the role is broken."** Many refusals are correct: the user is outside their scope. Fixing those widens access.
- **"`SU53` shows everything."** It shows the last failed check, at most 100 per user from the last three hours. A trace shows all checks in order.

### Key terms

- **Authorization object:** a named group of up to ten fields that the system checks together, such as an activity and a company code.
- **Authorization:** a set of allowed values for one object's fields. A role holds many.
- **Profile:** the generated, compiled form of a role's authorizations, written into the user master.
- **Proposal (`SU24`):** the objects and default values a transaction or app usually needs, read by the role editor.
- **Check indicator:** the `SU24` setting that decides whether a check in a transaction runs at all.
- **Organizational level:** an org field (company code, plant, purchasing organization) maintained once per role instead of in each authorization.
- **Derived role:** a role that inherits menu and authorizations from a master role and sets only its own org levels.
- **User comparison (`PFUD`):** the step that writes a role's profile into the user master for the assignment's valid dates.
- **User buffer:** the user's authorizations in memory, built at logon; changes reach it at the next logon.
- **`SU53`:** the screen that shows the user's last failed check: the object, the values needed and the values held.

### Check yourself

1. A manager asks why a new buyer can't create purchase orders on her first morning, although her role was assigned yesterday. What is the most likely cause to check first?
   - A. The buyer's derived role needs a different company code to work
   - B. The assignment starts today and nobody ran the user comparison
   - C. Purchase order creation needs a separate approval from SAP
   - D. The role editor shows a green light, so the role must be fine

   Answer: B. A role reaches the user master only through the user comparison, and only for dates the assignment covers. If the assignment starts today and the comparison ran yesterday, the user holds nothing yet. Check the assignment dates and the comparison job before touching the role.

2. The Rockford buyer is refused when he opens an Augsburg purchase order, and SU53 shows he holds the permission for Rockford's purchasing organization only. What should the lead do?
   - A. Add Augsburg's purchasing organization so the ticket can be closed
   - B. Switch the check off for that transaction so buyers can help each other
   - C. Treat the refusal as correct unless the job really needs Augsburg
   - D. Give him a temporary profile with every purchasing organization

   Answer: C. The refusal shows the design working: he is outside his scope. Widening the role to close a ticket is how access creeps. Only the role owner, deciding the job needs Augsburg, should change it.

3. Why is switching an authorization check off in SU24 a risk for the whole company, not one user?
   - A. It deletes the authorization object from every role in the system
   - B. The check then passes for everyone who can start the transaction
   - C. It forces every user to log on again before the next payment run
   - D. It stops the system from writing anything to the security audit log

   Answer: B. The check indicator applies to the transaction, not to a user. With "Do not check", every user who can start the transaction passes that check, in every org unit. SAP says it is never permissible for Basis and HR objects; for others it should be an exception with an owner.

4. Which question best tests whether a team understands how derived roles stay correct?
   - A. Which SAP partner configured our roles during the implementation?
   - B. How many transactions does our largest composite role contain?
   - C. Do our derived roles use the same names as SAP's delivered roles?
   - D. Who regenerates the derived roles when a master role's menu changes?

   Answer: D. Derived roles take their menu and authorizations from the master, but the change reaches users only when the derived roles are generated. At Calder, the Augsburg buyer lost a new function because one derived role was skipped. Someone must own that step.

5. SU53 answers "All authorization checks have so far been successful" for a user who reports an error. What does that tell you?
   - A. The user's role is fine, but the profile needs to be generated again
   - B. The error is very likely not an authorization problem at all
   - C. The check was switched off, so the security team must investigate
   - D. The user buffer is full and must be reset by the basis team

   Answer: B. SAP's training says that when SU53 shows only successful checks, the problem is not an authorization problem. The case goes back to the application team, for example because the document doesn't exist.

6. A consultant proposes giving a buyer who covers payables a profile directly in his user master "for two weeks". What is the main concern?
   - A. Profiles in the user master make the user's logon slower
   - B. The profile would be deleted by the next upgrade of the system
   - C. SAP charges a separate licence fee for each manual profile
   - D. No role owns it, so no review or comparison removes it on time

   Answer: D. SAP recommends generated profiles from roles and manual profiles only in exceptions. A manual profile sits outside the role process: nobody reviews it with the role, and the user comparison doesn't remove it. Calder's "two weeks" profile was still there two months later, with release rights everywhere.

## Deep layer

### Mental model

Think of the authorization concept as a **compiler and a cache**.

- **Source:** what people maintain. `SU24` says which checks each transaction makes and what values to propose. `PFCG` roles say which transactions a job gets and which org units it covers.
- **Compiled output:** the **profile**. Generating a role turns its source into a list of authorizations with concrete values.
- **Deployment:** the **user comparison** writes profiles into the user master, for the dates the assignment is valid.
- **Cache:** the **user buffer**. At logon, the system loads the user's authorizations into memory. Every check reads the buffer, not the role.
- **Runtime:** a check in the program asks the buffer for one object and a set of values. The answer is a return code.

Most failures happen between the layers: the source changed but wasn't compiled, the compiled output wasn't deployed, or the cache is old. Most dangerous changes happen in the source in a place nobody reviews, such as an `SU24` check indicator or a manual insert in a role. Read every ticket by asking which layer is out of step.

### How it works

#### The building blocks

SAP Learning defines the pieces from the bottom up ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/explaining-elements-and-terminology-of-the-abap-authorization-concept)):

- An **authorization field** is the smallest unit checked, such as `ACTVT` (activity) or a company code field.
- An **authorization object** groups one to ten fields that are checked together. Objects are grouped into **object classes**; the course's example is class `FI` with objects starting with `F_`.
- An **authorization** is one instance of an object: a set of allowed values for each field. A user can hold several authorizations for the same object.
- An **authorization profile** holds authorizations for many objects. A **role**, built in `PFCG`, generates its profile automatically.

Activities are coded values: the course points to table `TACT` for all activities and `TACTZ` for which activities each object allows. [Agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) used `01` create, `02` change, `03` display and `06` delete; this topic's lab uses the same.

Customer objects, classes and fields start with `Y` or `Z`. SAP delivers over 1,200 roles whose names begin with `SAP_`; SAP Learning calls them templates, and roles starting with `SAP_` can be overwritten at upgrade, so copy them before changing ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/creating-standard-roles)).

#### The check at runtime

```mermaid
sequenceDiagram
  participant U as User
  participant K as Kernel
  participant B as User buffer
  participant P as Program
  U->>K: start transaction
  K->>B: S_TCODE with TCD = transaction
  B-->>K: 0 or refused
  K->>B: object in TSTCA, if any
  K->>P: run
  P->>P: read document (org values)
  P->>B: AUTHORITY-CHECK object, fields, values
  B-->>P: sy-subrc
  P-->>U: proceed or "no authorization"
```

SAP Learning describes the order for a transaction ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/identifying-authorization-checks-in-the-sap-system)):

1. **Start check.** The user must hold `S_TCODE` with field `TCD` set to the transaction code.
2. **Transaction's own object.** If an object is assigned to the transaction (stored in table `TSTCA`), the user must hold it too.
3. **Program checks.** The program runs `AUTHORITY-CHECK` for the objects it protects, with values it knows at that point: the activity, and org values read from the document or the selection.

The same lesson lists the return codes: `0` the user is authorized; `4` the user holds the object but not with the checked values; `12` the user holds no authorization for the object; `16` no profile in the user master. One authorization must cover **all** checked fields at once; holding "display" in one authorization and "CP20" in another doesn't add up to "display in CP20".

A program can skip a field by checking it against `DUMMY`; SAP's `SU24` help says such fields stay empty in the proposal ([SAP Help](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/1e/ce3075dd4e4116b23e006552374ffc/content.htm)). And `AUTHORITY-CHECK` only answers; the program decides what to do with a non-zero code. That is why custom code needs review: a missing `IF sy-subrc <> 0` is an open door.

Transactions are one front door. SAP Learning names the others' start checks: `S_START` for Web Dynpro ABAP applications (inactive when delivered; SAP Note 1413011 activates it), `S_RFC` for remote function calls (checked on the function group first, then the module, once per RFC session) and `S_SERVICE` for SAP Fiori apps' data services. Behind every door, the program checks are the same objects.

#### Where the values come from: SU22, SU24 and PFCG

Nobody types every object into every role. The role editor reads **proposals**:

- SAP delivers default proposals per transaction or app in tables `USOBX` (which checks run) and `USOBT` (default values), maintained by SAP in `SU22`.
- The customer works on copies, `USOBX_C` and `USOBT_C`, maintained in `SU24`. `SU25` fills them at installation and compares them with SAP's new defaults after an upgrade ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/investigating-installation-and-upgrade-tasks)).

Each `SU24` line has two settings ([SAP Help](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/1e/ce3075dd4e4116b23e006552374ffc/content.htm)):

| Setting | Values | Effect |
| --- | --- | --- |
| Proposal | No; Yes; Yes, Without Values | Whether `PFCG` puts the object in the role, with default values or empty |
| Check indicator | Check; Do not check | Whether the check runs at all. "Do not check" makes `AUTHORITY-CHECK` return 0 for that transaction |

SAP's help says "Do not check" is never permissible for Basis and HR objects. Org fields in proposals hold variables such as `$BUKRS` that the role fills from its org levels. Two more warnings from SAP Learning: a change of values in `SU24` is redistributed as a new default to every role containing the transaction, and there is no standard restore for `SU24` data. `SU24` is configuration with company-wide reach; give it the same change control as a role.

#### Statuses and traffic lights in PFCG

When `PFCG` builds a role's authorizations from proposals, it marks each one ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/outlining-subtleties-of-authorization-maintenance)):

| Status | Meaning |
| --- | --- |
| Standard | All values as proposed |
| Maintained | A field the proposal left empty has been filled |
| Changed | A proposed value has been changed |
| Manual | The authorization was inserted by hand, not proposed by the menu |

After a menu change and comparison, authorizations are marked `Old` or `New`. Traffic lights summarize what's still open: red means an org level is empty, yellow means another field is empty, green means every field has a value. SAP's course is blunt that green doesn't mean correct.

For a reviewer, `Changed` and `Manual` are where to look. `Changed` means someone overrode SAP's or the security team's proposal. `Manual` means the role holds an authorization its menu doesn't need, which is still reachable through any other entry point that makes the same check. Set org levels with the **Organizational Levels** button, not in the tree; entering them directly sets the status to `Changed`.

#### Derived roles and org levels

[Roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/) introduced derived roles as the way to scope one job to many org units. The mechanics matter for operations ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/implementing-a-derived-role-strategy)):

- The derived role names its source in **Derive from Role**. It inherits the menu, which can't be changed in the derived role, and the authorizations. User assignments are not inherited.
- **Generate Derived Roles** in the master copies the normal field values to every derived role and generates their profiles. Org levels are not overwritten.
- **Transfer Data** in a derived role pulls the master's values, usually for the first fill.
- Inheritance can be cancelled, but not restored.

The failure mode: the master changes, the menu change shows up in the derived roles, but their **profiles** are not regenerated. The role editor looks right; users get the old profile.

#### From role to user: profiles, comparison, buffer

Generating a role creates its profile. `PFCG` then needs two more steps before a user benefits ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/creating-standard-roles)):

1. **User comparison.** The profile is written into the user master only if the assignment's validity includes today. For assignments with future dates, SAP names report `PFCG_TIME_DEPENDENCY`, scheduled as a background job, or transaction `PFUD`.
2. **Logon.** The user buffer is built at logon and holds all of the user's authorizations; `SU56` shows it ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/identifying-authorization-checks-in-the-sap-system)).

SAP warns never to enter generated profiles directly in `SU01`: the comparison removes generated profiles without a matching role. Manual profiles, built by hand, are not removed, which is exactly why they linger.

#### Fiori apps and CDS views

For an SAP Fiori app on S/4HANA with the embedded front-end server, one `PFCG` role in the S/4HANA system is enough. Adding the app's business catalog to the role menu brings in the start authorization for its OData service (object `S_SERVICE`) through the `SU24` proposals; the business authorizations come from the same proposals ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-fiori-on-sap-s-4hana/explaining-sap-fiori-authorization-model)).

Reads through CDS views add a second layer. A **CDS access control**, written in the Data Control Language, can tie view elements to authorization objects with a PFCG condition, so the database returns only rows the user is authorized for. If a view has no access control, no restriction applies. SAP recommends keeping classic checks for start authorizations and using CDS access control for instance-based checks ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-fiori-on-sap-s-4hana/describing-the-authorization-concept-for-abap-cds)). The practical difference: a classic check refuses; an access control filters. A missing row in a Fiori list may be an authorization, not missing data. [Grounding on SAP data with authorizations](https://erpfde.com/topics/grounding-on-sap-data-with-authorizations/) relies on exactly this filtering.

#### Upgrades

After an upgrade, SAP's new defaults arrive in `USOBX`/`USOBT`, and `SU25`'s post-processing compares them with the customer tables, flags roles to check, and transports the result. The role `SAP_NEW` bridges new checks; SAP Learning warns it is very broad, with `*` in org levels, and should be removed from users promptly. `SU24_AUTO_REPAIR` fixes inconsistencies in the proposal data ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/investigating-installation-and-upgrade-tasks)). An upgrade plan without these steps produces a wave of tickets, or worse, a wave of `SAP_NEW` that nobody takes away.

#### Troubleshooting a failed check

SAP Learning gives two tools and one rule ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/troubleshouting-authorization-checks)):

- **`SU53`** shows the user's last failed check: the object, the values the program needed and the values the user holds. It works from any session. It keeps at most 100 failed checks per user, from the last three hours at most, in a buffer on the application server. "All authorization checks have so far been successful" means it isn't an authorization problem.
- **`STAUTHTRACE`** traces only authorization checks, on one or all servers, optionally for one user; `ST01` is the general system trace. A trace line shows the object, the return code and each field with its tested value.
- **The rule:** don't turn trace or `SU53` results directly into roles. Analyze first. A trace records what a user did, including things the job shouldn't do.

For CDS access controls, the trace shows the CDS entity and the fields used to filter; SAP's Fiori course uses `STAUTHTRACE` and `STUSERTRACE` for this.

### Build it yourself: an authorization lab for Calder

You will run a local model of the authorization concept on Calder's procure-to-pay roles: proposals, master and derived roles, profiles, the user comparison, the user buffer, the check and its return codes, an `SU53` screen and a trace. Then you'll work Monday's four tickets, fix six findings and prove the fix with a review.

```mermaid
flowchart LR
  S[SU24 proposals] --> M[Master role]
  M -->|generate| D[Derived roles<br/>+ org levels]
  D -->|compare| UM[User master]
  UM -->|logon| B[User buffer]
  B --> C[check: S_TCODE,<br/>then program checks]
  C --> R[SU53 and trace]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 27](https://erpfde.com/topics/set-up-for-unit-27/). [Roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/) built Calder's role matrix; this lab works one level below it. This walkthrough doesn't repeat those steps.

> **Note** New words. **JSON** is a text format for structured data; the lab keeps Calder's roles and users in one JSON file. A **return code** is a number a check gives back: `0` means yes. A **self-test** runs the whole lab in a temporary folder and checks the results.

> **Note** The lab is a model, not SAP. `S_TCODE` and its field `TCD` are SAP's. The objects `ZLAB_*`, the transactions `ZP_*`, their proposals, the profile names `T_CP27…` and the rules `A01` to `A08` are course labels shaped like SAP's. Real transactions' proposals come from `SU24` and differ by release. All people and documents are fictional.

#### What you need

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

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

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

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

4. The `unit27` folder exists from the unit setup. If it doesn't, create it with `mkdir unit27`.

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

#### Step 2: Create the lab script

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

```python
"""A local model of the ABAP authorization concept, using Calder's procure-to-pay roles.

Course lab for the topic "The SAP authorization concept in depth" (Unit 27).
Built-in modules only, no randomness. Lab date: Tuesday 2026-12-01.

The objects (ZLAB_*), transactions (ZP_*), proposals, profile names and rules are course
labels shaped like SAP's. S_TCODE and its field TCD are SAP's. Real proposals come from SU24
and differ by release. All data is fictional.

    python unit27/auth_concept.py --init                       write unit27/auth/landscape.json
    python unit27/auth_concept.py review                       check the design against A01-A08
    python unit27/auth_concept.py roles [ROLE]                 show roles, statuses and profiles
    python unit27/auth_concept.py check USER TCODE [DOCUMENT]  start a transaction, like a user would
    python unit27/auth_concept.py su53 USER                    last failed check (like SU53)
    python unit27/auth_concept.py su56 USER                    the user buffer (like SU56)
    python unit27/auth_concept.py trace [N]                    last N trace lines
    python unit27/auth_concept.py compare USER|all             user comparison (like PFUD)
    python unit27/auth_concept.py logon USER|all               log on again: rebuild the buffer
    python unit27/auth_concept.py generate MASTER              generate derived roles from a master
    python unit27/auth_concept.py orglevel ROLE FIELD VALUES   set an org level and regenerate
    python unit27/auth_concept.py su24 TCODE OBJECT check|nocheck
    python unit27/auth_concept.py remove-auth MASTER OBJECT    delete a manual authorization
    python unit27/auth_concept.py remove-profile USER PROFILE  delete a profile from a user master
    python unit27/auth_concept.py add-master ROLE TCODE[,TCODE]
    python unit27/auth_concept.py derive ROLE MASTER FIELD=V1[,V2] ...
    python unit27/auth_concept.py assign USER ROLE FROM TO
    python unit27/auth_concept.py --selftest
"""
import copy
import json
import os
import sys
import tempfile
from pathlib import Path

HERE = Path(os.environ.get("AUTH_LAB_DIR", Path(__file__).resolve().parent / "auth"))
FILE = HERE / "landscape.json"
TODAY = "2026-12-01"
ORG_FIELDS = {"PURCH_ORG": "$PURCH_ORG", "PLANT": "$PLANT", "COMP_CODE": "$COMP_CODE"}


def sample():
    """The Calder landscape on Tuesday 2026-12-01 08:00, with six problems planted."""
    return {
        "clock": 10,
        "objects": {
            "S_TCODE": ["TCD"],
            "ZLAB_PO_ORG": ["ACTVT", "PURCH_ORG"],
            "ZLAB_PO_PLNT": ["ACTVT", "PLANT"],
            "ZLAB_INV_CC": ["ACTVT", "COMP_CODE"],
            "ZLAB_INV_REL": ["ACTVT", "COMP_CODE"],
        },
        # What each transaction's program checks, with the activity it needs (01 create,
        # 02 change, 03 display, 06 delete). Org values come from the document.
        "tcodes": {
            "ZP_PO_CREATE": {"text": "Create purchase order", "checks": [["ZLAB_PO_ORG", "01"], ["ZLAB_PO_PLNT", "01"]]},
            "ZP_PO_CHANGE": {"text": "Change purchase order", "checks": [["ZLAB_PO_ORG", "02"], ["ZLAB_PO_PLNT", "02"]]},
            "ZP_PO_DISPLAY": {"text": "Display purchase order", "checks": [["ZLAB_PO_ORG", "03"]]},
            "ZP_INV_ENTER": {"text": "Enter supplier invoice", "checks": [["ZLAB_INV_CC", "01"], ["ZLAB_PO_ORG", "03"]]},
            "ZP_INV_DISPLAY": {"text": "Display supplier invoice", "checks": [["ZLAB_INV_CC", "03"]]},
            "ZP_INV_RELEASE": {"text": "Release blocked invoice", "checks": [["ZLAB_INV_REL", "02"]]},
        },
        # SU24-style proposals: proposal YES, YES_NO_VALUES or NO; check indicator CHECK or NO_CHECK.
        "su24": {
            "ZP_PO_CREATE": [["ZLAB_PO_ORG", "YES", "CHECK", ["01"]], ["ZLAB_PO_PLNT", "YES_NO_VALUES", "CHECK", []]],
            "ZP_PO_CHANGE": [["ZLAB_PO_ORG", "YES", "CHECK", ["02"]], ["ZLAB_PO_PLNT", "YES_NO_VALUES", "CHECK", []]],
            "ZP_PO_DISPLAY": [["ZLAB_PO_ORG", "YES", "CHECK", ["03"]]],
            "ZP_INV_ENTER": [["ZLAB_INV_CC", "YES", "CHECK", ["01"]], ["ZLAB_PO_ORG", "YES", "CHECK", ["03"]]],
            "ZP_INV_DISPLAY": [["ZLAB_INV_CC", "YES", "CHECK", ["03"]]],
            # Planted: switched to NO_CHECK on 2026-11-25 to make a ticket go away.
            "ZP_INV_RELEASE": [["ZLAB_INV_REL", "YES", "NOCHECK", ["02"]]],
        },
        "masters": {
            "ZM_P2P_BUYER": {"menu": ["ZP_PO_CREATE", "ZP_PO_CHANGE", "ZP_PO_DISPLAY"], "changed": "2026-11-27", "tick": 5,
                             "edits": [["ZLAB_PO_PLNT", "maintain", ["01", "02", "03"]],
                                       ["ZLAB_PO_ORG", "change", ["01", "02", "03", "06"]]]},
            "ZM_P2P_AP_ACCOUNTANT": {"menu": ["ZP_INV_ENTER", "ZP_INV_DISPLAY", "ZP_PO_DISPLAY"], "changed": "2026-11-02", "tick": 1,
                                     # Planted: a release authorization inserted by hand.
                                     "edits": [["ZLAB_INV_REL", "manual", ["02"]]]},
            "ZM_P2P_AP_SUPERVISOR": {"menu": ["ZP_INV_RELEASE", "ZP_INV_DISPLAY", "ZP_PO_DISPLAY"], "changed": "2026-11-02", "tick": 1,
                                     "edits": []},
        },
        "derived": {
            "ZD_P2P_BUYER_US": {"from": "ZM_P2P_BUYER", "org": {"PURCH_ORG": ["PUUS"], "PLANT": ["CP11"], "COMP_CODE": ["CP10"]}, "generated": "2026-11-27", "tick": 6},
            # Planted: not regenerated after the master gained ZP_PO_CHANGE on 2026-11-27.
            "ZD_P2P_BUYER_DE": {"from": "ZM_P2P_BUYER", "org": {"PURCH_ORG": ["PUDE"], "PLANT": ["CP21"], "COMP_CODE": ["CP20"]}, "generated": "2026-11-20", "tick": 2},
            "ZD_P2P_AP_ACCOUNTANT_US": {"from": "ZM_P2P_AP_ACCOUNTANT", "org": {"PURCH_ORG": ["PUUS"], "PLANT": ["CP11"], "COMP_CODE": ["CP10"]}, "generated": "2026-11-20", "tick": 2},
            # Planted: purchasing org * ("she displays POs of both companies").
            "ZD_P2P_AP_ACCOUNTANT_DE": {"from": "ZM_P2P_AP_ACCOUNTANT", "org": {"PURCH_ORG": ["*"], "PLANT": ["CP21"], "COMP_CODE": ["CP20"]}, "generated": "2026-11-20", "tick": 2},
            "ZD_P2P_AP_SUPERVISOR_US": {"from": "ZM_P2P_AP_SUPERVISOR", "org": {"PURCH_ORG": ["PUUS"], "PLANT": ["CP11"], "COMP_CODE": ["CP10"]}, "generated": "2026-11-20", "tick": 2},
            # Planted: company code typed as CP10 instead of CP20.
            "ZD_P2P_AP_SUPERVISOR_DE": {"from": "ZM_P2P_AP_SUPERVISOR", "org": {"PURCH_ORG": ["PUDE"], "PLANT": ["CP21"], "COMP_CODE": ["CP10"]}, "generated": "2026-11-20", "tick": 2},
        },
        "manual_profiles": {
            # Planted: given in the user master on 2026-10-02 "for two weeks".
            "ZTEMP_AP_ALL": [["ZLAB_INV_CC", {"ACTVT": ["*"], "COMP_CODE": ["*"]}],
                             ["ZLAB_INV_REL", {"ACTVT": ["*"], "COMP_CODE": ["*"]}],
                             ["S_TCODE", {"TCD": ["ZP_INV*"]}]],
        },
        "users": {
            "00100211": {"text": "Buyer, Rockford", "roles": [["ZD_P2P_BUYER_US", "2026-01-01", "9999-12-31"]]},
            "00200031": {"text": "Buyer, Augsburg", "roles": [["ZD_P2P_BUYER_DE", "2026-01-01", "9999-12-31"],
                                                              ["ZD_P2P_AP_ACCOUNTANT_DE", "2026-01-01", "9999-12-31"]]},
            # Planted: hired 2026-11-30, role valid from today, nightly comparison job not scheduled.
            "00100263": {"text": "Buyer, Rockford (new)", "roles": [["ZD_P2P_BUYER_US", "2026-12-01", "9999-12-31"]]},
            "00100241": {"text": "AP accountant, shared service", "roles": [["ZD_P2P_AP_ACCOUNTANT_US", "2026-01-01", "9999-12-31"],
                                                                            ["ZD_P2P_AP_ACCOUNTANT_DE", "2026-01-01", "9999-12-31"]]},
            "00100244": {"text": "AP supervisor, shared service", "roles": [["ZD_P2P_AP_SUPERVISOR_US", "2026-01-01", "9999-12-31"],
                                                                            ["ZD_P2P_AP_SUPERVISOR_DE", "2026-01-01", "9999-12-31"]]},
            "00100259": {"text": "Buyer, Rockford, covers Augsburg AP", "roles": [["ZD_P2P_BUYER_US", "2026-01-01", "9999-12-31"],
                                                                                  ["ZD_P2P_AP_ACCOUNTANT_DE", "2026-01-01", "9999-12-31"]],
                         "manual": ["ZTEMP_AP_ALL"]},
            "00100272": {"text": "Internal auditor", "roles": []},
        },
        # Documents the programs read their org values from.
        "documents": {
            "4500000001": {"kind": "purchase order", "PURCH_ORG": "PUUS", "PLANT": "CP11", "COMP_CODE": "CP10"},
            "4500000002": {"kind": "purchase order", "PURCH_ORG": "PUUS", "PLANT": "CP11", "COMP_CODE": "CP10"},
            "4500001201": {"kind": "purchase order", "PURCH_ORG": "PUDE", "PLANT": "CP21", "COMP_CODE": "CP20"},
            "4500001203": {"kind": "purchase order", "PURCH_ORG": "PUDE", "PLANT": "CP21", "COMP_CODE": "CP20"},
            "5105600003": {"kind": "supplier invoice", "PURCH_ORG": "PUUS", "PLANT": "CP11", "COMP_CODE": "CP10"},
            "5105601201": {"kind": "supplier invoice", "PURCH_ORG": "PUDE", "PLANT": "CP21", "COMP_CODE": "CP20"},
        },
        "su53": {},
    }


# ---------- building roles and profiles ----------

def master_auths(L, name):
    """Merge the SU24 proposals of the menu, then apply the master's edits. Returns object -> entry."""
    m = L["masters"][name]
    out = {"S_TCODE": {"values": {"TCD": sorted(m["menu"])}, "status": "Standard"}}
    for t in m["menu"]:
        for obj, proposal, _check, actvt in L["su24"][t]:
            if proposal == "NO":
                continue
            e = out.setdefault(obj, {"values": {"ACTVT": []}, "status": "Standard", "empty": False})
            e["values"]["ACTVT"] = sorted(set(e["values"]["ACTVT"]) | set(actvt))
            e["empty"] = e["empty"] or proposal == "YES_NO_VALUES"
            for f in L["objects"][obj]:
                if f in ORG_FIELDS:
                    e["values"][f] = [ORG_FIELDS[f]]
    for obj, kind, actvt in m["edits"]:
        if kind == "manual":
            vals = {f: ([ORG_FIELDS[f]] if f in ORG_FIELDS else actvt) for f in L["objects"][obj]}
            out[obj] = {"values": vals, "status": "Manual"}
        else:
            out[obj]["values"]["ACTVT"] = sorted(actvt)
            out[obj]["status"] = "Maintained" if kind == "maintain" else "Changed"
    for e in out.values():
        e.pop("empty", None)
    return out


def derive_auths(L, role):
    d = L["derived"][role]
    auths = copy.deepcopy(master_auths(L, d["from"]))
    for e in auths.values():
        for f, vals in e["values"].items():
            if vals and vals[0].startswith("$"):
                e["values"][f] = d["org"].get(f, [])
    return auths


def light(entry):
    """Traffic light: red if an org level is empty, yellow if another field is empty, else green."""
    vals = entry["values"]
    if any(f in ORG_FIELDS and not v for f, v in vals.items()):
        return "red"
    if any(not v for v in vals.values()):
        return "yellow"
    return "green"


def generate(L, role):
    """Store the derived role's profile as it is now, like generating it in PFCG."""
    d = L["derived"][role]
    d["profile"] = {o: e["values"] for o, e in derive_auths(L, role).items()}
    d["generated"] = TODAY
    L["clock"] += 1
    d["tick"] = L["clock"]


def profile_name(L, role):
    """Course profile names; SAP generates its own names for each role's profile."""
    d = L["derived"][role]
    if "pname" not in d:
        taken = [x.get("pname", "T_CP27000000") for x in L["derived"].values()]
        d["pname"] = "T_CP27%06d" % (max(int(t[6:]) for t in taken) + 1)
    return d["pname"]


def valid_today(a):
    return a[1] <= TODAY <= a[2]


def compare(L, uid):
    u = L["users"][uid]
    u["profiles"] = [a[0] for a in u["roles"] if valid_today(a)]
    L["clock"] += 1
    u["compared"] = L["clock"]


def logon(L, uid):
    u = L["users"][uid]
    buf = []
    for r in u.get("profiles", []):
        for obj, vals in L["derived"][r]["profile"].items():
            buf.append([obj, vals, profile_name(L, r), r])
    for p in u.get("manual", []):
        for obj, vals in L["manual_profiles"][p]:
            buf.append([obj, vals, p, "(no role)"])
    u["buffer"] = buf
    L["clock"] += 1
    u["logon"] = L["clock"]


def init_state():
    L = sample()
    for i, r in enumerate(L["derived"], 1):
        L["derived"][r]["pname"] = "T_CP27%06d" % i
    # Profiles as generated on their dates, buffers as of Monday's logons.
    saved = copy.deepcopy(L["masters"]["ZM_P2P_BUYER"])
    L["masters"]["ZM_P2P_BUYER"]["menu"] = ["ZP_PO_CREATE", "ZP_PO_DISPLAY"]
    L["masters"]["ZM_P2P_BUYER"]["edits"] = [["ZLAB_PO_PLNT", "maintain", ["01", "03"]]]
    for r, d in L["derived"].items():
        if d["from"] == "ZM_P2P_BUYER" and d["generated"] < "2026-11-27":
            d["profile"] = {o: e["values"] for o, e in derive_auths(L, r).items()}
    L["masters"]["ZM_P2P_BUYER"] = saved
    for r, d in L["derived"].items():
        if "profile" not in d:
            d["profile"] = {o: e["values"] for o, e in derive_auths(L, r).items()}
    for uid, u in L["users"].items():
        u["profiles"] = [a[0] for a in u["roles"] if a[1] <= "2026-11-30" <= a[2]]
        u["compared"] = 7
        u["manual"] = u.get("manual", [])
        logon(L, uid)
        u["logon"] = 8
    L["clock"] = 10
    return L


# ---------- the check ----------

def matches(allowed, value):
    for a in allowed:
        if a == "*" or a == value or (a.endswith("*") and value.startswith(a[:-1])):
            return True
    return False


def authority_check(buffer, obj, needed):
    """Like AUTHORITY-CHECK: 0 if ONE authorization for the object allows ALL values,
    4 if the user has the object but not these values, 12 if no authorization for the object."""
    auths = [b for b in buffer if b[0] == obj]
    if not auths:
        return 12, None
    for b in auths:
        if all(f == "DUMMY" or v == "DUMMY" or matches(b[1].get(f, []), v) for f, v in needed.items()):
            return 0, b
    return 4, None


def record_fail(L, uid, obj, needed, rc):
    held = [b[1] for b in L["users"][uid]["buffer"] if b[0] == obj]
    lst = L["su53"].setdefault(uid, [])
    lst.append({"object": obj, "needed": needed, "rc": rc, "held": held})
    del lst[:-100]


def trace(lines, obj, rc, needed):
    lines.append("%s %d:::%s" % (obj, rc, ";".join(f"{k}={v}" for k, v in needed.items())))


def run_check(L, uid, tcode, doc=None, out=print):
    if uid not in L["users"]:
        raise SystemExit(f"Unknown user {uid}.")
    if tcode not in L["tcodes"]:
        raise SystemExit(f"Unknown transaction {tcode}. Known: {', '.join(L['tcodes'])}")
    u, lines = L["users"][uid], []
    out(f"{uid} ({u['text']}) starts {tcode} {L['tcodes'][tcode]['text']}" + (f" for {doc}" if doc else ""))
    needed = {"TCD": tcode}
    rc, hit = authority_check(u["buffer"], "S_TCODE", needed)
    trace(lines, "S_TCODE", rc, needed)
    if rc:
        out(f"  start check  S_TCODE  TCD={tcode}  sy-subrc {rc}")
        out(f"  RESULT: You are not authorized to use transaction {tcode}")
        record_fail(L, uid, "S_TCODE", needed, rc)
        return finish(L, lines, rc)
    out(f"  start check  S_TCODE  TCD={tcode}  sy-subrc 0  (profile {hit[2]})")
    if doc is None:
        out("  RESULT: transaction started; no document given, so no program checks ran")
        return finish(L, lines, 0)
    d = L["documents"].get(doc)
    if d is None:
        out(f"  RESULT: Document {doc} does not exist (not an authorization problem)")
        return finish(L, lines, 0)
    for obj, actvt in L["tcodes"][tcode]["checks"]:
        needed = {f: (actvt if f == "ACTVT" else d[f]) for f in L["objects"][obj]}
        shown = "  ".join(f"{k}={v}" for k, v in needed.items())
        flag = [c for o, _, c, _ in L["su24"][tcode] if o == obj]
        if flag and flag[0] == "NOCHECK":
            trace(lines, obj, 0, needed)
            out(f"  program      {obj:<12} {shown}  sy-subrc 0  (check switched off in SU24)")
            continue
        rc, hit = authority_check(u["buffer"], obj, needed)
        trace(lines, obj, rc, needed)
        out(f"  program      {obj:<12} {shown}  sy-subrc {rc}" + (f"  (profile {hit[2]})" if hit else ""))
        if rc:
            out(f"  RESULT: No authorization for {d['kind']} {doc}")
            record_fail(L, uid, obj, needed, rc)
            return finish(L, lines, rc)
    out(f"  RESULT: allowed")
    return finish(L, lines, 0)


def finish(L, lines, rc):
    with open(HERE / "trace.log", "a", encoding="utf-8") as fh:
        fh.write("\n".join(lines) + "\n")
    return rc


# ---------- the review ----------

def review(L):
    res = []

    def add(rid, verdict, text):
        res.append((rid, verdict, text))

    stale = [f"{r} (generated {d['generated']}, {d['from']} changed {L['masters'][d['from']]['changed']})"
             for r, d in L["derived"].items() if d["tick"] < L["masters"][d["from"]]["tick"]]
    add("A01", "FAIL" if stale else "OK", "Derived roles not generated since their master changed: " + ("; ".join(stale) or "none"))
    star = [f"{r} {f}=*" for r, d in L["derived"].items() for f, v in d["org"].items() if "*" in v]
    add("A02", "FAIL" if star else "OK", "Org levels set to * in derived roles: " + ("; ".join(star) or "none"))
    off = [f"{t} {o}" for t, rows in L["su24"].items() for o, _, c, _ in rows if c == "NOCHECK"]
    add("A03", "FAIL" if off else "OK", "Checks switched off in SU24: " + ("; ".join(off) or "none"))
    man = [f"{uid} {p}" for uid, u in L["users"].items() for p in u.get("manual", [])]
    add("A04", "FAIL" if man else "OK", "Profiles in user masters that no role generates: " + ("; ".join(man) or "none"))
    gap = []
    for uid, u in L["users"].items():
        want = sorted(a[0] for a in u["roles"] if valid_today(a))
        if want != sorted(u.get("profiles", [])):
            gap.append(f"{uid} has {', '.join(sorted(u.get('profiles', []))) or 'nothing'}, roles valid today: {', '.join(want) or 'none'}")
    add("A05", "FAIL" if gap else "OK", "User masters out of step with role assignments: " + ("; ".join(gap) or "none"))
    manual = [f"{m} {o[0]} ACTVT {','.join(o[2])}" for m, d in L["masters"].items() for o in d["edits"] if o[1] == "manual"]
    add("A06", "FAIL" if manual else "OK", "Manual authorizations the menu doesn't propose: " + ("; ".join(manual) or "none"))
    changed = [f"{m} {o[0]} ACTVT {','.join(o[2])}" for m, d in L["masters"].items() for o in d["edits"] if o[1] == "change"]
    add("A07", "WARN" if changed else "OK", "Changed proposal values to confirm: " + ("; ".join(changed) or "none"))
    old = []
    for uid, u in L["users"].items():
        newest = max([u["compared"]] + [L["derived"][r]["tick"] for r in u.get("profiles", [])])
        if u["logon"] < newest:
            old.append(uid)
    add("A08", "WARN" if old else "OK", "Users whose buffer predates a change (log on again): " + (", ".join(old) or "none"))
    return res


# ---------- commands ----------

def load():
    if not FILE.exists():
        raise SystemExit(f"{FILE} is missing. Run: python unit27/auth_concept.py --init")
    try:
        return json.loads(FILE.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        raise SystemExit(f"Cannot read {FILE}: {e}. Undo your edit, or delete the folder and run --init.")


def save(L):
    FILE.write_text(json.dumps(L, indent=1), encoding="utf-8")


def show_roles(L, only=None, out=print):
    for m in L["masters"]:
        if only and only != m and L["derived"].get(only, {}).get("from") != m:
            continue
        d = L["masters"][m]
        out(f"{m}  master, changed {d['changed']}  menu: {', '.join(d['menu'])}")
        for o, e in master_auths(L, m).items():
            vals = "  ".join(f"{f}={','.join(v) or '(empty)'}" for f, v in e["values"].items())
            out(f"    {o:<12} {e['status']:<10} {vals}")
        for r, dr in L["derived"].items():
            if dr["from"] != m or (only and only not in (m, r)):
                continue
            now = derive_auths(L, r)
            current = dr["tick"] >= d["tick"]
            lights = {light(e) for e in now.values()}
            lt = "red" if "red" in lights else "yellow" if "yellow" in lights else "green"
            org = "  ".join(f"{f}={','.join(v)}" for f, v in dr["org"].items())
            out(f"  {r}  {org}  profile {profile_name(L, r)} {'current' if current else 'NOT CURRENT'}  light {lt}")


def main(argv):
    if not argv:
        print(__doc__)
        return 0
    cmd, args = argv[0], argv[1:]
    if cmd == "--init":
        HERE.mkdir(parents=True, exist_ok=True)
        if FILE.exists():
            raise SystemExit(f"{FILE} already exists; delete the folder {HERE} first if you want the sample back.")
        save(init_state())
        (HERE / "trace.log").write_text("", encoding="utf-8")
        print(f"Wrote {os.path.relpath(FILE)} (Calder, Tuesday {TODAY} 08:00, synthetic)")
        return 0
    if cmd == "--selftest":
        return selftest()
    L = load()
    if cmd == "review":
        res = review(L)
        for rid, v, text in res:
            print(f"  {v:<4}  {rid}  {text}")
        n = {k: sum(1 for r in res if r[1] == k) for k in ("OK", "WARN", "FAIL")}
        print(f"{n['OK']} OK, {n['WARN']} WARN, {n['FAIL']} FAIL (synthetic data)")
        return 2 if n["FAIL"] else 0
    if cmd == "roles":
        show_roles(L, args[0] if args else None)
        return 0
    if cmd == "check":
        if len(args) < 2:
            raise SystemExit("Usage: check USER TCODE [DOCUMENT]")
        rc = run_check(L, args[0], args[1], args[2] if len(args) > 2 else None)
        save(L)
        return 0 if rc == 0 else 1
    if cmd == "su53":
        uid = args[0]
        fails = L["su53"].get(uid, [])
        if not fails:
            print(f"{uid}: All authorization checks have so far been successful")
            return 0
        f = fails[-1]
        print(f"{uid}: last failed check  sy-subrc {f['rc']}")
        print(f"  object   {f['object']}")
        print("  needed   " + "  ".join(f"{k}={v}" for k, v in f["needed"].items()))
        if not f["held"]:
            print("  held     no authorization for this object")
        for h in f["held"]:
            print("  held     " + "  ".join(f"{k}={','.join(v)}" for k, v in h.items()))
        return 0
    if cmd == "su56":
        u = L["users"][args[0]]
        print(f"{args[0]} ({u['text']}): {len(u['buffer'])} authorizations in the buffer")
        for obj, vals, prof, role in u["buffer"]:
            print(f"  {obj:<12} {'  '.join(f'{k}={chr(44).join(v)}' for k, v in vals.items()):<46} {prof}  {role}")
        return 0
    if cmd == "trace":
        n = int(args[0]) if args else 10
        for line in (HERE / "trace.log").read_text(encoding="utf-8").splitlines()[-n:]:
            print(line)
        return 0
    if cmd == "compare":
        uids = list(L["users"]) if args[0] == "all" else [args[0]]
        for uid in uids:
            compare(L, uid)
            print(f"{uid}: user master now holds {', '.join(L['users'][uid]['profiles']) or 'no generated profiles'}")
        save(L)
        print("Users must log on again before the change reaches their buffer.")
        return 0
    if cmd == "logon":
        for uid in (list(L["users"]) if args[0] == "all" else [args[0]]):
            logon(L, uid)
            print(f"{uid} logged on: buffer rebuilt with {len(L['users'][uid]['buffer'])} authorizations")
        save(L)
        return 0
    if cmd == "generate":
        m = args[0]
        if m not in L["masters"]:
            raise SystemExit(f"{m} is not a master role.")
        for r, d in L["derived"].items():
            if d["from"] == m:
                generate(L, r)
                print(f"Generated {r} from {m} (profile {profile_name(L, r)}); org levels kept")
        save(L)
        return 0
    if cmd == "orglevel":
        role, field, vals = args[0], args[1], args[2].split(",")
        if field not in ORG_FIELDS:
            raise SystemExit(f"{field} is not an org level. Org levels: {', '.join(ORG_FIELDS)}")
        L["derived"][role]["org"][field] = vals
        generate(L, role)
        save(L)
        print(f"{role}: {field}={','.join(vals)}; profile {profile_name(L, role)} regenerated")
        return 0
    if cmd == "su24":
        t, obj, flag = args
        for row in L["su24"][t]:
            if row[0] == obj:
                row[2] = "CHECK" if flag == "check" else "NOCHECK"
        save(L)
        print(f"SU24 {t} {obj}: check indicator {'Check' if flag == 'check' else 'Do not check'}")
        return 0
    if cmd == "remove-auth":
        m, obj = args
        d = L["masters"][m]
        d["edits"] = [e for e in d["edits"] if not (e[0] == obj and e[1] == "manual")]
        d["changed"] = TODAY
        L["clock"] += 1
        d["tick"] = L["clock"]
        save(L)
        print(f"{m}: manual {obj} removed. Generate its derived roles next.")
        return 0
    if cmd == "remove-profile":
        uid, p = args
        L["users"][uid]["manual"] = [x for x in L["users"][uid]["manual"] if x != p]
        L["clock"] += 1
        L["users"][uid]["compared"] = L["clock"]
        save(L)
        print(f"{uid}: profile {p} removed from the user master")
        return 0
    if cmd == "add-master":
        role, menu = args[0], args[1].split(",")
        L["clock"] += 1
        L["masters"][role] = {"menu": menu, "changed": TODAY, "tick": L["clock"], "edits": []}
        save(L)
        print(f"{role}: master role with {', '.join(menu)}")
        show_roles(L, role)
        return 0
    if cmd == "derive":
        role, master = args[0], args[1]
        org = {}
        for a in args[2:]:
            f, v = a.split("=")
            org[f] = v.split(",")
        L["derived"][role] = {"from": master, "org": org, "generated": TODAY, "tick": 0}
        generate(L, role)
        save(L)
        print(f"{role} derived from {master}; profile {profile_name(L, role)} generated")
        return 0
    if cmd == "assign":
        uid, role, frm, to = args
        L["users"][uid]["roles"].append([role, frm, to])
        save(L)
        print(f"{uid}: {role} assigned {frm} to {to}. Run the user comparison next.")
        return 0
    raise SystemExit(f"Unknown command {cmd}. Run without arguments for help.")


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

def selftest():
    global HERE, FILE
    with tempfile.TemporaryDirectory() as tmp:
        HERE, FILE = Path(tmp), Path(tmp) / "landscape.json"
        quiet = open(os.devnull, "w")
        old = sys.stdout
        sys.stdout = quiet
        try:
            main(["--init"])
            L = load()
            assert [v for _, v, _ in review(L)] == ["FAIL"] * 6 + ["WARN", "OK"], review(L)
            assert main(["check", "00100211", "ZP_PO_CREATE", "4500000001"]) == 0
            assert main(["check", "00100211", "ZP_PO_DISPLAY", "4500001201"]) == 1
            assert load()["su53"]["00100211"][-1]["rc"] == 4
            assert main(["check", "00100263", "ZP_PO_CREATE", "4500000002"]) == 1
            assert load()["su53"]["00100263"][-1]["rc"] == 12
            assert main(["check", "00200031", "ZP_PO_CHANGE", "4500001201"]) == 1
            assert main(["check", "00100244", "ZP_INV_RELEASE", "5105601201"]) == 0
            assert main(["check", "00100211", "ZP_PO_DISPLAY", "4500009999"]) == 0
            for cmd in (["compare", "00100263"], ["logon", "00100263"], ["generate", "ZM_P2P_BUYER"],
                        ["logon", "00200031"], ["su24", "ZP_INV_RELEASE", "ZLAB_INV_REL", "check"]):
                main(cmd)
            assert main(["check", "00100244", "ZP_INV_RELEASE", "5105601201"]) == 1
            for cmd in (["orglevel", "ZD_P2P_AP_SUPERVISOR_DE", "COMP_CODE", "CP20"], ["logon", "00100244"],
                        ["orglevel", "ZD_P2P_AP_ACCOUNTANT_DE", "PURCH_ORG", "PUDE"],
                        ["remove-auth", "ZM_P2P_AP_ACCOUNTANT", "ZLAB_INV_REL"], ["generate", "ZM_P2P_AP_ACCOUNTANT"],
                        ["remove-profile", "00100259", "ZTEMP_AP_ALL"]):
                main(cmd)
            main(["logon", "all"])
            assert main(["check", "00100263", "ZP_PO_CREATE", "4500000002"]) == 0
            assert main(["check", "00200031", "ZP_PO_CHANGE", "4500001201"]) == 0
            assert main(["check", "00100244", "ZP_INV_RELEASE", "5105601201"]) == 0
            assert main(["check", "00100241", "ZP_PO_DISPLAY", "4500000001"]) == 0
            assert main(["check", "00100259", "ZP_INV_RELEASE", "5105601201"]) == 1
            assert [v for _, v, _ in review(load())] == ["OK"] * 6 + ["WARN", "OK"], review(load())
        finally:
            sys.stdout = old
            quiet.close()
    print("Self-test passed: 8 rules and 12 checks behave as planted (synthetic data)")
    return 0


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

#### Step 3: Write the landscape and review it

1. Write Calder's landscape as of Tuesday 1 December 2026, 08:00:

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

   ```text
   Wrote unit27/auth/landscape.json (Calder, Tuesday 2026-12-01 08:00, synthetic)
   ```

2. Review it against the course rules:

   ```bash
   python unit27/auth_concept.py review
   ```

   ```text
     FAIL  A01  Derived roles not generated since their master changed: ZD_P2P_BUYER_DE (generated 2026-11-20, ZM_P2P_BUYER changed 2026-11-27)
     FAIL  A02  Org levels set to * in derived roles: ZD_P2P_AP_ACCOUNTANT_DE PURCH_ORG=*
     FAIL  A03  Checks switched off in SU24: ZP_INV_RELEASE ZLAB_INV_REL
     FAIL  A04  Profiles in user masters that no role generates: 00100259 ZTEMP_AP_ALL
     FAIL  A05  User masters out of step with role assignments: 00100263 has nothing, roles valid today: ZD_P2P_BUYER_US
     FAIL  A06  Manual authorizations the menu doesn't propose: ZM_P2P_AP_ACCOUNTANT ZLAB_INV_REL ACTVT 02
     WARN  A07  Changed proposal values to confirm: ZM_P2P_BUYER ZLAB_PO_ORG ACTVT 01,02,03,06
     OK    A08  Users whose buffer predates a change (log on again): none
   1 OK, 1 WARN, 6 FAIL (synthetic data)
   ```

   > **Note** These verdicts come from a synthetic landscape with six findings planted on purpose. They show the method, not the state of a real SAP system.

3. Look at the buyer roles:

   ```bash
   python unit27/auth_concept.py roles ZD_P2P_BUYER_DE
   ```

   ```text
   ZM_P2P_BUYER  master, changed 2026-11-27  menu: ZP_PO_CREATE, ZP_PO_CHANGE, ZP_PO_DISPLAY
       S_TCODE      Standard   TCD=ZP_PO_CHANGE,ZP_PO_CREATE,ZP_PO_DISPLAY
       ZLAB_PO_ORG  Changed    ACTVT=01,02,03,06  PURCH_ORG=$PURCH_ORG
       ZLAB_PO_PLNT Maintained ACTVT=01,02,03  PLANT=$PLANT
     ZD_P2P_BUYER_DE  PURCH_ORG=PUDE  PLANT=CP21  COMP_CODE=CP20  profile T_CP27000002 NOT CURRENT  light green
   ```

   Read it like `PFCG`: `S_TCODE` comes from the menu, `ZLAB_PO_ORG` was `Changed` (someone added `06` delete to the proposal), and `ZLAB_PO_PLNT` was `Maintained` (its proposal came empty). The derived role's light is green, yet its profile is not current. Green is not correct.

#### Step 4: Work Monday's tickets

Each command starts a transaction as a user, for one document, and prints every check with its return code.

1. **The Rockford buyer, inside and outside his scope.**

   ```bash
   python unit27/auth_concept.py check 00100211 ZP_PO_CREATE 4500000001
   python unit27/auth_concept.py check 00100211 ZP_PO_DISPLAY 4500001201
   ```

   ```text
   00100211 (Buyer, Rockford) starts ZP_PO_CREATE Create purchase order for 4500000001
     start check  S_TCODE  TCD=ZP_PO_CREATE  sy-subrc 0  (profile T_CP27000001)
     program      ZLAB_PO_ORG  ACTVT=01  PURCH_ORG=PUUS  sy-subrc 0  (profile T_CP27000001)
     program      ZLAB_PO_PLNT ACTVT=01  PLANT=CP11  sy-subrc 0  (profile T_CP27000001)
     RESULT: allowed
   00100211 (Buyer, Rockford) starts ZP_PO_DISPLAY Display purchase order for 4500001201
     start check  S_TCODE  TCD=ZP_PO_DISPLAY  sy-subrc 0  (profile T_CP27000001)
     program      ZLAB_PO_ORG  ACTVT=03  PURCH_ORG=PUDE  sy-subrc 4
     RESULT: No authorization for purchase order 4500001201
   ```

   Return code `4`: he holds `ZLAB_PO_ORG`, but for `PUUS`, and Augsburg's order belongs to `PUDE`. That refusal is correct. Close the ticket without a change.

2. **The new Rockford buyer.** `00100263` started on Monday; his role is valid from today.

   ```bash
   python unit27/auth_concept.py check 00100263 ZP_PO_CREATE 4500000002
   python unit27/auth_concept.py su53 00100263
   ```

   ```text
   00100263 (Buyer, Rockford (new)) starts ZP_PO_CREATE Create purchase order for 4500000002
     start check  S_TCODE  TCD=ZP_PO_CREATE  sy-subrc 12
     RESULT: You are not authorized to use transaction ZP_PO_CREATE
   00100263: last failed check  sy-subrc 12
     object   S_TCODE
     needed   TCD=ZP_PO_CREATE
     held     no authorization for this object
   ```

   Return code `12`: no `S_TCODE` at all. He holds no profile; the comparison ran last night, before his assignment started.

3. **The Augsburg buyer after Friday's change.**

   ```bash
   python unit27/auth_concept.py check 00200031 ZP_PO_CHANGE 4500001201
   python unit27/auth_concept.py su53 00200031
   ```

   ```text
   00200031 (Buyer, Augsburg) starts ZP_PO_CHANGE Change purchase order for 4500001201
     start check  S_TCODE  TCD=ZP_PO_CHANGE  sy-subrc 4
     RESULT: You are not authorized to use transaction ZP_PO_CHANGE
   00200031: last failed check  sy-subrc 4
     object   S_TCODE
     needed   TCD=ZP_PO_CHANGE
     held     TCD=ZP_PO_CREATE,ZP_PO_DISPLAY
     held     TCD=ZP_INV_DISPLAY,ZP_INV_ENTER,ZP_PO_DISPLAY
   ```

   Return code `4`: he holds `S_TCODE`, but not this value. His derived role still carries the profile from before the master changed. That is `A01`.

4. **The AP supervisor and the switched-off check.**

   ```bash
   python unit27/auth_concept.py check 00100244 ZP_INV_RELEASE 5105601201
   python unit27/auth_concept.py check 00100259 ZP_INV_RELEASE 5105600003
   ```

   ```text
   00100244 (AP supervisor, shared service) starts ZP_INV_RELEASE Release blocked invoice for 5105601201
     start check  S_TCODE  TCD=ZP_INV_RELEASE  sy-subrc 0  (profile T_CP27000005)
     program      ZLAB_INV_REL ACTVT=02  COMP_CODE=CP20  sy-subrc 0  (check switched off in SU24)
     RESULT: allowed
   00100259 (Buyer, Rockford, covers Augsburg AP) starts ZP_INV_RELEASE Release blocked invoice for 5105600003
     start check  S_TCODE  TCD=ZP_INV_RELEASE  sy-subrc 0  (profile ZTEMP_AP_ALL)
     program      ZLAB_INV_REL ACTVT=02  COMP_CODE=CP10  sy-subrc 0  (check switched off in SU24)
     RESULT: allowed
   ```

   Both pass, and both should worry you. On 25 November someone switched off the release check to stop the supervisor's tickets. Now the buyer `00100259`, through his "temporary" profile, releases blocked invoices in Rockford.

5. **A refusal that isn't one.**

   ```bash
   python unit27/auth_concept.py check 00100211 ZP_PO_DISPLAY 4500009999
   python unit27/auth_concept.py su53 00100244
   ```

   ```text
   00100211 (Buyer, Rockford) starts ZP_PO_DISPLAY Display purchase order for 4500009999
     start check  S_TCODE  TCD=ZP_PO_DISPLAY  sy-subrc 0  (profile T_CP27000001)
     RESULT: Document 4500009999 does not exist (not an authorization problem)
   00100244: All authorization checks have so far been successful
   ```

6. Look at the trace and one user's buffer:

   ```bash
   python unit27/auth_concept.py trace 4
   python unit27/auth_concept.py su56 00100259
   ```

   ```text
   ZLAB_INV_REL 0:::ACTVT=02;COMP_CODE=CP20
   S_TCODE 0:::TCD=ZP_INV_RELEASE
   ZLAB_INV_REL 0:::ACTVT=02;COMP_CODE=CP10
   S_TCODE 0:::TCD=ZP_PO_DISPLAY
   00100259 (Buyer, Rockford, covers Augsburg AP): 10 authorizations in the buffer
     S_TCODE      TCD=ZP_PO_CHANGE,ZP_PO_CREATE,ZP_PO_DISPLAY    T_CP27000001  ZD_P2P_BUYER_US
     ZLAB_PO_ORG  ACTVT=01,02,03,06  PURCH_ORG=PUUS              T_CP27000001  ZD_P2P_BUYER_US
     ZLAB_PO_PLNT ACTVT=01,02,03  PLANT=CP11                     T_CP27000001  ZD_P2P_BUYER_US
     S_TCODE      TCD=ZP_INV_DISPLAY,ZP_INV_ENTER,ZP_PO_DISPLAY  T_CP27000004  ZD_P2P_AP_ACCOUNTANT_DE
     ZLAB_INV_CC  ACTVT=01,03  COMP_CODE=CP20                    T_CP27000004  ZD_P2P_AP_ACCOUNTANT_DE
     ZLAB_PO_ORG  ACTVT=03  PURCH_ORG=*                          T_CP27000004  ZD_P2P_AP_ACCOUNTANT_DE
     ZLAB_INV_REL ACTVT=02  COMP_CODE=CP20                       T_CP27000004  ZD_P2P_AP_ACCOUNTANT_DE
     ZLAB_INV_CC  ACTVT=*  COMP_CODE=*                           ZTEMP_AP_ALL  (no role)
     ZLAB_INV_REL ACTVT=*  COMP_CODE=*                           ZTEMP_AP_ALL  (no role)
     S_TCODE      TCD=ZP_INV*                                    ZTEMP_AP_ALL  (no role)
   ```

   The buffer shows three more findings in one user: the manual profile (`A04`), an accountant role with `PURCH_ORG=*` (`A02`), and `ZLAB_INV_REL` in an accountant role whose menu has no release transaction (`A06`).

#### Step 5: Fix the six findings

Each fix uses the lab command named after the SAP step it stands for.

1. **`A05`, the new buyer:** run the comparison, then let him log on again.

   ```bash
   python unit27/auth_concept.py compare 00100263
   python unit27/auth_concept.py logon 00100263
   python unit27/auth_concept.py check 00100263 ZP_PO_CREATE 4500000002
   ```

   The check ends with `RESULT: allowed`. In SAP, the lasting fix is scheduling the comparison job in every client.

2. **`A01`, the Augsburg buyer:** generate the derived roles from the master.

   ```bash
   python unit27/auth_concept.py generate ZM_P2P_BUYER
   python unit27/auth_concept.py logon 00200031
   python unit27/auth_concept.py check 00200031 ZP_PO_CHANGE 4500001201
   ```

   ```text
   Generated ZD_P2P_BUYER_US from ZM_P2P_BUYER (profile T_CP27000001); org levels kept
   Generated ZD_P2P_BUYER_DE from ZM_P2P_BUYER (profile T_CP27000002); org levels kept
   00200031 logged on: buffer rebuilt with 7 authorizations
   00200031 (Buyer, Augsburg) starts ZP_PO_CHANGE Change purchase order for 4500001201
     start check  S_TCODE  TCD=ZP_PO_CHANGE  sy-subrc 0  (profile T_CP27000002)
     program      ZLAB_PO_ORG  ACTVT=02  PURCH_ORG=PUDE  sy-subrc 0  (profile T_CP27000002)
     program      ZLAB_PO_PLNT ACTVT=02  PLANT=CP21  sy-subrc 0  (profile T_CP27000002)
     RESULT: allowed
   ```

3. **`A03`, the switched-off check:** switch it back on and look at what it was hiding.

   ```bash
   python unit27/auth_concept.py su24 ZP_INV_RELEASE ZLAB_INV_REL check
   python unit27/auth_concept.py check 00100244 ZP_INV_RELEASE 5105601201
   python unit27/auth_concept.py su53 00100244
   ```

   ```text
   SU24 ZP_INV_RELEASE ZLAB_INV_REL: check indicator Check
   00100244 (AP supervisor, shared service) starts ZP_INV_RELEASE Release blocked invoice for 5105601201
     start check  S_TCODE  TCD=ZP_INV_RELEASE  sy-subrc 0  (profile T_CP27000005)
     program      ZLAB_INV_REL ACTVT=02  COMP_CODE=CP20  sy-subrc 4
     RESULT: No authorization for supplier invoice 5105601201
   00100244: last failed check  sy-subrc 4
     object   ZLAB_INV_REL
     needed   ACTVT=02  COMP_CODE=CP20
     held     ACTVT=02  COMP_CODE=CP10
     held     ACTVT=02  COMP_CODE=CP10
   ```

   Two authorizations, both for `CP10`. One of them should say `CP20`: her Augsburg derived role has a typo. That was the real cause of last week's ticket. Fix the org level, which regenerates the role, and log her on again:

   ```bash
   python unit27/auth_concept.py orglevel ZD_P2P_AP_SUPERVISOR_DE COMP_CODE CP20
   python unit27/auth_concept.py logon 00100244
   python unit27/auth_concept.py check 00100244 ZP_INV_RELEASE 5105601201
   ```

   The check now passes with `(profile T_CP27000006)`, her Augsburg role.

4. **`A02`, `A06` and `A04`:** narrow the org level, remove the manual authorization, regenerate, and remove the manual profile.

   ```bash
   python unit27/auth_concept.py orglevel ZD_P2P_AP_ACCOUNTANT_DE PURCH_ORG PUDE
   python unit27/auth_concept.py remove-auth ZM_P2P_AP_ACCOUNTANT ZLAB_INV_REL
   python unit27/auth_concept.py generate ZM_P2P_AP_ACCOUNTANT
   python unit27/auth_concept.py remove-profile 00100259 ZTEMP_AP_ALL
   ```

5. Review again:

   ```bash
   python unit27/auth_concept.py review
   ```

   ```text
     OK    A01  Derived roles not generated since their master changed: none
     OK    A02  Org levels set to * in derived roles: none
     OK    A03  Checks switched off in SU24: none
     OK    A04  Profiles in user masters that no role generates: none
     OK    A05  User masters out of step with role assignments: none
     OK    A06  Manual authorizations the menu doesn't propose: none
     WARN  A07  Changed proposal values to confirm: ZM_P2P_BUYER ZLAB_PO_ORG ACTVT 01,02,03,06
     WARN  A08  Users whose buffer predates a change (log on again): 00100211, 00200031, 00100263, 00100241, 00100259
   6 OK, 2 WARN, 0 FAIL (synthetic data)
   ```

   `A08` lists five users whose roles changed after their logon. Until they log on again, they work with yesterday's permissions, including `00100259`'s manual profile.

6. Log everyone on again and confirm:

   ```bash
   python unit27/auth_concept.py logon all
   python unit27/auth_concept.py review
   python unit27/auth_concept.py check 00100259 ZP_INV_RELEASE 5105600003
   ```

   ```text
   7 OK, 1 WARN, 0 FAIL (synthetic data)
   00100259 (Buyer, Rockford, covers Augsburg AP) starts ZP_INV_RELEASE Release blocked invoice for 5105600003
     start check  S_TCODE  TCD=ZP_INV_RELEASE  sy-subrc 4
     RESULT: You are not authorized to use transaction ZP_INV_RELEASE
   ```

   (The `logon all` lines and the eight review lines are left out above.) `A07` stays a warning on purpose: whether buyers may delete purchase orders is a decision for the purchasing manager, not a fix for the lab.

   > **Note** These results come from synthetic data and show the method, not a real SAP system.

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

1. Run the self-test. It replays Steps 3 to 5 in a temporary folder and leaves your files alone:

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

   ```text
   Self-test passed: 8 rules and 12 checks behave as planted (synthetic data)
   ```

2. Save your work with Git:

   ```bash
   git add unit27/auth_concept.py unit27/auth
   git commit -m "Unit 27: authorization concept lab"
   ```

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

#### How the code works

| Part | What it does |
| --- | --- |
| `sample()` | Calder's landscape: objects, transactions and the checks their programs make, `SU24`-style proposals, master and derived roles, a manual profile, users and documents, with six findings planted |
| `master_auths()` | Merges the proposals of the menu's transactions into one authorization per object, applies edits and sets the status: `Standard`, `Maintained`, `Changed` or `Manual` |
| `derive_auths()`, `generate()` | Replaces `$PURCH_ORG`-style variables with the derived role's org levels and stores the result as the role's profile, like generating it |
| `compare()`, `logon()` | Writes profiles into the user master for assignments valid today; builds the user buffer from the user master |
| `authority_check()` | Returns `0` if one authorization covers all values, `4` if the object is held with other values, `12` if it isn't held |
| `run_check()` | Start check on `S_TCODE`, then the program's checks with org values read from the document; honours the `SU24` check indicator; writes `SU53` entries and trace lines |
| `review()` | Applies course rules `A01` to `A08` and returns `OK`, `WARN` or `FAIL` for each |
| `selftest()` | Replays the walkthrough in a temporary folder and asserts every planted result |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your PATH, or `.venv` is off | Turn on `.venv` (Step 1); on macOS/Linux try `python3` |
| `landscape.json is missing` | `--init` hasn't run | Run `python unit27/auth_concept.py --init` |
| `already exists; delete the folder ... first` | `--init` won't overwrite your work | Delete `unit27/auth` only if you want the sample back |
| `Cannot read ... landscape.json` | A hand edit broke the JSON | Undo the edit, or delete `unit27/auth` and run `--init` |
| `KeyError` with a user or role name | A typo in a user number, role or transaction | Copy the command from the step |
| Your output differs from a step | You ran steps out of order or twice | Delete `unit27/auth`, run `--init`, and redo from Step 3 |
| `ModuleNotFoundError` | You ran a different script | This one uses built-in modules only; check the file name |
| `review` ends with exit code 2 | Expected while a rule fails | Nothing; it lets scripts stop on a `FAIL` |

### The SAP way

In a real S/4HANA Cloud Private Edition, on-premise or ECC system, the lab's commands map to these SAP steps (names as read on SAP Learning and SAP Help on 1 December 2026):

| Lab command | SAP | Notes |
| --- | --- | --- |
| `roles` | `PFCG`, **Authorizations** tab | Statuses and traffic lights as described above |
| `su24` | `SU24` (customer), `SU22` (SAP) | Changes redistribute to every role with the transaction; no standard restore |
| `generate` | **Generate Derived Roles** in the master | Org levels kept; profiles generated |
| `orglevel` | **Organizational Levels** button | Not in the tree, or the status becomes `Changed` |
| `compare` | User comparison, `PFUD` or report `PFCG_TIME_DEPENDENCY` as a job | Writes profiles for today's valid assignments |
| `su56`, `logon` | `SU56`; the buffer is built at logon | |
| `su53`, `trace` | `SU53`, `STAUTHTRACE`, `ST01` | `SU53` keeps at most 100 failures per user, three hours |
| `review` | User information system (`SU01` > **Information System**, `RSUSR998` per SAP Learning) and a governance tool | The access control topic in Unit 27 covers the tooling |

Two SAP-side points the lab can't show:

- **Mass changes.** SAP Learning names `PFCGMASSVAL` for mass maintenance of values across roles. Use it with the same review as single changes.
- **Transport.** Roles move from development to production by transport, and users are assigned in each system. SAP Learning names `ROLE_CMP` for comparing role menus across systems ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/creating-standard-roles)).

> **Note** **Sketch, needs a system.** Everything in this section needs an SAP ABAP system with user administration rights. Calder's `S4D` and `S4P` are fictional; the lab is the free path.

### Build vs. SAP

| Need | Use SAP's tools | Build something |
| --- | --- | --- |
| Maintain roles, proposals and profiles | Always `PFCG` and `SU24` | Never generate profiles by hand or by script |
| Find stale derived roles, `*` in org levels, manual profiles | User information system and an access governance tool, if licensed | A read-only report like the lab's `review`, run against exported role data, when no tool is licensed |
| Explain a refusal | `SU53` and `STAUTHTRACE` | A help desk guide that asks for `SU53` first |
| Check custom code for missing checks | ABAP code reviews and SAP's code checks | Course-level review rules in the transport gate |
| Prove a role change is safe | Test users and negative test cases | A small regression list of "must be refused" checks, replayed after each change |

### Architecture view

**Where it sits.** Authorization checks run inside each ABAP system: Calder's `S4P` for `CP10` and, until the July 2027 rollout, ECC `ECP` for `CP20`. Roles are built in development (`S4D`), transported to `S4Q` and `S4P`, and assigned in each system. Users arrive from the identity provider; identity provisioning and single sign-on are later Unit 27 topics.

```mermaid
flowchart LR
  IDP[Identity provider] -->|users| S4P
  S4D[S4D: PFCG, SU24] -->|transport roles| S4Q[S4Q] -->|transport| S4P[S4P: assignments,<br/>comparison, buffer]
  API[APIs and agents] -->|technical or<br/>propagated user| S4P
  S4P -->|SU53, traces, logs| SEC[Security team]
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Access reaches a new hire on day one | Comparison job daily in every client, before working hours | Tickets on the first morning; users share passwords |
| Role changes reach users the same day | Regenerate, compare and ask users to log on again | People work with yesterday's rights, wider or narrower |
| No silent widening | `SU24` check indicators, `*` in org levels, manual profiles reviewed monthly (course target) | A single change opens a transaction to everyone |
| Explainable refusals | `SU53` available to the service desk | Roles are widened by guessing |
| Upgrade safety | `SU25` post-processing and `SAP_NEW` removal in the upgrade plan | A wave of tickets, or broad access nobody removes |

**Integration and identity.** An API call or an RFC runs as a user too: the caller's own user through principal propagation, or a technical user. The same objects are checked, with `S_RFC` or `S_SERVICE` as the start check. [Agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) shows why an agent should carry the person's identity rather than a broad technical user.

**The decision to record.**

- *Context:* Calder's procure-to-pay roles exist as master and derived roles for `CP10` and `CP20`. Last week, a switched-off check and a manual profile widened invoice release.
- *Options:* (1) keep fixing tickets as they arrive; (2) a monthly read-only review of `SU24` indicators, org-level wildcards, manual profiles and stale derived roles, with owners; (3) buy an access governance tool first.
- *Decision:* option 2 now, with the review run by the security team and findings owned by role owners; option 3 is assessed in the access control topic.
- *Consequences:* a small recurring effort; "Do not check" in `SU24` needs a named owner and an expiry; manual profiles are banned except for documented emergencies.

**What a design review will ask.**

1. Who may change `SU24`, and how is a switched-off check found?
2. Which job runs the user comparison, in which clients, and who is alerted when it fails?
3. Which roles have `*` in an org level, and why?
4. How do API, RFC and agent calls map to users and roles?
5. What does the upgrade plan say about `SU25` and `SAP_NEW`?

### Production concerns

- **Authorizations on authorizations.** SAP Learning names the objects that protect user and role maintenance, such as `S_USER_GRP`, `S_USER_PRO`, `S_USER_AGR` and `S_USER_TCD` ([SAP Learning](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/maintaining-and-evaluating-user-data)). Whoever holds them can give themselves anything. Treat them like the emergency ID.
- **Separate build and assign.** The person who builds a role should not assign it in production; the access control topic turns this into a rule.
- **Test with negative cases.** Each role change gets a short list of checks that must be refused, replayed after every transport, as the lab's self-test does.
- **Custom code.** Every custom transaction, report and API needs its checks, its `SU24` proposals and a review that the return code is handled. Clean-core extensions on ABAP Cloud use released APIs and CDS access controls; ask for both in design.
- **Logs.** Changes to users and roles leave change documents; the audit logging topic of Unit 27 covers what to keep.
- **Cost.** None of this is licensed separately; the cost is people's time. A recurring review costs hours a month; one widened release check can cost a payment run.

### Where AI fits

Nothing in SAP's authorization concept changes for AI, and that is the point. An agent that reads or writes SAP data is one more user. Its calls hit the same `S_SERVICE` or `S_RFC` start checks and the same objects, under either its own technical user or the person's identity. Design it like any role: a small menu, scoped org levels, no manual authorizations, and checks never switched off for its convenience. [Joule authorizations and security](https://erpfde.com/topics/joule-authorizations-and-security/) applies the same idea to Joule.

AI can help read authorization data: explaining an `SU53` screen in plain words, or summarizing which roles contain `*`. Keep the decision with a person, and never let a model's suggestion become a role change without the normal change process. As SAP's course says about traces, what a user did is not proof of what the job needs.

### Pitfalls

- Closing a ticket by widening a role, when the refusal was correct.
- Switching a check off in `SU24` to make a ticket go away, with no owner and no end date.
- Changing a master role and regenerating only the derived role the ticket mentioned.
- Entering org values in the authorization tree instead of with the **Organizational Levels** button.
- Giving a "temporary" profile directly in `SU01`.
- Scheduling the comparison job in one client and forgetting the others.
- Building roles from a trace of a power user's day.
- Leaving `SAP_NEW` on users after an upgrade.
- Forgetting that a user must log on again before a change applies.

### Exercise: a read-only role for the internal auditor

Calder's internal auditor, `00100272`, reviews emergency sessions and now needs to display purchase orders and supplier invoices in both companies until the end of March, with no change rights and no wildcards.

1. Create a master role with the two display transactions:

   ```bash
   python unit27/auth_concept.py add-master ZM_P2P_AUDITOR ZP_PO_DISPLAY,ZP_INV_DISPLAY
   ```

   The output shows `S_TCODE`, `ZLAB_PO_ORG` with `ACTVT=03` and `ZLAB_INV_CC` with `ACTVT=03`, all `Standard`.

2. Derive one role with both companies listed explicitly:

   ```bash
   python unit27/auth_concept.py derive ZD_P2P_AUDITOR_ALL ZM_P2P_AUDITOR PURCH_ORG=PUUS,PUDE PLANT=CP11,CP21 COMP_CODE=CP10,CP20
   ```

   ```text
   ZD_P2P_AUDITOR_ALL derived from ZM_P2P_AUDITOR; profile T_CP27000007 generated
   ```

3. Assign it with an end date, compare and log on:

   ```bash
   python unit27/auth_concept.py assign 00100272 ZD_P2P_AUDITOR_ALL 2026-12-01 2027-03-31
   python unit27/auth_concept.py compare 00100272
   python unit27/auth_concept.py logon 00100272
   ```

4. Prove it works, and prove it refuses:

   ```bash
   python unit27/auth_concept.py check 00100272 ZP_PO_DISPLAY 4500001201
   python unit27/auth_concept.py check 00100272 ZP_INV_DISPLAY 5105600003
   python unit27/auth_concept.py check 00100272 ZP_PO_CHANGE 4500001201
   ```

   The first two end with `RESULT: allowed`; the third with `sy-subrc 4` on `S_TCODE`.

5. Run `python unit27/auth_concept.py review`. It still prints `7 OK, 1 WARN, 0 FAIL (synthetic data)`.
6. In `unit27/notes.md`, write two sentences: why listing `CP10,CP20` beats `*` even though they give the same access today, and what must happen on 1 April 2027.

**Done when** the auditor's display checks pass, the change check is refused with `sy-subrc 4`, the review still shows `0 FAIL`, and `notes.md` holds your two sentences. The access control topic in Unit 27 reuses this role as its first read-only role in the risk rule set.

### Check yourself

1. In the lab, the Rockford buyer opens Augsburg's purchase order 4500001201 and the program check returns sy-subrc 4. What does the 4 tell you?
   - A. He holds no authorization at all for the purchase order object
   - B. He holds the object, but not for the purchasing organization PUDE
   - C. The check was switched off in SU24 for display transactions
   - D. His user master has no profile, so he must be compared again

   Answer: B. Return code 4 means the user has the object but not with the checked values; 12 means no authorization for the object. SU53 showed he holds ZLAB_PO_ORG for PUUS only, so the refusal is the scope working as designed.

2. The Augsburg buyer's derived role shows the new transaction in its menu and a green light, yet his start check fails. Which step was missed?
   - A. Copying the master role into a new role with a Z name
   - B. Setting the org levels in the authorization tree directly
   - C. Generating the derived roles after the master's menu changed
   - D. Running SU25 to fill the customer tables after the upgrade

   Answer: C. The derived role inherits the menu, but its profile changes only when it is generated. The lab's A01 rule caught it; Generate Derived Roles in the master regenerates every derived role and keeps their org levels.

3. A check for releasing invoices is set to "Do not check" in SU24 for the release transaction. What does that do at runtime?
   - A. The check runs only for users without a derived role
   - B. The object is removed from the roles at the next upgrade
   - C. The release needs a second approval from the AP supervisor
   - D. AUTHORITY-CHECK returns 0 for that object in that transaction

   Answer: D. SAP's SU24 help says "Do not check" makes the check return sy-subrc 0. Everyone who can start the transaction passes, in every company code, which is how buyer 00100259 released a Rockford invoice in the lab.

4. Why does the lab's A06 rule fail on a "Manual" release authorization in the AP accountant's role, although the accountant's menu has no release transaction?
   - A. Another program or API making the same check would still say yes
   - B. Manual authorizations stop the derived roles from being generated
   - C. SAP deletes manual authorizations at the next user comparison
   - D. Manual authorizations always carry an asterisk in every field

   Answer: A. The menu only controls the S_TCODE start check. An authorization in the profile answers any program that checks the same object, including reports and APIs. Status Manual means the menu didn't propose it, so it needs a reason or removal.

5. An administrator fixes an org-level typo in the AP supervisor's Augsburg role and regenerates it. The supervisor is still refused five minutes later. What do you check first?
   - A. Whether SU24 needs a new proposal for the release object
   - B. Whether she has logged on again since the profile changed
   - C. Whether the master role has a newer date than the derived role
   - D. Whether SU53 keeps failures from the last three hours only

   Answer: B. Checks read the user buffer, which is built at logon. A regenerated profile reaches her buffer only at her next logon; the lab's A08 rule lists users in that state.

6. Your team wants to build a new role from STAUTHTRACE output recorded while a senior buyer worked for a day. What is the problem?
   - A. STAUTHTRACE records only failed checks, so the role will be empty
   - B. Traces are not available on S/4HANA Cloud Private Edition systems
   - C. The trace format can't be read by the role editor at all
   - D. The trace shows what one person did, not what the job needs

   Answer: D. SAP's course says not to turn trace or SU53 results directly into roles. A trace includes everything the person happened to do, including tasks outside the job, so it is input for analysis, not a design.

7. A Fiori list app shows fewer purchase orders to an Augsburg user than to a Rockford user, with no error message. What is the most likely explanation?
   - A. The app's start authorization S_SERVICE failed for the Augsburg user
   - B. The Augsburg user's buffer is full and drops later authorizations
   - C. A CDS access control filtered the rows by the user's authorizations
   - D. The comparison job wrote only half of the user's profile in the morning

   Answer: C. CDS access controls filter rather than refuse: the database returns only rows the user may see. A failed start check would stop the app with an error. The trace shows the CDS entity and the fields used to filter.

## Sources

- [Explaining Elements and Terminology of the ABAP Authorization Concept (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/explaining-elements-and-terminology-of-the-abap-authorization-concept): object class, object (1 to 10 fields checked together), field, authorization as an instance of an object, profile, role generates a profile; activities in table TACT, valid activities per object in TACTZ; predelivered SAP_ roles are templates; profiles generated by role maintenance, manual profiles only in exceptional cases
- [Identifying Authorization Checks in the SAP System (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/identifying-authorization-checks-in-the-sap-system): start checks S_TCODE (transactions), S_START (Web Dynpro ABAP, inactive when delivered), S_RFC (function groups then modules, once per RFC session), S_SERVICE (SAP Fiori apps); TSTCA object at transaction start; return codes 0, 4, 12, 16; user buffer built at logon, shown in SU56
- [Creating Standard Roles (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/creating-standard-roles): PFCG; role names up to 30 characters, SAP_ roles may be overwritten on upgrade; Organizational Levels button; proposals from SU24, SAP variants in SU22; time-dependent assignments need a comparison, report pfcg_time_dependency or PFUD; profile written to the user master only if the role's validity includes today; never enter generated profiles in SU01
- [Outlining Subtleties of Authorization Maintenance (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/outlining-subtleties-of-authorization-maintenance): traffic lights green, yellow, red; statuses Standard, Maintained, Changed, Manual, plus Old and New after a comparison; set org levels with the button, not in the tree; mass maintenance PFCGMASSVAL
- [Implementing a Derived Role Strategy (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/implementing-a-derived-role-strategy): Derive from Role; menu inherited and not changeable in derived roles; user assignments not inherited; Generate Derived Roles copies normal fields, not org levels, and generates profiles; Transfer Data; cancelling inheritance can't be undone
- [Investigating Installation and Upgrade Tasks (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/investigating-installation-and-upgrade-tasks): USOBX and USOBT delivered by SAP, USOBX_C and USOBT_C the customer tables; SU25 initial fill and post-upgrade steps; SAP_NEW is broad and should be removed promptly; SU24_AUTO_REPAIR; no standard restore for SU24 data
- [Troubleshooting Authorization Checks (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-s-4hana-and-sap-business-suite/troubleshouting-authorization-checks): SU53 shows the last failed check with required and assigned values, at most 100 failed checks per user from the last three hours; 'all checks successful' means not an authorization problem; STAUTHTRACE and ST01; trace format; don't turn trace or SU53 results directly into roles
- [Editing Authorization Default Data (Customer System) (SAP Help, SU24, read 2026-12-01)](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/1e/ce3075dd4e4116b23e006552374ffc/content.htm): proposal statuses No, Yes, Yes Without Values; check indicator Check or Do not check; Do not check makes AUTHORITY-CHECK return 0 and is never permissible for Basis and HR objects; org fields filled with $ variables; DUMMY fields
- [Explaining SAP Fiori Authorization Model (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-fiori-on-sap-s-4hana/explaining-sap-fiori-authorization-model): embedded front-end server needs one PFCG role in S/4HANA; stand-alone needs a front-end and a back-end role; OData start authorization plus business authorizations; adding a catalog to the role menu brings in start authorizations; SU24 holds the proposals
- [Describing the Authorization Concept for ABAP CDS (SAP Learning, read 2026-12-01)](https://learning.sap.com/courses/exploring-the-authorization-concept-for-sap-fiori-on-sap-s-4hana/describing-the-authorization-concept-for-abap-cds): DCL roles (DEFINE ROLE, GRANT SELECT ON ... WHERE); PFCG conditions tie CDS elements to authorization objects; no CDS role means no restriction; keep classic checks for start authorizations and use CDS access control for instance-based checks
