diff --git a/db/last-dev/csn.json b/db/last-dev/csn.json index 4acd32589..f00464bf7 100644 --- a/db/last-dev/csn.json +++ b/db/last-dev/csn.json @@ -8008,7 +8008,7 @@ } }, "meta": { - "creator": "CDS Compiler v7.0.1", + "creator": "CDS Compiler v7.2.1", "compilerCsnFlavor": "$internal", "flavor": "inferred", "sap.changelog.enhanced": true, diff --git a/docs/developers/operations/testing-endpoints.md b/docs/developers/operations/testing-endpoints.md index 5c1cad796..ba4e7cc03 100644 --- a/docs/developers/operations/testing-endpoints.md +++ b/docs/developers/operations/testing-endpoints.md @@ -158,6 +158,8 @@ When `EXPOSE_CAP_UI=true` is set on the CAP srv app, these are accessible throug | `/admin/analytics/` | AnalyticsService — `@analytics.exposed` entity surface + `runSelectQuery` action | XSUAA + `Admin` | | `/admin/exports/$metadata` | ExportsService OData metadata | XSUAA + `Admin` | | `/admin/exports/` | ExportsService — `exportLegacyData(format)` action | XSUAA + `Admin` | +| `/admin/data-privacy/$metadata` | DataPrivacyService OData metadata | XSUAA + `Admin` | +| `/admin/data-privacy/` | DataPrivacyService — `exportDataSubject(userId)` function | XSUAA + `Admin` | | `/display/$metadata` | DisplayService OData metadata | XSUAA | | `/display/` | DisplayService — read-only data for event dashboards | XSUAA | | `/drawings/$metadata` | DrawingService OData metadata | XSUAA + `Admin` | diff --git a/docs/superpowers/plans/2026-11-16-dpi-local-export.md b/docs/superpowers/plans/2026-11-16-dpi-local-export.md new file mode 100644 index 000000000..4acce1cc9 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-dpi-local-export.md @@ -0,0 +1,145 @@ +# DPI local data-subject export + subject-resolution fix — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build an admin-only data-subject JSON export reusing the existing `@PersonalData` annotation layer, and correct the shared subject-resolution gap (non-`user_ID`-keyed entities) in both the export and the live anonymization cascade. + +**Architecture:** A new `@requires:'Admin'` `DataPrivacyService` exposes `exportDataSubject(userId)` whose handler walks `getCascadePlan()` and SELECTs each personal entity's rows for the subject. A shared subject-resolver maps a `Users` row to the three DataSubjectID shapes (direct `user_ID`, the `Users` scalar `ID`, and the non-`user` cases `authorId`/`tab_ID`). The same resolver is wired into `anonymization-cascade.js`, closing a live erasure gap. + +**Tech Stack:** CAP Node.js (`@sap/cds` 10.x), CDS QL, vitest (in-memory SQLite), XSUAA `Admin` scope. + +**Spec:** `docs/superpowers/specs/2026-11-13-dpi-local-export-design.md` + +## Global Constraints + +- Never remove or weaken any `@PersonalData` annotation (audit-logging + cascade gate on `@PersonalData.EntitySemantics` presence). +- Do NOT add `@cap-js/data-privacy` as a dependency; do NOT merge `feat/adopt-data-privacy-0.7.0`. +- Admin auth: `@requires: 'Admin'` (XSUAA scope `$XSAPPNAME.Admin`). +- Never SELECT a HANA BLOB alongside metadata in one CDS QL query — N/A here (targets are `LargeString`/NCLOB, read via CDS QL is fine), but do not widen to any `LargeBinary` column. +- Model reflection must handle both CSN shapes (flat dotted keys + nested object) — reuse `getCascadePlan()`, which already does. +- Audit event name is literally `'SecurityEvent'`; the discriminator goes in `data.action` (the `#769` quirk). +- `getCascadePlan()` memoizes on the defs object — call `_resetPlanForTest()` between unit tests. +- Handler must use `(cds.model ?? cds.db?.model).definitions` (vitest-on-Windows leaves `cds.model` null). +- New `srv/lib/` files that become transitive deps of `content-store.js` must be added to `.deploy/mta.yaml`'s `srv-qa` `cp` list. +- Branch off `origin/DEV`; nothing merges to DEV without maintainer confirmation that the journaling release is stable. + +## Review Focus + +- **Anonymized subject (ghost user):** export against a `Users.ID` whose personal fields were already scrubbed should return a valid envelope with scrubbed values, not crash — Task 4. +- **Subject with zero rows in an entity:** a section with `count: 0` and empty `rows`, not an omitted section or a null-key SELECT — Task 4. +- **`authorId` claim-vs-`sapId` divergence:** a subject whose login-claim id differs from `sapId` (per `devtoberfest-registration.js:22`) must still resolve `AuthorAiRequests` rows — Task 2. +- **Unknown `userId`:** nonexistent `Users.ID` → `req.error(404)`, not an empty 200 — Task 4. +- **`AuthorAiRequests` row keyed only by `authorId` (no `user_ID` backfill):** both export and cascade must still hit it — Tasks 1, 2, 5. + +--- + +### Task 1: Prove the cascade erasure gap is real (characterization test) + +Establishes the bug exists before fixing it (per the #1 rule: test the actual thing). A failing/surviving-row test that Task 5 will flip to green. + +**Files:** +- Test: `test/unit/anonymization-cascade-authorid-gap.test.js` + +**Interfaces:** +- Consumes: `getCascadePlan`, `_resetPlanForTest` from `srv/lib/anonymization-cascade.js`; the cascade entry point it exposes (verify exact export name — `runAnonymizationCascade`/`cascadeForUser` — at implementation). +- Produces: nothing; characterization only. + +- [ ] **Step 1: Write the characterization test** — seed a `Users` row (`ID`=UUID, `sapId`=`'S00ALICE'`) and an `AuthorAiRequests` row with `authorId='S00ALICE'`, `sourceMarkdown='secret'`, `user_ID=null`. Run the cascade for that user's `ID`. Assert the **current** behavior: the `AuthorAiRequests` row still exists (documents the gap). Name: `test_cascade_misses_authorId_keyed_rows_today`. +- [ ] **Step 2: Run it** — Run: `npm test -- test/unit/anonymization-cascade-authorid-gap.test.js`. Expected: PASS (row survives — the gap is real), or if it unexpectedly already deletes, STOP and report (gap not real; revisit scope). +- [ ] **Step 3: Commit** — `git add test/unit/... && git commit -m "test(#977): characterize AuthorAiRequests cascade erasure gap"` + +--- + +### Task 2: Shared subject-resolver + +The core correction: map a `Users` row to every DataSubjectID shape. Consumed by both export and cascade. + +**Files:** +- Create: `srv/lib/data-subject-resolver.js` +- Test: `test/unit/data-subject-resolver.test.js` + +**Interfaces:** +- Consumes: `getCascadePlan` entries `{ entityName, dataSubjectField }`. Does NOT use `resolveTutorialAuthor` — that helper (`packages/core/resolve-tutorial-author.js:70`) maps tutorial contributor emails/logins → `Users.ID` (the opposite direction). For `AuthorAiRequests`, `authorId` holds `req.user.id` (the XSUAA login claim), matched to `Users.sapId` elsewhere (`mcp-homepage-tools.js:36`), with a documented claim-vs-`sapId` divergence (`devtoberfest-registration.js:22`). So candidate values come from `user.sapId` (primary) + `user.uuid` (secondary), derived directly — no cross-package resolver call. +- Produces: `async resolveSubjectKeys(user, planEntry) -> { column: string, values: string[] } | null`. `user` is a full `Users` row. Returns the WHERE column and the candidate values for that entity, or `null` when the entry is unresolvable/skip. Specifically: `Users` → `{column:'ID', values:[user.ID]}`; direct-`user` entities → `{column:'user_ID', values:[user.ID]}`; `AuthorAiRequests` → `{column:'authorId', values:[]}` **and** the handler also sweeps `user_ID` (expose `authorIdCandidates(user)` returning the resolved id list); `DeveloperEnvironmentLinks` → resolved via parent (return `{column:'tab_ID', values:}` given the tab IDs — accept them as an arg, or signal "nested" so the caller resolves Tabs first). + +- [ ] **Step 1: Write failing tests** — cover: (a) `Users` → `{column:'ID',...}`; (b) a `user_ID` entity (`UserMetaData`) → `{column:'user_ID', values:[user.ID]}`; (c) `AuthorAiRequests` for a user with `sapId='S00X'`, `uuid='U-1'` → candidate values include both `'S00X'` and `'U-1'` on column `authorId`; (d) a `skip`/null-DataSubjectID entry → `null`. +- [ ] **Step 2: Run to verify fail** — Run: `npm test -- test/unit/data-subject-resolver.test.js`. Expected: FAIL (module not found). +- [ ] **Step 3: Implement `resolveSubjectKeys` + `authorIdCandidates` in `srv/lib/data-subject-resolver.js`** — switch on `planEntry.dataSubjectField`/`entityName`; `authorIdCandidates(user)` returns `[user.sapId, user.uuid].filter(Boolean)`. Handle the nested `tab_ID` case per the signature above. +- [ ] **Step 4: Run to verify pass** — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "feat(#977): shared data-subject key resolver"` + +--- + +### Task 3: DataPrivacyService definition + +**Files:** +- Create: `srv/data-privacy-service.cds` +- Test: `test/unit/data-privacy-service-metadata.test.js` + +**Interfaces:** +- Produces: service `DataPrivacyService @(path:'/admin/data-privacy')` `@requires:'Admin'` with `function exportDataSubject(userId : String) returns LargeString;`. + +- [ ] **Step 1: Write failing test** — boot the model, assert `DataPrivacyService.exportDataSubject` exists and the service carries `@requires:'Admin'` and `@path:'/admin/data-privacy'`. (Mirror an existing service-metadata test if one exists.) +- [ ] **Step 2: Run to verify fail** — Expected: FAIL. +- [ ] **Step 3: Write `srv/data-privacy-service.cds`** — clone the `ExportsService` shell shape; one `function` as above. +- [ ] **Step 4: Run to verify pass** — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "feat(#977): DataPrivacyService definition"` + +--- + +### Task 4: Export handler + +Assembles the JSON envelope by walking the plan + resolver + per-entity SELECT. + +**Files:** +- Create: `srv/data-privacy-service.js` +- Test: `test/unit/data-privacy-export.test.js` + +**Interfaces:** +- Consumes: `getCascadePlan`, `_resetPlanForTest` (`anonymization-cascade.js`); `resolveSubjectKeys`, `authorIdCandidates` (Task 2); audit emitter (`srv/lib/audit-event.js`). +- Produces: `on('exportDataSubject')` handler returning a JSON string `{ exportedAt, exportedBy, subject:{<9 Users fields>}, sections:[{entity,count,rows}] }`. + +- [ ] **Step 1: Write failing tests (TDD, load-bearing fixtures first)** — seed one `Users` + one row each in: `UserMetaData` (user_ID), `CodeCheckSubmissions` (LargeString `submittedCode`), `AuthorAiRequests` (`authorId`-keyed, `user_ID` null), `DeveloperEnvironmentTabs`+`DeveloperEnvironmentLinks` (tab-nested), `AnalyticsQueryHistory` (skip/null). Assert: envelope has the 9 `Users` fields in `subject`; `AuthorAiRequests.sourceMarkdown` **appears** (proves the resolver fix); Links appear nested under their Tab; the Analytics entity is absent without crashing; a `count:0` section for an entity with no rows; unknown `userId` → the handler throws a 404-shaped error. Call `_resetPlanForTest()` in `beforeEach`. +- [ ] **Step 2: Run to verify fail** — Expected: FAIL (handler not implemented). +- [ ] **Step 3: Implement the handler in `srv/data-privacy-service.js`** — look up `Users` by `ID` (404 if absent) using the `(cds.model ?? cds.db?.model)` fallback for the plan; for each non-skip plan entry, resolve keys via Task 2 and `SELECT` the subject's rows projected to `personalFields` + resolving FK + `createdAt`/`modifiedAt`; nest Links under Tabs; emit `SecurityEvent`/`data.action:'DataSubjectExport'` fail-open; `return JSON.stringify(doc)`. +- [ ] **Step 4: Run to verify pass** — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "feat(#977): data-subject export handler"` + +--- + +### Task 5: Wire the resolver into the cascade (close the erasure gap) + +**Files:** +- Modify: `srv/lib/anonymization-cascade.js` +- Test: `test/unit/anonymization-cascade-authorid-gap.test.js` (flip Task 1's assertion) + +**Interfaces:** +- Consumes: `resolveSubjectKeys`/`authorIdCandidates` (Task 2). + +- [ ] **Step 1: Flip the characterization test** — change `test_cascade_misses_authorId_keyed_rows_today` to assert the `AuthorAiRequests` row is **deleted** after the cascade; rename to `test_cascade_deletes_authorId_keyed_rows`. Add a second case: a `tab`-keyed `DeveloperEnvironmentLinks` row is deleted via its parent. +- [ ] **Step 2: Run to verify fail** — Expected: FAIL (row still survives). +- [ ] **Step 3: Modify the cascade** — replace the direct `dataSubjectField` WHERE with `resolveSubjectKeys`-driven keying so `authorId`/`tab_ID` entities resolve correctly; preserve existing behavior for `user_ID` entities (no regression). +- [ ] **Step 4: Run cascade tests** — Run: `npm test -- test/unit/anonymization-cascade-authorid-gap.test.js` and the existing cascade suite. Expected: PASS, no regression. +- [ ] **Step 5: Commit** — `git commit -m "fix(#977): resolve non-user_ID subjects in anonymization cascade"` + +--- + +### Task 6: Wiring, deploy-manifest, hybrid verification + +**Files:** +- Modify: `.deploy/mta.yaml` (`srv-qa` `cp` list — only if Task 2/4 files became transitive `content-store.js` deps) +- Modify: `docs/developers/operations/testing-endpoints.md` (register `/admin/data-privacy` + `Admin` scope) + +**Interfaces:** none produced. + +- [ ] **Step 1: Audit transitive deps** — re-walk `./` imports from `content-store.js`; if `data-subject-resolver.js` / `data-privacy-service.js` are reachable, add to `srv-qa` `cp` list. Document the check result either way. +- [ ] **Step 2: Add the endpoint + scope row** to `testing-endpoints.md`. +- [ ] **Step 3: Full unit suite (scoped) + CDS build** — Run: `npm test -- test/unit/data-privacy-export.test.js test/unit/data-subject-resolver.test.js test/unit/anonymization-cascade-authorid-gap.test.js`; then `cds build --production` (wrap in `scripts/quiet-run.sh`). Expected: PASS, build exit 0. +- [ ] **Step 4: Hybrid NCLOB verification** — Run: `npm run test:hybrid` for the export (needs `cds bind`/`cf login`) to prove `LargeString` reads against real HANA. If hybrid env unavailable, mark skipped and flag for pre-merge. +- [ ] **Step 5: Commit** — `git commit -m "chore(#977): register DPI export endpoint + deploy-manifest audit"` + +--- + +## Notes +- The `feat/adopt-data-privacy-0.7.0` branch is NOT merged. Upstream PR cap-js/data-privacy#62 stands independently. +- Already-orphaned `AuthorAiRequests` rows (anonymized before Task 5) may need a one-off repair sweep — flag as a follow-up if hybrid data shows any. diff --git a/docs/superpowers/specs/2026-11-13-dpi-local-export-design.md b/docs/superpowers/specs/2026-11-13-dpi-local-export-design.md new file mode 100644 index 000000000..1f495621d --- /dev/null +++ b/docs/superpowers/specs/2026-11-13-dpi-local-export-design.md @@ -0,0 +1,230 @@ +# Design: Local data-subject export (DPI) — build-not-adopt (#977) + +**Date:** 2026-11-13 +**Status:** Draft — pending approval +**Issue:** sap-tutorials/tutorials-ims#977 +**Supersedes the adoption direction in:** branch `feat/adopt-data-privacy-0.7.0`, `docs/developers/reference/data-privacy-v070-eval.md` + +## Intent & the why + +Issue #977 set out to enable `@cap-js/data-privacy@0.7.0` to provide Data Privacy +Integration (DPI) for the platform ahead of the end-of-July-2026 PROD cutover. Prior +sessions crash-fixed the plugin (upstream PR cap-js/data-privacy#62) and attempted +adoption, but turning the plugin on produces ~126 CDS compile errors and no buildable +project. The root cause is architectural, not a bug (see Approaches). + +The compliance requirement, confirmed with the maintainer this session, is narrower than +the plugin's surface: **a data-subject ACCESS/EXPORT capability (GDPR Art. 15), plus the +ERASURE the platform already performs.** No SAP ILM retention objects / blocking / +destruction scheduling, and no standard SAP Fiori "Manage Personal Data" app, are +required for cutover. + +Given that scope, the plugin's value (generated `InformationService` + `RetentionService`, +ILM object registration, Fiori DPP app compatibility) is mostly unused, while its cost +(126 errors, a pinned pre-GA patch to re-verify on every bump, and a shared-CSN +architecture that fights selective exposure) is entirely paid. **This design builds a +small local export service instead of adopting the plugin.** + +## Goals + +- Provide an admin/DPO-triggered **data-subject export**: given a `Users` ID, return a + JSON document containing all personal data the platform holds for that subject. +- Reuse the existing `@PersonalData` annotation layer as the single source of truth for + what is personal — the same annotations `@cap-js/audit-logging` and the custom + `anonymization-cascade.js` already read. Zero new annotation work. +- Match existing codebase conventions (admin auth, model reflection, JSON-string return). +- **Correct the shared subject-resolution gap** (see Subject resolution): fix both the + export AND the live `anonymization-cascade.js` so entities whose DataSubjectID is not + `user_ID` (`AuthorAiRequests` keyed on `authorId`; `DeveloperEnvironmentLinks` keyed on + `tab`) resolve to the correct subject. This is in-scope for #977 because export and + cascade share the same resolution logic — fixing one without the other is incoherent. + +## Non-goals + +- No SAP ILM retention/blocking/destruction scheduling. +- No standard Fiori "Manage Personal Data" app integration. +- No self-service ("export my own data") surface in v1 — admin/DPO-triggered only. +- No change to erasure *mechanism*: `anonymization-cascade.js` stays the erasure walker. + (Its subject-resolution is corrected under this issue — see Subject resolution — but the + cascade-walk design is unchanged.) +- No change to the 17 `@PersonalData` annotations in `db/audit-logging.cds` / + `db/analytics-builder.cds`. They remain exactly as-is for audit-logging + cascade. + +## Anti-goals (would make this a failure even if it "works") + +- Dropping or weakening any `@PersonalData` annotation (would silently break audit-logging + at `@cap-js/audit-logging` `utils.js:16` and the cascade at `anonymization-cascade.js:37` + — both gate on the *presence* of `@PersonalData.EntitySemantics`). +- Inventing a second, divergent notion of "what is personal" that drifts from the + annotation layer the other two subsystems use. +- Keeping `@cap-js/data-privacy` as a dependency "just in case" — it carries the patch + maintenance burden with no runtime benefit under this scope. + +## Constraints + +- **Shared CSN:** CAP gives all plugins one loaded CSN (`cds.model`). The three + consumers — data-privacy exposure, audit-logging, and `anonymization-cascade.js` — all + gate on the *presence* of `@PersonalData.EntitySemantics`. There is no per-plugin model + view and no per-entity opt-out in data-privacy 0.7.0 (verified against installed source; + the only opt-outs suppress retention *fields*, not the projection). This is why + selective exposure via the plugin is not achievable without fighting the framework, and + why "build locally" is the framework-aligned path. +- **Admin scope:** `@requires: 'Admin'` (XSUAA scope `$XSAPPNAME.Admin`, role collection + "Tutorials Admin"), per `srv/exports-service.cds` and `srv/admin-service.cds:18-19`. +- **CSN annotation shapes:** annotations appear as flat dotted keys in real CSN and as + nested objects in test mocks; the reflection must handle both (as `anonymization-cascade.js` + already does). +- **DataSubjectID is usually an association** → the FK column is `${field}_ID` + (`user` → `user_ID`); on `Users` itself the subject key is the scalar `ID`. +- **LOB:** the "no BLOB alongside metadata in one CDS QL SELECT" rule is BLOB-only. The + personal `LargeString`/NCLOB columns (`submittedCode`, `submittedAnswer`, `sourceMarkdown`) + read fine via CDS QL — proven by existing write paths and the cascade's NCLOB UPDATEs. +- **Scheduling:** implementation is deferred until the in-flight journaling release deploys + stable on DEV (maintainer instruction). Nothing lands on DEV before the maintainer + confirms. + +## Approaches considered + +### A. Adopt the plugin, suppress exposure per-entity via annotations +Rejected — **mechanism does not exist.** Data-privacy 0.7.0 exposes any entity carrying +`@PersonalData.EntitySemantics` into both generated services, with no allowlist/denylist +and no per-entity opt-out that stops the projection. Verified in installed source +(`lib/csn-enhancements/index.js:60,72-103`). + +### B. Adopt the plugin, give it a reduced CSN via a loaded-hook strip or build profile +Rejected — **fights the framework.** All three consumers read the same shared +`cds.model`; audit-logging (`utils.js:16`) and the cascade (`anonymization-cascade.js:37`) +break the instant `EntitySemantics` is removed from an entity. A hook that strips +annotations only for the plugin requires a private CSN the framework doesn't provide; +ordering-dependent and fragile. A build-time profile split risks audit-logging silently +losing entities in the DPI-profile build. + +### C. Adopt the plugin, expose all 17 and repair the 126 errors +Rejected on cost/benefit given the confirmed scope. The errors are fixable in principle +(association-redirects on `Users`/`Advocates` hubs ~61; aggregate-view column-push on +`TaskRecords`/`BranchDecisions` ~51), but the entire payoff is the `RetentionService` + +Fiori DPP app we do **not** need, plus an export we can build in ~100 lines. We would also +inherit the pinned pre-GA patch forever. + +### D. (Chosen) Build a local admin export service; drop the plugin +A new read-only `@requires: 'Admin'` service exposes one function: +`exportDataSubject(userId : String) returns LargeString` (JSON string). Its handler reuses +`getCascadePlan()` from `anonymization-cascade.js` to enumerate personal entities + their +DataSubjectID FK + personal fields, then SELECTs each entity's rows for that subject and +assembles a JSON document. The `@cap-js/data-privacy` dependency and its patch are removed. + +**Why D wins:** it delivers exactly the confirmed requirement (admin export; erasure +already owned), reuses the one source of truth for "what is personal," matches existing +conventions, adds no framework fight, and removes a maintenance liability. The upstream +crash-fix PR (#62) stands on its own merit regardless. + +## The how (decided) + +- **Service:** standalone `@requires: 'Admin'` service, cloning the `ExportsService` shell + (`@(path: '/admin/exports')` family). *Builder's/my call, flagged for review:* either a + new `DataPrivacyService @(path:'/admin/data-privacy')` with `function exportDataSubject`, + or an added function on the existing `ExportsService`. Recommendation: **new standalone + service** for a clean compliance boundary and independent testability. +- **Return shape:** `LargeString` holding a JSON document (matches `getMetricsSnapshot() + returns String` JSON precedent, `admin-service.cds:1024-1029`). Not the streaming-binary + GET bridge — that exists for large CSV/XLSX, not a bounded JSON doc. +- **Reflection:** reuse `getCascadePlan()` (`srv/lib/anonymization-cascade.js`) directly; + do not duplicate the annotation walk. It returns + `{ entityName, action, dataSubjectField, personalFields }` per entity. Entries with + `action: 'skip'` / `dataSubjectField: null` (the Analytics `Other` entities with no + DataSubjectID field — `AnalyticsQueryHistory`, `AnalyticsSavedQuery`) are **skipped** by + the export loop (and by the cascade already); a `WHERE {null: ...}` would otherwise + crash. These rows are not keyed to a single subject; their omission is documented, not + silent. +- **Subject resolution (the corrected core — settles the builder-check blockers):** the + `dataSubjectField` returned by `getCascadePlan()` is NOT uniformly `user_ID`. Three + shapes exist and the export + cascade must handle each: + 1. **Direct `user_ID` (most entities):** `WHERE user_ID = `. Straightforward. + 2. **`Users` itself (the DataSubject):** key on scalar `ID`. + 3. **Non-`user` DataSubjectID — the gap:** + - `AuthorAiRequests.dataSubjectField = 'authorId'`, a `String(80)` holding + `req.user.id` (the XSUAA/login claim), **not** `Users.ID` (a cuid UUID). A naive + `WHERE authorId = ` returns zero rows → silent GDPR-completeness failure. + Resolution: from the `Users` row, derive the XSUAA identity via the existing + `resolveTutorialAuthor` helper (`srv/lib/resolve-tutorial-author.js` → `@tutorials/core`), + then `WHERE authorId = ` **AND** sweep `WHERE user_ID = ` for + rows where the association was backfilled. Note the documented claim-vs-`sapId` + divergence (`srv/lib/devtoberfest-registration.js:22`) — this is exactly why the + resolution must go through the shared helper, not a bare `where({ sapId })`. + - `DeveloperEnvironmentLinks.dataSubjectField = 'tab_ID'`, not `user_ID`. A flat + per-entity loop would query `WHERE tab_ID = ` → zero rows. Resolution: + export `DeveloperEnvironmentLinks` **nested under their parent `DeveloperEnvironmentTabs`** + (resolve the subject's Tabs first, then their Links by `tab_ID IN ()`), + matching the composition structure. + **The same correction applies to `anonymization-cascade.js`** — it drives off the same + `getCascadePlan()` and today keys `AuthorAiRequests` on `authorId` without resolving the + XSUAA identity, so those rows (`sourceMarkdown`, `variants`) survive user anonymization + as FK-ghosts (a live erasure gap). Fixing the resolver in one shared place corrects both. +- **Document structure:** top-level subject identity (from `Users`) + one section per + personal entity, each listing the subject's rows projected to annotated personal fields + plus FKs needed for context. Include entities regardless of EntitySemantics value + (`DataSubject`/`DataSubjectDetails`/`Other`) — the export is about completeness, not the + plugin's exposure rules. (Settles the earlier "which of the 20" question: the export is + comprehensive; there is no suppression problem once the plugin is gone.) +- **TaskRecords / BranchDecisions aggregate views:** irrelevant to this design — the export + reads base entities, not views, so the GROUP-BY/FK-drop problem that broke the plugin + does not arise. + +## Removal of the plugin + +- The `feat/adopt-data-privacy-0.7.0` branch (dependency + `patches/@cap-js+data-privacy+0.7.0.patch`) + is **not** merged. The patch's value is the upstream PR #62; it does not ship here. +- No `cds.requires` entry for the plugin is added. `db/audit-logging.cds` is untouched. + +## Decided (settled this session; builder follows as written) + +- **Service:** new standalone `DataPrivacyService @(path: '/admin/data-privacy')`, + `@requires: 'Admin'`, one `function exportDataSubject(userId : String) returns LargeString` + (a read → `function`, not `action`). +- **Subject key input:** `userId` is `Users.ID` (cuid UUID). Handler looks up the `Users` + row by `ID` first; a nonexistent row → `req.error(404)` (operator tool). +- **`Users` identity block:** emit exactly the 9 `@PersonalData.IsPotentiallyPersonal` + fields on `Users` (`firstName, lastName, email, displayName, sapId, khorosId, + khorosLogin, khorosAvatarUrl, uuid`) as the top-level `subject` block; do not also + double-list `Users` as a section. +- **Document envelope:** + `{ exportedAt, exportedBy, subject: {<9 Users fields>}, sections: [{ entity, count, rows: [...] }] }`. + Per row: `personalFields` + the resolving FK + `createdAt`/`modifiedAt` context. Render + association FKs as their raw `_ID` scalar. `variants`/`sourceMarkdown` are already + JSON/markdown strings — emit raw, do not re-parse (avoid double-encoding). +- **`DeveloperEnvironmentLinks`:** exported nested under their parent Tab (see Subject + resolution). +- **Analytics `Other` (null DataSubjectID):** skipped by the loop; omission documented. +- **Audit:** the export emits a `SecurityEvent` with `data.action: 'DataSubjectExport'` + via the existing audit emitter (`srv/lib/audit-event.js` — event NAME is `'SecurityEvent'`, + the action goes in `data.action`, per the `#769` quirk). Fail-open — never throw into + the export. +- **v1 scope:** export-only; no count/preview endpoint. +- **vitest:** handler uses the `(cds.model ?? cds.db?.model).definitions` fallback (mirrors + `anonymization-cascade.js:108`) or `getCascadePlan` throws under unit tests. +- **Tests (TDD, write first):** unit fixtures seed one `Users` + one row in each + distinct-shape entity — a `user_ID`-keyed detail, the LargeString case + (`CodeCheckSubmissions`), the **`authorId`-keyed case (`AuthorAiRequests`)**, the + **`tab`-keyed nested case (`DeveloperEnvironmentLinks`)**, and a `skip`/null case + (`AnalyticsQueryHistory`). The `authorId` + `tab` fixtures are load-bearing — they turn + the two resolution gaps into red tests before the fix. Call `_resetPlanForTest()` + (`anonymization-cascade.js:15`) between tests (plan memoizes on the defs object). Hybrid + NCLOB test via `npm run test:hybrid` (needs `cds bind`/`cf login`). + +## What's left to the builder + +- Exact `resolveTutorialAuthor` signature/return (it's a shim to `@tutorials/core`) — + verify at implementation time and reuse rather than reinvent subject resolution. +- JSON field-naming fine points (camelCase vs the raw CSN element names). +- Whether the cascade fix needs a backfill/repair for already-orphaned `AuthorAiRequests` + rows (rows whose subject was anonymized before the fix) — flag if the hybrid data shows + any; may spin a follow-up. +- `srv-qa` cp-list audit: the new `srv/lib/` file(s) must be added to `.deploy/mta.yaml`'s + `srv-qa` `cp` list (CLAUDE.md rule) if they become transitive deps of `content-store.js` + — verify before deploy. + +## Scheduling + +Implementation deferred until the journaling release is stable on DEV. Work proceeds in the +worktree `worktree-977-dpi-minimal-set` (off `origin/DEV`). Nothing merges to DEV without +explicit maintainer go-ahead. diff --git a/srv/data-privacy-service.cds b/srv/data-privacy-service.cds new file mode 100644 index 000000000..060cc0744 --- /dev/null +++ b/srv/data-privacy-service.cds @@ -0,0 +1,4 @@ +@requires : 'Admin' +service DataPrivacyService @(path : '/admin/data-privacy') { + function exportDataSubject(userId : String) returns LargeString; +} diff --git a/srv/data-privacy-service.js b/srv/data-privacy-service.js new file mode 100644 index 000000000..da9a4ff78 --- /dev/null +++ b/srv/data-privacy-service.js @@ -0,0 +1,217 @@ +// srv/data-privacy-service.js +// +// Handler for DataPrivacyService -- GDPR/DPI local data-subject export. +// +// Implements the exportDataSubject(userId) function: +// 1. Looks up the Users row by ID (404 if absent). +// 2. Builds a JSON envelope: { exportedAt, exportedBy, subject, sections }. +// - subject: the 9 @PersonalData.IsPotentiallyPersonal fields on Users. +// - sections: one entry per @PersonalData entity (excluding Users itself), +// projected to personalFields + resolving FK + createdAt/modifiedAt. +// 3. Handles the nested marker for DeveloperEnvironmentLinks (tab_ID cannot +// be resolved without a DB query -- see resolver docs). +// 4. Emits a fail-open audit event for action 'DataSubjectExport'. +// +// Reuses: +// - srv/lib/anonymization-cascade.js getCascadePlan +// - srv/lib/data-subject-resolver.js resolveSubjectKeys +// - srv/lib/audit-event.js createAuditEmitter + +import cds from '@sap/cds'; +import { getCascadePlan } from './lib/anonymization-cascade.js'; +import { resolveSubjectKeys } from './lib/data-subject-resolver.js'; +import { createAuditEmitter } from './lib/audit-event.js'; + +const LOG = cds.log('data-privacy-service'); + +// The 9 @PersonalData.IsPotentiallyPersonal fields on ims.Users. +// Kept as an explicit list so the subject block is stable even if the model +// gains new fields in future (the export is intentionally opt-in, not catch-all). +const USER_PERSONAL_FIELDS = [ + 'firstName', 'lastName', 'email', 'displayName', + 'sapId', 'khorosId', 'khorosLogin', 'khorosAvatarUrl', 'uuid', +]; + +// Additional columns to project alongside personalFields in each section row. +const SECTION_META_COLS = ['createdAt', 'modifiedAt']; + +export default class DataPrivacyService extends cds.ApplicationService { + async init() { + this.on('exportDataSubject', this._handleExport.bind(this)); + return super.init(); + } + + async _handleExport(req) { + const { userId } = req.data; + + // -- 1. Look up Users row ----------------------------------------------- + // cds.model can be null in vitest+CDS on Windows; fall back to cds.db.model. + // Resolved once here and passed into helpers to avoid repeated lookups. + const definitions = (cds.model ?? cds.db?.model)?.definitions; + if (!definitions) { + return req.reject(500, 'CDS model not available'); + } + + const { Users } = cds.entities('com.sap.developers.ims'); + const user = await SELECT.one.from(Users).where({ ID: userId }); + if (!user) { + return req.reject(404, `User not found: ${userId}`); + } + + // -- 2. Build subject block (9 personal fields) ------------------------- + const subject = {}; + for (const f of USER_PERSONAL_FIELDS) { + subject[f] = user[f] ?? null; + } + + // -- 3. Walk the cascade plan and collect sections ---------------------- + // Single pass: resolve all subject keys upfront, classify nested parents, + // then iterate the resolved map to build sections. + const plan = getCascadePlan(definitions); + + // Resolve subject keys for every plan entry in one pass, and identify + // entity names that will be output as nested parents so they can be skipped + // in the direct-section loop. + const resolvedMap = new Map(); // entityName -> resolved keys (or null) + const nestedParents = new Set(); + for (const entry of plan) { + if (entry.action === 'skip') continue; + const resolved = await resolveSubjectKeys(user, entry); + resolvedMap.set(entry.entityName, resolved); + if (resolved?.nested && resolved.via) { + // resolved.via is a short name; find the fully-qualified entity name. + for (const name of Object.keys(definitions)) { + if (name.endsWith(`.${resolved.via}`) || name === resolved.via) { + nestedParents.add(name); + break; + } + } + } + } + + const sections = []; + for (const entry of plan) { + const { entityName, action, personalFields } = entry; + + if (action === 'skip') continue; + + // Skip the Users/DataSubject root entity -- it becomes the subject block. + if (entry.dataSubjectField === 'ID') continue; + + // Skip entities that will be output as nested parents (handled below). + if (nestedParents.has(entityName)) continue; + + const resolved = resolvedMap.get(entityName); + if (!resolved) continue; // unresolvable, skip + + // Handle nested marker (DeveloperEnvironmentLinks). + if (resolved.nested) { + const section = await this._fetchNestedLinks(user, entry, personalFields); + if (section) sections.push(section); + continue; + } + + // Normal case: SELECT rows projected to personalFields + FK + meta. + const { column, values } = resolved; + if (!values?.length) { + LOG.warn(`exportDataSubject: no data-subject candidates for ${entityName} (user ${userId}) - rows omitted, subject not resolvable`); + } + const rows = await this._selectRows(entityName, column, values, personalFields, definitions); + sections.push({ entity: entityName, count: rows.length, rows }); + } + + // -- 4. Emit audit event (fail-open) ------------------------------------ + // createAuditEmitter is already fail-open; binding may be null in unit tests. + const auditBinding = await cds.connect.to('audit-log').catch(() => null); + const audit = createAuditEmitter(auditBinding, LOG); + await audit('DataSubjectExport', { + subjectId: userId, + by: req.user?.id ?? 'unknown', + }); + + // -- 5. Assemble and return the envelope -------------------------------- + const doc = { + exportedAt: new Date().toISOString(), + exportedBy: req.user?.id ?? 'unknown', + subject, + sections, + }; + return JSON.stringify(doc); + } + + // Select rows for a direct-FK entity, projected to relevant columns. + // Filters out columns that do not exist on the entity (some entities use + // non-standard keys or do not have the 'managed' aspect). + // + // GDPR safety: if any personalField declared in the model annotation is NOT + // present as a selectable element, LOG.warn is emitted so schema drift is + // surfaced immediately rather than silently omitting personal data. + async _selectRows(entityName, column, values, personalFields, definitions) { + if (!values || values.length === 0) return []; + const entityDef = definitions?.[entityName]; + const elements = entityDef?.elements ?? {}; + + // Warn on any declared personalField that is missing from the entity elements. + const missing = personalFields.filter((f) => !(f in elements)); + if (missing.length) { + LOG.warn(`_selectRows: personalFields not selectable for ${entityName}: ${missing.join(', ')}`); + } + + // Build projection from columns that actually exist on this entity. + const candidates = ['ID', column, ...personalFields, ...SECTION_META_COLS]; + const cols = [...new Set(candidates.filter((c) => c in elements))]; + if (cols.length === 0) return []; + const rows = await SELECT.from(entityName).columns(cols).where(`${column} in`, values); + return rows; + } + + // Handle the nested marker for DeveloperEnvironmentLinks. + // Step 1: fetch the subject's DeveloperEnvironmentTabs rows. + // Step 2: for each Tab, fetch its DeveloperEnvironmentLinks. + // Returns a section for DeveloperEnvironmentTabs with links nested inside. + async _fetchNestedLinks(user, entry, _personalFields) { + // entry is the DeveloperEnvironmentLinks plan entry. + // Query DeveloperEnvironmentTabs first. + const TABS_ENTITY = 'com.sap.developers.ims.DeveloperEnvironmentTabs'; + const LINKS_ENTITY = entry.entityName; // com.sap.developers.ims.DeveloperEnvironmentLinks + + // TODO: tabCols and linkCols are hardcoded because DeveloperEnvironmentTabs/Links + // currently carry no @PersonalData.IsPotentiallyPersonal fields. MUST be updated + // (or switched to the model-driven personalFields projection) if any personal field + // is ever annotated on those entities. + const tabCols = [...new Set(['ID', 'user_ID', 'tabName', 'tabOrder'])]; + const tabRows = await SELECT.from(TABS_ENTITY) + .columns(tabCols) + .where({ user_ID: user.ID }); + + if (!tabRows.length) { + return { entity: TABS_ENTITY, count: 0, rows: [] }; + } + + const tabIds = tabRows.map((t) => t.ID); + + // Fetch all links for these tabs in one query. + const linkCols = [...new Set(['ID', 'tab_ID', 'title', 'url', 'linkOrder'])]; + const allLinks = await SELECT.from(LINKS_ENTITY) + .columns(linkCols) + .where(`tab_ID in`, tabIds); + + // Group links by tab_ID. + const linksByTab = {}; + for (const link of allLinks) { + (linksByTab[link.tab_ID] ??= []).push(link); + } + + // Attach links array to each tab row. + const enrichedTabRows = tabRows.map((t) => ({ + ...t, + links: linksByTab[t.ID] ?? [], + })); + + return { + entity: TABS_ENTITY, + count: enrichedTabRows.length, + rows: enrichedTabRows, + }; + } +} diff --git a/srv/lib/anonymization-cascade.js b/srv/lib/anonymization-cascade.js index 6497122e7..2e9aaab88 100644 --- a/srv/lib/anonymization-cascade.js +++ b/srv/lib/anonymization-cascade.js @@ -1,4 +1,5 @@ import cds from '@sap/cds'; +import { resolveSubjectKeys } from './data-subject-resolver.js'; const LOG = cds.log('anonymization-cascade'); @@ -17,6 +18,13 @@ export function _resetPlanForTest() { cachedDefs = null; } +// Test seam: exposes cascadeDelete for direct invocation in unit tests. +// Mirrors the _resetPlanForTest convention — underscore prefix signals test-only use. +// DO NOT call from production code; use executeAnonymizationCascade instead. +export async function _cascadeDeleteForTest(user, step, db) { + return cascadeDelete(user, step, db); +} + /** * Walk model definitions, return cascade plan for every @PersonalData entity. * Cached on first call; the same defs object reuses the cache. @@ -116,19 +124,71 @@ export async function executeAnonymizationCascade(user, db) { } async function cascadeNullPersonal(user, step, _db) { - const update = { [step.dataSubjectField]: null }; - for (const f of step.personalFields) update[f] = null; - await UPDATE.entity(step.entityName).where({ [step.dataSubjectField]: user.ID }).set(update); + const resolved = await resolveSubjectKeys(user, step); + if (!resolved) return; + if (resolved.nested) { + // Nested case: look up parent IDs first, then apply action on child entity. + const parentRows = await SELECT.from(resolved.via).columns('ID').where({ user_ID: user.ID }); + const parentIds = parentRows.map(r => r.ID); + if (!parentIds.length) return; + const update = { [resolved.column]: null }; + for (const f of step.personalFields) update[f] = null; + await UPDATE.entity(step.entityName).where({ [resolved.column]: { in: parentIds } }).set(update); + } else { + // Guard: empty candidate list (e.g. sapId + uuid both null) would produce + // WHERE col IN () which is a SQL syntax error on HANA — skip and warn. + if (!resolved.values?.length) { + LOG.warn(`cascade: no data-subject candidates for ${step.entityName} (user ${user.ID}) - skipping; possible incomplete erasure`); + return; + } + const update = { [resolved.column]: null }; + for (const f of step.personalFields) update[f] = null; + await UPDATE.entity(step.entityName).where({ [resolved.column]: { in: resolved.values } }).set(update); + } } async function cascadeDelete(user, step, _db) { - await DELETE.from(step.entityName).where({ [step.dataSubjectField]: user.ID }); + const resolved = await resolveSubjectKeys(user, step); + if (!resolved) return; + if (resolved.nested) { + // Nested case: look up parent IDs first, then delete child rows. + const parentRows = await SELECT.from(resolved.via).columns('ID').where({ user_ID: user.ID }); + const parentIds = parentRows.map(r => r.ID); + if (!parentIds.length) return; + await DELETE.from(step.entityName).where({ [resolved.column]: { in: parentIds } }); + } else { + // Guard: empty candidate list (e.g. sapId + uuid both null) would produce + // WHERE col IN () which is a SQL syntax error on HANA — skip and warn. + if (!resolved.values?.length) { + LOG.warn(`cascade: no data-subject candidates for ${step.entityName} (user ${user.ID}) - skipping; possible incomplete erasure`); + return; + } + await DELETE.from(step.entityName).where({ [resolved.column]: { in: resolved.values } }); + } } async function cascadeAuditOnly(user, step, _db) { - await UPDATE.entity(step.entityName) - .where({ [step.dataSubjectField]: user.ID }) - .set({ createdBy: 'ANONYMIZED', modifiedBy: 'ANONYMIZED' }); + const resolved = await resolveSubjectKeys(user, step); + if (!resolved) return; + if (resolved.nested) { + // Nested case: look up parent IDs first, then apply action on child entity. + const parentRows = await SELECT.from(resolved.via).columns('ID').where({ user_ID: user.ID }); + const parentIds = parentRows.map(r => r.ID); + if (!parentIds.length) return; + await UPDATE.entity(step.entityName) + .where({ [resolved.column]: { in: parentIds } }) + .set({ createdBy: 'ANONYMIZED', modifiedBy: 'ANONYMIZED' }); + } else { + // Guard: empty candidate list (e.g. sapId + uuid both null) would produce + // WHERE col IN () which is a SQL syntax error on HANA — skip and warn. + if (!resolved.values?.length) { + LOG.warn(`cascade: no data-subject candidates for ${step.entityName} (user ${user.ID}) - skipping; possible incomplete erasure`); + return; + } + await UPDATE.entity(step.entityName) + .where({ [resolved.column]: { in: resolved.values } }) + .set({ createdBy: 'ANONYMIZED', modifiedBy: 'ANONYMIZED' }); + } } async function cascadeIdentityReplace(user, step, _db) { diff --git a/srv/lib/data-subject-resolver.js b/srv/lib/data-subject-resolver.js new file mode 100644 index 000000000..4959ab919 --- /dev/null +++ b/srv/lib/data-subject-resolver.js @@ -0,0 +1,89 @@ +/** + * srv/lib/data-subject-resolver.js + * + * Shared data-subject key resolver for GDPR/DPI local export and anonymization cascade. + * + * Given a `Users` row and a `getCascadePlan()` entry, returns the WHERE column + * and candidate values needed to SELECT that subject's rows in a given entity. + * + * Pure module — no `cds` import, no DB access. `async` is kept on + * `resolveSubjectKeys` so callers can await it uniformly (future proofing). + * + * ### Nested marker (DeveloperEnvironmentLinks) + * + * DeveloperEnvironmentLinks links to DeveloperEnvironmentTabs via `tab_ID`. + * The resolver cannot produce tab IDs without a DB query, so it returns a + * nested marker instead of resolved values: + * + * { column: 'tab_ID', values: null, nested: true, via: 'DeveloperEnvironmentTabs' } + * + * Task-4 (export handler) and Task-5 (anonymization cascade fix) MUST check + * for `result.nested === true` and: + * 1. Query `DeveloperEnvironmentTabs` for rows where `user_ID = user.ID` + * 2. Collect the resulting `ID` values + * 3. Then query `DeveloperEnvironmentLinks` where `tab_ID IN ()` + * + * The exact shape of this marker is load-bearing for those consumers — do not + * change the field names without updating both callers. + */ + +/** + * Return the candidate XSUAA/IAS login claim values for a `Users` row. + * + * `AuthorAiRequests.authorId` holds `req.user.id` (the XSUAA login claim). + * Across the codebase that claim is matched against `Users.sapId` (primary), + * with a documented divergence that for some providers the claim may be stored + * in `Users.uuid` instead (see `srv/lib/devtoberfest-registration.js:22`). + * + * @param {object} user Full `Users` row ({ ID, sapId, uuid, ... }) + * @returns {string[]} Filtered list of non-null candidate id strings + */ +export function authorIdCandidates(user) { + return [user.sapId, user.uuid].filter(Boolean); +} + +/** + * Map a `Users` row + a cascade plan entry to { column, values } for WHERE + * filtering, or `null` when the entry cannot / should not be queried. + * + * @param {object} user Full `Users` row ({ ID, sapId, uuid, ... }) + * @param {object} planEntry Entry from `getCascadePlan()`: + * { entityName, action, dataSubjectField, personalFields } + * @returns {Promise} + * null — entry is skip/unresolvable + * { column, values: string[] } — normal direct FK case + * { column, values: null, nested, via } — nested case (DeveloperEnvironmentLinks) + */ +export async function resolveSubjectKeys(user, planEntry) { + const { entityName, action, dataSubjectField } = planEntry; + + // Skip entries — action explicitly skipped, or no data-subject field identified + if (action === 'skip' || !dataSubjectField) { + return null; + } + + // Users entity (DataSubject root) — key is the UUID PK + // Match on entityName suffix OR on dataSubjectField === 'ID' (the DataSubjectID element) + if (dataSubjectField === 'ID') { + return { column: 'ID', values: [user.ID] }; + } + + // AuthorAiRequests — authorId holds the XSUAA login claim (NOT the user UUID) + if (dataSubjectField === 'authorId') { + return { column: 'authorId', values: authorIdCandidates(user) }; + } + + // DeveloperEnvironmentLinks — linked via parent DeveloperEnvironmentTabs (tab_ID) + // Cannot resolve without a DB query; return a nested marker for the caller to handle. + if (dataSubjectField === 'tab_ID') { + return { + column: 'tab_ID', + values: null, + nested: true, + via: 'DeveloperEnvironmentTabs' + }; + } + + // Default: direct user FK column (e.g. user_ID, created_by, etc.) + return { column: dataSubjectField, values: [user.ID] }; +} diff --git a/test/unit/anonymization-cascade-authorid-gap.test.js b/test/unit/anonymization-cascade-authorid-gap.test.js new file mode 100644 index 000000000..55900e14d --- /dev/null +++ b/test/unit/anonymization-cascade-authorid-gap.test.js @@ -0,0 +1,283 @@ +import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'; +import path from 'node:path'; +import cds from '@sap/cds'; +import { _resetPlanForTest, getCascadePlan, executeAnonymizationCascade, _cascadeDeleteForTest } from '../../srv/lib/anonymization-cascade.js'; + +describe('anonymization-cascade: AuthorAiRequests authorId gap', () => { + beforeAll(async () => { + // Load schema.cds + audit-logging.cds so @PersonalData annotations are present + // in cds.db.model.definitions (plain schema.cds omits the annotate directives). + await cds.deploy([ + path.join(process.cwd(), 'db', 'schema.cds'), + path.join(process.cwd(), 'db', 'audit-logging.cds') + ]).to('sqlite::memory:'); + }); + + beforeEach(async () => { + const { Users, AuthorAiRequests } = cds.entities('com.sap.developers.ims'); + await DELETE.from(AuthorAiRequests); + await DELETE.from(Users); + _resetPlanForTest(); + vi.restoreAllMocks(); + }); + + it('test_cascade_deletes_authorId_keyed_rows', async () => { + const { Users, AuthorAiRequests } = cds.entities('com.sap.developers.ims'); + + // Seed a Users row with ID (UUID) and sapId (XSUAA id) + const userId = '11111111-1111-1111-1111-111111111111'; + const sapId = 'S00ALICE'; + await INSERT.into(Users).entries({ + ID: userId, + sapId: sapId, + firstName: 'Alice', + email: 'alice@example.com' + }); + + // Seed an AuthorAiRequests row with authorId (XSUAA id, same as sapId), + // sourceMarkdown content, and NO user_ID FK (null). + // The cascade must resolve authorId -> sapId and delete the row. + const reqId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'; + await INSERT.into(AuthorAiRequests).entries({ + ID: reqId, + authorId: sapId, // XSUAA id, NOT the UUID + feature: 'os-variants', + sourceMarkdown: 'secret content that should be anonymized', + user_ID: null // no FK to Users + }); + + // Run cascade for the user + await executeAnonymizationCascade( + { ID: userId, sapId: sapId }, + await cds.connect.to('db') + ); + + // Assert: the AuthorAiRequests row is DELETED (gap is closed). + // The resolver maps authorId -> sapId candidates and the cascade + // deletes rows WHERE authorId IN [sapId, uuid]. + const rows = await SELECT.from(AuthorAiRequests).where({ ID: reqId }); + expect(rows).toHaveLength(0); + }); + + // CRITICAL guard: user with sapId=null AND uuid=null must not throw (empty IN list) + it('test_cascade_no_throw_when_authorId_candidates_empty', async () => { + const { Users, AuthorAiRequests } = cds.entities('com.sap.developers.ims'); + + // A legacy/partially-anonymized user with both sapId and uuid null. + // authorIdCandidates(user) returns [] — without the empty-array guard + // the cascade would emit WHERE authorId IN () which is a SQL syntax error + // on HANA, aborting the whole erasure run. + const userId = '33333333-3333-3333-3333-333333333333'; + await INSERT.into(Users).entries({ + ID: userId, + sapId: null, + uuid: null, + firstName: 'Legacy', + email: 'legacy@example.com' + }); + + // Seed an AuthorAiRequests row — it should survive (no key to match) + // but the cascade must not throw. + const reqId = 'cccccccc-cccc-cccc-cccc-cccccccccccc'; + await INSERT.into(AuthorAiRequests).entries({ + ID: reqId, + authorId: 'some-old-id', + feature: 'os-variants', + sourceMarkdown: 'legacy content', + user_ID: null + }); + + // Spy on LOG to verify the warn fires for the unmatched entity. + // The module uses cds.log('anonymization-cascade'); we intercept warn + // on the active logger instance. Use cds.log as a factory to get the + // same logger instance the module holds. + const logger = cds.log('anonymization-cascade'); + const warnSpy = vi.spyOn(logger, 'warn'); + + // Must not throw — the empty-candidates guard skips instead of + // issuing WHERE authorId IN () which is a HANA syntax error. + await expect( + executeAnonymizationCascade( + { ID: userId, sapId: null, uuid: null }, + await cds.connect.to('db') + ) + ).resolves.toBeUndefined(); + + // The LOG.warn for the empty-candidates skip must have fired. + const warnCalls = warnSpy.mock.calls.map(c => c[0]); + const emptyGuardFired = warnCalls.some( + msg => typeof msg === 'string' && msg.includes('no data-subject candidates') + ); + expect(emptyGuardFired).toBe(true); + + // Row survives — no key to match; flagged for manual GDPR review via LOG.warn. + const rows = await SELECT.from(AuthorAiRequests).where({ ID: reqId }); + expect(rows).toHaveLength(1); + }); + + it('test_cascade_deletes_tab_nested_DeveloperEnvironmentLinks', async () => { + const { + Users, + DeveloperEnvironmentTabs, + DeveloperEnvironmentLinks + } = cds.entities('com.sap.developers.ims'); + + // Clean up before this test case (beforeEach only cleans AuthorAiRequests/Users) + await DELETE.from(DeveloperEnvironmentLinks); + await DELETE.from(DeveloperEnvironmentTabs); + + const userId = '22222222-2222-2222-2222-222222222222'; + const sapId = 'S00BOB'; + await INSERT.into(Users).entries({ + ID: userId, + sapId: sapId, + firstName: 'Bob', + email: 'bob@example.com' + }); + + // A Tab owned by the user + const tabId = 'tttttttt-tttt-tttt-tttt-tttttttttttt'; + await INSERT.into(DeveloperEnvironmentTabs).entries({ + ID: tabId, + user_ID: userId, + legacyId: 1 + }); + + // A Link nested under the Tab. + // The cascade must delete this via the nested-marker path: + // 1. SELECT DeveloperEnvironmentTabs WHERE user_ID = userId -> [tabId] + // 2. DELETE DeveloperEnvironmentLinks WHERE tab_ID IN [tabId] + // + // DeveloperEnvironmentTabs runs at plan index 3 and DeveloperEnvironmentLinks + // at index 4 (stable sort, both cascade:'delete'), so the Tabs step also + // deletes the Link via Composition. The spy below independently verifies + // the nested-marker branch issued its own DELETE, isolating the code path. + const linkId = 'llllllll-llll-llll-llll-llllllllllll'; + await INSERT.into(DeveloperEnvironmentLinks).entries({ + ID: linkId, + tab_ID: tabId, + legacyId: 10 + }); + + // Manual spy on cds.db.run using an own-property override so that the deep + // prototype method (DatabaseService.run at depth 3) is intercepted. + // vi.spyOn cannot reliably wrap a method that far up the prototype chain, + // so we use Object.defineProperty on the instance directly. + // This captures every CQL query dispatched through the connected DB service. + const capturedRuns = []; + const origRun = cds.db.run.bind(cds.db); + Object.defineProperty(cds.db, 'run', { + value: async function (q, ...args) { + try { + const s = JSON.stringify(q); + if (s) capturedRuns.push(s); + } catch { /* non-serializable query; skip */ } + return origRun(q, ...args); + }, + writable: true, + configurable: true + }); + + try { + await executeAnonymizationCascade( + { ID: userId, sapId: sapId }, + await cds.connect.to('db') + ); + } finally { + // Always remove the own-property override so prototype is restored. + delete cds.db.run; + } + + // Verify the nested-marker branch in cascadeDelete fired correctly: + // it must have issued a SELECT on DeveloperEnvironmentTabs (the `via` entity) + // with WHERE user_ID = userId to resolve the parent IDs before deciding + // whether to delete child Links. + // + // If the nested branch were removed entirely, the resolved.nested check + // would be skipped; with resolved.values = null the empty-array guard + // (`!resolved.values?.length`) fires and LOG.warn is emitted — the DELETE + // never runs AND this intermediate SELECT never runs either. + // If `resolved.via` were changed to a wrong entity, a different SELECT + // would appear instead — both cases cause this assertion to fail. + const nestedSelectFired = capturedRuns.some( + s => s.includes('"DeveloperEnvironmentTabs"') && s.includes('user_ID') && s.includes(userId) + ); + expect(nestedSelectFired).toBe(true); + + // Belt-and-braces: the Link must be gone from DB. + const links = await SELECT.from(DeveloperEnvironmentLinks).where({ ID: linkId }); + expect(links).toHaveLength(0); + }); + + // Isolation test: invokes cascadeDelete for the DeveloperEnvironmentLinks plan entry + // DIRECTLY — no full orchestrator, so the Tabs step never runs and the Composition + // never pre-deletes the Link. The Tab is still in DB when the Links step fires, so + // parentIds is non-empty and the nested DELETE must actually execute. + // + // This test FAILS if: + // - resolved.via is wrong (SELECT targets wrong entity -> parentIds = [] -> no DELETE) + // - resolved.column is wrong (DELETE targets wrong column -> Link survives) + // - the nested branch is removed entirely (empty-array guard fires, Link survives) + it('test_cascadeDelete_nested_isolation_DeveloperEnvironmentLinks', async () => { + const { + Users, + DeveloperEnvironmentTabs, + DeveloperEnvironmentLinks + } = cds.entities('com.sap.developers.ims'); + + // Clean slate for this test + await DELETE.from(DeveloperEnvironmentLinks); + await DELETE.from(DeveloperEnvironmentTabs); + + const userId = '44444444-4444-4444-4444-444444444444'; + const sapId = 'S00CAROL'; + await INSERT.into(Users).entries({ + ID: userId, + sapId: sapId, + firstName: 'Carol', + email: 'carol@example.com' + }); + + // Tab owned by the user — must be in DB when cascadeDelete fires for Links + const tabId = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'; + await INSERT.into(DeveloperEnvironmentTabs).entries({ + ID: tabId, + user_ID: userId, + legacyId: 2 + }); + + // Link pointing at the Tab + const linkId = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; + await INSERT.into(DeveloperEnvironmentLinks).entries({ + ID: linkId, + tab_ID: tabId, + legacyId: 20 + }); + + // Locate the DeveloperEnvironmentLinks plan entry from the real model + const definitions = (cds.model ?? cds.db?.model)?.definitions; + const plan = getCascadePlan(definitions); + const linksStep = plan.find( + e => e.entityName === 'com.sap.developers.ims.DeveloperEnvironmentLinks' + ); + expect(linksStep).toBeDefined(); // sanity: plan entry exists + expect(linksStep.dataSubjectField).toBe('tab_ID'); // resolver returns nested marker on this field + expect(linksStep.action).toBe('delete'); + + const db = await cds.connect.to('db'); + + // Invoke cascadeDelete directly for the Links plan entry. + // The Tab is STILL in the DB here — the Tabs step has NOT run. + // The nested path must: SELECT DeveloperEnvironmentTabs WHERE user_ID = userId + // -> [tabId] -> DELETE DeveloperEnvironmentLinks WHERE tab_ID IN [tabId] + await _cascadeDeleteForTest({ ID: userId, sapId }, linksStep, db); + + // Assert the Link is deleted by THIS call (not by a prior Composition cascade) + const linksAfter = await SELECT.from(DeveloperEnvironmentLinks).where({ ID: linkId }); + expect(linksAfter).toHaveLength(0); + + // The Tab itself must still be in DB (we only ran the Links step, not the Tabs step) + const tabsAfter = await SELECT.from(DeveloperEnvironmentTabs).where({ ID: tabId }); + expect(tabsAfter).toHaveLength(1); + }); +}); diff --git a/test/unit/data-privacy-export.test.js b/test/unit/data-privacy-export.test.js new file mode 100644 index 000000000..66ef27653 --- /dev/null +++ b/test/unit/data-privacy-export.test.js @@ -0,0 +1,347 @@ +// test/unit/data-privacy-export.test.js +// +// TDD suite for DataPrivacyService.exportDataSubject(userId). +// +// Boots ONLY the DataPrivacyService (cds.serve().from()) rather than the +// full project (cds.test('serve')), so that other srv/*.js files that depend +// on built artifacts (srv/lib/_shared/mcp.bundle.mjs) are not loaded. +// Pattern: admin-last-chance-action.test.js (cds.deploy + cds.serve().from). +// +// Assertions: +// - envelope.subject carries the 9 @PersonalData.IsPotentiallyPersonal fields +// - AuthorAiRequests row (authorId=user.sapId, user_ID=null) appears in output +// (end-to-end proof that the authorId resolver path works) +// - DeveloperEnvironmentLinks appear nested under their parent Tab +// - CodeCheckSubmissions.submittedCode (LargeString) round-trips in output +// - count:0 section for an entity with no rows for this user (not omitted) +// - AnalyticsQueryHistory (EntitySemantics: 'Other', no DataSubjectID) does +// NOT appear in sections and does NOT crash +// - unknown userId -> handler rejects with a 404-shaped error + +import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'; +import path from 'node:path'; +import cds from '@sap/cds'; +import { _resetPlanForTest } from '../../srv/lib/anonymization-cascade.js'; + +// Schema paths -- load schema.cds + audit-logging.cds so @PersonalData +// annotations are present (same pattern as anonymization-cascade.test.js). +const SCHEMA_PATH = path.join(process.cwd(), 'db', 'schema.cds'); +const AUDIT_PATH = path.join(process.cwd(), 'db', 'audit-logging.cds'); +const SVC_PATH = path.join(process.cwd(), 'srv', 'data-privacy-service.cds'); + +const ADMIN = { id: 'admin@example.com', roles: ['Admin'] }; + +// Deterministic UUIDs for reproducible tests. +const USER_ID = 'aaaaaaaa-1111-1111-1111-111111111111'; +const OTHER_ID = 'bbbbbbbb-2222-2222-2222-222222222222'; +const SAP_ID = 'S00ALICE'; +const USER_UUID = 'cccccccc-3333-3333-3333-333333333333'; +const TAB_ID = 'dddddddd-4444-4444-4444-444444444444'; +const LINK_ID = 'eeeeeeee-5555-5555-5555-555555555555'; + +// Send a function call as the admin user. +async function callExport(srv, userId) { + const user = new cds.User({ id: ADMIN.id, roles: ADMIN.roles }); + return srv.tx({ user }, (tx) => + tx.send('exportDataSubject', { userId }) + ); +} + +describe('DataPrivacyService.exportDataSubject', () => { + let srv; + + beforeAll(async () => { + // Deploy schema + annotations to in-memory SQLite, then serve ONLY + // DataPrivacyService from its handler file. + await cds.deploy([SCHEMA_PATH, AUDIT_PATH, SVC_PATH]).to('sqlite::memory:'); + srv = await cds.serve('DataPrivacyService').from('./srv/data-privacy-service'); + // cds.model can be null on Windows with cds.deploy() (ESM singleton divergence). + // CAP's internal scheduling queue accesses cds.model.definitions at commit time; + // backfill cds.model from cds.db.model to prevent unhandled rejections. + if (!cds.model && cds.db?.model) cds.model = cds.db.model; + }); + + beforeEach(async () => { + _resetPlanForTest(); + + // Clear all relevant tables in dependency order (children before parents). + const { + DeveloperEnvironmentLinks, + DeveloperEnvironmentTabs, + CodeCheckSubmissions, + ValidateAnswerSubmissions, + AuthorAiRequests, + UserMetaData, + UserLearningPreferences, + PrizeRecords, + AccomplishmentRecords, + Users, + } = cds.entities('com.sap.developers.ims'); + + await DELETE.from(DeveloperEnvironmentLinks); + await DELETE.from(DeveloperEnvironmentTabs); + await DELETE.from(CodeCheckSubmissions); + await DELETE.from(ValidateAnswerSubmissions); + await DELETE.from(AuthorAiRequests); + await DELETE.from(UserMetaData); + await DELETE.from(UserLearningPreferences); + await DELETE.from(PrizeRecords); + await DELETE.from(AccomplishmentRecords); + await DELETE.from(Users); + }); + + // --- Seed helper --- + async function seedFixtures() { + const { + Users, + UserMetaData, + CodeCheckSubmissions, + AuthorAiRequests, + DeveloperEnvironmentLinks, + DeveloperEnvironmentTabs, + } = cds.entities('com.sap.developers.ims'); + + await INSERT.into(Users).entries({ + ID: USER_ID, + sapId: SAP_ID, + uuid: USER_UUID, + firstName: 'Alice', + lastName: 'Smith', + email: 'alice@example.com', + displayName: 'Alice Smith', + khorosId: 'kh-001', + khorosLogin: 'alice_khoros', + khorosAvatarUrl: 'https://cdn.example/alice.png', + }); + + // Another user -- her rows must NOT appear in Alice's export. + await INSERT.into(Users).entries({ + ID: OTHER_ID, sapId: 'S00BOB', + uuid: 'cccccccc-9999-9999-9999-999999999999', + firstName: 'Bob', email: 'bob@example.com', + }); + + // UserMetaData -- direct user_ID FK. + await INSERT.into(UserMetaData).entries({ + ID: 'aabb0001-0000-0000-0000-000000000001', + user_ID: USER_ID, + }); + await INSERT.into(UserMetaData).entries({ + ID: 'aabb0001-0000-0000-0000-000000000002', + user_ID: OTHER_ID, + }); + + // CodeCheckSubmissions -- LargeString round-trip. + await INSERT.into(CodeCheckSubmissions).entries({ + ID: 'ffffffff-6666-6666-6666-666666666666', + user_ID: USER_ID, + tutorialSlug: 'test-tutorial', + stepNumber: 1, + submittedCode: 'console.log("hello world");', + verdict: 'pass', + }); + + // AuthorAiRequests -- authorId path (user_ID intentionally null). + await INSERT.into(AuthorAiRequests).entries({ + ID: '11111111-7777-7777-7777-777777777777', + authorId: SAP_ID, + feature: 'os-variants', + sourceMarkdown: '# Test markdown', + variants: '[{"os":"linux","markdown":"# Test"}]', + user_ID: null, + }); + + // DeveloperEnvironmentTabs + Links -- nested output. + await INSERT.into(DeveloperEnvironmentTabs).entries({ + ID: TAB_ID, + user_ID: USER_ID, + tabName: 'My Tab', + tabOrder: 1, + }); + await INSERT.into(DeveloperEnvironmentLinks).entries({ + ID: LINK_ID, + tab_ID: TAB_ID, + title: 'SAP Developers', + url: 'https://developers.sap.com', + linkOrder: 1, + }); + } + + // ------------------------------------------------------------------------- + + it('returns a valid JSON envelope with subject block containing 9 personal fields', async () => { + await seedFixtures(); + const raw = await callExport(srv, USER_ID); + const doc = JSON.parse(raw); + + expect(doc.exportedAt).toBeTruthy(); + expect(doc.exportedBy).toBe(ADMIN.id); + expect(Array.isArray(doc.sections)).toBe(true); + + const s = doc.subject; + expect(s.firstName).toBe('Alice'); + expect(s.lastName).toBe('Smith'); + expect(s.email).toBe('alice@example.com'); + expect(s.displayName).toBe('Alice Smith'); + expect(s.sapId).toBe(SAP_ID); + expect(s.uuid).toBe(USER_UUID); + expect(s.khorosId).toBe('kh-001'); + expect(s.khorosLogin).toBe('alice_khoros'); + expect(s.khorosAvatarUrl).toBe('https://cdn.example/alice.png'); + }); + + it('AuthorAiRequests row (authorId path, no user_ID FK) appears in sections', async () => { + await seedFixtures(); + const raw = await callExport(srv, USER_ID); + const doc = JSON.parse(raw); + + const section = doc.sections.find((s) => s.entity.includes('AuthorAiRequests')); + expect(section).toBeTruthy(); + expect(section.count).toBe(1); + expect(section.rows).toHaveLength(1); + expect(section.rows[0].sourceMarkdown).toBe('# Test markdown'); + }); + + it('DeveloperEnvironmentLinks appear nested under their parent Tab row', async () => { + await seedFixtures(); + const raw = await callExport(srv, USER_ID); + const doc = JSON.parse(raw); + + const tabSection = doc.sections.find( + (s) => s.entity.includes('DeveloperEnvironmentTabs') + ); + expect(tabSection).toBeTruthy(); + expect(tabSection.count).toBe(1); + + const tabRow = tabSection.rows.find((r) => r.ID === TAB_ID); + expect(tabRow).toBeTruthy(); + expect(Array.isArray(tabRow.links)).toBe(true); + expect(tabRow.links).toHaveLength(1); + expect(tabRow.links[0].title).toBe('SAP Developers'); + expect(tabRow.links[0].url).toBe('https://developers.sap.com'); + }); + + it('CodeCheckSubmissions.submittedCode (LargeString) round-trips through JSON output', async () => { + await seedFixtures(); + const raw = await callExport(srv, USER_ID); + const doc = JSON.parse(raw); + + const section = doc.sections.find( + (s) => s.entity.includes('CodeCheckSubmissions') + ); + expect(section).toBeTruthy(); + expect(section.count).toBe(1); + expect(section.rows[0].submittedCode).toBe('console.log("hello world");'); + }); + + it('entity with no rows for the subject has count:0 and empty rows array (not omitted)', async () => { + await seedFixtures(); + const raw = await callExport(srv, USER_ID); + const doc = JSON.parse(raw); + + // ValidateAnswerSubmissions is a @PersonalData entity with user FK, + // but no rows seeded for Alice -> must appear with count:0. + const section = doc.sections.find( + (s) => s.entity.includes('ValidateAnswerSubmissions') + ); + expect(section).toBeTruthy(); + expect(section.count).toBe(0); + expect(section.rows).toEqual([]); + }); + + it('AnalyticsQueryHistory does not appear in sections (Other semantics, no DataSubjectID)', async () => { + await seedFixtures(); + const raw = await callExport(srv, USER_ID); + const doc = JSON.parse(raw); + + const section = doc.sections.find( + (s) => s.entity.includes('AnalyticsQueryHistory') + ); + expect(section).toBeUndefined(); + }); + + it('unknown userId rejects with a 404-shaped error', async () => { + const missingId = 'zzzzzzzz-0000-0000-0000-000000000000'; + await expect( + callExport(srv, missingId) + ).rejects.toMatchObject({ code: 404 }); + }); + + it('AuthorAiRequests rows for another user (different sapId) do not appear', async () => { + await seedFixtures(); + const { AuthorAiRequests } = cds.entities('com.sap.developers.ims'); + await INSERT.into(AuthorAiRequests).entries({ + ID: '22222222-8888-8888-8888-888888888888', + authorId: 'S00BOB', + feature: 'os-variants', + sourceMarkdown: 'Bob private data', + user_ID: null, + }); + + const raw = await callExport(srv, USER_ID); + const doc = JSON.parse(raw); + + const section = doc.sections.find( + (s) => s.entity.includes('AuthorAiRequests') + ); + expect(section.rows.every((r) => r.authorId === SAP_ID)).toBe(true); + expect(section.rows.some((r) => r.sourceMarkdown === 'Bob private data')).toBe(false); + }); + + it('_selectRows warns when a declared personalField is not a selectable element', async () => { + // Seed a UserMetaData row so the SELECT returns at least one row. + const { Users, UserMetaData } = cds.entities('com.sap.developers.ims'); + await INSERT.into(Users).entries({ + ID: USER_ID, sapId: SAP_ID, uuid: USER_UUID, + firstName: 'Alice', email: 'alice@example.com', + }); + await INSERT.into(UserMetaData).entries({ + ID: 'aabb0001-0000-0000-0000-000000000001', + user_ID: USER_ID, + }); + + // Build a minimal definitions object that represents UserMetaData with a + // phantom personal field 'nonExistentField'. We do NOT use the real model + // here -- we want to exercise the warn path in isolation. + const ENTITY = 'com.sap.developers.ims.UserMetaData'; + const fakeDefs = { + [ENTITY]: { + elements: { + ID: {}, + user_ID: {}, + // 'nonExistentField' intentionally absent + } + } + }; + + // cds.log returns an object whose .warn is a function. Spy on it. + // The LOG instance inside the module is bound at module load time to the + // 'data-privacy-service' tag. We obtain a reference by asking cds.log for + // the same tag -- cds.log caches instances by tag. + const logger = cds.log('data-privacy-service'); + const warnSpy = vi.spyOn(logger, 'warn'); + + // Call _selectRows directly on the service instance. + const rows = await srv._selectRows( + ENTITY, + 'user_ID', + [USER_ID], + ['nonExistentField'], // declared personal field that does not exist + fakeDefs + ); + + // warn must have fired mentioning the entity and the missing field. + expect(warnSpy).toHaveBeenCalled(); + const warnMsg = warnSpy.mock.calls[0].join(' '); + expect(warnMsg).toMatch(/nonExistentField/); + expect(warnMsg).toMatch(/UserMetaData/); + + // The row must still be exported using the real columns that do exist. + // With fakeDefs (no ID in elements -- wait, ID IS in fakeDefs), user_ID is + // the only included column from the candidates after filtering. + // Rows length: 1 (the seeded UserMetaData row). + expect(rows.length).toBe(1); + + warnSpy.mockRestore(); + }); +}); diff --git a/test/unit/data-privacy-service-metadata.test.js b/test/unit/data-privacy-service-metadata.test.js new file mode 100644 index 000000000..947584ac4 --- /dev/null +++ b/test/unit/data-privacy-service-metadata.test.js @@ -0,0 +1,36 @@ +import { expect, describe, it } from 'vitest'; +import cds from '@sap/cds'; + +describe('DataPrivacyService metadata', () => { + it('service DataPrivacyService is defined', async () => { + const csn = await cds.load('srv/data-privacy-service.cds'); + const svc = csn.definitions['DataPrivacyService']; + expect(svc).toBeDefined(); + }); + + it('carries @requires annotation set to Admin', async () => { + const csn = await cds.load('srv/data-privacy-service.cds'); + const svc = csn.definitions['DataPrivacyService']; + expect(svc['@requires']).toBe('Admin'); + }); + + it('carries @path annotation set to /admin/data-privacy', async () => { + const csn = await cds.load('srv/data-privacy-service.cds'); + const svc = csn.definitions['DataPrivacyService']; + expect(svc['@path']).toBe('/admin/data-privacy'); + }); + + it('defines exportDataSubject operation', async () => { + const csn = await cds.load('srv/data-privacy-service.cds'); + // In CSN from cds.load, operations are defined in the service source and + // accessible via the service definition object. The operation structure + // is validated at compile time by CDS. This test confirms the definition + // file structure is well-formed (service loads without parse error). + const svc = csn.definitions['DataPrivacyService']; + expect(svc).toBeDefined(); + // The actual operation can be accessed after full model compilation. + // This test ensures the .cds file syntax is valid; handler tests and + // full compilation test (e.g., via cds.test boot) verify the operation + // is properly compiled and callable. + }); +}); diff --git a/test/unit/data-subject-resolver.test.js b/test/unit/data-subject-resolver.test.js new file mode 100644 index 000000000..35b28aeb1 --- /dev/null +++ b/test/unit/data-subject-resolver.test.js @@ -0,0 +1,122 @@ +// test/unit/data-subject-resolver.test.js +// +// Pure unit tests for srv/lib/data-subject-resolver.js. +// No CDS boot needed — the resolver is a pure function module. +// planEntry objects are constructed as plain literals (same shape as getCascadePlan output). + +import { describe, it, expect } from 'vitest'; +import { authorIdCandidates, resolveSubjectKeys } from '../../srv/lib/data-subject-resolver.js'; + +// ─── Fixtures ──────────────────────────────────────────────────────────────── + +const USER = { + ID: 'aaaabbbb-cccc-dddd-eeee-ffffaaaabbbb', + sapId: 'S00ALICE', + uuid: 'U-ALICE-1' +}; + +const USER_NO_UUID = { + ID: 'aaaabbbb-cccc-dddd-eeee-ffffaaaabbbb', + sapId: 'S00ALICE', + uuid: null +}; + +const USER_NO_SAPID = { + ID: 'aaaabbbb-cccc-dddd-eeee-ffffaaaabbbb', + sapId: null, + uuid: 'U-ALICE-1' +}; + +// Plan-entry factory (mirrors getCascadePlan output shape) +function entry(entityName, dataSubjectField, action = 'delete') { + return { entityName, action, dataSubjectField, personalFields: [] }; +} + +// ─── authorIdCandidates ─────────────────────────────────────────────────────── + +describe('authorIdCandidates', () => { + it('returns [sapId, uuid] for a user with both', () => { + expect(authorIdCandidates(USER)).toEqual(['S00ALICE', 'U-ALICE-1']); + }); + + it('filters out null uuid', () => { + expect(authorIdCandidates(USER_NO_UUID)).toEqual(['S00ALICE']); + }); + + it('filters out null sapId', () => { + expect(authorIdCandidates(USER_NO_SAPID)).toEqual(['U-ALICE-1']); + }); + + it('returns empty array when both are null', () => { + expect(authorIdCandidates({ ID: 'x', sapId: null, uuid: null })).toEqual([]); + }); +}); + +// ─── resolveSubjectKeys ─────────────────────────────────────────────────────── + +describe('resolveSubjectKeys', () => { + // (a) Users → { column:'ID', values:[user.ID] } + it('(a) Users entity → column ID, values [user.ID]', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.Users', 'ID', 'identity-replace')); + expect(result).toEqual({ column: 'ID', values: [USER.ID] }); + }); + + // Also handles plain dataSubjectField === 'ID' regardless of entityName + it('(a-2) dataSubjectField===ID (any entity) → column ID, values [user.ID]', async () => { + const result = await resolveSubjectKeys(USER, entry('com.sap.developers.ims.Users', 'ID', 'identity-replace')); + expect(result).toEqual({ column: 'ID', values: [USER.ID] }); + }); + + // (b) user_ID entity (e.g. UserMetaData) → { column:'user_ID', values:[user.ID] } + it('(b) UserMetaData entry → column user_ID, values [user.ID]', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.UserMetaData', 'user_ID')); + expect(result).toEqual({ column: 'user_ID', values: [USER.ID] }); + }); + + // (c) AuthorAiRequests → column authorId, values contain both sapId and uuid + it('(c) AuthorAiRequests → column authorId, values contain sapId and uuid', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.AuthorAiRequests', 'authorId')); + expect(result).not.toBeNull(); + expect(result.column).toBe('authorId'); + expect(result.values).toContain('S00ALICE'); + expect(result.values).toContain('U-ALICE-1'); + }); + + it('(c-2) AuthorAiRequests user with only sapId → values=[sapId]', async () => { + const result = await resolveSubjectKeys(USER_NO_UUID, entry('ims.AuthorAiRequests', 'authorId')); + expect(result.values).toEqual(['S00ALICE']); + }); + + // (d) skip action or null dataSubjectField → null + it('(d) action===skip → null', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.AnalyticsQueryHistory', null, 'skip')); + expect(result).toBeNull(); + }); + + it('(d-2) dataSubjectField===null → null', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.Foo', null, 'delete')); + expect(result).toBeNull(); + }); + + it('(d-3) dataSubjectField===false-y empty string → null', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.Foo', '', 'delete')); + expect(result).toBeNull(); + }); + + // (e) DeveloperEnvironmentLinks → nested marker + it('(e) DeveloperEnvironmentLinks (tab_ID) → nested marker { column, nested, via }', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.DeveloperEnvironmentLinks', 'tab_ID')); + expect(result).not.toBeNull(); + expect(result.column).toBe('tab_ID'); + expect(result.nested).toBe(true); + expect(result.via).toBe('DeveloperEnvironmentTabs'); + // values should be null (caller must resolve the parent Tabs first) + expect(result.values).toBeNull(); + }); + + // default branch: any *_ID field not specifically handled → { column, values:[user.ID] } + it('default: arbitrary _ID FK field → column=field, values=[user.ID]', async () => { + const result = await resolveSubjectKeys(USER, entry('ims.TutorialProgress', 'user_ID')); + expect(result).toEqual({ column: 'user_ID', values: [USER.ID] }); + }); +});